context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace DataBoss.Data
{
public delegate void Updater<TSource, T>(TSource reader, ref T target);
public class ConverterFactory
{
class ConverterContext
{
readonly ConverterCollection converters;
readonly MethodInfo getFieldValueT;
ConverterContext(ParameterExpression arg0, MethodInfo isDBNull, Type resultType, ConverterCollection converters) {
this.Arg0 = arg0;
this.IsDBNull = isDBNull;
this.ResultType = resultType;
this.converters = converters;
this.getFieldValueT = arg0.Type.GetMethod("GetFieldValue");
}
public readonly Type ResultType;
public readonly ParameterExpression Arg0;
public readonly MethodInfo IsDBNull;
public static ConverterContext Create(Type recordType, Type resultType, ConverterCollection converters) {
return new ConverterContext(Expression.Parameter(recordType, "x"),
recordType.GetMethod(nameof(IDataRecord.IsDBNull)) ?? typeof(IDataRecord).GetMethod(nameof(IDataRecord.IsDBNull)),
resultType,
converters);
}
public bool TryReadFieldAs(Type fieldType, Expression ordinal, Type itemType, out Expression reader) {
if(TryReadField(fieldType, ordinal, out var readRaw)
&& TryConvertField(readRaw, itemType, out reader))
return true;
reader = null;
return false;
}
public bool TryReadField(Type fieldType, Expression ordinal, out Expression reader) {
if(TryGetGetMethod(fieldType, out var getter)) {
reader = Expression.Call(Arg0, getter, ordinal);
return true;
}
reader = null;
return false;
}
bool TryGetGetMethod(Type fieldType, out MethodInfo getter) {
getter = GetGetMethod(Arg0.Type, "Get" + fieldType.Name, fieldType);
if (getter == null && getFieldValueT != null)
getter = getFieldValueT.MakeGenericMethod(fieldType);
if (getter == null)
getter = GetGetMethod(Arg0.Type, "Get" + MapFieldType(fieldType), fieldType);
return getter != null;
}
static MethodInfo GetGetMethod(Type arg0, string name, Type type) {
var found = arg0.GetMethod(name) ?? typeof(IDataRecord).GetMethod(name);
if(found != null && ParametersEqual(found, typeof(int)))
return found;
return null;
}
static bool ParametersEqual(MethodInfo method, params Type[] parameterTypes) {
var ps = method.GetParameters();
if (ps.Length != parameterTypes.Length)
return false;
for (var i = 0; i != ps.Length; ++i)
if (ps[i].ParameterType != parameterTypes[i])
return false;
return true;
}
bool TryConvertField(Expression rawField, Type to, out Expression convertedField) {
var from = rawField.Type;
if (from == to) {
convertedField = rawField;
return true;
}
if (TryGetConverter(rawField, to, out convertedField))
return true;
return false;
}
bool TryGetConverter(Expression rawField, Type to, out Expression converter) {
if (converters.TryGetConverter(rawField, to, out converter))
return true;
if(IsByteArray(rawField, to)
|| IsEnum(rawField, to)
|| IsTimeSpan(rawField, to)
|| ToIsAssignableFrom(rawField, to)
|| FromIsCastableTo(rawField, to)
) {
converter = Expression.Convert(rawField, to);
return true;
}
return false;
}
static bool IsByteArray(Expression rawField, Type to) =>
rawField.Type == typeof(object) && to == typeof(byte[]);
static bool IsTimeSpan(Expression rawField, Type to) =>
rawField.Type == typeof(object) && to == typeof(TimeSpan);
static bool IsEnum(Expression rawField, Type to) =>
to.IsEnum && Enum.GetUnderlyingType(to) == rawField.Type;
static bool ToIsAssignableFrom(Expression rawField, Type to) {
var t = new[] { rawField.Type };
var cast = to.GetMethod("op_Implicit", t) ?? to.GetMethod("op_Explicit", t);
return cast != null && to.IsAssignableFrom(cast.ReturnType);
}
static bool FromIsCastableTo(Expression rawField, Type to) =>
rawField.Type.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Any(x => x.IsSpecialName && (x.Name == "op_Implicit" || x.Name == "op_Explicit") && x.ReturnType == to);
public Expression IsNull(Expression o) => Expression.Call(Arg0, IsDBNull, o);
public Expression DbNullToDefault(FieldMapItem field, Expression o, Type itemType, Expression readIt) {
if(!field.CanBeNull)
return readIt;
return Expression.Condition(
Expression.Call(Arg0, IsDBNull, o),
Expression.Default(itemType),
readIt);
}
public BindingResult BindItem(FieldMap map, in ItemInfo item, out MemberReader reader) {
if (item.Type.TryGetNullableTargetType(out var baseType)) {
var r = BindItem(map, new ItemInfo(item.Name, baseType), out var childReader);
if (r == BindingResult.Ok) {
reader = new MemberReader(
childReader.Ordinal,
item.Name,
Expression.Condition(
childReader.IsDbNull ?? Expression.Constant(false),
Expression.Default(item.Type),
Expression.Convert(childReader.Read, item.Type)),
null);
return BindingResult.Ok;
}
reader = default;
return r;
}
if (map.TryGetField(item.Name, out var field)) {
var o = Expression.Constant(field.Ordinal);
Expression convertedField;
var canReadAsItem =
TryReadFieldAs(field.FieldType, o, item.Type, out convertedField)
|| TryReadProviderSpecificFieldAs(item, field, o, ref convertedField);
if (!canReadAsItem) {
reader = default;
return BindingResult.InvalidCast;
}
var thisNull = field.CanBeNull
? new[] { (item.Name, IsNull(o)) }
: null;
reader = new MemberReader(field.Ordinal, item.Name, convertedField, thisNull);
return BindingResult.Ok;
}
if (map.TryGetSubMap(item.Name, out var subMap)) {
reader = FieldInit(subMap, item);
return BindingResult.Ok;
}
reader = default;
return BindingResult.NotFound;
}
private bool TryReadProviderSpecificFieldAs(ItemInfo item, FieldMapItem field, ConstantExpression o, ref Expression convertedField) {
if (field.ProviderSpecificFieldType == null)
return false;
if (TryReadFieldAs(field.ProviderSpecificFieldType, o, item.Type, out convertedField))
return true;
var getProviderSpecificValue = Arg0.Type.GetMethod("GetProviderSpecificValue");
if (getProviderSpecificValue == null)
return false;
var readProviderSpecific = Expression.Convert(
Expression.Call(Arg0, getProviderSpecificValue, o),
field.ProviderSpecificFieldType);
return TryConvertField(readProviderSpecific, item.Type, out convertedField);
}
internal InvalidConversionException InvalidConversion(FieldMap map, in ItemInfo item) {
map.TryGetField(item.Name, out var field);
return new InvalidConversionException($"Can't read '{item.Name}' of type {item.Type.Name} given {field.FieldType.Name}", ResultType);
}
public MemberReader FieldInit(FieldMap map, in ItemInfo item) =>
GetCtor(map, item)
?? GetFactoryFunction(map, item)
?? InitValueType(map, item)
?? ReadScalar(map, item)
?? throw new InvalidConversionException($"No suitable way found to init {item.Name ?? "$"} of type {item.Type}", ResultType);
MemberReader? GetCtor(FieldMap map, in ItemInfo item) {
if(map.Count == 1 && item.Type == map.Single().Item.FieldType)
return null;
var ctors = item.Type.GetConstructors()
.Select(ctor => (ctor, p: Array.ConvertAll(ctor.GetParameters(), x => new ItemInfo(x.Name, x.ParameterType))))
.OrderByDescending(x => x.p.Length);
var itemType = item.Type;
return MakeReader(map, item.Name, ctors, (ctor, ps) =>
Expression.MemberInit(
Expression.New(ctor, ps),
GetMembers(map, itemType, new HashSet<string>(ctor.GetParameters().Select(x => x.Name), StringComparer.InvariantCultureIgnoreCase))));
}
MemberReader? GetFactoryFunction(FieldMap map, in ItemInfo item) {
var factoryFuns = item.Type
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(x => x.GetCustomAttribute(typeof(ConsiderAsCtorAttribute)) != null)
.Select(f => (fun: f, p: Array.ConvertAll(f.GetParameters(), x => new ItemInfo(x.Name, x.ParameterType))))
.OrderByDescending(x => x.p.Length);
return MakeReader(map, item.Name, factoryFuns, Expression.Call);
}
MemberReader? MakeReader<T>(FieldMap map, string itemName, IEnumerable<(T, ItemInfo[])> xs, Func<T, Expression[], Expression> makeExpr) {
foreach (var (ctor, p) in xs) {
var pn = new MemberReader[p.Length];
if (TryMapParameters(map, p, pn)) {
var nullability = pn
.Where(x => x.Read.Type.IsValueType && x.IsDbNull != null)
.Select(x => (x.Name, x.IsDbNull))
.ToArray();
return new MemberReader(
map.MinOrdinal,
itemName,
makeExpr(ctor, Array.ConvertAll(pn, x => x.IsDbNull == null
? x.Read
: Expression.Condition(x.IsDbNull, Expression.Default(x.Read.Type), x.Read))),
nullability);
}
}
return null;
}
MemberReader? InitValueType(FieldMap map, in ItemInfo item) {
if (!item.Type.IsValueType)
return null;
var foundMembers = GetMembers(map, item.Type);
if (foundMembers.Count == 0)
return null;
return new MemberReader(map.MinOrdinal, item.Name, Expression.MemberInit(Expression.New(item.Type), foundMembers), null);
}
MemberReader? ReadScalar(FieldMap map, in ItemInfo item) {
var (fieldName, field) = map.First();
var o = Expression.Constant(field.Ordinal);
var isNull = IsNull(o);
if (TryReadFieldAs(field.FieldType, o, item.Type, out var read)) {
if (item.Type.IsValueType && !item.Type.IsNullable())
return new MemberReader(field.Ordinal, item.Name, read, new[] { (fieldName, isNull) });
else return new MemberReader(field.Ordinal, item.Name, Expression.Condition(isNull, Expression.Default(item.Type), read), null);
}
return null;
}
public ArraySegment<MemberAssignment> GetMembers(FieldMap map, Type targetType, HashSet<string> excludedMembers = null, bool defaultOnNull = true) {
var fields = targetType.GetFields().Where(x => !x.IsInitOnly).Select(x => (Item: new ItemInfo(x.Name, x.FieldType), Member: (MemberInfo)x));
var props = targetType.GetProperties().Where(x => x.CanWrite).Select(x => (Item: new ItemInfo(x.Name, x.PropertyType), Member: (MemberInfo)x));
var allMembers = fields.Concat(props);
var members = (excludedMembers == null ? allMembers : allMembers.Where(x => !excludedMembers.Contains(x.Item.Name))).ToArray();
var ordinals = new int[members.Length];
var bindings = new MemberAssignment[members.Length];
var found = 0;
foreach (var x in members) {
switch(BindItem(map, x.Item, out var reader)) {
case BindingResult.InvalidCast: throw InvalidConversion(map, x.Item);
case BindingResult.NotFound:
if (x.Member.GetCustomAttribute(typeof(RequiredAttribute), false) != null)
throw new ArgumentException("Failed to set required member.", x.Item.Name);
else continue;
case BindingResult.Ok:
ordinals[found] = reader.Ordinal;
bindings[found] = Expression.Bind(x.Member, defaultOnNull ? ReadOrDefault(reader) : reader.Read);
++found;
break;
}
}
Array.Sort(ordinals, bindings, 0, found);
return new ArraySegment<MemberAssignment>(bindings, 0, found);
}
bool TryMapParameters(FieldMap map, ItemInfo[] parameters, MemberReader[] exprs) {
for (var i = 0; i != parameters.Length; ++i) {
if (BindItem(map, parameters[i], out exprs[i]) != BindingResult.Ok)
return false;
}
return true;
}
}
readonly struct ItemInfo
{
public ItemInfo(string name, Type type) {
this.Name = name;
this.Type = type;
}
public readonly string Name;
public readonly Type Type;
}
readonly struct MemberReader
{
public MemberReader(int ordinal, string name, Expression reader, IReadOnlyCollection<(string Name, Expression IsDbNull)> isDbNull) {
this.Ordinal = ordinal;
this.Name = name;
this.Read = reader;
if(isDbNull != null && isDbNull.Any(x => x.IsDbNull == null))
throw new InvalidOperationException("Null nullability check.");
this.NullableFields = isDbNull;
}
public readonly int Ordinal;
public readonly string Name;
public readonly Expression Read;
public Expression IsDbNull {
get {
if(NullableFields == null || NullableFields.Count == 0)
return null;
return AnyOf(NullableFields.Select(x => x.IsDbNull));
}
}
public readonly IReadOnlyCollection<(string Name, Expression IsDbNull)> NullableFields;
}
static Expression ReadOrDefault(in MemberReader reader) =>
reader.IsDbNull == null ? reader.Read : Expression.Condition(reader.IsDbNull, MakeDefault(reader.Read.Type), reader.Read);
static Expression GuardedRead(in MemberReader reader) {
if(reader.IsDbNull == null)
return reader.Read;
return GuardedExpression(reader.Read, reader.IsDbNull, reader.NullableFields);
}
static Expression GuardedInvoke(Expression body, MemberReader[] args) {
var isNull = AnyOf(args.Where(x => x.Read.Type.IsPrimitive).Select(x => x.IsDbNull));
body = Expression.Invoke(body, Array.ConvertAll(args, x => x.Read));
if (isNull == null)
return body;
return GuardedExpression(body, isNull, args
.Where(x => x.Read.Type.IsPrimitive && x.IsDbNull != null)
.Select(x => (x.Name, x.IsDbNull)));
}
static Expression GuardedExpression(Expression expr, Expression isNull, IEnumerable<(string Name, Expression IsDbNull)> fields) {
var nullFields = Expression.NewArrayInit(
typeof(string),
fields.Select(x =>
Expression.Condition(x.IsDbNull,
Expression.Constant(x.Name, typeof(string)),
Expression.Constant(null, typeof(string)))));
var @throw = Expression.Throw(
Expression.New(
typeof(DataRowNullCastException).GetConstructor(new[] { typeof(string[]) }),
nullFields),
expr.Type);
return Expression.Condition(isNull, @throw, expr);
}
class DataRowNullCastException : InvalidCastException
{
public DataRowNullCastException(string[] nullFields) :
base(string.Format("'{0}' was null.", string.Join(", ", nullFields.Where(x => !string.IsNullOrEmpty(x))))) { }
}
static Expression MakeDefault(Type type) =>
Expression.Default(type);
enum BindingResult
{
Ok,
NotFound,
InvalidCast
}
class DataRecordConverterFactory
{
readonly ConverterCollection customConversions;
public DataRecordConverterFactory(ConverterCollection customConversions) { this.customConversions = customConversions ?? new ConverterCollection(); }
public DataRecordConverter BuildConverter(Type readerType, FieldMap map, Type result) {
var context = ConverterContext.Create(readerType, result, customConversions);
var reader = context.FieldInit(map, new ItemInfo(null, context.ResultType));
return new DataRecordConverter(Expression.Lambda(
GuardedRead(reader), context.Arg0));
}
public DataRecordConverter BuildConverter<TReader>(FieldMap map, LambdaExpression resultFactory) where TReader : IDataReader {
var context = ConverterContext.Create(typeof(TReader), resultFactory.Type, customConversions);
return new DataRecordConverter(Expression.Lambda(
GuardedInvoke(
resultFactory,
BindAllParameters(context, map, resultFactory.Parameters.Select(x => new ItemInfo(x.Name, x.Type)).ToArray())),
context.Arg0));
}
public DataRecordConverter BuildConverter(Type readerType, FieldMap map, Delegate exemplar) {
var m = exemplar.Method;
var context = ConverterContext.Create(readerType, m.ReturnType, customConversions);
var pn = BindAllParameters(context, map,
Array.ConvertAll(m.GetParameters(), x => new ItemInfo(x.Name, x.ParameterType)));
var arg1 = Expression.Parameter(exemplar.GetType());
return new DataRecordConverter(Expression.Lambda(GuardedInvoke(arg1, pn), context.Arg0, arg1));
}
MemberReader[] BindAllParameters(ConverterContext context, FieldMap map, ItemInfo[] parameters) {
var pn = new MemberReader[parameters.Length];
for (var i = 0; i != pn.Length; ++i) {
switch (context.BindItem(map, parameters[i], out pn[i])) {
case BindingResult.InvalidCast: throw context.InvalidConversion(map, parameters[i]);
case BindingResult.NotFound: throw new InvalidOperationException($"Failed to map parameter \"{parameters[i].Name}\"");
}
}
return pn;
}
}
readonly DataRecordConverterFactory recordConverterFactory;
readonly IConverterCache converterCache;
readonly ConcurrentDictionary<ConverterCacheKey, Delegate> readIntoCache = new ConcurrentDictionary<ConverterCacheKey, Delegate>();
public ConverterFactory(ConverterCollection customConversions) : this(customConversions, new ConcurrentConverterCache())
{ }
public ConverterFactory(ConverterCollection customConversions, IConverterCache converterCache) {
this.recordConverterFactory = new DataRecordConverterFactory(customConversions);
this.converterCache = converterCache;
}
public static ConverterFactory Default = new(null, new ConcurrentConverterCache());
public static DataRecordConverter<TReader, T> GetConverter<TReader, T>(TReader reader, ConverterCollection customConversions) where TReader : IDataReader {
var recordConverterFactory = new DataRecordConverterFactory(customConversions);
return recordConverterFactory.BuildConverter(typeof(TReader), FieldMap.Create(reader), typeof(T)).ToTyped<TReader, T>();
}
public Func<TReader, TResult> Compile<TReader, T1, TResult>(TReader reader, Expression<Func<T1, TResult>> selector) where TReader : IDataReader =>
(Func<TReader, TResult>)GetConverter(reader, selector).Compile();
public Func<TReader, TResult> Compile<TReader, T1, T2, TResult>(TReader reader, Expression<Func<T1, T2, TResult>> selector) where TReader : IDataReader =>
(Func<TReader, TResult>)GetConverter(reader, selector).Compile();
public Func<TReader, TResult> Compile<TReader, T1, T2, T3, TResult>(TReader reader, Expression<Func<T1, T2, T3, TResult>> selector) where TReader : IDataReader =>
(Func<TReader, TResult>)GetConverter(reader, selector).Compile();
public Func<TReader, TResult> Compile<TReader, T1, T2, T3, T4, TResult>(TReader reader, Expression<Func<T1, T2, T3, T4, TResult>> selector) where TReader : IDataReader =>
(Func<TReader, TResult>)GetConverter(reader, selector).Compile();
public Func<TReader, TResult> Compile<TReader, T1, T2, T3, T4, T5, TResult>(TReader reader, Expression<Func<T1, T2, T3, T4, T5, TResult>> selector) where TReader : IDataReader =>
(Func<TReader, TResult>)GetConverter(reader, selector).Compile();
public Func<TReader, TResult> Compile<TReader, T1, T2, T3, T4, T5, T6, TResult>(TReader reader, Expression<Func<T1, T2, T3, T4, T5, T6, TResult>> selector) where TReader : IDataReader =>
(Func<TReader, TResult>)GetConverter(reader, selector).Compile();
public Func<TReader, TResult> Compile<TReader, T1, T2, T3, T4, T5, T6, T7, TResult>(TReader reader, Expression<Func<T1, T2, T3, T4, T5, T6, T7, TResult>> selector) where TReader : IDataReader =>
(Func<TReader, TResult>)GetConverter(reader, selector).Compile();
public DataRecordConverter<TReader, T> GetConverter<TReader, T>(TReader reader) where TReader : IDataReader =>
converterCache.GetOrAdd(
reader, ConverterCacheKey.Create(reader, typeof(TReader), typeof(T)),
x => recordConverterFactory.BuildConverter(typeof(TReader), x, typeof(T)))
.ToTyped<TReader, T>();
public Updater<IDataReader, T> GetReadInto<T>(IDataReader reader) =>
(Updater<IDataReader, T>)readIntoCache.GetOrAdd(ConverterCacheKey.Into(reader, typeof(IDataReader), typeof(T)), delegate {
return (Updater<IDataReader, T>)GetReadInto(reader, typeof(IDataReader), typeof(T)).Compile();
});
public LambdaExpression GetReadInto(IDataReader reader, Type readerType, Type targetType) {
var fields = FieldMap.Create(reader);
var context = ConverterContext.Create(readerType, targetType, null);
var members = context.GetMembers(fields, context.ResultType, defaultOnNull: false);
var target = Expression.Parameter(targetType.MakeByRefType(), "target");
return Expression.Lambda(
typeof(Updater<,>).MakeGenericType(readerType, targetType),
Expression.Block(
members.Select(x => Expression.Assign(Expression.MakeMemberAccess(target, x.Member), x.Expression))),
context.Arg0,
target);
}
public DataRecordConverter GetConverter<TReader>(TReader reader, LambdaExpression factory) where TReader : IDataReader {
if (ConverterCacheKey.TryCreate(reader, factory, out var key)) {
return converterCache.GetOrAdd(
reader, key,
x => recordConverterFactory.BuildConverter<TReader>(x, factory));
}
return recordConverterFactory.BuildConverter<TReader>(FieldMap.Create(reader), factory);
}
public DataRecordConverter<TReader, T> BuildConverter<TReader, T>(FieldMap fields) =>
recordConverterFactory.BuildConverter(typeof(TReader), fields, typeof(T)).ToTyped<TReader, T>();
public DataRecordConverter GetTrampoline<TReader>(TReader reader, Delegate exemplar) where TReader : IDataReader =>
converterCache.GetOrAdd(
reader, ConverterCacheKey.Create(reader, exemplar),
x => recordConverterFactory.BuildConverter(typeof(TReader), x, exemplar));
public Delegate CompileTrampoline<TReader>(TReader reader, Delegate exemplar) where TReader : IDataReader =>
GetTrampoline(reader, exemplar).Compile();
static Expression OrElse(Expression left, Expression right) {
if(left == null)
return right;
if(right == null)
return left;
return Expression.OrElse(left, right);
}
static Expression AnyOf(IEnumerable<Expression> exprs) =>
exprs.Aggregate((Expression)null, OrElse);
static string MapFieldType(Type fieldType) {
switch(fieldType.FullName) {
case "System.Single": return "Float";
case "System.Byte[]":
case "System.TimeSpan":
case "System.Object": return "Value";
case "System.Data.SqlTypes.SqlByte": return "Byte";
}
if(fieldType.IsEnum)
return Enum.GetUnderlyingType(fieldType).Name;
return fieldType.Name;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright fieldInfole="_AutoWebProxyScriptWrapper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
// Two implementations of AutoWebProxyScriptWrapper live in this file. The first uses jscript.dll via COM, the second
// uses Microsoft.JScript using an external AppDomain.
#pragma warning disable 618
#define AUTOPROXY_MANAGED_JSCRIPT
#if !AUTOPROXY_MANAGED_JSCRIPT
namespace System.Net
{
using System.Net.ComImports;
using System.Runtime.InteropServices;
using EXCEPINFO = System.Runtime.InteropServices.ComTypes.EXCEPINFO;
using System.Threading;
using System.Reflection;
using System.Net.Configuration;
using System.Globalization;
internal class AutoWebProxyScriptWrapper
{
const string c_ScriptHelperName = "__AutoWebProxyScriptHelper";
private static TimerThread.Queue s_TimerQueue = TimerThread.CreateQueue(SettingsSectionInternal.Section.ExecutionTimeout);
private static TimerThread.Callback s_InterruptCallback = new TimerThread.Callback(InterruptCallback);
//
// Methods called by the AutoWebProxyScriptEngine
//
internal static AutoWebProxyScriptWrapper CreateInstance()
{
return new AutoWebProxyScriptWrapper();
}
internal void Close()
{
if (Interlocked.Increment(ref closed) != 1)
{
return;
}
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Close() Closing engine.");
// Time out any running thread.
TimerThread.Timer timer = activeTimer;
if (timer != null)
{
if (timer.Cancel())
{
InterruptCallback(timer, 0, this);
}
activeTimer = null;
}
jscript.Close();
jscriptObject = null;
jscript = null;
host = null;
jscriptParser = null;
dispatch = null;
script = null;
scriptText = null;
lastModified = DateTime.MinValue;
}
internal string FindProxyForURL(string url, string host)
{
if (url == null || host == null)
{
throw new ArgumentNullException(url == null ? "url" : "host");
}
if (closed != 0)
{
throw new ObjectDisposedException(GetType().Name);
}
EXCEPINFO exceptionInfo = new EXCEPINFO();
object result = null;
jscript.GetCurrentScriptThreadID(out interruptThreadId);
TimerThread.Timer timer = s_TimerQueue.CreateTimer(s_InterruptCallback, this);
activeTimer = timer;
try
{
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::FindProxyForURL() Calling url:" + url + " host:" + host);
result = script.FindProxyForURL(url, host);
}
catch (Exception exception)
{
if (NclUtilities.IsFatal(exception)) throw;
if (exception is TargetInvocationException)
{
exception = exception.InnerException;
}
COMException comException = exception as COMException;
if (comException == null || comException.ErrorCode != (int) HRESULT.SCRIPT_E_REPORTED)
{
throw;
}
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::FindProxyForURL() Script error:[" + this.host.ExceptionMessage == null ? "" : this.host.ExceptionMessage + "]");
}
catch {
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::FindProxyForURL() Script error:[Non-CLS Compliant Exception]");
throw;
}
finally
{
activeTimer = null;
timer.Cancel();
}
string proxy = result as string;
if (proxy != null)
{
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::FindProxyForURL() found:" + proxy);
return proxy;
}
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::FindProxyForURL() Returning null. result:" + ValidationHelper.ToString(exceptionInfo.bstrDescription) + " result:" + ValidationHelper.ToString(result) + " error:" + ValidationHelper.ToString(exceptionInfo.bstrDescription));
return null;
}
internal AutoWebProxyState Compile(Uri engineScriptLocation, string scriptBody, byte[] buffer)
{
if (closed != 0)
{
throw new ObjectDisposedException(GetType().Name);
}
if (jscriptObject != null)
{
jscript.Close();
}
scriptText = null;
scriptBytes = null;
jscriptObject = new JScriptEngine();
jscript = (IActiveScript) jscriptObject;
host = new ScriptHost();
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Binding to ScriptHost#" + ValidationHelper.HashString(this));
jscriptParser = new ActiveScriptParseWrapper(jscriptObject);
jscriptParser.InitNew();
jscript.SetScriptSite(host);
jscript.SetScriptState(ScriptState.Initialized);
//
// Inform the script engine that this host implements the IInternetHostSecurityManager interface, which
// is used to prevent the script code from using any ActiveX objects.
//
IObjectSafety objSafety = jscript as IObjectSafety;
if (objSafety != null)
{
Guid guid = Guid.Empty;
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Setting up IInternetHostSecurityManager");
objSafety.SetInterfaceSafetyOptions(ref guid, ComConstants.INTERFACE_USES_SECURITY_MANAGER, ComConstants.INTERFACE_USES_SECURITY_MANAGER);
objSafety = null;
}
EXCEPINFO exceptionInfo = new EXCEPINFO();
object result = null;
try
{
jscriptParser.ParseScriptText(scriptBody, null, null, null, IntPtr.Zero, 0, ScriptText.IsPersistent | ScriptText.IsVisible, out result, out exceptionInfo);
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() ParseScriptText() success:" + ValidationHelper.ToString(exceptionInfo.bstrDescription) + " result:" + ValidationHelper.ToString(result));
}
catch (Exception exception)
{
if (NclUtilities.IsFatal(exception)) throw;
if (exception is TargetInvocationException)
{
exception = exception.InnerException;
}
COMException comException = exception as COMException;
if (comException == null || comException.ErrorCode != (int) HRESULT.SCRIPT_E_REPORTED)
{
throw;
}
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Script load error:[" + host.ExceptionMessage == null ? "" : host.ExceptionMessage + "]");
throw new COMException(SR.GetString(SR.net_jscript_load, host.ExceptionMessage), comException.ErrorCode);
}
catch {
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Script load error:[Non-CLS Compliant Exception]");
throw;
}
jscript.AddNamedItem(c_ScriptHelperName, ScriptItem.GlobalMembers | ScriptItem.IsPersistent | ScriptItem.IsVisible);
// This part can run global code - time it out if necessary.
jscript.GetCurrentScriptThreadID(out interruptThreadId);
TimerThread.Timer timer = s_TimerQueue.CreateTimer(s_InterruptCallback, this);
activeTimer = timer;
try
{
jscript.SetScriptState(ScriptState.Started);
jscript.SetScriptState(ScriptState.Connected);
}
finally
{
activeTimer = null;
timer.Cancel();
}
jscript.GetScriptDispatch(null, out script);
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Got IDispatch:" + ValidationHelper.ToString(dispatch));
scriptText = scriptBody;
scriptBytes = buffer;
return AutoWebProxyState.CompilationSuccess;
}
internal string ScriptBody
{
get
{
return scriptText;
}
}
internal byte[] Buffer
{
get
{
return scriptBytes;
}
set
{
scriptBytes = value;
}
}
internal DateTime LastModified
{
get
{
return lastModified;
}
set
{
lastModified = value;
}
}
private static void InterruptCallback(TimerThread.Timer timer, int timeNoticed, object context)
{
AutoWebProxyScriptWrapper pThis = (AutoWebProxyScriptWrapper)context;
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(pThis) + "::InterruptCallback()");
if (!object.ReferenceEquals(timer, pThis.activeTimer))
{
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(pThis) + "::InterruptCallback() Spurious - returning.");
return;
}
EXCEPINFO exceptionInfo;
try
{
pThis.jscript.InterruptScriptThread(pThis.interruptThreadId, out exceptionInfo, 0);
}
catch (Exception ex)
{
if (NclUtilities.IsFatal(ex)) throw;
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(pThis) + "::InterruptCallback() InterruptScriptThread() threw:" + ValidationHelper.ToString(ex));
}
catch {
GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(pThis) + "::InterruptCallback() InterruptScriptThread() threw: Non-CLS Compliant Exception");
}
}
//
// Privates
//
private JScriptEngine jscriptObject;
private IActiveScript jscript;
private ActiveScriptParseWrapper jscriptParser;
private ScriptHost host;
private object dispatch;
private IScript script;
private string scriptText;
private byte[] scriptBytes;
private DateTime lastModified;
// 'activeTimer' is used to protect the engine from spurious callbacks and when the engine is closed.
private TimerThread.Timer activeTimer;
private uint interruptThreadId;
private int closed;
// IActiveScriptSite implementation
private class ScriptHost : IActiveScriptSite, IInternetHostSecurityManager, IOleServiceProvider
{
private WebProxyScriptHelper helper = new WebProxyScriptHelper();
private string exceptionMessage;
internal string ExceptionMessage
{
get
{
return exceptionMessage;
}
}
//
// IActiveScriptSite
//
public void GetLCID(out int lcid)
{
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetLCID()");
lcid = Thread.CurrentThread.CurrentCulture.LCID;
}
public void GetItemInfo(
string name,
ScriptInfo returnMask,
[Out] [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.IUnknown)] object[] item,
[Out] [MarshalAs(UnmanagedType.LPArray)] IntPtr[] typeInfo)
{
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetItemInfo() name:" + ValidationHelper.ToString(name));
if (name == null)
{
throw new ArgumentNullException("name");
}
if (name != c_ScriptHelperName)
{
throw new COMException(null, (int) HRESULT.TYPE_E_ELEMENTNOTFOUND);
}
if ((returnMask & ScriptInfo.IUnknown) != 0)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetItemInfo() Setting item.");
item[0] = helper;
}
if ((returnMask & ScriptInfo.ITypeInfo) != 0)
{
if (typeInfo == null)
{
throw new ArgumentNullException("typeInfo");
}
typeInfo[0] = IntPtr.Zero;
}
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetItemInfo() Done.");
}
public void GetDocVersionString(out string version)
{
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetDocVersionString()");
throw new NotImplementedException();
}
public void OnScriptTerminate(object result, EXCEPINFO exceptionInfo)
{
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::OnScriptTerminate() result:" + ValidationHelper.ToString(result) + " error:" + ValidationHelper.ToString(exceptionInfo.bstrDescription));
}
public void OnStateChange(ScriptState scriptState)
{
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::OnStateChange() state:" + ValidationHelper.ToString(scriptState));
if (scriptState == ScriptState.Closed)
{
helper = null;
}
}
public void OnScriptError(IActiveScriptError scriptError)
{
EXCEPINFO exceptionInfo;
uint dummy;
uint line;
int pos;
scriptError.GetExceptionInfo(out exceptionInfo);
scriptError.GetSourcePosition(out dummy, out line, out pos);
exceptionMessage = exceptionInfo.bstrDescription + " (" + line + "," + pos + ")";
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::OnScriptError() error:" + ValidationHelper.ToString(exceptionInfo.bstrDescription) + " line:" + line + " pos:" + pos);
}
public void OnEnterScript()
{
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::OnEnterScript()");
}
public void OnLeaveScript()
{
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::OnLeaveScript()");
}
// IOleServiceProvider methods
public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject) {
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::QueryService(" + guidService.ToString() + ")");
int hr = (int)HRESULT.E_NOINTERFACE;
ppvObject = IntPtr.Zero;
if (guidService == typeof(IInternetHostSecurityManager).GUID) {
IntPtr ppObj = Marshal.GetIUnknownForObject(this);
try {
hr = Marshal.QueryInterface(ppObj, ref riid, out ppvObject);
}
finally {
Marshal.Release(ppObj);
}
}
return hr;
}
// IInternetHostSecurityManager methods.
// Implementation based on inetcore\wininet\autoconf\cscpsite.cpp
// The current implementation disallows all ActiveX control activation from script.
public int GetSecurityId(byte[] pbSecurityId, ref IntPtr pcbSecurityId, IntPtr dwReserved) {
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetSecurityId()");
return (int)HRESULT.E_NOTIMPL;
}
public int ProcessUrlAction(int dwAction, int[] pPolicy, int cbPolicy, byte[] pContext, int cbContext, int dwFlags, int dwReserved) {
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::ProcessUrlAction()");
if (pPolicy != null && cbPolicy >= Marshal.SizeOf(typeof(int))) {
pPolicy[0] = (int)UrlPolicy.DisAllow;
}
return (int)HRESULT.S_FALSE; // S_FALSE means the policy != URLPOLICY_ALLOW.
}
public int QueryCustomPolicy(Guid guidKey, out byte[] ppPolicy, out int pcbPolicy, byte[] pContext, int cbContext, int dwReserved) {
GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::QueryCustomPolicy()");
ppPolicy = null;
pcbPolicy = 0;
return (int) HRESULT.E_NOTIMPL;
}
}
}
}
#else
namespace System.Net
{
using System.Collections;
using System.Reflection;
using System.Security;
using System.Security.Policy;
using System.Security.Permissions;
using System.Runtime.Remoting;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
using System.Threading;
// This interface is useless to users. We need it to interact with our Microsoft.JScript helper class.
public interface IWebProxyScript
{
bool Load(Uri scriptLocation, string script, Type helperType);
string Run(string url, string host);
void Close();
}
internal class AutoWebProxyScriptWrapper
{
private const string c_appDomainName = "WebProxyScript";
// The index is required for the hashtable because calling GetHashCode() on an unloaded AppDomain throws.
private int appDomainIndex;
private AppDomain scriptDomain;
private IWebProxyScript site;
// s_ExcessAppDomain is a holding spot for the most recently created AppDomain. Until we guarantee it gets
// into s_AppDomains (or is unloaded), no additional AppDomains can be created, to avoid leaking them.
private static volatile AppDomain s_ExcessAppDomain;
private static Hashtable s_AppDomains = new Hashtable();
private static bool s_CleanedUp;
private static int s_NextAppDomainIndex;
private static AppDomainSetup s_AppDomainInfo;
private static volatile Type s_ProxyScriptHelperType;
private static volatile Exception s_ProxyScriptHelperLoadError;
private static object s_ProxyScriptHelperLock = new object();
static AutoWebProxyScriptWrapper()
{
AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload);
}
[ReflectionPermission(SecurityAction.Assert, Flags = ReflectionPermissionFlag.MemberAccess)]
[ReflectionPermission(SecurityAction.Assert, Flags = ReflectionPermissionFlag.TypeInformation)]
internal AutoWebProxyScriptWrapper()
{
GlobalLog.Print("AutoWebProxyScriptWrapper::.ctor() Creating AppDomain: " + c_appDomainName);
Exception exception = null;
if (s_ProxyScriptHelperLoadError == null && s_ProxyScriptHelperType == null)
{
lock (s_ProxyScriptHelperLock)
{
if (s_ProxyScriptHelperLoadError == null && s_ProxyScriptHelperType == null)
{
// Try to load the type late-bound out of Microsoft.JScript.
try
{
s_ProxyScriptHelperType = Type.GetType("System.Net.VsaWebProxyScript, Microsoft.JScript, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true);
}
catch (Exception ex)
{
exception = ex;
}
if (s_ProxyScriptHelperType == null)
{
s_ProxyScriptHelperLoadError = exception == null ? new InternalException() : exception;
}
}
}
}
if (s_ProxyScriptHelperLoadError != null)
{
throw new TypeLoadException(SR.GetString(SR.net_cannot_load_proxy_helper), s_ProxyScriptHelperLoadError is InternalException ? null : s_ProxyScriptHelperLoadError);
}
CreateAppDomain();
exception = null;
try
{
GlobalLog.Print("AutoWebProxyScriptWrapper::CreateInstance() Creating Object. type.Assembly.FullName: [" + s_ProxyScriptHelperType.Assembly.FullName + "] type.FullName: [" + s_ProxyScriptHelperType.FullName + "]");
ObjectHandle handle = Activator.CreateInstance(scriptDomain, s_ProxyScriptHelperType.Assembly.FullName, s_ProxyScriptHelperType.FullName, false,
BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod,
null, null, null, null, null);
if (handle != null)
{
site = (IWebProxyScript) handle.Unwrap();
}
GlobalLog.Print("AutoWebProxyScriptWrapper::CreateInstance() Create script site:" + ValidationHelper.HashString(site));
}
catch (Exception ex)
{
exception = ex;
}
if (site == null)
{
lock (s_ProxyScriptHelperLock)
{
if (s_ProxyScriptHelperLoadError == null)
{
s_ProxyScriptHelperLoadError = exception == null ? new InternalException() : exception;
}
}
throw new TypeLoadException(SR.GetString(SR.net_cannot_load_proxy_helper), s_ProxyScriptHelperLoadError is InternalException ? null : s_ProxyScriptHelperLoadError);
}
}
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.ControlAppDomain)]
private void CreateAppDomain()
{
// Locking s_AppDomains must happen in a CER so we don't orphan a lock that gets taken by AppDomain.DomainUnload.
bool lockHeld = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_AppDomains.SyncRoot, ref lockHeld);
if (s_CleanedUp)
{
throw new InvalidOperationException(SR.GetString(SR.net_cant_perform_during_shutdown));
}
// Create singleton.
if (s_AppDomainInfo == null)
{
s_AppDomainInfo = new AppDomainSetup();
s_AppDomainInfo.DisallowBindingRedirects = true;
s_AppDomainInfo.DisallowCodeDownload = true;
NamedPermissionSet perms = new NamedPermissionSet("__WebProxySandbox", PermissionState.None);
perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
ApplicationTrust trust = new ApplicationTrust();
trust.DefaultGrantSet = new PolicyStatement(perms);
s_AppDomainInfo.ApplicationTrust = trust;
s_AppDomainInfo.ApplicationBase = Environment.SystemDirectory;
}
// If something's already in s_ExcessAppDomain, try to dislodge it again.
AppDomain excessAppDomain = s_ExcessAppDomain;
if (excessAppDomain != null)
{
TimerThread.GetOrCreateQueue(0).CreateTimer(new TimerThread.Callback(CloseAppDomainCallback), excessAppDomain);
throw new InvalidOperationException(SR.GetString(SR.net_cant_create_environment));
}
appDomainIndex = s_NextAppDomainIndex++;
try { }
finally
{
PermissionSet permissionSet = new PermissionSet(PermissionState.None);
permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
//
s_ExcessAppDomain = AppDomain.CreateDomain(c_appDomainName, null, s_AppDomainInfo, permissionSet, null);
try
{
s_AppDomains.Add(appDomainIndex, s_ExcessAppDomain);
// This indicates to the finally and the finalizer that everything succeeded.
scriptDomain = s_ExcessAppDomain;
}
finally
{
// ReferenceEquals has a ReliabilityContract.
if (object.ReferenceEquals(scriptDomain, s_ExcessAppDomain))
{
s_ExcessAppDomain = null;
}
else
{
// Something failed. Leave the domain in s_ExcessAppDomain until we can get rid of it. No
// more AppDomains can be created until we do. In the mean time, keep attempting to get the
// TimerThread to remove it. Also, might as well remove it from the hash if it made it in.
try
{
s_AppDomains.Remove(appDomainIndex);
}
finally
{
// Can't call AppDomain.Unload from a user thread (or in a lock).
TimerThread.GetOrCreateQueue(0).CreateTimer(new TimerThread.Callback(CloseAppDomainCallback), s_ExcessAppDomain);
}
}
}
}
}
finally
{
if (lockHeld)
{
Monitor.Exit(s_AppDomains.SyncRoot);
}
}
}
internal void Close()
{
site.Close();
// Can't call AppDomain.Unload() from a user thread.
TimerThread.GetOrCreateQueue(0).CreateTimer(new TimerThread.Callback(CloseAppDomainCallback), appDomainIndex);
GC.SuppressFinalize(this);
}
// Bug 434828
//
// It's very hard to guarantee cleanup of an AppDomain. They aren't garbage collected, and Unload() is synchronous and
// can't be called from the finalizer thread. So we must have a finalizer that uses another thread, in this case the
// TimerThread, to unload the domain.
//
// A case this will come up is if the user replaces the DefaultWebProxy. The old one will be GC'd - there's no chance to
// clean it up properly. If the user wants to avoid the TimerThread being spun up for that purpose, they should save the
// existing DefaultWebProxy in a static before replacing it.
~AutoWebProxyScriptWrapper()
{
if (!NclUtilities.HasShutdownStarted && scriptDomain != null)
{
// Can't call AppDomain.Unload() from the finalizer thread.
TimerThread.GetOrCreateQueue(0).CreateTimer(new TimerThread.Callback(CloseAppDomainCallback), appDomainIndex);
}
}
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.ControlAppDomain)]
private static void CloseAppDomainCallback(TimerThread.Timer timer, int timeNoticed, object context)
{
try
{
AppDomain domain = context as AppDomain;
if (domain == null)
{
CloseAppDomain((int) context);
}
else
{
if (object.ReferenceEquals(domain, s_ExcessAppDomain))
{
try
{
AppDomain.Unload(domain);
}
catch (AppDomainUnloadedException) { }
s_ExcessAppDomain = null;
}
}
}
catch (Exception exception)
{
if (NclUtilities.IsFatal(exception)) throw;
}
}
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.ControlAppDomain)]
private static void CloseAppDomain(int index)
{
AppDomain appDomain;
// Locking s_AppDomains must happen in a CER so we don't orphan a lock that gets taken by AppDomain.DomainUnload.
bool lockHeld = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_AppDomains.SyncRoot, ref lockHeld);
if (s_CleanedUp)
{
return;
}
appDomain = (AppDomain) s_AppDomains[index];
}
finally
{
if (lockHeld)
{
Monitor.Exit(s_AppDomains.SyncRoot);
lockHeld = false;
}
}
try
{
// Cannot call Unload() in a lock shared by OnDomainUnload() - deadlock with ADUnload thread.
// So we may try to unload the same domain twice.
AppDomain.Unload(appDomain);
}
catch (AppDomainUnloadedException) { }
finally
{
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_AppDomains.SyncRoot, ref lockHeld);
s_AppDomains.Remove(index);
}
finally
{
if (lockHeld)
{
Monitor.Exit(s_AppDomains.SyncRoot);
}
}
}
}
[ReliabilityContract(Consistency.MayCorruptProcess, Cer.MayFail)]
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.ControlAppDomain)]
private static void OnDomainUnload(object sender, EventArgs e)
{
lock (s_AppDomains.SyncRoot)
{
if (!s_CleanedUp)
{
s_CleanedUp = true;
foreach (AppDomain domain in s_AppDomains.Values)
{
try
{
AppDomain.Unload(domain);
}
catch { }
}
s_AppDomains.Clear();
AppDomain excessAppDomain = s_ExcessAppDomain;
if (excessAppDomain != null)
{
try
{
AppDomain.Unload(excessAppDomain);
}
catch { }
s_ExcessAppDomain = null;
}
}
}
}
internal string ScriptBody
{
get
{
return scriptText;
}
}
internal byte[] Buffer
{
get
{
return scriptBytes;
}
set
{
scriptBytes = value;
}
}
internal DateTime LastModified
{
get
{
return lastModified;
}
set
{
lastModified = value;
}
}
private string scriptText;
private byte[] scriptBytes;
private DateTime lastModified;
// Forward these to the site.
internal string FindProxyForURL(string url, string host)
{
GlobalLog.Print("AutoWebProxyScriptWrapper::FindProxyForURL() Calling JScript for url:" + url.ToString() + " host:" + host.ToString());
return site.Run(url, host);
}
internal bool Compile(Uri engineScriptLocation, string scriptBody, byte[] buffer)
{
if (site.Load(engineScriptLocation, scriptBody, typeof(WebProxyScriptHelper)))
{
GlobalLog.Print("AutoWebProxyScriptWrapper::Compile() Compilation succeeded for engineScriptLocation:" + engineScriptLocation.ToString());
scriptText = scriptBody;
scriptBytes = buffer;
return true;
}
GlobalLog.Print("AutoWebProxyScriptWrapper::Compile() Compilation failed for engineScriptLocation:" + engineScriptLocation.ToString());
return false;
}
}
}
#endif
| |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using BitSharper.IO;
namespace BitSharper
{
/// <summary>
/// A transaction represents the movement of coins from some addresses to some other addresses. It can also represent
/// the minting of new coins. A Transaction object corresponds to the equivalent in the BitCoin C++ implementation.
/// </summary>
/// <remarks>
/// It implements TWO serialization protocols - the BitCoin proprietary format which is identical to the C++
/// implementation and is used for reading/writing transactions to the wire and for hashing. It also implements Java
/// serialization which is used for the wallet. This allows us to easily add extra fields used for our own accounting
/// or UI purposes.
/// </remarks>
[Serializable]
public class Transaction : Message
{
// These are serialized in both BitCoin and java serialization.
private uint _version;
private List<TransactionInput> _inputs;
private List<TransactionOutput> _outputs;
private uint _lockTime;
// This is an in memory helper only.
[NonSerialized] private Sha256Hash _hash;
internal Transaction(NetworkParameters @params)
: base(@params)
{
_version = 1;
_inputs = new List<TransactionInput>();
_outputs = new List<TransactionOutput>();
// We don't initialize appearsIn deliberately as it's only useful for transactions stored in the wallet.
}
/// <summary>
/// Creates a transaction from the given serialized bytes, eg, from a block or a tx network message.
/// </summary>
/// <exception cref="ProtocolException"/>
public Transaction(NetworkParameters @params, byte[] payloadBytes)
: base(@params, payloadBytes, 0)
{
}
/// <summary>
/// Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed.
/// </summary>
/// <exception cref="ProtocolException"/>
public Transaction(NetworkParameters @params, byte[] payload, int offset)
: base(@params, payload, offset)
{
// inputs/outputs will be created in parse()
}
/// <summary>
/// Returns a read-only list of the inputs of this transaction.
/// </summary>
public IList<TransactionInput> Inputs
{
get { return _inputs.AsReadOnly(); }
}
/// <summary>
/// Returns a read-only list of the outputs of this transaction.
/// </summary>
public IList<TransactionOutput> Outputs
{
get { return _outputs.AsReadOnly(); }
}
/// <summary>
/// Returns the transaction hash as you see them in the block explorer.
/// </summary>
public Sha256Hash Hash
{
get { return _hash ?? (_hash = new Sha256Hash(Utils.ReverseBytes(Utils.DoubleDigest(BitcoinSerialize())))); }
}
public string HashAsString
{
get { return Hash.ToString(); }
}
/// <summary>
/// Calculates the sum of the outputs that are sending coins to a key in the wallet. The flag controls whether to
/// include spent outputs or not.
/// </summary>
internal ulong GetValueSentToMe(Wallet wallet, bool includeSpent)
{
// This is tested in WalletTest.
var v = 0UL;
foreach (var o in _outputs)
{
if (!o.IsMine(wallet)) continue;
if (!includeSpent && !o.IsAvailableForSpending) continue;
v += o.Value;
}
return v;
}
/// <summary>
/// Calculates the sum of the outputs that are sending coins to a key in the wallet.
/// </summary>
public ulong GetValueSentToMe(Wallet wallet)
{
return GetValueSentToMe(wallet, true);
}
/// <summary>
/// Returns a set of blocks which contain the transaction, or null if this transaction doesn't have that data
/// because it's not stored in the wallet or because it has never appeared in a block.
/// </summary>
internal ICollection<StoredBlock> AppearsIn { get; private set; }
/// <summary>
/// Adds the given block to the internal serializable set of blocks in which this transaction appears. This is
/// used by the wallet to ensure transactions that appear on side chains are recorded properly even though the
/// block stores do not save the transaction data at all.
/// </summary>
internal void AddBlockAppearance(StoredBlock block)
{
if (AppearsIn == null)
{
AppearsIn = new HashSet<StoredBlock>();
}
AppearsIn.Add(block);
}
/// <summary>
/// Calculates the sum of the inputs that are spending coins with keys in the wallet. This requires the
/// transactions sending coins to those keys to be in the wallet. This method will not attempt to download the
/// blocks containing the input transactions if the key is in the wallet but the transactions are not.
/// </summary>
/// <returns>Sum in nanocoins.</returns>
/// <exception cref="ScriptException"/>
public ulong GetValueSentFromMe(Wallet wallet)
{
// This is tested in WalletTest.
var v = 0UL;
foreach (var input in _inputs)
{
// This input is taking value from an transaction in our wallet. To discover the value,
// we must find the connected transaction.
var connected = input.GetConnectedOutput(wallet.Unspent);
if (connected == null)
connected = input.GetConnectedOutput(wallet.Spent);
if (connected == null)
connected = input.GetConnectedOutput(wallet.Pending);
if (connected == null)
continue;
// The connected output may be the change to the sender of a previous input sent to this wallet. In this
// case we ignore it.
if (!connected.IsMine(wallet))
continue;
v += connected.Value;
}
return v;
}
internal bool DisconnectInputs()
{
var disconnected = false;
foreach (var input in _inputs)
{
disconnected |= input.Disconnect();
}
return disconnected;
}
/// <summary>
/// Connects all inputs using the provided transactions. If any input cannot be connected returns that input or
/// null on success.
/// </summary>
internal TransactionInput ConnectForReorganize(IDictionary<Sha256Hash, Transaction> transactions)
{
foreach (var input in _inputs)
{
// Coinbase transactions, by definition, do not have connectable inputs.
if (input.IsCoinBase) continue;
var result = input.Connect(transactions, false);
// Connected to another tx in the wallet?
if (result == TransactionInput.ConnectionResult.Success)
continue;
// The input doesn't exist in the wallet, eg because it belongs to somebody else (inbound spend).
if (result == TransactionInput.ConnectionResult.NoSuchTx)
continue;
// Could not connect this input, so return it and abort.
return input;
}
return null;
}
/// <returns>true if every output is marked as spent.</returns>
public bool IsEveryOutputSpent()
{
foreach (var output in _outputs)
{
if (output.IsAvailableForSpending)
return false;
}
return true;
}
/// <summary>
/// These constants are a part of a scriptSig signature on the inputs. They define the details of how a
/// transaction can be redeemed, specifically, they control how the hash of the transaction is calculated.
/// </summary>
/// <remarks>
/// In the official client, this enum also has another flag, SIGHASH_ANYONECANPAY. In this implementation,
/// that's kept separate. Only SIGHASH_ALL is actually used in the official client today. The other flags
/// exist to allow for distributed contracts.
/// </remarks>
public enum SigHash
{
All, // 1
None, // 2
Single, // 3
}
/// <exception cref="ProtocolException"/>
protected override void Parse()
{
_version = ReadUint32();
// First come the inputs.
var numInputs = ReadVarInt();
_inputs = new List<TransactionInput>((int) numInputs);
for (var i = 0UL; i < numInputs; i++)
{
var input = new TransactionInput(Params, this, Bytes, Cursor);
_inputs.Add(input);
Cursor += input.MessageSize;
}
// Now the outputs
var numOutputs = ReadVarInt();
_outputs = new List<TransactionOutput>((int) numOutputs);
for (var i = 0UL; i < numOutputs; i++)
{
var output = new TransactionOutput(Params, this, Bytes, Cursor);
_outputs.Add(output);
Cursor += output.MessageSize;
}
_lockTime = ReadUint32();
}
/// <summary>
/// A coinbase transaction is one that creates a new coin. They are the first transaction in each block and their
/// value is determined by a formula that all implementations of BitCoin share. In 2011 the value of a coinbase
/// transaction is 50 coins, but in future it will be less. A coinbase transaction is defined not only by its
/// position in a block but by the data in the inputs.
/// </summary>
public bool IsCoinBase
{
get { return _inputs[0].IsCoinBase; }
}
/// <returns>A human readable version of the transaction useful for debugging.</returns>
public override string ToString()
{
var s = new StringBuilder();
s.Append(" ");
s.Append(HashAsString);
s.AppendLine();
if (IsCoinBase)
{
string script;
string script2;
try
{
script = _inputs[0].ScriptSig.ToString();
script2 = _outputs[0].ScriptPubKey.ToString();
}
catch (ScriptException)
{
script = "???";
script2 = "???";
}
return " == COINBASE TXN (scriptSig " + script + ") (scriptPubKey " + script2 + ")";
}
foreach (var @in in _inputs)
{
s.Append(" ");
s.Append("from ");
try
{
s.Append(@in.ScriptSig.FromAddress.ToString());
}
catch (Exception e)
{
s.Append("[exception: ").Append(e.Message).Append("]");
throw;
}
s.AppendLine();
}
foreach (var @out in _outputs)
{
s.Append(" ");
s.Append("to ");
try
{
var toAddr = new Address(Params, @out.ScriptPubKey.PubKeyHash);
s.Append(toAddr.ToString());
s.Append(" ");
s.Append(Utils.BitcoinValueToFriendlyString(@out.Value));
s.Append(" BTC");
}
catch (Exception e)
{
s.Append("[exception: ").Append(e.Message).Append("]");
}
s.AppendLine();
}
return s.ToString();
}
/// <summary>
/// Adds an input to this transaction that imports value from the given output. Note that this input is NOT
/// complete and after every input is added with addInput() and every output is added with addOutput(),
/// signInputs() must be called to finalize the transaction and finish the inputs off. Otherwise it won't be
/// accepted by the network.
/// </summary>
public void AddInput(TransactionOutput from)
{
AddInput(new TransactionInput(Params, this, from));
}
/// <summary>
/// Adds an input directly, with no checking that it's valid.
/// </summary>
public void AddInput(TransactionInput input)
{
_inputs.Add(input);
}
/// <summary>
/// Adds the given output to this transaction. The output must be completely initialized.
/// </summary>
public void AddOutput(TransactionOutput to)
{
to.ParentTransaction = this;
_outputs.Add(to);
}
/// <summary>
/// Once a transaction has some inputs and outputs added, the signatures in the inputs can be calculated. The
/// signature is over the transaction itself, to prove the redeemer actually created that transaction,
/// so we have to do this step last.
/// </summary>
/// <remarks>
/// This method is similar to SignatureHash in script.cpp
/// </remarks>
/// <param name="hashType">This should always be set to SigHash.ALL currently. Other types are unused. </param>
/// <param name="wallet">A wallet is required to fetch the keys needed for signing.</param>
/// <exception cref="ScriptException"/>
public void SignInputs(SigHash hashType, Wallet wallet)
{
Debug.Assert(_inputs.Count > 0);
Debug.Assert(_outputs.Count > 0);
// I don't currently have an easy way to test other modes work, as the official client does not use them.
Debug.Assert(hashType == SigHash.All);
// The transaction is signed with the input scripts empty except for the input we are signing. In the case
// where addInput has been used to set up a new transaction, they are already all empty. The input being signed
// has to have the connected OUTPUT program in it when the hash is calculated!
//
// Note that each input may be claiming an output sent to a different key. So we have to look at the outputs
// to figure out which key to sign with.
var signatures = new byte[_inputs.Count][];
var signingKeys = new EcKey[_inputs.Count];
for (var i = 0; i < _inputs.Count; i++)
{
var input = _inputs[i];
Debug.Assert(input.ScriptBytes.Length == 0, "Attempting to sign a non-fresh transaction");
// Set the input to the script of its output.
input.ScriptBytes = input.Outpoint.ConnectedPubKeyScript;
// Find the signing key we'll need to use.
var connectedPubKeyHash = input.Outpoint.ConnectedPubKeyHash;
var key = wallet.FindKeyFromPubHash(connectedPubKeyHash);
// This assert should never fire. If it does, it means the wallet is inconsistent.
Debug.Assert(key != null, "Transaction exists in wallet that we cannot redeem: " + Utils.BytesToHexString(connectedPubKeyHash));
// Keep the key around for the script creation step below.
signingKeys[i] = key;
// The anyoneCanPay feature isn't used at the moment.
const bool anyoneCanPay = false;
var hash = HashTransactionForSignature(hashType, anyoneCanPay);
// Set the script to empty again for the next input.
input.ScriptBytes = TransactionInput.EmptyArray;
// Now sign for the output so we can redeem it. We use the keypair to sign the hash,
// and then put the resulting signature in the script along with the public key (below).
using (var bos = new MemoryStream())
{
bos.Write(key.Sign(hash));
bos.Write((byte) (((int) hashType + 1) | (anyoneCanPay ? 0x80 : 0)));
signatures[i] = bos.ToArray();
}
}
// Now we have calculated each signature, go through and create the scripts. Reminder: the script consists of
// a signature (over a hash of the transaction) and the complete public key needed to sign for the connected
// output.
for (var i = 0; i < _inputs.Count; i++)
{
var input = _inputs[i];
Debug.Assert(input.ScriptBytes.Length == 0);
var key = signingKeys[i];
input.ScriptBytes = Script.CreateInputScript(signatures[i], key.PubKey);
}
// Every input is now complete.
}
private byte[] HashTransactionForSignature(SigHash type, bool anyoneCanPay)
{
using (var bos = new MemoryStream())
{
BitcoinSerializeToStream(bos);
// We also have to write a hash type.
var hashType = (uint) type + 1;
if (anyoneCanPay)
hashType |= 0x80;
Utils.Uint32ToByteStreamLe(hashType, bos);
// Note that this is NOT reversed to ensure it will be signed correctly. If it were to be printed out
// however then we would expect that it is IS reversed.
return Utils.DoubleDigest(bos.ToArray());
}
}
/// <exception cref="IOException"/>
public override void BitcoinSerializeToStream(Stream stream)
{
Utils.Uint32ToByteStreamLe(_version, stream);
stream.Write(new VarInt((ulong) _inputs.Count).Encode());
foreach (var @in in _inputs)
@in.BitcoinSerializeToStream(stream);
stream.Write(new VarInt((ulong) _outputs.Count).Encode());
foreach (var @out in _outputs)
@out.BitcoinSerializeToStream(stream);
Utils.Uint32ToByteStreamLe(_lockTime, stream);
}
public override bool Equals(object other)
{
if (!(other is Transaction)) return false;
var t = (Transaction) other;
return t.Hash.Equals(Hash);
}
public override int GetHashCode()
{
return Hash.GetHashCode();
}
}
}
| |
/*
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.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Info;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.IO;
using System.Xml.Linq;
using System.Linq;
using System.Windows.Threading;
namespace WPCordovaClassLib.Cordova.Commands
{
/// <summary>
/// Listens for changes to the state of the battery on the device.
/// Currently only the "isPlugged" parameter available via native APIs.
/// </summary>
public class SplashScreen : BaseCommand
{
private Popup popup;
// Time until we dismiss the splashscreen
private int prefDelay = 3000;
// Whether we hide it by default
private bool prefAutoHide = true;
// Path to image to use
private string prefImagePath = "SplashScreenImage.jpg";
// static because autodismiss is only ever applied once, at app launch
// subsequent page loads should not cause the SplashScreen to be shown.
private static bool WasShown = false;
public SplashScreen()
{
LoadConfigPrefs();
Image SplashScreen = new Image()
{
Height = Application.Current.Host.Content.ActualHeight,
Width = Application.Current.Host.Content.ActualWidth,
Stretch = Stretch.Fill
};
var imageResource = GetSplashScreenImageResource();
if (imageResource != null)
{
BitmapImage splash_image = new BitmapImage();
splash_image.SetSource(imageResource.Stream);
SplashScreen.Source = splash_image;
}
// Instansiate the popup and set the Child property of Popup to SplashScreen
popup = new Popup() { IsOpen = false,
Child = SplashScreen,
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Center
};
}
public override void OnInit()
{
// we only want to autoload on the first page load.
// but OnInit is called for every page load.
if (!SplashScreen.WasShown)
{
SplashScreen.WasShown = true;
show();
}
}
private void LoadConfigPrefs()
{
StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("config.xml", UriKind.Relative));
if (streamInfo != null)
{
using (StreamReader sr = new StreamReader(streamInfo.Stream))
{
//This will Read Keys Collection for the xml file
XDocument configFile = XDocument.Parse(sr.ReadToEnd());
string configAutoHide = configFile.Descendants()
.Where(x => x.Name.LocalName == "preference")
.Where(x => (string)x.Attribute("name") == "AutoHideSplashScreen")
.Select(x => (string)x.Attribute("value"))
.FirstOrDefault();
bool bVal;
prefAutoHide = bool.TryParse(configAutoHide, out bVal) ? bVal : prefAutoHide;
string configDelay = configFile.Descendants()
.Where(x => x.Name.LocalName == "preference")
.Where(x => (string)x.Attribute("name") == "SplashScreenDelay")
.Select(x => (string)x.Attribute("value"))
.FirstOrDefault();
int nVal;
prefDelay = int.TryParse(configDelay, out nVal) ? nVal : prefDelay;
string configImage = configFile.Descendants()
.Where(x => x.Name.LocalName == "preference")
.Where(x => (string)x.Attribute("name") == "SplashScreen")
.Select(x => (string)x.Attribute("value"))
.FirstOrDefault();
if (!String.IsNullOrEmpty(configImage))
{
prefImagePath = configImage;
}
}
}
}
private StreamResourceInfo GetSplashScreenImageResource()
{
// Get the base filename for the splash screen images
string imageName = System.IO.Path.GetFileNameWithoutExtension(prefImagePath);
Uri imageUri = null;
StreamResourceInfo imageResource = null;
// First, try to get a resolution-specific splashscreen
try
{
// Determine the device's resolution
switch (ResolutionHelper.CurrentResolution)
{
case Resolutions.HD:
imageUri = new Uri(imageName + ".screen-720p.jpg", UriKind.Relative);
break;
case Resolutions.WVGA:
imageUri = new Uri(imageName + ".screen-WVGA.jpg", UriKind.Relative);
break;
case Resolutions.WXGA:
default:
imageUri = new Uri(imageName + ".screen-WXGA.jpg", UriKind.Relative);
break;
}
imageResource = Application.GetResourceStream(imageUri);
}
catch (Exception)
{
// It's OK if we didn't get a resolution-specific image
}
// Fallback to the default image name without decoration
if (imageResource == null)
{
imageUri = new Uri(prefImagePath, UriKind.Relative);
imageResource = Application.GetResourceStream(imageUri);
}
if (imageUri != null) Debug.WriteLine("INFO :: SplashScreen: using image {0}", imageUri.OriginalString);
return imageResource;
}
public void show(string options = null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (!popup.IsOpen)
{
popup.Child.Opacity = 0;
Storyboard story = new Storyboard();
DoubleAnimation animation = new DoubleAnimation()
{
From = 0.0,
To = 1.0,
Duration = new Duration(TimeSpan.FromSeconds(0.2))
};
Storyboard.SetTarget(animation, popup.Child);
Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity"));
story.Children.Add(animation);
story.Begin();
popup.IsOpen = true;
if (prefAutoHide)
{
StartAutoHideTimer();
}
}
});
}
public void hide(string options = null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (popup.IsOpen)
{
popup.Child.Opacity = 1.0;
Storyboard story = new Storyboard();
DoubleAnimation animation = new DoubleAnimation()
{
From = 1.0,
To = 0.0,
Duration = new Duration(TimeSpan.FromSeconds(0.4))
};
Storyboard.SetTarget(animation, popup.Child);
Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity"));
story.Children.Add(animation);
story.Completed += (object sender, EventArgs e) =>
{
popup.IsOpen = false;
};
story.Begin();
}
});
}
private void StartAutoHideTimer()
{
var timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(prefDelay) };
timer.Tick += (object sender, EventArgs e) =>
{
hide();
timer.Stop();
};
timer.Start();
}
}
}
| |
//*********************************************************************
//
// geo_print.cs -- Key-dumping routines for GEOTIFF files.
//
// Written By: Niles D. Ritter
// The Authors
//
// Copyright (c) 1995 Niles D. Ritter
// Copyright (c) 2008-2009 by the Authors
//
// Permission granted to use this software, so long as this copyright
// notice accompanies any products derived therefrom.
//
// Revision History;
//
// 20 June, 1995 Niles D. Ritter New
// 07 July, 1995 NDR Fix indexing
// 27 July, 1995 NDR Added Import utils
// 28 July, 1995 NDR Made parser more strict.
// 29 Sept, 1995 NDR Fixed matrix printing.
// 30 Sept, 2008 The Authors Port to C#
// 11 Dec, 2009 The Authors Update to current SVN version
//
//*********************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Free.Ports.LibTiff;
namespace Free.Ports.LibGeoTiff
{
public static partial class libgeotiff
{
const string FMT_GEOTIFF="Geotiff_Information:";
const string FMT_VERSION="Version: {0}";
const string FMT_REV="Key_Revision: {0}.{1}";
const string FMT_TAGS="Tagged_Information:";
const string FMT_TAGEND="End_Of_Tags.";
const string FMT_KEYS="Keyed_Information:";
const string FMT_KEYEND="End_Of_Keys.";
const string FMT_GEOEND="End_Of_Geotiff.";
const string FMT_DOUBLE="{0,-17:g15}";
const string FMT_SHORT="{0,-11}";
// Print off the directory info, using whatever method is specified
// (defaults to fprintf if null). The "aux" parameter is provided for user
// defined method for passing parameters or whatever.
//
// The output format is a "GeoTIFF meta-data" file, which may be
// used to import information with the GTIFFImport() routine.
public static void GTIFPrint(GTIF gtif)
{
GTIFPrint(gtif, null, null);
}
public static void GTIFPrint(GTIF gtif, GTIFPrintMethod print, object aux)
{
if(print==null) print=DefaultPrint;
if(aux==null) aux=Console.Out;
string message=FMT_GEOTIFF+"\n"; print(message, aux);
message=string.Format("\t"+FMT_VERSION+"\n", gtif.gt_version); print(message, aux);
message=string.Format("\t"+FMT_REV+"\n", gtif.gt_rev_major, gtif.gt_rev_minor); print(message, aux);
message=string.Format("\t{0}\n", FMT_TAGS); print(message, aux);
PrintGeoTags(gtif, print, aux);
message=string.Format("\t\t{0}\n", FMT_TAGEND); print(message, aux);
message=string.Format("\t{0}\n", FMT_KEYS); print(message, aux);
foreach(GeoKey key in gtif.gt_keys.Values) PrintKey(key, print, aux);
message=string.Format("\t\t{0}\n", FMT_KEYEND); print(message, aux);
message=string.Format("\t{0}\n", FMT_GEOEND); print(message, aux);
}
static void PrintGeoTags(GTIF gt, GTIFPrintMethod print, object aux)
{
TIFF tif=gt.gt_tif;
if(tif==null) return;
object data;
int count;
if(gt.gt_methods.get(tif, (ushort)GTIFF_TIEPOINTS, out count, out data))
PrintTag((int)GTIFF_TIEPOINTS, count/3, (double[])data, 3, print, aux);
if(gt.gt_methods.get(tif, (ushort)GTIFF_PIXELSCALE, out count, out data))
PrintTag((int)GTIFF_PIXELSCALE, count/3, (double[])data, 3, print, aux);
if(gt.gt_methods.get(tif, (ushort)GTIFF_TRANSMATRIX, out count, out data))
PrintTag((int)GTIFF_TRANSMATRIX, count/4, (double[])data, 4, print, aux);
}
static void PrintTag(int tag, int nrows, double[] data, int ncols, GTIFPrintMethod print, object aux)
{
print("\t\t", aux);
print(GTIFTagName(tag), aux);
string message=string.Format(" ({0},{1}):\n", nrows, ncols);
print(message, aux);
int ind=0;
for(int i=0; i<nrows; i++)
{
print("\t\t\t", aux);
for(int j=0; j<ncols; j++)
{
message=string.Format(FMT_DOUBLE, data[ind++]);
print(message, aux);
if(j<ncols-1) print(" ", aux);
}
print("\n", aux);
}
}
static void PrintKey(GeoKey key, GTIFPrintMethod print, object aux)
{
print("\t\t", aux);
geokey_t keyid=key.gk_key;
print(GTIFKeyName(keyid), aux);
int count=key.gk_count;
string message=string.Format(" ({0},{1}): ", GTIFTypeName(key.gk_type), count);
print(message, aux);
object data=key.gk_data;
switch(key.gk_type)
{
case tagtype_t.TYPE_ASCII:
{
string str=data as string;
if(str==null) throw new Exception("string expected.");
if(str.Length<count) throw new Exception("string too short.");
message="\"";
for(int i=0; i<count; i++)
{
char c=str[i];
if(c=='\n') message+="\\n";
else if(c=='\\') message+="\\\\";
else if(c=='\t') message+="\\t";
else if(c=='\b') message+="\\b";
else if(c=='\r') message+="\\r";
else if(c=='"') message+="\\\"";
else if(c=='\0') message+="\\0";
else message+=c;
}
message+="\"\n";
print(message, aux);
}
break;
case tagtype_t.TYPE_DOUBLE:
double[] dptr=data as double[];
if(dptr==null) throw new Exception("double[] expected.");
if(dptr.Length<count) throw new Exception("double[] too short.");
for(int i=0; i<count; i+=3)
{
int done=Math.Min(i+3, count);
for(int j=i; j<done; j++)
{
message=string.Format(FMT_DOUBLE, dptr[j]);
print(message, aux);
}
print("\n", aux);
}
break;
case tagtype_t.TYPE_SHORT:
ushort[] sptr=data as ushort[];
if(sptr==null) throw new Exception("ushort[] expected.");
if(sptr.Length<count) throw new Exception("ushort[] too short.");
if(count==1)
{
print(GTIFValueName(keyid, sptr[0]), aux);
print("\n", aux);
}
else
{
for(int i=0; i<count; i+=3)
{
int done=Math.Min(i+3, count);
for(int j=i; j<done; j++)
{
message=string.Format(FMT_SHORT, sptr[j]);
print(message, aux);
}
print("\n", aux);
}
}
break;
default:
message=string.Format("Unknown Type ({0})\n", key.gk_type);
print(message, aux);
break;
}
}
static void DefaultPrint(string str, object aux)
{
// Pretty boring
TextWriter writer=aux as TextWriter;
if(writer!=null) writer.Write(str);
}
// Importing metadata file
// Import the directory info, using whatever method is specified
// (defaults to fscanf if null). The "aux" parameter is provided for user
// defined method for passing file or whatever.
//
// The input format is a "GeoTIFF meta-data" file, which may be
// generated by the GTIFFPrint() routine.
public static bool GTIFImport(GTIF gtif)
{
return GTIFImport(gtif, null, null);
}
public static bool GTIFImport(GTIF gtif, GTIFReadMethod scan, object aux)
{
if(scan==null) scan=DefaultRead;
if(aux==null) aux=Console.In;
string message=scan(aux);
if(message==null||message.Length<20) return false;
if(message.ToLower().Substring(0, 20)!=FMT_GEOTIFF.ToLower().Substring(0, 20)) return false;
message=scan(aux);
if(message==null||message.Length<10) return false;
if(message.ToLower().Substring(0, 8)!=FMT_VERSION.ToLower().Substring(0, 8)) return false;
message=message.Substring(9);
try
{
gtif.gt_version=ushort.Parse(message);
}
catch
{
return false;
}
message=scan(aux);
if(message==null||message.Length<15) return false;
if(message.ToLower().Substring(0, 13)!=FMT_REV.ToLower().Substring(0, 13)) return false;
message=message.Substring(14);
try
{
string[] spl=message.Split('.');
if(spl.Length!=2) return false;
gtif.gt_rev_major=ushort.Parse(spl[0]);
gtif.gt_rev_minor=ushort.Parse(spl[1]);
}
catch
{
return false;
}
message=scan(aux);
if(message==null||message.Length<19) return false;
if(message.ToLower().Substring(0, 19)!=FMT_TAGS.ToLower().Substring(0, 19)) return false;
int status;
while((status=ReadTag(gtif, scan, aux))>0) ;
if(status<0) return false;
message=scan(aux);
if(message==null||message.Length<18) return false;
if(message.ToLower().Substring(0, 18)!=FMT_KEYS.ToLower().Substring(0, 18)) return false;
while((status=ReadKey(gtif, scan, aux))>0) ;
return (status==0); // success
}
static int StringError(string str)
{
Console.Error.WriteLine("Parsing Error at '{0}'", str);
return -1;
}
static int ReadTag(GTIF gt, GTIFReadMethod scan, object aux)
{
string message=scan(aux);
if(message==null) return -1;
if(message.Length>=12) if(message.ToLower().Substring(0, 12)==FMT_TAGEND.ToLower().Substring(0, 12)) return 0;
try
{
int firstp=message.IndexOfAny(new char[] { '(', ' ', '\t' });
if(firstp<0) return StringError(message);
string tagname=message.Substring(0, firstp).Trim();
message=message.Substring(firstp);
int colon=message.IndexOf(':');
if(colon<0) return StringError(message);
message=message.Substring(0, colon);
message=message.Trim(' ', '\t', '(', ')');
string[] spl=message.Split(',');
if(spl.Length!=2) return StringError(message);
int nrows=int.Parse(spl[0]);
int ncols=int.Parse(spl[1]);
int tag=GTIFTagCode(tagname);
if(tag<0) return StringError(tagname);
int count=nrows*ncols;
double[] dptr=new double[count];
for(int i=0; i<nrows; i++)
{
message=scan(aux);
if(message==null) return -1;
spl=message.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if(spl.Length!=ncols) StringError(message);
for(int j=0; j<ncols; j++)
{
message=spl[j];
dptr[i*ncols+j]=GTIFAtof(message);
}
}
gt.gt_methods.set(gt.gt_tif, (ushort)tag, count, dptr);
}
catch
{
return StringError(message);
}
return 1;
}
static int ReadKey(GTIF gt, GTIFReadMethod scan, object aux)
{
string message=scan(aux);
if(message==null) return -1;
if(message.Length>=12) if(message.ToLower().Substring(0, 12)==FMT_KEYEND.ToLower().Substring(0, 12)) return 0;
try
{
int firstp=message.IndexOfAny(new char[] { '(', ' ', '\t' });
if(firstp<0) return StringError(message);
string name=message.Substring(0, firstp).Trim();
string message1=message.Substring(firstp);
int colon=message1.IndexOf(':');
if(colon<0) return StringError(message1);
string head=message1.Substring(0, colon);
head=head.Trim(' ', '\t', '(', ')');
string[] spl=head.Split(',');
if(spl.Length!=2) return StringError(head);
string type=spl[0];
int count=int.Parse(spl[1]);
// skip white space
string data=message1.Substring(colon+1).Trim();
if(data.Length==0) return StringError(message);
if(GTIFKeyCode(name)<0) return StringError(name);
geokey_t key=(geokey_t)GTIFKeyCode(name);
if(GTIFTypeCode(type)<0) return StringError(type);
tagtype_t ktype=(tagtype_t)GTIFTypeCode(type);
switch(ktype)
{
case tagtype_t.TYPE_ASCII:
{
string cdata="";
int firstDoubleQuote=data.IndexOf('"');
if(firstDoubleQuote<0) return StringError(data);
data=data.Substring(firstDoubleQuote+1);
bool wasesc=false;
char c='\0';
for(int i=0; i<data.Length; i++)
{
c=data[i];
if(wasesc)
{
if(c=='\\') cdata+='\\';
else if(c=='"') cdata+='"';
else if(c=='n') cdata+='\n';
else if(c=='t') cdata+='\t';
else if(c=='b') cdata+='\b';
else if(c=='r') cdata+='\r';
else if(c=='0') cdata+='\0';
wasesc=false;
continue;
}
if(c=='\\')
{
wasesc=true;
continue;
}
if(c=='\0') break;
if(c=='"') break;
cdata+=c;
if(cdata.Length==count)
{
c=data[i+1];
break;
}
}
if(cdata.Length<count) return StringError(message);
if(c!='"') return StringError(message);
GTIFKeySet(gt, key, cdata);
}
break;
case tagtype_t.TYPE_DOUBLE:
{
double[] dptr=new double[count];
int i=0;
for(; count>0; count-=3)
{
spl=data.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if(spl.Length!=Math.Min(3, count)) return StringError(data);
foreach(string part in spl)
{
message=part;
dptr[i++]=GTIFAtof(part);
}
if(count>3) message=data=scan(aux);
}
GTIFKeySet(gt, key, dptr);
}
break;
case tagtype_t.TYPE_SHORT:
if(count==1)
{
int icode=GTIFValueCode(key, data);
if(icode<0) return StringError(data);
ushort code=(ushort)icode;
GTIFKeySet(gt, key, code);
}
else // multi-valued short - no such thing yet
{
ushort[] sptr=new ushort[count];
int i=0;
for(; count>0; count-=3)
{
spl=data.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if(spl.Length!=Math.Min(3, count)) return StringError(data);
foreach(string part in spl)
{
message=part;
sptr[i++]=ushort.Parse(part);
}
if(count>3) message=data=scan(aux);
}
GTIFKeySet(gt, key, sptr);
}
break;
default: return -1;
}
}
catch
{
return StringError(message);
}
return 1;
}
static string DefaultRead(object aux)
{
// Pretty boring
TextReader reader=aux as TextReader;
if(reader!=null) return reader.ReadLine().Trim();
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace Ivy
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class Player : Entity
{
Weapon m_armCannon;
// Sound Effects
SoundEffect m_rollEffect;
SoundEffectInstance m_rollInstance;
SoundEffect m_landEffect;
public Player(IvyGame game) : base(game)
{
}
public override void Initialize()
{
Movable = true;
Damagable = true;
m_animGraph = new AnimGraph(this);
m_animGraph.Initialize();
m_armCannon = new Weapon(this, new Point(10, 10), Direction);
m_armCannon.Initialize();
m_landEffect = Game.Content.Load<SoundEffect>("Audio\\samus_land");
m_rollEffect = Game.Content.Load<SoundEffect>("Audio\\samus_jump_roll");
m_rollInstance = m_rollEffect.CreateInstance();
#region Anim Rects
Rectangle samusTurnRect = new Rectangle(0, 156, 78, 47);
Rectangle samusWaitRightRect = new Rectangle(0, 203, 140, 45);
Rectangle samusWaitLeftRect = new Rectangle(0, 248, 140, 45);
Rectangle samusRunRightRect = new Rectangle(0, 66, 460, 45);
Rectangle samusRunLeftRect = new Rectangle(0, 111, 460, 45);
Rectangle samusJumpRollRightRect = new Rectangle(0, 0, 280, 32);
Rectangle samusJumpRollLeftRect = new Rectangle(0, 33, 280, 32);
Rectangle samusJumpAscendRightRect = new Rectangle(0, 293, 56, 47);
Rectangle samusJumpAscendLeftRect = new Rectangle(0, 340, 56, 47);
Rectangle samusJumpDescendRightRect = new Rectangle(56, 293, 112, 47);
Rectangle samusJumpDescendLeftRect = new Rectangle(56, 340, 112, 47);
Rectangle samusJumpLandRightRect = new Rectangle(168, 293, 56, 47);
Rectangle samusJumpLandLeftRect = new Rectangle(168, 340, 56, 47);
#endregion
Texture2D samusMap = Game.Content.Load<Texture2D>("Sprites\\samusMap");
#region Animation Setup
AnimatedSprite samusTurnLeftAnim = new AnimatedSprite(samusMap, samusTurnRect, 3, 24f);
IAnimGraphNode samusTurnLeftNode = m_animGraph.AddAnim(samusTurnLeftAnim);
samusTurnLeftNode.Anim.Initialize();
samusTurnLeftNode.Anim.Loop = false;
samusTurnLeftNode.Anim.Name = "SamusTurnLeft";
AnimatedSprite samusTurnRightAnim = new AnimatedSprite(samusMap, samusTurnRect, 3, 24f);
IAnimGraphNode samusTurnRightNode = m_animGraph.AddAnim(samusTurnRightAnim);
samusTurnRightNode.Anim.Initialize();
samusTurnRightNode.Anim.Loop = false;
samusTurnRightNode.Anim.Reverse = true;
samusTurnRightNode.Anim.Name = "SamusTurnRight";
IAnimGraphNode samusWaitLeftNode = m_animGraph.AddAnim(
new AnimatedSprite(samusMap, samusWaitLeftRect, 5, 6f));
samusWaitLeftNode.Anim.Initialize();
samusWaitLeftNode.Anim.Name = "SamusWaitLeft";
IAnimGraphNode samusWaitRightNode = m_animGraph.AddAnim(
new AnimatedSprite(samusMap, samusWaitRightRect, 5, 6f));
samusWaitRightNode.Anim.Initialize();
samusWaitRightNode.Anim.Name = "SamusWaitRight";
IAnimGraphNode samusRunLeftNode = m_animGraph.AddAnim(
new AnimatedSprite(samusMap, samusRunLeftRect, 10, 18f));
samusRunLeftNode.Anim.Initialize();
samusRunLeftNode.Anim.Name = "SamusRunLeft";
IAnimGraphNode samusRunRightNode = m_animGraph.AddAnim(
new AnimatedSprite(samusMap, samusRunRightRect, 10, 18f));
samusRunRightNode.Anim.Initialize();
samusRunRightNode.Anim.Name = "SamusRunRight";
// Stand & Run code
m_animGraph.AddTransition(samusWaitLeftNode, MessageType.MoveLeft, samusRunLeftNode);
m_animGraph.AddTransition(samusRunLeftNode, MessageType.Stand, samusWaitLeftNode);
m_animGraph.AddTransition(samusWaitRightNode, MessageType.MoveRight, samusRunRightNode);
m_animGraph.AddTransition(samusRunRightNode, MessageType.Stand, samusWaitRightNode);
// Turn Code
// Turning Left to Right
m_animGraph.AddTransition(samusWaitLeftNode, MessageType.MoveRight, samusTurnRightNode);
m_animGraph.AddTransition(samusRunLeftNode, MessageType.MoveRight, samusTurnRightNode);
m_animGraph.AddTransitionOnAnimEnd(samusTurnRightNode, samusRunRightNode);
m_animGraph.AddTransitionOnAnimEnd(samusTurnRightNode, MessageType.Stand, samusWaitRightNode);
m_animGraph.AddTransitionOnAnimEnd(samusTurnRightNode, MessageType.MoveRight, samusRunRightNode);
// Turning Right to Left
m_animGraph.AddTransition(samusWaitRightNode, MessageType.MoveLeft, samusTurnLeftNode);
m_animGraph.AddTransition(samusRunRightNode, MessageType.MoveLeft, samusTurnLeftNode);
m_animGraph.AddTransitionOnAnimEnd(samusTurnLeftNode, samusRunLeftNode);
m_animGraph.AddTransitionOnAnimEnd(samusTurnLeftNode, MessageType.Stand, samusWaitLeftNode);
m_animGraph.AddTransitionOnAnimEnd(samusTurnLeftNode, MessageType.MoveLeft, samusRunLeftNode);
// Change turn direction
m_animGraph.AddTransition(samusTurnLeftNode, MessageType.MoveRight, samusTurnRightNode);
m_animGraph.AddTransition(samusTurnRightNode, MessageType.MoveLeft, samusTurnLeftNode);
IAnimGraphNode samusJumpRollLeftNode = m_animGraph.AddAnim(
new AnimatedSprite(samusMap, samusJumpRollLeftRect, 8, 16f));
samusJumpRollLeftNode.Anim.Initialize();
IAnimGraphNode samusJumpRollRightNode = m_animGraph.AddAnim(
new AnimatedSprite(samusMap, samusJumpRollRightRect, 8, 16f));
samusJumpRollRightNode.Anim.Initialize();
IAnimGraphNode samusJumpAscendLeftNode = m_animGraph.AddAnim(
new AnimatedSprite(samusMap, samusJumpAscendLeftRect, 2, 16f));
samusJumpAscendLeftNode.Anim.Initialize();
samusJumpAscendLeftNode.Anim.Loop = false;
IAnimGraphNode samusJumpAscendRightNode = m_animGraph.AddAnim(
new AnimatedSprite(samusMap, samusJumpAscendRightRect, 2, 16f));
samusJumpAscendRightNode.Anim.Initialize();
samusJumpAscendRightNode.Anim.Loop = false;
IAnimGraphNode samusJumpDescendLeftNode = m_animGraph.AddAnim(
new AnimatedSprite(samusMap, samusJumpDescendLeftRect, 4, 16f));
samusJumpDescendLeftNode.Anim.Initialize();
samusJumpDescendLeftNode.Anim.Loop = false;
IAnimGraphNode samusJumpDescendRightNode = m_animGraph.AddAnim(
new AnimatedSprite(samusMap, samusJumpDescendRightRect, 4, 16f));
samusJumpDescendRightNode.Anim.Initialize();
samusJumpDescendRightNode.Anim.Loop = false;
AnimatedSprite landLeftAnim = new AnimatedSprite(samusMap, samusJumpLandLeftRect, 2, 16f);
IAnimGraphNode samusJumpRollLandLeftNode = m_animGraph.AddAnim(landLeftAnim);
samusJumpRollLandLeftNode.Anim.Initialize();
samusJumpRollLandLeftNode.Anim.Loop = false;
IAnimGraphNode samusJumpDescendLandLeftNode = m_animGraph.AddAnim(landLeftAnim);
samusJumpDescendLandLeftNode.Anim.Initialize();
samusJumpDescendLandLeftNode.Anim.Loop = false;
AnimatedSprite landRightAnim = new AnimatedSprite(samusMap, samusJumpLandRightRect, 2, 16f);
IAnimGraphNode samusJumpRollLandRightNode = m_animGraph.AddAnim(landRightAnim);
samusJumpRollLandRightNode.Anim.Initialize();
samusJumpRollLandRightNode.Anim.Loop = false;
IAnimGraphNode samusJumpDescendLandRightNode = m_animGraph.AddAnim(landRightAnim);
samusJumpDescendLandRightNode.Anim.Initialize();
samusJumpDescendLandRightNode.Anim.Loop = false;
// Jump Ascend & Descend
m_animGraph.AddTransition(samusRunLeftNode, MessageType.Jump, samusJumpRollLeftNode);
m_animGraph.AddTransition(samusRunRightNode, MessageType.Jump, samusJumpRollRightNode);
m_animGraph.AddTransition(samusWaitLeftNode, MessageType.Jump, samusJumpAscendLeftNode);
m_animGraph.AddTransition(samusWaitRightNode, MessageType.Jump, samusJumpAscendRightNode);
m_animGraph.AddTransition(samusJumpAscendLeftNode, MessageType.Fall, samusJumpDescendLeftNode);
m_animGraph.AddTransition(samusJumpAscendRightNode, MessageType.Fall, samusJumpDescendRightNode);
// Jump Turn
m_animGraph.AddTransition(samusJumpRollLeftNode, MessageType.MoveRight, samusJumpRollRightNode);
m_animGraph.AddTransition(samusJumpRollRightNode, MessageType.MoveLeft, samusJumpRollLeftNode);
m_animGraph.AddTransition(samusJumpAscendLeftNode, MessageType.MoveRight, samusJumpAscendRightNode);
m_animGraph.AddTransition(samusJumpAscendRightNode, MessageType.MoveLeft, samusJumpAscendLeftNode);
m_animGraph.AddTransition(samusJumpDescendLeftNode, MessageType.MoveRight, samusJumpDescendRightNode);
m_animGraph.AddTransition(samusJumpDescendRightNode, MessageType.MoveLeft, samusJumpDescendLeftNode);
// Land
m_animGraph.AddTransition(samusJumpRollLeftNode, MessageType.Land, samusJumpRollLandLeftNode);
m_animGraph.AddTransitionOnAnimEnd(samusJumpRollLandLeftNode, samusRunLeftNode);
m_animGraph.AddTransitionOnAnimEnd(samusJumpRollLandLeftNode, MessageType.Stand, samusWaitLeftNode);
m_animGraph.AddTransitionOnAnimEnd(samusJumpRollLandLeftNode, MessageType.MoveLeft, samusRunLeftNode);
m_animGraph.AddTransitionOnAnimEnd(samusJumpRollLandLeftNode, MessageType.MoveRight, samusTurnRightNode);
m_animGraph.AddTransition(samusJumpDescendLeftNode, MessageType.Land, samusJumpDescendLandLeftNode);
m_animGraph.AddTransitionOnAnimEnd(samusJumpDescendLandLeftNode, samusWaitLeftNode);
m_animGraph.AddTransition(samusJumpRollRightNode, MessageType.Land, samusJumpRollLandRightNode);
m_animGraph.AddTransitionOnAnimEnd(samusJumpRollLandRightNode, samusRunRightNode);
m_animGraph.AddTransition(samusJumpDescendRightNode, MessageType.Land, samusJumpDescendLandRightNode);
m_animGraph.AddTransitionOnAnimEnd(samusJumpDescendLandRightNode, samusWaitRightNode);
m_animGraph.SetCurrentNode(samusWaitRightNode);
#endregion
base.Initialize();
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
m_animGraph.Update(gameTime);
m_armCannon.Update(gameTime);
}
public override void Draw(SpriteBatch spriteBatch)
{
m_armCannon.Draw(spriteBatch);
m_animGraph.Draw(spriteBatch);
Console.WriteLine(Position);
}
public override void ReceiveMessage(Message msg)
{
switch (msg.Type)
{
case MessageType.FireWeapon:
FireWeapon();
break;
default:
base.ReceiveMessage(msg);
break;
}
m_animGraph.ReceiveMessage(msg);
if (msg.Type == MessageType.TakeDamage)
{
if (Energy <= 0)
{
MessageDispatcher.Get().SendMessage(new Message(MessageType.EndGame, this, IvyGame.Get()));
}
}
}
private void FireWeapon()
{
m_armCannon.Fire();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace VirtualSales.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayer
{
public class UniverseSyncCache
{
public string cacheDirectory
{
get
{
return Path.Combine(Path.Combine(Client.dmpClient.gameDataDir, "DarkMultiPlayer"), "Cache");
}
}
private AutoResetEvent incomingEvent = new AutoResetEvent(false);
private Queue<byte[]> incomingQueue = new Queue<byte[]>();
private Dictionary<string, long> fileLengths = new Dictionary<string, long>();
private Dictionary<string, DateTime> fileCreationTimes = new Dictionary<string, DateTime>();
//Services
private Settings dmpSettings;
public long currentCacheSize
{
get;
private set;
}
public UniverseSyncCache(Settings dmpSettings)
{
this.dmpSettings = dmpSettings;
Thread processingThread = new Thread(new ThreadStart(ProcessingThreadMain));
processingThread.IsBackground = true;
processingThread.Start();
}
private void ProcessingThreadMain()
{
while (true)
{
if (incomingQueue.Count == 0)
{
incomingEvent.WaitOne(500);
}
else
{
byte[] incomingBytes;
lock (incomingQueue)
{
incomingBytes = incomingQueue.Dequeue();
}
SaveToCache(incomingBytes);
}
}
}
private string[] GetCachedFiles()
{
return Directory.GetFiles(cacheDirectory);
}
public string[] GetCachedObjects()
{
string[] cacheFiles = GetCachedFiles();
string[] cacheObjects = new string[cacheFiles.Length];
for (int i = 0; i < cacheFiles.Length; i++)
{
cacheObjects[i] = Path.GetFileNameWithoutExtension(cacheFiles[i]);
}
return cacheObjects;
}
public void ExpireCache()
{
DarkLog.Debug("Expiring cache!");
//No folder, no delete.
if (!Directory.Exists(Path.Combine(cacheDirectory, "Incoming")))
{
DarkLog.Debug("No sync cache folder, skipping expire.");
return;
}
//Delete partial incoming files
string[] incomingFiles = Directory.GetFiles(Path.Combine(cacheDirectory, "Incoming"));
foreach (string incomingFile in incomingFiles)
{
DarkLog.Debug("Deleting partially cached object " + incomingFile);
File.Delete(incomingFile);
}
//Delete old files
string[] cacheObjects = GetCachedObjects();
currentCacheSize = 0;
foreach (string cacheObject in cacheObjects)
{
if (!string.IsNullOrEmpty(cacheObject))
{
string cacheFile = Path.Combine(cacheDirectory, cacheObject + ".txt");
//If the file is older than a week, delete it.
if (File.GetCreationTime(cacheFile).AddDays(7d) < DateTime.Now)
{
DarkLog.Debug("Deleting cached object " + cacheObject + ", reason: Expired!");
File.Delete(cacheFile);
}
else
{
FileInfo fi = new FileInfo(cacheFile);
fileCreationTimes[cacheObject] = fi.CreationTime;
fileLengths[cacheObject] = fi.Length;
currentCacheSize += fi.Length;
}
}
}
//While the directory is over (cacheSize) MB
while (currentCacheSize > (dmpSettings.cacheSize * 1024 * 1024))
{
string deleteObject = null;
//Find oldest file
foreach (KeyValuePair<string, DateTime> testFile in fileCreationTimes)
{
if (deleteObject == null)
{
deleteObject = testFile.Key;
}
if (testFile.Value < fileCreationTimes[deleteObject])
{
deleteObject = testFile.Key;
}
}
DarkLog.Debug("Deleting cached object " + deleteObject + ", reason: Cache full!");
string deleteFile = Path.Combine(cacheDirectory, deleteObject + ".txt");
File.Delete(deleteFile);
currentCacheSize -= fileLengths[deleteObject];
if (fileCreationTimes.ContainsKey(deleteObject))
{
fileCreationTimes.Remove(deleteObject);
}
if (fileLengths.ContainsKey(deleteObject))
{
fileLengths.Remove(deleteObject);
}
}
}
/// <summary>
/// Queues to cache. This method is non-blocking, using SaveToCache for a blocking method.
/// </summary>
/// <param name="fileData">File data.</param>
public void QueueToCache(byte[] fileData)
{
lock (incomingQueue)
{
incomingQueue.Enqueue(fileData);
}
incomingEvent.Set();
}
/// <summary>
/// Saves to cache. This method is blocking, use QueueToCache for a non-blocking method.
/// </summary>
/// <param name="fileData">File data.</param>
public void SaveToCache(byte[] fileData)
{
if (fileData == null || fileData.Length == 0)
{
//Don't save 0 byte data.
return;
}
string objectName = Common.CalculateSHA256Hash(fileData);
string objectFile = Path.Combine(cacheDirectory, objectName + ".txt");
string incomingFile = Path.Combine(Path.Combine(cacheDirectory, "Incoming"), objectName + ".txt");
if (!File.Exists(objectFile))
{
File.WriteAllBytes(incomingFile, fileData);
File.Move(incomingFile, objectFile);
currentCacheSize += fileData.Length;
fileLengths[objectName] = fileData.Length;
fileCreationTimes[objectName] = new FileInfo(objectFile).CreationTime;
}
else
{
File.SetCreationTime(objectFile, DateTime.Now);
fileCreationTimes[objectName] = new FileInfo(objectFile).CreationTime;
}
}
public byte[] GetFromCache(string objectName)
{
string objectFile = Path.Combine(cacheDirectory, objectName + ".txt");
if (File.Exists(objectFile))
{
return File.ReadAllBytes(objectFile);
}
else
{
throw new IOException("Cached object " + objectName + " does not exist");
}
}
public void DeleteCache()
{
DarkLog.Debug("Deleting cache!");
foreach (string cacheFile in GetCachedFiles())
{
File.Delete(cacheFile);
}
fileLengths = new Dictionary<string, long>();
fileCreationTimes = new Dictionary<string, DateTime>();
currentCacheSize = 0;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Windows.Forms;
using System.Globalization;
using System.Linq;
using Microsoft.Build.Construction;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem
{
/// <summary>
/// Creates projects within the solution
/// </summary>
internal abstract class ProjectFactory : Microsoft.VisualStudio.Shell.Flavor.FlavoredProjectFactoryBase
{
private Microsoft.VisualStudio.Shell.Package package;
private System.IServiceProvider site;
private Microsoft.Build.Evaluation.ProjectCollection buildEngine;
private Microsoft.Build.Evaluation.Project buildProject;
public Microsoft.VisualStudio.Shell.Package Package
{
get
{
return this.package;
}
}
public System.IServiceProvider Site
{
get
{
return this.site;
}
}
/// <summary>
/// The msbuild engine that we are going to use.
/// </summary>
public Microsoft.Build.Evaluation.ProjectCollection BuildEngine
{
get
{
return this.buildEngine;
}
}
/// <summary>
/// The msbuild project for the temporary project file.
/// </summary>
public Microsoft.Build.Evaluation.Project BuildProject
{
get
{
return this.buildProject;
}
set
{
this.buildProject = value;
}
}
public ProjectFactory(Microsoft.VisualStudio.Shell.Package package)
{
this.package = package;
this.site = package;
this.buildEngine = Utilities.InitializeMsBuildEngine(this.buildEngine);
}
protected abstract ProjectNode CreateProject();
/// <summary>
/// Rather than directly creating the project, ask VS to initate the process of
/// creating an aggregated project in case we are flavored. We will be called
/// on the IVsAggregatableProjectFactory to do the real project creation.
/// </summary>
/// <param name="fileName">Project file</param>
/// <param name="location">Path of the project</param>
/// <param name="name">Project Name</param>
/// <param name="flags">Creation flags</param>
/// <param name="projectGuid">Guid of the project</param>
/// <param name="project">Project that end up being created by this method</param>
/// <param name="canceled">Was the project creation canceled</param>
protected override void CreateProject(string fileName, string location, string name, uint flags, ref Guid projectGuid, out IntPtr project, out int canceled)
{
project = IntPtr.Zero;
canceled = 0;
if ((flags & ((uint)__VSCREATEPROJFLAGS2.CPF_DEFERREDSAVE)) != 0)
{
throw new NotSupportedException(SR.GetString(SR.NoZeroImpactProjects));
}
if ((flags & ((uint)__VSCREATEPROJFLAGS.CPF_OPENFILE)) != 0)
{
if (new ProjectInspector(fileName).IsPoisoned(Site))
{
// error out
int ehr = unchecked((int)0x80042003); // VS_E_INCOMPATIBLEPROJECT
ErrorHandler.ThrowOnFailure(ehr);
}
}
// Solution properties
IVsSolution solution = this.Site.GetService(typeof(SVsSolution)) as IVsSolution;
Debug.Assert(solution != null, "Could not retrieve the solution service from the global service provider");
// We do not want to throw. If we cannot set the solution related constants we set them to empty string.
string solutionDirectory, solutionPath, userOptionsFile;
solution.GetSolutionInfo(out solutionDirectory, out solutionPath, out userOptionsFile);
if (solutionDirectory == null)
{
solutionDirectory = String.Empty;
}
if (solutionPath == null)
{
solutionPath = String.Empty;
}
string solutionFileName = (solutionPath.Length == 0) ? String.Empty : Path.GetFileName(solutionPath);
string solutionName = (solutionPath.Length == 0) ? String.Empty : Path.GetFileNameWithoutExtension(solutionPath);
var solutionExtension = Path.GetExtension(solutionPath);
// DevEnvDir property
IVsShell shell = this.Site.GetService(typeof(SVsShell)) as IVsShell;
Debug.Assert(shell != null, "Could not retrieve the IVsShell service from the global service provider");
object installDirAsObject;
// We do not want to throw. If we cannot set the solution related constants we set them to empty string.
shell.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out installDirAsObject);
string installDir = ((string)installDirAsObject);
if (String.IsNullOrEmpty(installDir))
{
installDir = String.Empty;
}
else
{
// Ensure that we have trailing backslash as this is done for the langproj macros too.
if (installDir[installDir.Length - 1] != Path.DirectorySeparatorChar)
{
installDir += Path.DirectorySeparatorChar;
}
}
// Get the list of GUIDs from the project/template
string guidsList = this.ProjectTypeGuids(fileName);
// Launch the aggregate creation process (we should be called back on our IVsAggregatableProjectFactoryCorrected implementation)
IVsCreateAggregateProject aggregateProjectFactory = (IVsCreateAggregateProject)this.Site.GetService(typeof(SVsCreateAggregateProject));
int hr = aggregateProjectFactory.CreateAggregateProject(guidsList, fileName, location, name, flags, ref projectGuid, out project);
if (hr == VSConstants.E_ABORT)
{
canceled = 1;
}
ErrorHandler.ThrowOnFailure(hr);
this.buildProject = null;
}
/// <summary>
/// Instantiate the project class, but do not proceed with the
/// initialization just yet.
/// Delegate to CreateProject implemented by the derived class.
/// </summary>
protected override object PreCreateForOuter(IntPtr outerProjectIUnknown)
{
Debug.Assert(this.buildProject != null, "The build project should have been initialized before calling PreCreateForOuter.");
// Please be very carefull what is initialized here on the ProjectNode. Normally this should only instantiate and return a project node.
// The reason why one should very carefully add state to the project node here is that at this point the aggregation has not yet been created and anything that would cause a CCW for the project to be created would cause the aggregation to fail
// Our reasoning is that there is no other place where state on the project node can be set that is known by the Factory and has to execute before the Load method.
ProjectNode node = this.CreateProject();
Debug.Assert(node != null, "The project failed to be created");
node.BuildEngine = this.buildEngine;
node.BuildProject = this.buildProject;
node.Package = this.package as ProjectPackage;
node.ProjectEventsProvider = GetProjectEventsProvider();
return node;
}
internal Microsoft.Build.Evaluation.Project ReinitializeMsBuildProject(string filename)
{
// Solution properties
IVsSolution solution = this.Site.GetService(typeof(SVsSolution)) as IVsSolution;
Debug.Assert(solution != null, "Could not retrieve the solution service from the global service provider");
// We do not want to throw.If we cannot set the solution related constants we set them to empty string.
string solutionDirectory, solutionPath, userOptionsFile;
solution.GetSolutionInfo(out solutionDirectory, out solutionPath, out userOptionsFile);
if (solutionDirectory == null)
{
solutionDirectory = String.Empty;
}
if (solutionPath == null)
{
solutionPath = String.Empty;
}
string solutionFileName = (solutionPath.Length == 0) ? String.Empty : Path.GetFileName(solutionPath);
string solutionName = (solutionPath.Length == 0) ? String.Empty : Path.GetFileNameWithoutExtension(solutionPath);
string solutionExtension = String.Empty;
if (solutionPath.Length > 0 && Path.HasExtension(solutionPath))
{
solutionExtension = Path.GetExtension(solutionPath);
}
//DevEnvDir property
IVsShell shell = this.Site.GetService(typeof(SVsShell)) as IVsShell;
Debug.Assert(shell != null, "Could not retrieve the IVsShell service from the global service provider");
object installDirAsObject;
//We do not want to throw.If we cannot set the solution related constants we set them to empty string.
shell.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out installDirAsObject);
string installDir = ((string)installDirAsObject);
if (String.IsNullOrEmpty(installDir))
{
installDir = String.Empty;
}
else
{
//Ensure that we have trailing backslash as this is done for the langproj macros too.
if (installDir[installDir.Length - 1] != Path.DirectorySeparatorChar)
{
installDir += Path.DirectorySeparatorChar;
}
}
var projectGlobalPropertiesThatAllProjectSystemsMustSet = new Dictionary<string, string>()
{
{ GlobalProperty.SolutionDir.ToString(), solutionDirectory },
{ GlobalProperty.SolutionPath.ToString(), solutionPath },
{ GlobalProperty.SolutionFileName.ToString(), solutionFileName },
{ GlobalProperty.SolutionName.ToString(), solutionName },
{ GlobalProperty.SolutionExt.ToString(), solutionExtension },
{ GlobalProperty.BuildingInsideVisualStudio.ToString(), "true" },
{ GlobalProperty.Configuration.ToString(), "" },
{ GlobalProperty.Platform.ToString(), "" },
{ GlobalProperty.DevEnvDir.ToString(), installDir }
};
return Utilities.ReinitializeMsBuildProject(this.buildEngine, filename, projectGlobalPropertiesThatAllProjectSystemsMustSet, this.buildProject);
}
/// <summary>
/// Retrives the list of project guids from the project file.
/// If you don't want your project to be flavorable, override
/// to only return your project factory Guid:
/// return this.GetType().GUID.ToString("B");
/// </summary>
/// <param name="file">Project file to look into to find the Guid list</param>
/// <returns>List of semi-colon separated GUIDs</returns>
protected override string ProjectTypeGuids(string file)
{
// Load the project so we can extract the list of GUIDs
this.buildProject = this.ReinitializeMsBuildProject(file);
// Retrieve the list of GUIDs, if it is not specify, make it our GUID
string guids = buildProject.GetPropertyValue(ProjectFileConstants.ProjectTypeGuids);
if (String.IsNullOrEmpty(guids))
guids = this.GetType().GUID.ToString("B");
return guids;
}
private class ProjectInspector
{
private Microsoft.Build.Construction.ProjectRootElement xmlProj;
private const string MinimumVisualStudioVersion = "MinimumVisualStudioVersion";
public ProjectInspector(string filename)
{
try
{
xmlProj = Microsoft.Build.Construction.ProjectRootElement.Open(filename);
}
catch (Microsoft.Build.Exceptions.InvalidProjectFileException)
{
// leave xmlProj non-initialized, other methods will check its state in prologue
}
}
/// we consider project to be Dev10- if it doesn't have any imports that belong to higher versions
public bool IsLikeDev10MinusProject()
{
if (xmlProj == null)
return false;
const string fsharpFS45TargetsPath = @"$(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.FSharp.Targets";
const string fsharpPortableDev11TargetsPath = @"$(MSBuildExtensionsPath32)\..\Microsoft SDKs\F#\3.0\Framework\v4.0\Microsoft.Portable.FSharp.Targets";
// Dev12+ projects import *.targets files using property
const string fsharpDev12PlusImportsValue = @"$(FSharpTargetsPath)";
foreach(var import in xmlProj.Imports)
{
if (
IsEqual(import.Project, fsharpFS45TargetsPath) ||
IsEqual(import.Project, fsharpPortableDev11TargetsPath) ||
IsEqual(import.Project, fsharpDev12PlusImportsValue)
)
{
return false;
}
}
return true;
}
private bool IsEqual(string s1, string s2)
{
return string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase);
}
public bool IsPoisoned(System.IServiceProvider sp)
{
if (xmlProj == null)
return false;
// use IVsAppCompat service to determine current VS version
var appCompatService = (IVsAppCompat)sp.GetService(typeof(SVsSolution));
string currentDesignTimeCompatVersionString = null;
appCompatService.GetCurrentDesignTimeCompatVersion(out currentDesignTimeCompatVersionString);
// currentDesignTimeCompatVersionString can look like 12.0
// code in vsproject\vsproject\vsprjfactory.cpp uses _wtoi that will ignore part of string after dot
// we'll do the same trick
var indexOfDot = currentDesignTimeCompatVersionString.IndexOf('.');
if (indexOfDot != -1)
{
currentDesignTimeCompatVersionString = currentDesignTimeCompatVersionString.Substring(0, indexOfDot);
}
var currentDesignTimeCompatVersion = int.Parse(currentDesignTimeCompatVersionString);
foreach (var pg in xmlProj.PropertyGroups)
{
foreach (var p in pg.Properties)
{
if (string.CompareOrdinal(p.Name, MinimumVisualStudioVersion) == 0)
{
var s = p.Value;
if (!string.IsNullOrEmpty(s))
{
int ver;
int.TryParse(s, out ver);
if (ver > currentDesignTimeCompatVersion)
return true;
}
}
}
}
return false;
}
}
private IProjectEvents GetProjectEventsProvider()
{
ProjectPackage projectPackage = this.package as ProjectPackage;
Debug.Assert(projectPackage != null, "Package not inherited from framework");
if (projectPackage != null)
{
foreach (SolutionListener listener in projectPackage.SolutionListeners)
{
IProjectEvents projectEvents = listener as IProjectEvents;
if (projectEvents != null)
{
return projectEvents;
}
}
}
return null;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION WITH THE USE OF THIS CODE
// AND INFORMATION REMAINS WITH THE USER.
/*********************************************************************
* NOTE: A copy of this file exists at: WF\Activities\Common
* The two files must be kept in [....]. Any change made here must also
* be made to WF\Activities\Common\Walker.cs
*********************************************************************/
namespace System.Workflow.ComponentModel
{
#region Imports
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
#endregion
// Returns true to continue the walk, false to stop.
internal delegate void WalkerEventHandler(Walker walker, WalkerEventArgs eventArgs);
internal enum WalkerAction
{
Continue = 0,
Skip = 1,
Abort = 2
}
#region Class WalkerEventArgs
internal sealed class WalkerEventArgs : EventArgs
{
private Activity currentActivity = null;
private object currentPropertyOwner = null;
private PropertyInfo currentProperty = null;
private object currentValue = null;
private WalkerAction action = WalkerAction.Continue;
internal WalkerEventArgs(Activity currentActivity)
{
this.currentActivity = currentActivity;
this.currentPropertyOwner = null;
this.currentProperty = null;
this.currentValue = null;
}
internal WalkerEventArgs(Activity currentActivity, object currentValue, PropertyInfo currentProperty, object currentPropertyOwner)
: this(currentActivity)
{
this.currentPropertyOwner = currentPropertyOwner;
this.currentProperty = currentProperty;
this.currentValue = currentValue;
}
public WalkerAction Action
{
get
{
return this.action;
}
set
{
this.action = value;
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public PropertyInfo CurrentProperty
{
get
{
return this.currentProperty;
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public object CurrentPropertyOwner
{
get
{
return this.currentPropertyOwner;
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public object CurrentValue
{
get
{
return this.currentValue;
}
}
public Activity CurrentActivity
{
get
{
return this.currentActivity;
}
}
}
#endregion
internal sealed class Walker
{
#region Members
internal event WalkerEventHandler FoundActivity;
internal event WalkerEventHandler FoundProperty;
private bool useEnabledActivities = false;
#endregion
#region Methods
public Walker()
: this(false)
{
}
public Walker(bool useEnabledActivities)
{
this.useEnabledActivities = useEnabledActivities;
}
public void Walk(Activity seedActivity)
{
Walk(seedActivity, true);
}
public void Walk(Activity seedActivity, bool walkChildren)
{
Queue queue = new Queue();
queue.Enqueue(seedActivity);
while (queue.Count > 0)
{
Activity activity = queue.Dequeue() as Activity;
if (FoundActivity != null)
{
WalkerEventArgs args = new WalkerEventArgs(activity);
FoundActivity(this, args);
if (args.Action == WalkerAction.Abort)
return;
if (args.Action == WalkerAction.Skip)
continue;
}
if (FoundProperty != null)
{
if (!WalkProperties(activity))
return;
}
if (walkChildren && activity is CompositeActivity)
{
if (useEnabledActivities)
{
foreach (Activity activity2 in Design.Helpers.GetAllEnabledActivities((CompositeActivity)activity))
queue.Enqueue(activity2);
}
else
{
foreach (Activity activity2 in ((CompositeActivity)activity).Activities)
queue.Enqueue(activity2);
}
}
}
}
private bool WalkProperties(Activity seedActivity)
{
return WalkProperties(seedActivity as Activity, seedActivity);
}
public bool WalkProperties(Activity activity, object obj)
{
Activity currentActivity = obj as Activity;
PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
// !!Work around: no indexer property walking
if (prop.GetIndexParameters() != null && prop.GetIndexParameters().Length > 0)
continue;
DesignerSerializationVisibility visibility = GetSerializationVisibility(prop);
if (visibility == DesignerSerializationVisibility.Hidden)
continue;
//Try to see if we have dynamic property associated with the object on the same object
//if so then we should compare if the dynamic property values match with the property type
//if not we bail out
object propValue = null;
DependencyProperty dependencyProperty = DependencyProperty.FromName(prop.Name, obj.GetType());
if (dependencyProperty != null && currentActivity != null)
{
if (currentActivity.IsBindingSet(dependencyProperty))
propValue = currentActivity.GetBinding(dependencyProperty);
else
propValue = currentActivity.GetValue(dependencyProperty);
}
else
{
try
{
propValue = prop.CanRead ? prop.GetValue(obj, null) : null;
}
catch
{
// Eat exceptions that occur while invoking the getter.
}
}
if (FoundProperty != null)
{
WalkerEventArgs args = new WalkerEventArgs(activity, propValue, prop, obj);
FoundProperty(this, args);
if (args.Action == WalkerAction.Skip)
continue;
else if (args.Action == WalkerAction.Abort)
return false;
}
if (propValue is IList)
{
//We do not need to reflect on the properties of the list
foreach (object childObj in (IList)propValue)
{
if (FoundProperty != null)
{
WalkerEventArgs args = new WalkerEventArgs(activity, childObj, null, propValue);
FoundProperty(this, args);
if (args.Action == WalkerAction.Skip)
continue;
else if (args.Action == WalkerAction.Abort)
return false;
}
if (childObj != null && IsBrowsableType(childObj.GetType()))
{
if (!WalkProperties(activity, childObj))
return false;
}
}
}
else if (propValue != null && IsBrowsableType(propValue.GetType()))
{
if (!WalkProperties(activity, propValue))
return false;
}
}
return true;
}
private static DesignerSerializationVisibility GetSerializationVisibility(PropertyInfo prop)
{
// work around!!! for Activities collection
if (prop.DeclaringType == typeof(CompositeActivity) && string.Equals(prop.Name, "Activities", StringComparison.Ordinal))
return DesignerSerializationVisibility.Hidden;
DesignerSerializationVisibility visibility = DesignerSerializationVisibility.Visible;
DesignerSerializationVisibilityAttribute[] visibilityAttrs = (DesignerSerializationVisibilityAttribute[])prop.GetCustomAttributes(typeof(DesignerSerializationVisibilityAttribute), true);
if (visibilityAttrs.Length > 0)
visibility = visibilityAttrs[0].Visibility;
return visibility;
}
private static bool IsBrowsableType(Type type)
{
bool browsable = false;
BrowsableAttribute[] browsableAttrs = (BrowsableAttribute[])type.GetCustomAttributes(typeof(BrowsableAttribute), true);
if (browsableAttrs.Length > 0)
browsable = browsableAttrs[0].Browsable;
return browsable;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics.EngineV2;
using Microsoft.CodeAnalysis.Internal.Log;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal class SolutionCrawlerLogger
{
private const string Id = nameof(Id);
private const string Kind = nameof(Kind);
private const string Analyzer = nameof(Analyzer);
private const string DocumentCount = nameof(DocumentCount);
private const string HighPriority = nameof(HighPriority);
private const string Enabled = nameof(Enabled);
private const string AnalyzerCount = nameof(AnalyzerCount);
private const string PersistentStorage = nameof(PersistentStorage);
private const string GlobalOperation = nameof(GlobalOperation);
private const string HigherPriority = nameof(HigherPriority);
private const string LowerPriority = nameof(LowerPriority);
private const string TopLevel = nameof(TopLevel);
private const string MemberLevel = nameof(MemberLevel);
private const string NewWorkItem = nameof(NewWorkItem);
private const string UpdateWorkItem = nameof(UpdateWorkItem);
private const string ProjectEnqueue = nameof(ProjectEnqueue);
private const string ResetStates = nameof(ResetStates);
private const string ProjectNotExist = nameof(ProjectNotExist);
private const string DocumentNotExist = nameof(DocumentNotExist);
private const string ProcessProject = nameof(ProcessProject);
private const string OpenDocument = nameof(OpenDocument);
private const string CloseDocument = nameof(CloseDocument);
private const string SolutionHash = nameof(SolutionHash);
private const string ProcessDocument = nameof(ProcessDocument);
private const string ProcessDocumentCancellation = nameof(ProcessDocumentCancellation);
private const string ProcessProjectCancellation = nameof(ProcessProjectCancellation);
private const string ActiveFileEnqueue = nameof(ActiveFileEnqueue);
private const string ActiveFileProcessDocument = nameof(ActiveFileProcessDocument);
private const string ActiveFileProcessDocumentCancellation = nameof(ActiveFileProcessDocumentCancellation);
private const string Max = "Maximum";
private const string Min = "Minimum";
private const string Median = nameof(Median);
private const string Mean = nameof(Mean);
private const string Mode = nameof(Mode);
private const string Range = nameof(Range);
private const string Count = nameof(Count);
public static void LogRegistration(int correlationId, Workspace workspace)
{
Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Register, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[Kind] = workspace.Kind;
}));
}
public static void LogUnregistration(int correlationId)
{
Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Unregister, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
}));
}
public static void LogReanalyze(int correlationId, IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds, bool highPriority)
{
Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Reanalyze, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[Analyzer] = analyzer.ToString();
m[DocumentCount] = documentIds == null ? 0 : documentIds.Count();
m[HighPriority] = highPriority;
}));
}
public static void LogOptionChanged(int correlationId, bool value)
{
Logger.Log(FunctionId.WorkCoordinator_SolutionCrawlerOption, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[Enabled] = value;
}));
}
public static void LogAnalyzers(int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered, bool onlyHighPriorityAnalyzer)
{
if (onlyHighPriorityAnalyzer)
{
LogAnalyzersWorker(
FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzers, FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzer,
correlationId, workspace, reordered);
}
else
{
LogAnalyzersWorker(
FunctionId.IncrementalAnalyzerProcessor_Analyzers, FunctionId.IncrementalAnalyzerProcessor_Analyzer,
correlationId, workspace, reordered);
}
}
private static void LogAnalyzersWorker(
FunctionId analyzersId, FunctionId analyzerId, int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered)
{
if (workspace.Kind == WorkspaceKind.Preview)
{
return;
}
// log registered analyzers.
Logger.Log(analyzersId, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[AnalyzerCount] = reordered.Length;
}));
foreach (var analyzer in reordered)
{
Logger.Log(analyzerId, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[Analyzer] = analyzer.ToString();
}));
}
}
public static void LogWorkCoordinatorShutdownTimeout(int correlationId)
{
Logger.Log(FunctionId.WorkCoordinator_ShutdownTimeout, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
}));
}
public static void LogWorkspaceEvent(LogAggregator logAggregator, int kind)
{
logAggregator.IncreaseCount(kind);
}
public static void LogWorkCoordinatorShutdown(int correlationId, LogAggregator logAggregator)
{
Logger.Log(FunctionId.WorkCoordinator_Shutdown, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
foreach (var kv in logAggregator)
{
var change = ((WorkspaceChangeKind)kv.Key).ToString();
m[change] = kv.Value.GetCount();
}
}));
}
public static void LogGlobalOperation(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(GlobalOperation);
}
public static void LogActiveFileEnqueue(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(ActiveFileEnqueue);
}
public static void LogWorkItemEnqueue(LogAggregator logAggregator, ProjectId projectId)
{
logAggregator.IncreaseCount(ProjectEnqueue);
}
public static void LogWorkItemEnqueue(
LogAggregator logAggregator, string language, DocumentId documentId, InvocationReasons reasons, bool lowPriority, SyntaxPath activeMember, bool added)
{
logAggregator.IncreaseCount(language);
logAggregator.IncreaseCount(added ? NewWorkItem : UpdateWorkItem);
if (documentId != null)
{
logAggregator.IncreaseCount(activeMember == null ? TopLevel : MemberLevel);
if (lowPriority)
{
logAggregator.IncreaseCount(LowerPriority);
logAggregator.IncreaseCount(ValueTuple.Create(LowerPriority, documentId.Id));
}
}
foreach (var reason in reasons)
{
logAggregator.IncreaseCount(reason);
}
}
public static void LogHigherPriority(LogAggregator logAggregator, Guid documentId)
{
logAggregator.IncreaseCount(HigherPriority);
logAggregator.IncreaseCount(ValueTuple.Create(HigherPriority, documentId));
}
public static void LogResetStates(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(ResetStates);
}
public static void LogIncrementalAnalyzerProcessorStatistics(int correlationId, Solution solution, LogAggregator logAggregator, ImmutableArray<IIncrementalAnalyzer> analyzers)
{
Logger.Log(FunctionId.IncrementalAnalyzerProcessor_Shutdown, KeyValueLogMessage.Create(m =>
{
var solutionHash = GetSolutionHash(solution);
m[Id] = correlationId;
m[SolutionHash] = solutionHash.ToString();
var statMap = new Dictionary<string, List<int>>();
foreach (var kv in logAggregator)
{
if (kv.Key is string)
{
m[kv.Key.ToString()] = kv.Value.GetCount();
continue;
}
if (kv.Key is ValueTuple<string, Guid>)
{
var tuple = (ValueTuple<string, Guid>)kv.Key;
var list = statMap.GetOrAdd(tuple.Item1, _ => new List<int>());
list.Add(kv.Value.GetCount());
continue;
}
throw ExceptionUtilities.Unreachable;
}
foreach (var kv in statMap)
{
var key = kv.Key.ToString();
var result = LogAggregator.GetStatistics(kv.Value);
m[CreateProperty(key, Max)] = result.Maximum;
m[CreateProperty(key, Min)] = result.Minimum;
m[CreateProperty(key, Median)] = result.Median;
m[CreateProperty(key, Mean)] = result.Mean;
m[CreateProperty(key, Mode)] = result.Mode;
m[CreateProperty(key, Range)] = result.Range;
m[CreateProperty(key, Count)] = result.Count;
}
}));
foreach (var analyzer in analyzers)
{
var diagIncrementalAnalyzer = analyzer as DiagnosticIncrementalAnalyzer;
if (diagIncrementalAnalyzer != null)
{
diagIncrementalAnalyzer.LogAnalyzerCountSummary();
break;
}
}
}
private static int GetSolutionHash(Solution solution)
{
if (solution != null && solution.FilePath != null)
{
return solution.FilePath.ToLowerInvariant().GetHashCode();
}
return 0;
}
private static string CreateProperty(string parent, string child)
{
return parent + "." + child;
}
public static void LogProcessCloseDocument(LogAggregator logAggregator, Guid documentId)
{
logAggregator.IncreaseCount(CloseDocument);
logAggregator.IncreaseCount(ValueTuple.Create(CloseDocument, documentId));
}
public static void LogProcessOpenDocument(LogAggregator logAggregator, Guid documentId)
{
logAggregator.IncreaseCount(OpenDocument);
logAggregator.IncreaseCount(ValueTuple.Create(OpenDocument, documentId));
}
public static void LogProcessActiveFileDocument(LogAggregator logAggregator, Guid documentId, bool processed)
{
if (processed)
{
logAggregator.IncreaseCount(ActiveFileProcessDocument);
}
else
{
logAggregator.IncreaseCount(ActiveFileProcessDocumentCancellation);
}
}
public static void LogProcessDocument(LogAggregator logAggregator, Guid documentId, bool processed)
{
if (processed)
{
logAggregator.IncreaseCount(ProcessDocument);
}
else
{
logAggregator.IncreaseCount(ProcessDocumentCancellation);
}
logAggregator.IncreaseCount(ValueTuple.Create(ProcessDocument, documentId));
}
public static void LogProcessDocumentNotExist(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(DocumentNotExist);
}
public static void LogProcessProject(LogAggregator logAggregator, Guid projectId, bool processed)
{
if (processed)
{
logAggregator.IncreaseCount(ProcessProject);
}
else
{
logAggregator.IncreaseCount(ProcessProjectCancellation);
}
logAggregator.IncreaseCount(ValueTuple.Create(ProcessProject, projectId));
}
public static void LogProcessProjectNotExist(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(ProjectNotExist);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Text;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Intellisense;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
namespace Microsoft.PythonTools.Project {
internal class PythonFileNode : CommonFileNode {
internal PythonFileNode(CommonProjectNode root, ProjectElement e)
: base(root, e) { }
public override string Caption {
get {
var res = base.Caption;
if (res == "__init__.py" && Parent != null) {
StringBuilder fullName = new StringBuilder(res);
fullName.Append(" (");
GetPackageName(this, fullName);
fullName.Append(")");
res = fullName.ToString();
}
return res;
}
}
internal static void GetPackageName(HierarchyNode self, StringBuilder fullName) {
List<HierarchyNode> nodes = new List<HierarchyNode>();
var curNode = self.Parent;
do {
nodes.Add(curNode);
curNode = curNode.Parent;
} while (curNode != null && curNode.FindImmediateChildByName("__init__.py") != null);
for (int i = nodes.Count - 1; i >= 0; i--) {
fullName.Append(GetNodeNameForPackage(nodes[i]));
if (i != 0) {
fullName.Append('.');
}
}
}
private static string GetNodeNameForPackage(HierarchyNode node) {
var project = node as ProjectNode;
if (project != null) {
return CommonUtils.GetFileOrDirectoryName(project.ProjectHome);
} else {
return node.Caption;
}
}
internal override int ExecCommandOnNode(Guid guidCmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
Debug.Assert(this.ProjectMgr != null, "The Dynamic FileNode has no project manager");
Utilities.CheckNotNull(this.ProjectMgr);
if (guidCmdGroup == GuidList.guidPythonToolsCmdSet) {
switch (cmd) {
case CommonConstants.SetAsStartupFileCmdId:
// Set the StartupFile project property to the Url of this node
ProjectMgr.SetProjectProperty(
CommonConstants.StartupFile,
CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, Url)
);
return VSConstants.S_OK;
case CommonConstants.StartDebuggingCmdId:
case CommonConstants.StartWithoutDebuggingCmdId:
IProjectLauncher starter = ((CommonProjectNode)ProjectMgr).GetLauncher();
if (starter != null) {
if (!Utilities.SaveDirtyFiles()) {
// Abort
return VSConstants.E_ABORT;
}
var starter2 = starter as IProjectLauncher2;
if (starter2 != null) {
starter2.LaunchFile(
this.Url,
cmd == CommonConstants.StartDebuggingCmdId,
new Microsoft.PythonTools.Commands.StartScriptCommand.LaunchFileProperties(
null,
CommonUtils.GetParent(this.Url),
((PythonProjectNode)ProjectMgr).GetInterpreterFactory().Configuration.PathEnvironmentVariable,
ProjectMgr.GetWorkingDirectory()
)
);
} else {
starter.LaunchFile(this.Url, cmd == CommonConstants.StartDebuggingCmdId);
}
}
return VSConstants.S_OK;
}
}
return base.ExecCommandOnNode(guidCmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
internal override int QueryStatusOnNode(Guid guidCmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) {
if (guidCmdGroup == GuidList.guidPythonToolsCmdSet) {
if (this.ProjectMgr.IsCodeFile(this.Url)) {
switch (cmd) {
case CommonConstants.SetAsStartupFileCmdId:
//We enable "Set as StartUp File" command only on current language code files,
//the file is in project home dir and if the file is not the startup file already.
string startupFile = ((CommonProjectNode)ProjectMgr).GetStartupFile();
if (IsInProjectHome() &&
!CommonUtils.IsSamePath(startupFile, Url) &&
!IsNonMemberItem) {
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
}
return VSConstants.S_OK;
case CommonConstants.StartDebuggingCmdId:
case CommonConstants.StartWithoutDebuggingCmdId:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
}
return base.QueryStatusOnNode(guidCmdGroup, cmd, pCmdText, ref result);
}
private bool IsInProjectHome() {
HierarchyNode parent = this.Parent;
while (parent != null) {
if (parent is CommonSearchPathNode) {
return false;
}
parent = parent.Parent;
}
return true;
}
private void TryDelete(string filename) {
if (!File.Exists(filename)) {
return;
}
var node = ((PythonProjectNode)ProjectMgr).FindNodeByFullPath(filename);
if (node != null) {
if (node.IsNonMemberItem) {
node.Remove(true);
}
return;
}
try {
File.Delete(filename);
} catch (IOException) {
} catch (UnauthorizedAccessException) {
} catch (SecurityException) {
}
}
public override void Remove(bool removeFromStorage) {
((PythonProjectNode)ProjectMgr).GetAnalyzer().UnloadFile(GetProjectEntry());
if (Url.EndsWith(PythonConstants.FileExtension, StringComparison.OrdinalIgnoreCase) && removeFromStorage) {
TryDelete(Url + "c");
TryDelete(Url + "o");
}
base.Remove(removeFromStorage);
}
public override string GetEditLabel() {
if (IsLinkFile) {
// cannot rename link files
return null;
}
// dispatch to base class which doesn't include package name, just filename.
return base.Caption;
}
public override string FileName {
get {
return base.Caption;
}
set {
base.FileName = value;
}
}
public IProjectEntry GetProjectEntry() {
var textBuffer = GetTextBuffer(false);
IProjectEntry entry;
if (textBuffer != null && textBuffer.TryGetProjectEntry(out entry)) {
return entry;
}
return ((PythonProjectNode)this.ProjectMgr).GetAnalyzer().GetEntryFromFile(Url);
}
private void TryRename(string oldFile, string newFile) {
if (!File.Exists(oldFile) || File.Exists(newFile)) {
return;
}
var node = ((PythonProjectNode)ProjectMgr).FindNodeByFullPath(oldFile);
if (node != null && !node.IsNonMemberItem) {
return;
}
try {
File.Move(oldFile, newFile);
} catch (IOException) {
} catch (UnauthorizedAccessException) {
} catch (SecurityException) {
}
}
internal override FileNode RenameFileNode(string oldFileName, string newFileName) {
var res = base.RenameFileNode(oldFileName, newFileName);
if (newFileName.EndsWith(PythonConstants.FileExtension, StringComparison.OrdinalIgnoreCase)) {
TryRename(oldFileName + "c", newFileName + "c");
TryRename(oldFileName + "o", newFileName + "o");
}
if (res != null) {
var analyzer = ((PythonProjectNode)this.ProjectMgr).GetAnalyzer();
var analysis = GetProjectEntry();
if (analysis != null) {
analyzer.UnloadFile(analysis);
}
var textBuffer = GetTextBuffer(false);
BufferParser parser;
if (textBuffer != null && textBuffer.Properties.TryGetProperty<BufferParser>(typeof(BufferParser), out parser)) {
analyzer.ReAnalyzeTextBuffers(parser);
}
}
return res;
}
internal override int IncludeInProject(bool includeChildren) {
var analyzer = ((PythonProjectNode)this.ProjectMgr).GetAnalyzer();
analyzer.AnalyzeFile(Url);
return base.IncludeInProject(includeChildren);
}
internal override int ExcludeFromProject() {
var analyzer = ((PythonProjectNode)this.ProjectMgr).GetAnalyzer();
var analysis = GetProjectEntry();
if (analysis != null) {
analyzer.UnloadFile(analysis);
}
return base.ExcludeFromProject();
}
protected override ImageMoniker CodeFileIconMoniker {
get { return KnownMonikers.PYFileNode; }
}
protected override ImageMoniker StartupCodeFileIconMoniker {
get { return KnownMonikers.PYFileNode; }
}
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Threading;
using Overflow.Test.Fakes;
using Overflow.Test.TestingInfrastructure;
using Ploeh.AutoFixture;
using Xunit;
namespace Overflow.Test
{
public class TextWriterWorkflowLoggerTests : TestBase
{
[Fact]
public void Logging_an_operation_start_writes_the_operation_type_to_the_output()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
Assert.Equal("FakeOperation", sw.ToString());
}
}
[Fact]
public void Guards_are_verified()
{
Fixture.Register(() => Console.Out);
VerifyGuards<TextWriterWorkflowLogger>();
}
[Fact]
public void Logging_an_operation_start_and_finish_writes_the_operation_type_to_the_output()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
Assert.Equal("FakeOperation [duration: 0ms]", sw.ToString());
}
}
[Fact]
public void The_execution_duration_is_added_in_milliseconds()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.FromMilliseconds(15));
Assert.Equal("FakeOperation [duration: 15ms]", sw.ToString());
}
}
[Fact]
public void Log_durations_are_properly_formatted_according_to_cultures_using_period_as_thousands_seperator()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK");
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.FromMilliseconds(1500000));
Assert.Equal("FakeOperation [duration: 1.500.000ms]", sw.ToString());
}
}
[Fact]
public void Log_durations_are_properly_formatted_according_to_cultures_using_comma_as_thousands_seperator()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.FromMilliseconds(1500000));
Assert.Equal("FakeOperation [duration: 1,500,000ms]", sw.ToString());
}
}
[Fact]
public void Logging_an_operation_start_before_the_previous_operation_was_finished_writes_a_beggining_brace_and_the_new_operation_type_indented_to_the_output()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationStarted(new FakeOperation());
Assert.Equal($"FakeOperation {{{NL} FakeOperation", sw.ToString());
}
}
[Fact]
public void Logging_an_operation_starting_and_finishing_within_another_operation_start_and_finish_writes_the_inner_operation_type_name_nested_in_braces_to_the_output()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
Assert.Equal($"FakeOperation {{{NL} FakeOperation [duration: 0ms]{NL}}} [duration: 0ms]", sw.ToString());
}
}
[Fact]
public void Logging_multiple_operation_on_the_same_level_adds_a_seperation_line_between_them()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
Assert.Equal($"FakeOperation {{{NL} FakeOperation [duration: 0ms]{NL}{NL} FakeOperation [duration: 0ms]{NL}}} [duration: 0ms]", sw.ToString());
}
}
[Fact]
public void Nesting_increased_by_two_speces_for_every_started_unfinished_operation()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationStarted(new FakeOperation());
sut.OperationStarted(new FakeOperation());
sut.OperationStarted(new FakeOperation());
Assert.Equal($"FakeOperation {{{NL} FakeOperation {{{NL} FakeOperation {{{NL} FakeOperation", sw.ToString());
}
}
[Fact]
public void Failures_are_logged_nested_between_braces()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationFailed(new FakeOperation(), new InvalidOperationException("MESSAGE"));
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
Assert.Equal($"FakeOperation {{{NL} Error [InvalidOperationException]: MESSAGE{NL}}} [duration: 0ms]", sw.ToString());
}
}
[Fact]
public void Failures_are_correctly_indented_after_a_sibling_operation()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
sut.OperationFailed(new FakeOperation(), new InvalidOperationException("MESSAGE"));
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
Assert.Equal($"FakeOperation {{{NL} FakeOperation [duration: 0ms]{NL}{NL} Error [InvalidOperationException]: MESSAGE{NL}}} [duration: 0ms]", sw.ToString());
}
}
[Fact]
public void You_cannot_log_a_failure_without_a_started_operation()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
Assert.Throws<InvalidOperationException>(() => sut.OperationFailed(new FakeOperation(), new Exception()));
}
}
[Fact]
public void You_cannot_log_a_failure_when_the_last_operation_has_been_logged_as_finished()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
Assert.Throws<InvalidOperationException>(() => sut.OperationFailed(new FakeOperation(), new Exception()));
}
}
[Fact]
public void You_cannot_log_a_finished_operation_without_a_started_operation()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
Assert.Throws<InvalidOperationException>(() => sut.OperationFinished(new FakeOperation(), TimeSpan.Zero));
}
}
[Fact]
public void You_cannot_log_a_finished_operation_when_the_last_operation_has_already_been_logged_as_finished()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
Assert.Throws<InvalidOperationException>(() => sut.OperationFinished(new FakeOperation(), TimeSpan.Zero));
}
}
[Fact]
public void Behaviors_are_logged_nested_between_braces()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.BehaviorWasApplied(new FakeOperation(), new FakeOperationBehavior(), "DESCRIPTION");
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
Assert.Equal($"FakeOperation {{{NL} FakeOperationBehavior: DESCRIPTION{NL}}} [duration: 0ms]", sw.ToString());
}
}
[Fact]
public void Behaviors_are_correctly_indented_after_a_sibling_operation()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
sut.BehaviorWasApplied(new FakeOperation(), new FakeOperationBehavior(), "DESCRIPTION");
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
Assert.Equal($"FakeOperation {{{NL} FakeOperation [duration: 0ms]{NL}{NL} FakeOperationBehavior: DESCRIPTION{NL}}} [duration: 0ms]", sw.ToString());
}
}
[Fact]
public void You_cannot_log_a_behavior_without_a_started_operation()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
Assert.Throws<InvalidOperationException>(() => sut.BehaviorWasApplied(new FakeOperation(), new FakeOperationBehavior(), "DESCRIPTION"));
}
}
[Fact]
public void You_cannot_log_a_behavior_when_the_last_operation_has_been_logged_as_finished()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
Assert.Throws<InvalidOperationException>(() => sut.BehaviorWasApplied(new FakeOperation(), new FakeOperationBehavior(), "DESCRIPTION"));
}
}
[Fact]
public void Nested_operations_are_correctly_indented()
{
using (var sw = new StringWriter())
{
var sut = new TextWriterWorkflowLogger(sw);
sut.OperationStarted(new FakeOperation());
sut.OperationStarted(new FakeOperation());
sut.OperationStarted(new FakeOperation());
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
sut.OperationFinished(new FakeOperation(), TimeSpan.Zero);
Assert.Equal($"FakeOperation {{{NL} FakeOperation {{{NL} FakeOperation [duration: 0ms]{NL} }} [duration: 0ms]{NL}}} [duration: 0ms]", sw.ToString());
}
}
}
}
| |
// MvxRestClient.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, [email protected]
using MvvmCross.Platform;
using MvvmCross.Platform.Exceptions;
using System;
using System.Collections.Generic;
using System.Net;
namespace MvvmCross.Plugins.Network.Rest
{
public class MvxRestClient : IMvxRestClient
{
protected static void TryCatch(Action toTry, Action<Exception> errorAction)
{
try
{
toTry();
}
catch (Exception exception)
{
errorAction?.Invoke(exception);
}
}
protected Dictionary<string, object> Options { set; private get; }
public MvxRestClient()
{
Options = new Dictionary<string, object>
{
{MvxKnownOptions.ForceWindowsPhoneToUseCompression, "true"}
};
}
public void ClearSetting(string key)
{
try
{
Options.Remove(key);
}
catch (KeyNotFoundException)
{
// ignored - not a problem
}
}
public void SetSetting(string key, object value)
{
Options[key] = value;
}
public IMvxAbortable MakeRequest(MvxRestRequest restRequest, Action<MvxStreamRestResponse> successAction, Action<Exception> errorAction)
{
HttpWebRequest httpRequest = null;
TryCatch(() =>
{
httpRequest = BuildHttpRequest(restRequest);
Action processResponse = () => ProcessResponse(restRequest, httpRequest, successAction, errorAction);
if (restRequest.NeedsRequestStream)
{
ProcessRequestThen(restRequest, httpRequest, processResponse, errorAction);
}
else
{
processResponse();
}
}, errorAction);
return httpRequest != null ? new MvxRestRequestAsyncHandle(httpRequest) : null;
}
public IMvxAbortable MakeRequest(MvxRestRequest restRequest, Action<MvxRestResponse> successAction, Action<Exception> errorAction)
{
HttpWebRequest httpRequest = null;
TryCatch(() =>
{
httpRequest = BuildHttpRequest(restRequest);
Action processResponse = () => ProcessResponse(restRequest, httpRequest, successAction, errorAction);
if (restRequest.NeedsRequestStream)
{
ProcessRequestThen(restRequest, httpRequest, processResponse, errorAction);
}
else
{
processResponse();
}
}, errorAction);
return httpRequest != null ? new MvxRestRequestAsyncHandle(httpRequest) : null;
}
protected virtual HttpWebRequest BuildHttpRequest(MvxRestRequest restRequest)
{
var httpRequest = CreateHttpWebRequest(restRequest);
SetMethod(restRequest, httpRequest);
SetContentType(restRequest, httpRequest);
SetUserAgent(restRequest, httpRequest);
SetAccept(restRequest, httpRequest);
SetCookieContainer(restRequest, httpRequest);
SetCredentials(restRequest, httpRequest);
SetCustomHeaders(restRequest, httpRequest);
SetPlatformSpecificProperties(restRequest, httpRequest);
return httpRequest;
}
private static void SetCustomHeaders(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
if (restRequest.Headers != null)
{
foreach (var kvp in restRequest.Headers)
{
httpRequest.Headers[kvp.Key] = kvp.Value;
}
}
}
protected virtual void SetCredentials(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
if (restRequest.Credentials != null)
{
httpRequest.Credentials = restRequest.Credentials;
}
}
protected virtual void SetCookieContainer(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
// note that we don't call
// httpRequest.SupportsCookieContainer
// here - this is because Android complained about this...
try
{
if (restRequest.CookieContainer != null)
{
httpRequest.CookieContainer = restRequest.CookieContainer;
}
}
catch (Exception exception)
{
Mvx.Warning("Error masked during Rest call - cookie creation - {0}", exception.ToLongString());
}
}
protected virtual void SetAccept(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
if (!string.IsNullOrEmpty(restRequest.Accept))
{
httpRequest.Accept = restRequest.Accept;
}
}
protected virtual void SetUserAgent(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
if (!string.IsNullOrEmpty(restRequest.UserAgent))
{
httpRequest.Headers["user-agent"] = restRequest.UserAgent;
}
}
protected virtual void SetContentType(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
if (!string.IsNullOrEmpty(restRequest.ContentType))
{
httpRequest.ContentType = restRequest.ContentType;
}
}
protected virtual void SetMethod(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
httpRequest.Method = restRequest.Verb;
}
protected virtual HttpWebRequest CreateHttpWebRequest(MvxRestRequest restRequest)
{
return (HttpWebRequest)WebRequest.Create(restRequest.Uri);
}
protected virtual void SetPlatformSpecificProperties(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
// do nothing by default
}
protected virtual void ProcessResponse(
MvxRestRequest restRequest,
HttpWebRequest httpRequest,
Action<MvxRestResponse> successAction,
Action<Exception> errorAction)
{
httpRequest.BeginGetResponse(result =>
TryCatch(() =>
{
var response = (HttpWebResponse)httpRequest.EndGetResponse(result);
var code = response.StatusCode;
var restResponse = new MvxRestResponse
{
CookieCollection = response.Cookies,
Tag = restRequest.Tag,
StatusCode = code
};
successAction?.Invoke(restResponse);
}, errorAction)
, null);
}
protected virtual void ProcessResponse(
MvxRestRequest restRequest,
HttpWebRequest httpRequest,
Action<MvxStreamRestResponse> successAction,
Action<Exception> errorAction)
{
httpRequest.BeginGetResponse(result =>
TryCatch(() =>
{
var response = (HttpWebResponse)httpRequest.EndGetResponse(result);
var code = response.StatusCode;
var responseStream = response.GetResponseStream();
var restResponse = new MvxStreamRestResponse
{
CookieCollection = response.Cookies,
Stream = responseStream,
Tag = restRequest.Tag,
StatusCode = code
};
successAction?.Invoke(restResponse);
}, errorAction)
, null);
}
protected virtual void ProcessRequestThen(
MvxRestRequest restRequest,
HttpWebRequest httpRequest,
Action continueAction,
Action<Exception> errorAction)
{
httpRequest.BeginGetRequestStream(result =>
TryCatch(() =>
{
using (var stream = httpRequest.EndGetRequestStream(result))
{
restRequest.ProcessRequestStream(stream);
stream.Flush();
}
continueAction?.Invoke();
}, errorAction)
, null);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.at_dynamic001.at_dynamic001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.at_dynamic001.at_dynamic001;
// <Area> Implicitly Typed Local variables </Area>
// <Title> Referring to @dynamic will always refer to the type and will give no warning </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
@dynamic x = new dynamic();
if (!x.GetType().Equals(typeof(dynamic)))
{
return 1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamicfieldorlocal002.dynamicfieldorlocal002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamicfieldorlocal002.dynamicfieldorlocal002;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Can use var as the name of a local variable or field </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class C
{
private int _dynamic = 1;
public int M()
{
_dynamic = 2;
dynamic i = 3;
return (int)i + _dynamic;
}
}
public class D
{
public int M()
{
int dynamic = 4;
dynamic i = 5;
return (int)i + dynamic;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
C c = new C();
D d = new D();
if (c.M() != 5)
{
return -1;
}
if (d.M() != 9)
{
return -1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared001.dynamictypedeclared001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared001.dynamictypedeclared001;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Referring to a type named var in a method body should not give a warning</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
public int i = 0;
}
public class A
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic x = new dynamic();
dynamic y = null;
dynamic z;
if (x.i != 0)
return -1;
if (y != null)
return -1;
JustToGetRidOfWarning(out z);
return 0;
}
private static void JustToGetRidOfWarning(out dynamic z)
{
z = null;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared002.dynamictypedeclared002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared002.dynamictypedeclared002;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Returning a type named var from a function member should give no warnings</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
public dynamic(int i)
{
this.i = i;
}
public int i = 0;
}
public class Test
{
private dynamic MyMethod(int i)
{
return new dynamic(i);
}
private dynamic _mydynamic;
public dynamic MyProperty
{
get
{
return _mydynamic;
}
set
{
_mydynamic = value;
}
}
public dynamic this[int index]
{
get
{
return new dynamic(index);
}
set
{ /* set the specified index to value here */
}
}
public static dynamic operator +(Test i, int j)
{
return new dynamic(j);
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test test = new Test();
if (test.MyMethod(1).i != 1)
{
return -1;
}
test.MyProperty = new dynamic(2);
if (test.MyProperty.i != 2)
{
return -1;
}
if (test[3].i != 3)
{
return -1;
}
if ((test + 4).i != 4)
{
return -1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared003.dynamictypedeclared003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared003.dynamictypedeclared003;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Function members containing formal parameters of type var should not give a warning</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
public dynamic(int i)
{
this.i = i;
}
public int i = 0;
public static int operator +(dynamic v1, dynamic v2)
{
return v1.i + v2.i;
}
}
public class Test
{
private int MyMethod(dynamic v)
{
return v.i;
}
public int this[dynamic v]
{
get
{
return v.i;
}
set
{ /* set the specified index to value here */
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test test = new Test();
@dynamic v1 = new dynamic(1);
if (test.MyMethod(v1) != 1)
{
return -1;
}
@dynamic v2 = new dynamic(2);
if (test[v2] != 2)
{
return -1;
}
@dynamic v3 = new dynamic(3);
if ((v1 + v2) != 3)
{
return -1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared004.dynamictypedeclared004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared004.dynamictypedeclared004;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var type as type constraint gives no warnings</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
}
public class G<T>
where T : dynamic
{
public R M<R>(R r) where R : dynamic
{
return r;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared005.dynamictypedeclared005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared005.dynamictypedeclared005;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var type in a nullable type declaration gives no warnings </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public struct dynamic
{
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic? v = null;
if (v != null)
{
return 1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared006.dynamictypedeclared006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared006.dynamictypedeclared006;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var type in an array type gives no errors </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
}
public class D : dynamic
{
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic[] dynamicr = new dynamic[4];
if (dynamicr.Length != 4)
{
return -1;
}
dynamic[][] dynamicr2 = new dynamic[3][];
if (dynamicr2.Length != 3)
{
return -1;
}
;
D x = new D();
dynamic[,] dynamicr3 =
{
{
x, x
}
, {
x, x
}
, {
x, x
}
}
;
if (dynamicr3.Length != 6)
{
return -1;
}
;
if (!(dynamicr3[0, 0].Equals(x)))
{
return -1;
}
;
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared007.dynamictypedeclared007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared007.dynamictypedeclared007;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var type in a generic type declaration gives no warnings </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic<T>
{
public T GetT()
{
return default(T);
}
}
public class dynamic<T, S>
{
public T GetT()
{
return default(T);
}
public S GetS()
{
return default(S);
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic<int> v1 = new dynamic<int>();
if (!v1.GetT().GetType().Equals(typeof(int)))
{
return -1;
}
dynamic<char, short> v2 = new dynamic<char, short>();
if (!v2.GetT().GetType().Equals(typeof(char)))
{
return -1;
}
if (!v2.GetS().GetType().Equals(typeof(short)))
{
return -1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared008.dynamictypedeclared008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared008.dynamictypedeclared008;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var type in typeof expression gives no warnings</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
}
public class Test
{
private static dynamic s_v = new dynamic();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (!s_v.GetType().Equals(typeof(dynamic)))
{
return 1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared009.dynamictypedeclared009
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared009.dynamictypedeclared009;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var type as operand in 'as' or 'is' operator gives no warnings</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
}
public class Test
{
private static dynamic s_v1 = new dynamic();
private static dynamic s_v2;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
s_v2 = s_v1 as dynamic;
if (!(s_v1 is dynamic))
{
return -1;
}
if (!(s_v2 is dynamic))
{
return -1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared010.dynamictypedeclared010
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared010.dynamictypedeclared010;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var type in cast expression gives no warnings</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
}
public class Test
{
private static dynamic s_v1;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
object o = new dynamic();
s_v1 = (dynamic)o;
if (s_v1 != o)
{
return -1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared011.dynamictypedeclared011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared011.dynamictypedeclared011;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var as a type argument gives no warnings </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
}
public class G<T>
where T : new()
{
public T V = new T();
public R M<R>() where R : new()
{
return new R();
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
G<dynamic> g = new G<dynamic>();
if (!g.V.GetType().Equals(typeof(dynamic)))
{
return -1;
}
if (!g.M<dynamic>().GetType().Equals(typeof(dynamic)))
{
return -1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared012.dynamictypedeclared012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared012.dynamictypedeclared012;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var as a type parameter gives no warnings</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class G<dynamic>
where dynamic : new()
{
public dynamic V = new dynamic();
}
public class C
{
public dynamic M<dynamic>() where dynamic : new()
{
return new dynamic();
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
G<C> g = new G<C>();
if (!g.V.GetType().Equals(typeof(C)))
{
return -1;
}
C c = new C();
if (!c.M<C>().GetType().Equals(typeof(C)))
{
return -1;
}
NS.G2<NS.C2> g2 = new NS.G2<NS.C2>();
if (!g2.V.GetType().Equals(typeof(NS.C2)))
{
return -1;
}
NS.C2 c2 = new NS.C2();
if (!c2.M<NS.C2>().GetType().Equals(typeof(NS.C2)))
{
return -1;
}
return 0;
}
}
namespace NS
{
public class dynamic
{
}
public class G2<dynamic>
where dynamic : new()
{
public dynamic V = new dynamic();
}
public class C2
{
public dynamic M<dynamic>() where dynamic : new()
{
return new dynamic();
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared013.dynamictypedeclared013
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared013.dynamictypedeclared013;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> When a type named var is defined, using var as a type parameter gives no warnings</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
}
public class G<dynamic>
where dynamic : new()
{
public dynamic V = new dynamic();
}
public class C
{
public dynamic M<dynamic>() where dynamic : new()
{
return new dynamic();
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
G<C> g = new G<C>();
if (!g.V.GetType().Equals(typeof(C)))
{
return -1;
}
C c = new C();
if (!c.M<C>().GetType().Equals(typeof(C)))
{
return -1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared014.dynamictypedeclared014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared014.dynamictypedeclared014;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var type in a delegate type gives no warnings</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
}
internal delegate dynamic D(dynamic v);
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
D d = delegate (dynamic v)
{
return new dynamic();
}
;
if (!d(new dynamic()).GetType().Equals(typeof(dynamic)))
{
return -1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared015.dynamictypedeclared015
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared015.dynamictypedeclared015;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var type as the referent type in a pointer gives no warnings </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
//public struct dynamic
//{
//}
//[TestClass]
//public unsafe class Test
//{
// [Test]
// [Priority(Priority.Priority2)]
// public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod()); }
// public static int MainMethod()
// {
// @dynamic v = new dynamic();
// dynamic* vp = &v;
// if (!vp->GetType().Equals(typeof(dynamic)))
// {
// return -1;
// }
// return 0;
// }
//}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared016.dynamictypedeclared016
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared016.dynamictypedeclared016;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Declaring a const var gives no warning</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
internal enum dynamic
{
foo,
bar
}
public class A
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
const dynamic x = dynamic.foo;
if (!x.GetType().Equals(typeof(dynamic)))
{
return -1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared017.dynamictypedeclared017
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared017.dynamictypedeclared017;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var type as the operand of the default operator </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class dynamic
{
}
public class A
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
object v = default(dynamic);
if (v != null)
{
return -1;
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared018.dynamictypedeclared018
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared018.dynamictypedeclared018;
// <Area> Implicitly Typed Local Variables </Area>
// <Title> Using var type as the type of an event </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
public class A
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
A a = new A();
int c = 0;
a.MyEvent += delegate (int i)
{
c += i;
}
;
a.MyEvent(1);
a.MyEvent(2);
if (c != 3)
{
return -1;
}
return 0;
}
private event dynamic MyEvent;
private delegate void dynamic(int i);
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared019.dynamictypedeclared019
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared019.dynamictypedeclared019;
public class Test
{
public class dynamic
{
public int Foo()
{
return 0;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
var d = new dynamic();
return d.Foo();
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared021.dynamictypedeclared021
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared021.dynamictypedeclared021;
// <Title> Interaction between object and dynamic</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class App
{
public class dynamic
{
public int Foo()
{
return 0;
}
}
public class Test
{
public dynamic Bar()
{
return new dynamic();
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Test t = new Test();
dynamic d = t.Bar();
return d.Foo(); //This should not have anything dynamic
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared023.dynamictypedeclared023
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamictypedeclared023.dynamictypedeclared023;
public class Test
{
public class dynamic
{
public int Foo()
{
return 0;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new dynamic();
return d.Foo();
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.errorverifier.errorverifier
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.variablenameddynamic001.variablenameddynamic001;
using System;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Resources;
using Microsoft.CSharp.RuntimeBinder;
public enum ErrorElementId
{
None,
SK_METHOD, // method
SK_CLASS, // type
SK_NAMESPACE, // namespace
SK_FIELD, // field
SK_PROPERTY, // property
SK_UNKNOWN, // element
SK_VARIABLE, // variable
SK_EVENT, // event
SK_TYVAR, // type parameter
SK_ALIAS, // using alias
ERRORSYM, // <error>
NULL, // <null>
GlobalNamespace, // <global namespace>
MethodGroup, // method group
AnonMethod, // anonymous method
Lambda, // lambda expression
AnonymousType, // anonymous type
}
public enum ErrorMessageId
{
None,
BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'
IntDivByZero, // Division by constant zero
BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}'
BadIndexCount, // Wrong number of indices inside []; expected '{0}'
BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}'
NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}'
NoExplicitConv, // Cannot convert type '{0}' to '{1}'
ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}'
AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'
AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}'
ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type
WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}'
NoSuchMember, // '{0}' does not contain a definition for '{1}'
ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}'
AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}'
BadAccess, // '{0}' is inaccessible due to its protection level
MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}'
AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer
NoConstructors, // The type '{0}' has no constructors defined
BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor
PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor
ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead
AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer)
RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor)
AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only
AbstractBaseCall, // Cannot call an abstract base member: '{0}'
RefProperty, // A property or indexer may not be passed as an out or ref parameter
ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')
FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression
UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers
BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters
MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false
CheckedOverflow, // The operation overflows at compile time in checked mode
ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override)
AmbigMember, // Ambiguity between '{0}' and '{1}'
SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}'
CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.
CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor.
BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression
NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?)
InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible
InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible
BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments
BadTypeArgument, // The type '{0}' may not be used as a type argument
TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments
HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments
NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}'
GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'.
GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints.
GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'.
TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.
BadRetType, // '{1} {0}' has the wrong return type
CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.
MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?
RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'
ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}'
CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}'
BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}'
ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}'
AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}'
PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported
PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly
BindToBogus, // '{0}' is not supported by the language
CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor
BogusType, // '{0}' is a type not supported by the language
MissingPredefinedMember, // Missing compiler required member '{0}.{1}'
LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type
UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions
ConvertToStaticClass, // Cannot convert to static type '{0}'
GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments
PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration
IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer
NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?)
ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates
BadArgCount, // No overload for method '{0}' takes '{1}' arguments
BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments
BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}'
RefLvalueExpected, // A ref or out argument must be an assignable variable
BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it)
BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}'
BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}'
BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments
BadDelArgTypes, // Delegate '{0}' has some invalid arguments
AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only
RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only
ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable
BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword
// DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED)
BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword
AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer)
RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor)
AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}'
RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}'
ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead.
DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>'
BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments
BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments
BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}'
BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments
InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.
NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method.
NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified
BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}'
BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}'
DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times
NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given
}
public enum RuntimeErrorId
{
None,
// RuntimeBinderInternalCompilerException
InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation
// ArgumentException
BindRequireArguments, // Cannot bind call with no calling object
// RuntimeBinderException
BindCallFailedOverloadResolution, // Overload resolution failed
// ArgumentException
BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments
// ArgumentException
BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument
// RuntimeBinderException
BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property
// RuntimeBinderException
BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -=
// RuntimeBinderException
BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type
// ArgumentException
BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument
// ArgumentException
BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument
// ArgumentException
BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument
// RuntimeBinderException
BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference
// RuntimeBinderException
NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference
// RuntimeBinderException
BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute
// RuntimeBinderException
BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object'
// EE?
EmptyDynamicView, // No further information on this object could be discovered
// MissingMemberException
GetValueonWriteOnlyProperty, // Write Only properties are not supported
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.variablenameddynamic001.variablenameddynamic001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.variablenameddynamic001.variablenameddynamic001;
// <Title> Interaction between object and dynamic</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class App
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
int dynamic = 3;
dynamic d = dynamic;
try
{
d.Foo();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamicnsdeclared.dynamicnsdeclared
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.backwardscompatible.dynamicnsdeclared.dynamicnsdeclared;
// <Title>declare dynamic namespace</Title>
// <Description>regression test
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(12,13\).*CS0219</Expects>
public class A
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var x = 1; // OK
dynamic y = 1; // error CS0118: 'dynamic' is a 'namespace' but is used like a 'type'
return 0;
}
}
namespace var
{
}
namespace dynamic
{
}
// </Code>
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace System.DirectoryServices.AccountManagement
{
#if TESTHOOK
public class AccountInfo
#else
internal class AccountInfo
#endif
{
//
// Properties exposed to the public through AuthenticablePrincipal
//
// AccountLockoutTime
private Nullable<DateTime> _accountLockoutTime = null;
private LoadState _accountLockoutTimeLoaded = LoadState.NotSet;
public Nullable<DateTime> AccountLockoutTime
{
[System.Security.SecurityCritical]
get
{
return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _accountLockoutTime, PropertyNames.AcctInfoAcctLockoutTime, ref _accountLockoutTimeLoaded);
}
}
// LastLogon
private Nullable<DateTime> _lastLogon = null;
private LoadState _lastLogonLoaded = LoadState.NotSet;
public Nullable<DateTime> LastLogon
{
[System.Security.SecurityCritical]
get
{
return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _lastLogon, PropertyNames.AcctInfoLastLogon, ref _lastLogonLoaded);
}
}
// PermittedWorkstations
private PrincipalValueCollection<string> _permittedWorkstations = new PrincipalValueCollection<string>();
private LoadState _permittedWorkstationsLoaded = LoadState.NotSet;
public PrincipalValueCollection<string> PermittedWorkstations
{
[System.Security.SecurityCritical]
get
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoPermittedWorkstations))
throw new InvalidOperationException(StringResources.InvalidPropertyForStore);
return _owningPrincipal.HandleGet<PrincipalValueCollection<string>>(ref _permittedWorkstations, PropertyNames.AcctInfoPermittedWorkstations, ref _permittedWorkstationsLoaded);
}
}
// PermittedLogonTimes
// We have to handle the change-tracking for this differently than for the other properties, because
// a byte[] is mutable. After calling the get accessor, the app can change the permittedLogonTimes,
// without needing to ever call the set accessor. Therefore, rather than a simple "changed" flag set
// by the set accessor, we need to track the original value of the property, and flag it as changed
// if current value != original value.
private byte[] _permittedLogonTimes = null;
private byte[] _permittedLogonTimesOriginal = null;
private LoadState _permittedLogonTimesLoaded = LoadState.NotSet;
public byte[] PermittedLogonTimes
{
[System.Security.SecurityCritical]
get
{
return _owningPrincipal.HandleGet<byte[]>(ref _permittedLogonTimes, PropertyNames.AcctInfoPermittedLogonTimes, ref _permittedLogonTimesLoaded);
}
[System.Security.SecurityCritical]
set
{
// We don't use HandleSet<T> here because of the slightly non-standard implementation of the change-tracking
// for this property.
// Check that we actually support this propery in our store
//this.owningPrincipal.CheckSupportedProperty(PropertyNames.AcctInfoPermittedLogonTimes);
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoPermittedLogonTimes))
throw new InvalidOperationException(StringResources.InvalidPropertyForStore);
// If we get to this point we know that the value of the property has changed and we should not load it from the store.
// If value is retrived the state is set to loaded. Even if user modifies the reference we will
// not overwrite it because we mark it as loaded.
// If the user sets it before reading it we mark it as changed. When the users accesses it we just return the current
// value. All change tracking to the store is done off of an actual object comparison because users can change the value
// either through property set or modifying the reference returned.
_permittedLogonTimesLoaded = LoadState.Changed;
_permittedLogonTimes = value;
}
}
// AccountExpirationDate
private Nullable<DateTime> _expirationDate = null;
private LoadState _expirationDateChanged = LoadState.NotSet;
public Nullable<DateTime> AccountExpirationDate
{
[System.Security.SecurityCritical]
get
{
return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _expirationDate, PropertyNames.AcctInfoExpirationDate, ref _expirationDateChanged);
}
[System.Security.SecurityCritical]
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoExpirationDate))
throw new InvalidOperationException(StringResources.InvalidPropertyForStore);
_owningPrincipal.HandleSet<Nullable<DateTime>>(ref _expirationDate, value, ref _expirationDateChanged,
PropertyNames.AcctInfoExpirationDate);
}
}
// SmartcardLogonRequired
private bool _smartcardLogonRequired = false;
private LoadState _smartcardLogonRequiredChanged = LoadState.NotSet;
public bool SmartcardLogonRequired
{
[System.Security.SecurityCritical]
get
{
return _owningPrincipal.HandleGet<bool>(ref _smartcardLogonRequired, PropertyNames.AcctInfoSmartcardRequired, ref _smartcardLogonRequiredChanged);
}
[System.Security.SecurityCritical]
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoSmartcardRequired))
throw new InvalidOperationException(StringResources.InvalidPropertyForStore);
_owningPrincipal.HandleSet<bool>(ref _smartcardLogonRequired, value, ref _smartcardLogonRequiredChanged,
PropertyNames.AcctInfoSmartcardRequired);
}
}
// DelegationPermitted
private bool _delegationPermitted = false;
private LoadState _delegationPermittedChanged = LoadState.NotSet;
public bool DelegationPermitted
{
[System.Security.SecurityCritical]
get
{
return _owningPrincipal.HandleGet<bool>(ref _delegationPermitted, PropertyNames.AcctInfoDelegationPermitted, ref _delegationPermittedChanged);
}
[System.Security.SecurityCritical]
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoDelegationPermitted))
throw new InvalidOperationException(StringResources.InvalidPropertyForStore);
_owningPrincipal.HandleSet<bool>(ref _delegationPermitted, value, ref _delegationPermittedChanged,
PropertyNames.AcctInfoDelegationPermitted);
}
}
// BadLogonCount
private int _badLogonCount = 0;
private LoadState _badLogonCountChanged = LoadState.NotSet;
public int BadLogonCount
{
[System.Security.SecurityCritical]
get
{
return _owningPrincipal.HandleGet<int>(ref _badLogonCount, PropertyNames.AcctInfoBadLogonCount, ref _badLogonCountChanged);
}
}
// HomeDirectory
private string _homeDirectory = null;
private LoadState _homeDirectoryChanged = LoadState.NotSet;
public string HomeDirectory
{
[System.Security.SecurityCritical]
get
{
return _owningPrincipal.HandleGet<string>(ref _homeDirectory, PropertyNames.AcctInfoHomeDirectory, ref _homeDirectoryChanged);
}
[System.Security.SecurityCritical]
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoHomeDirectory))
throw new InvalidOperationException(StringResources.InvalidPropertyForStore);
_owningPrincipal.HandleSet<string>(ref _homeDirectory, value, ref _homeDirectoryChanged,
PropertyNames.AcctInfoHomeDirectory);
}
}
// HomeDrive
private string _homeDrive = null;
private LoadState _homeDriveChanged = LoadState.NotSet;
public string HomeDrive
{
[System.Security.SecurityCritical]
get
{
return _owningPrincipal.HandleGet<string>(ref _homeDrive, PropertyNames.AcctInfoHomeDrive, ref _homeDriveChanged);
}
[System.Security.SecurityCritical]
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoHomeDrive))
throw new InvalidOperationException(StringResources.InvalidPropertyForStore);
_owningPrincipal.HandleSet<string>(ref _homeDrive, value, ref _homeDriveChanged,
PropertyNames.AcctInfoHomeDrive);
}
}
// ScriptPath
private string _scriptPath = null;
private LoadState _scriptPathChanged = LoadState.NotSet;
public string ScriptPath
{
[System.Security.SecurityCritical]
get
{
return _owningPrincipal.HandleGet<string>(ref _scriptPath, PropertyNames.AcctInfoScriptPath, ref _scriptPathChanged);
}
[System.Security.SecurityCritical]
set
{
if (!_owningPrincipal.GetStoreCtxToUse().IsValidProperty(_owningPrincipal, PropertyNames.AcctInfoScriptPath))
throw new InvalidOperationException(StringResources.InvalidPropertyForStore);
_owningPrincipal.HandleSet<string>(ref _scriptPath, value, ref _scriptPathChanged,
PropertyNames.AcctInfoScriptPath);
}
}
//
// Methods exposed to the public through AuthenticablePrincipal
//
[System.Security.SecurityCritical]
public bool IsAccountLockedOut()
{
if (!_owningPrincipal.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "IsAccountLockedOut: sending lockout query");
Debug.Assert(_owningPrincipal.Context != null);
return _owningPrincipal.GetStoreCtxToUse().IsLockedOut(_owningPrincipal);
}
else
{
// A Principal that hasn't even been persisted can't be locked out
return false;
}
}
[System.Security.SecurityCritical]
public void UnlockAccount()
{
if (!_owningPrincipal.unpersisted)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "UnlockAccount: sending unlock request");
Debug.Assert(_owningPrincipal.Context != null);
_owningPrincipal.GetStoreCtxToUse().UnlockAccount(_owningPrincipal);
}
// Since a Principal that's not persisted can't have been locked-out,
// there's nothing to do in that case
}
//
// Internal constructor
//
[System.Security.SecurityCritical]
internal AccountInfo(AuthenticablePrincipal principal)
{
_owningPrincipal = principal;
}
//
// Private implementation
//
private AuthenticablePrincipal _owningPrincipal;
//
// Load/Store
//
//
// Loading with query results
//
[System.Security.SecurityCritical]
internal void LoadValueIntoProperty(string propertyName, object value)
{
// GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "LoadValueIntoProperty: name=" + propertyName + " value=" + value.ToString());
switch (propertyName)
{
case (PropertyNames.AcctInfoAcctLockoutTime):
_accountLockoutTime = (Nullable<DateTime>)value;
_accountLockoutTimeLoaded = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoLastLogon):
_lastLogon = (Nullable<DateTime>)value;
_lastLogonLoaded = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoPermittedWorkstations):
_permittedWorkstations.Load((List<string>)value);
_permittedWorkstationsLoaded = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoPermittedLogonTimes):
_permittedLogonTimes = (byte[])value;
_permittedLogonTimesOriginal = (byte[])((byte[])value).Clone();
_permittedLogonTimesLoaded = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoExpirationDate):
_expirationDate = (Nullable<DateTime>)value;
_expirationDateChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoSmartcardRequired):
_smartcardLogonRequired = (bool)value;
_smartcardLogonRequiredChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoDelegationPermitted):
_delegationPermitted = (bool)value;
_delegationPermittedChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoBadLogonCount):
_badLogonCount = (int)value;
_badLogonCountChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoHomeDirectory):
_homeDirectory = (string)value;
_homeDirectoryChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoHomeDrive):
_homeDrive = (string)value;
_homeDriveChanged = LoadState.Loaded;
break;
case (PropertyNames.AcctInfoScriptPath):
_scriptPath = (string)value;
_scriptPathChanged = LoadState.Loaded;
break;
default:
Debug.Fail(String.Format(CultureInfo.CurrentCulture, "AccountInfo.LoadValueIntoProperty: fell off end looking for {0}", propertyName));
break;
}
}
//
// Getting changes to persist (or to build a query from a QBE filter)
//
// Given a property name, returns true if that property has changed since it was loaded, false otherwise.
[System.Security.SecurityCritical]
internal bool GetChangeStatusForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "GetChangeStatusForProperty: name=" + propertyName);
switch (propertyName)
{
case (PropertyNames.AcctInfoPermittedWorkstations):
return _permittedWorkstations.Changed;
case (PropertyNames.AcctInfoPermittedLogonTimes):
// If they're equal, they have _not_ changed
if ((_permittedLogonTimes == null) && (_permittedLogonTimesOriginal == null))
return false;
if ((_permittedLogonTimes == null) || (_permittedLogonTimesOriginal == null))
return true;
return !Utils.AreBytesEqual(_permittedLogonTimes, _permittedLogonTimesOriginal);
case (PropertyNames.AcctInfoExpirationDate):
return _expirationDateChanged == LoadState.Changed;
case (PropertyNames.AcctInfoSmartcardRequired):
return _smartcardLogonRequiredChanged == LoadState.Changed;
case (PropertyNames.AcctInfoDelegationPermitted):
return _delegationPermittedChanged == LoadState.Changed;
case (PropertyNames.AcctInfoHomeDirectory):
return _homeDirectoryChanged == LoadState.Changed;
case (PropertyNames.AcctInfoHomeDrive):
return _homeDriveChanged == LoadState.Changed;
case (PropertyNames.AcctInfoScriptPath):
return _scriptPathChanged == LoadState.Changed;
default:
Debug.Fail(String.Format(CultureInfo.CurrentCulture, "AccountInfo.GetChangeStatusForProperty: fell off end looking for {0}", propertyName));
return false;
}
}
// Given a property name, returns the current value for the property.
internal object GetValueForProperty(string propertyName)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "GetValueForProperty: name=" + propertyName);
switch (propertyName)
{
case (PropertyNames.AcctInfoPermittedWorkstations):
return _permittedWorkstations;
case (PropertyNames.AcctInfoPermittedLogonTimes):
return _permittedLogonTimes;
case (PropertyNames.AcctInfoExpirationDate):
return _expirationDate;
case (PropertyNames.AcctInfoSmartcardRequired):
return _smartcardLogonRequired;
case (PropertyNames.AcctInfoDelegationPermitted):
return _delegationPermitted;
case (PropertyNames.AcctInfoHomeDirectory):
return _homeDirectory;
case (PropertyNames.AcctInfoHomeDrive):
return _homeDrive;
case (PropertyNames.AcctInfoScriptPath):
return _scriptPath;
default:
Debug.Fail(String.Format(CultureInfo.CurrentCulture, "AccountInfo.GetValueForProperty: fell off end looking for {0}", propertyName));
return null;
}
}
// Reset all change-tracking status for all properties on the object to "unchanged".
[System.Security.SecurityCritical]
internal void ResetAllChangeStatus()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "AccountInfo", "ResetAllChangeStatus");
_permittedWorkstations.ResetTracking();
_permittedLogonTimesOriginal = (_permittedLogonTimes != null) ?
(byte[])_permittedLogonTimes.Clone() :
null;
_expirationDateChanged = (_expirationDateChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_smartcardLogonRequiredChanged = (_smartcardLogonRequiredChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_delegationPermittedChanged = (_delegationPermittedChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_homeDirectoryChanged = (_homeDirectoryChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_homeDriveChanged = (_homeDriveChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
_scriptPathChanged = (_scriptPathChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Reflection;
// Cartoon FX Easy Editor
// (c) 2013, 2014 - Jean Moreno
public class CFXEasyEditor : EditorWindow
{
static private CFXEasyEditor SingleWindow;
[MenuItem("Window/CartoonFX Easy Editor")]
static void ShowWindow()
{
CFXEasyEditor window = EditorWindow.GetWindow<CFXEasyEditor>(EditorPrefs.GetBool("CFX_ShowAsToolbox", true), "CartoonFX Easy Editor", true);
window.minSize = new Vector2(300, 8);
window.maxSize = new Vector2(300, 8);
window.foldoutChanged = true;
}
//Change Start Color
private bool AffectAlpha = true;
private Color ColorValue = Color.white;
private Color ColorValue2 = Color.white;
//Scale
private float ScalingValue = 2.0f;
private float LTScalingValue = 100.0f;
//Delay
private float DelayValue = 1.0f;
//Duration
private float DurationValue = 5.0f;
//Tint
private bool TintStartColor = true;
private bool TintColorModule = true;
private bool TintColorSpeedModule = true;
private Color TintColorValue = Color.white;
//Change Lightness
private int LightnessStep = 10;
//Module copying
private ParticleSystem sourceObject;
private Color ColorSelected = new Color(0.8f,0.95f,1.0f,1.0f);
private bool[] b_modules = new bool[16];
//Foldouts
bool basicFoldout = false;
bool colorFoldout = false;
bool copyFoldout = false;
bool foldoutChanged;
//Editor Prefs
private bool pref_ShowAsToolbox;
private bool pref_IncludeChildren;
void OnEnable()
{
//Load Settings
pref_ShowAsToolbox = EditorPrefs.GetBool("CFX_ShowAsToolbox", true);
pref_IncludeChildren = EditorPrefs.GetBool("CFX_IncludeChildren", true);
basicFoldout = EditorPrefs.GetBool("CFX_BasicFoldout", false);
colorFoldout = EditorPrefs.GetBool("CFX_ColorFoldout", false);
copyFoldout = EditorPrefs.GetBool("CFX_CopyFoldout", false);
}
void OnDisable()
{
//Save Settings
EditorPrefs.SetBool("CFX_BasicFoldout", basicFoldout);
EditorPrefs.SetBool("CFX_ColorFoldout", colorFoldout);
EditorPrefs.SetBool("CFX_CopyFoldout", copyFoldout);
}
void OnGUI()
{
GUILayout.BeginArea(new Rect(0,0,this.position.width - 8,this.position.height));
GUILayout.Space(4);
GUILayout.BeginHorizontal();
GUILayout.Label("CARTOON FX Easy Editor", EditorStyles.boldLabel);
pref_ShowAsToolbox = GUILayout.Toggle(pref_ShowAsToolbox, new GUIContent("Toolbox", "If enabled, the window will be displayed as an external toolbox.\nIf false, it will act as a dockable Unity window."), GUILayout.Width(60));
if(GUI.changed)
{
EditorPrefs.SetBool("CFX_ShowAsToolbox", pref_ShowAsToolbox);
this.Close();
CFXEasyEditor.ShowWindow();
}
GUILayout.EndHorizontal();
GUILayout.Label("Easily change properties of any Particle System!", EditorStyles.miniLabel);
//----------------------------------------------------------------
pref_IncludeChildren = GUILayout.Toggle(pref_IncludeChildren, new GUIContent("Include Children", "If checked, changes will affect every Particle Systems from each child of the selected GameObject(s)"));
if(GUI.changed)
{
EditorPrefs.SetBool("CFX_IncludeChildren", pref_IncludeChildren);
}
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Test effect(s):");
if(GUILayout.Button("Play", EditorStyles.miniButtonLeft, GUILayout.Width(50f)))
{
foreach(GameObject go in Selection.gameObjects)
{
ParticleSystem[] systems = go.GetComponents<ParticleSystem>();
if(systems.Length == 0) continue;
foreach(ParticleSystem system in systems)
system.Play(pref_IncludeChildren);
}
}
if(GUILayout.Button("Pause", EditorStyles.miniButtonMid, GUILayout.Width(50f)))
{
foreach(GameObject go in Selection.gameObjects)
{
ParticleSystem[] systems = go.GetComponents<ParticleSystem>();
if(systems.Length == 0) continue;
foreach(ParticleSystem system in systems)
system.Pause(pref_IncludeChildren);
}
}
if(GUILayout.Button("Stop", EditorStyles.miniButtonMid, GUILayout.Width(50f)))
{
foreach(GameObject go in Selection.gameObjects)
{
ParticleSystem[] systems = go.GetComponents<ParticleSystem>();
if(systems.Length == 0) continue;
foreach(ParticleSystem system in systems)
system.Stop(pref_IncludeChildren);
}
}
if(GUILayout.Button("Clear", EditorStyles.miniButtonRight, GUILayout.Width(50f)))
{
foreach(GameObject go in Selection.gameObjects)
{
ParticleSystem[] systems = go.GetComponents<ParticleSystem>();
if(systems.Length == 0) continue;
foreach(ParticleSystem system in systems)
{
system.Stop(pref_IncludeChildren);
system.Clear(pref_IncludeChildren);
}
}
}
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
//----------------------------------------------------------------
//Separator
GUILayout.Box("",GUILayout.Width(this.position.width - 12), GUILayout.Height(3));
EditorGUI.BeginChangeCheck();
basicFoldout = EditorGUILayout.Foldout(basicFoldout, "QUICK EDIT");
if(EditorGUI.EndChangeCheck())
{
foldoutChanged = true;
}
if(basicFoldout)
{
//----------------------------------------------------------------
GUILayout.BeginHorizontal();
if(GUILayout.Button(new GUIContent("Scale Size", "Changes the size of the Particle System(s) and other values accordingly (speed, gravity, etc.)"), GUILayout.Width(120)))
{
applyScale();
}
GUILayout.Label("Multiplier:",GUILayout.Width(110));
ScalingValue = EditorGUILayout.FloatField(ScalingValue,GUILayout.Width(50));
if(ScalingValue <= 0) ScalingValue = 0.1f;
GUILayout.EndHorizontal();
//----------------------------------------------------------------
GUILayout.BeginHorizontal();
if(GUILayout.Button(new GUIContent("Set Speed", "Changes the speed of the Particle System(s) (if you want quicker or longer effects, 100% = default speed)"), GUILayout.Width(120)))
{
applySpeed();
}
GUILayout.Label("Speed (%):",GUILayout.Width(110));
LTScalingValue = EditorGUILayout.FloatField(LTScalingValue,GUILayout.Width(50));
if(LTScalingValue < 0.1f) LTScalingValue = 0.1f;
else if(LTScalingValue > 9999) LTScalingValue = 9999;
GUILayout.EndHorizontal();
//----------------------------------------------------------------
GUILayout.BeginHorizontal();
if(GUILayout.Button(new GUIContent("Set Duration", "Changes the duration of the Particle System(s)"), GUILayout.Width(120)))
{
applyDuration();
}
GUILayout.Label("Duration (sec):",GUILayout.Width(110));
DurationValue = EditorGUILayout.FloatField(DurationValue,GUILayout.Width(50));
if(DurationValue < 0.1f) DurationValue = 0.1f;
else if(DurationValue > 9999) DurationValue = 9999;
GUILayout.EndHorizontal();
//----------------------------------------------------------------
GUILayout.BeginHorizontal();
if(GUILayout.Button(new GUIContent("Set Delay", "Changes the delay of the Particle System(s)"), GUILayout.Width(120)))
{
applyDelay();
}
GUILayout.Label("Delay :",GUILayout.Width(110));
DelayValue = EditorGUILayout.FloatField(DelayValue,GUILayout.Width(50));
if(DelayValue < 0.0f) DelayValue = 0.0f;
else if(DelayValue > 9999f) DelayValue = 9999f;
GUILayout.EndHorizontal();
//----------------------------------------------------------------
GUILayout.Space(2);
GUILayout.BeginHorizontal();
if(GUILayout.Button(new GUIContent("Loop", "Loop the effect (might not work properly on some effects such as explosions)"), EditorStyles.miniButtonLeft))
{
loopEffect(true);
}
if(GUILayout.Button(new GUIContent("Unloop", "Remove looping from the effect"), EditorStyles.miniButtonRight))
{
loopEffect(false);
}
if(GUILayout.Button(new GUIContent("Prewarm On", "Prewarm the effect (if looped)"), EditorStyles.miniButtonLeft))
{
prewarmEffect(true);
}
if(GUILayout.Button(new GUIContent("Prewarm Off", "Don't prewarm the effect (if looped)"), EditorStyles.miniButtonRight))
{
prewarmEffect(false);
}
GUILayout.EndHorizontal();
GUILayout.Space(2);
//----------------------------------------------------------------
}
//Separator
GUILayout.Box("",GUILayout.Width(this.position.width - 12), GUILayout.Height(3));
EditorGUI.BeginChangeCheck();
colorFoldout = EditorGUILayout.Foldout(colorFoldout, "COLOR EDIT");
if(EditorGUI.EndChangeCheck())
{
foldoutChanged = true;
}
if(colorFoldout)
{
//----------------------------------------------------------------
GUILayout.BeginHorizontal();
if(GUILayout.Button(new GUIContent("Set Start Color(s)", "Changes the color(s) of the Particle System(s)\nSecond Color is used when Start Color is 'Random Between Two Colors'."),GUILayout.Width(120)))
{
applyColor();
}
ColorValue = EditorGUILayout.ColorField(ColorValue);
ColorValue2 = EditorGUILayout.ColorField(ColorValue2);
AffectAlpha = GUILayout.Toggle(AffectAlpha, new GUIContent("Alpha", "If checked, the alpha value will also be changed"));
GUILayout.EndHorizontal();
//----------------------------------------------------------------
GUILayout.BeginHorizontal();
if(GUILayout.Button(new GUIContent("Tint Colors", "Tints the colors of the Particle System(s), including gradients!\n(preserving their saturation and lightness)"),GUILayout.Width(120)))
{
tintColor();
}
TintColorValue = EditorGUILayout.ColorField(TintColorValue);
TintColorValue = HSLColor.FromRGBA(TintColorValue).VividColor();
GUILayout.EndHorizontal();
//----------------------------------------------------------------
/*
GUILayout.BeginHorizontal();
GUILayout.Label("Add/Substract Lightness:");
LightnessStep = EditorGUILayout.IntField(LightnessStep, GUILayout.Width(30));
if(LightnessStep > 99) LightnessStep = 99;
else if(LightnessStep < 1) LightnessStep = 1;
GUILayout.Label("%");
if(GUILayout.Button("-", EditorStyles.miniButtonLeft, GUILayout.Width(22)))
{
addLightness(true);
}
if(GUILayout.Button("+", EditorStyles.miniButtonRight, GUILayout.Width(22)))
{
addLightness(false);
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
*/
//----------------------------------------------------------------
GUILayout.Label("Color Modules to affect:");
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.color = TintStartColor ? ColorSelected : Color.white; if(GUILayout.Button(new GUIContent("Start Color", "If checked, the \"Start Color\" value(s) will be affected."), EditorStyles.toolbarButton, GUILayout.Width(70))) TintStartColor = !TintStartColor;
GUI.color = TintColorModule ? ColorSelected : Color.white; if(GUILayout.Button(new GUIContent("Color over Lifetime", "If checked, the \"Color over Lifetime\" value(s) will be affected."), EditorStyles.toolbarButton, GUILayout.Width(110))) TintColorModule = !TintColorModule;
GUI.color = TintColorSpeedModule ? ColorSelected : Color.white; if(GUILayout.Button(new GUIContent("Color by Speed", "If checked, the \"Color by Speed\" value(s) will be affected."), EditorStyles.toolbarButton, GUILayout.Width(100))) TintColorSpeedModule = !TintColorSpeedModule;
GUI.color = Color.white;
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(4);
//----------------------------------------------------------------
}
//Separator
GUILayout.Box("",GUILayout.Width(this.position.width - 12), GUILayout.Height(3));
// GUILayout.Space(6);
//----------------------------------------------------------------
EditorGUI.BeginChangeCheck();
copyFoldout = EditorGUILayout.Foldout(copyFoldout, "COPY MODULES");
if(EditorGUI.EndChangeCheck())
{
foldoutChanged = true;
}
if(copyFoldout)
{
GUILayout.Label("Copy properties from a Particle System to others!", EditorStyles.miniLabel);
GUILayout.BeginHorizontal();
GUILayout.Label("Source Object:", GUILayout.Width(110));
sourceObject = (ParticleSystem)EditorGUILayout.ObjectField(sourceObject, typeof(ParticleSystem), true);
GUILayout.EndHorizontal();
EditorGUILayout.LabelField("Modules to Copy:");
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if(GUILayout.Button("ALL", EditorStyles.miniButtonLeft, GUILayout.Width(120)))
{
for(int i = 0; i < b_modules.Length; i++) b_modules[i] = true;
}
if(GUILayout.Button("NONE", EditorStyles.miniButtonRight, GUILayout.Width(120)))
{
for(int i = 0; i < b_modules.Length; i++) b_modules[i] = false;
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(4);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.color = b_modules[0] ? ColorSelected : Color.white; if(GUILayout.Button("Initial", EditorStyles.toolbarButton, GUILayout.Width(70))) b_modules[0] = !b_modules[0];
GUI.color = b_modules[1] ? ColorSelected : Color.white; if(GUILayout.Button("Emission", EditorStyles.toolbarButton, GUILayout.Width(70))) b_modules[1] = !b_modules[1];
GUI.color = b_modules[2] ? ColorSelected : Color.white; if(GUILayout.Button("Shape", EditorStyles.toolbarButton, GUILayout.Width(70))) b_modules[2] = !b_modules[2];
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.color = b_modules[3] ? ColorSelected : Color.white; if(GUILayout.Button("Velocity", EditorStyles.toolbarButton, GUILayout.Width(70))) b_modules[3] = !b_modules[3];
GUI.color = b_modules[4] ? ColorSelected : Color.white; if(GUILayout.Button("Limit Velocity", EditorStyles.toolbarButton, GUILayout.Width(100))) b_modules[4] = !b_modules[4];
GUI.color = b_modules[5] ? ColorSelected : Color.white; if(GUILayout.Button("Force", EditorStyles.toolbarButton, GUILayout.Width(70))) b_modules[5] = !b_modules[5];
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.color = b_modules[6] ? ColorSelected : Color.white; if(GUILayout.Button("Color over Lifetime", EditorStyles.toolbarButton, GUILayout.Width(120))) b_modules[6] = !b_modules[6];
GUI.color = b_modules[7] ? ColorSelected : Color.white; if(GUILayout.Button("Color by Speed", EditorStyles.toolbarButton, GUILayout.Width(120))) b_modules[7] = !b_modules[7];
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.color = b_modules[8] ? ColorSelected : Color.white; if(GUILayout.Button("Size over Lifetime", EditorStyles.toolbarButton, GUILayout.Width(120))) b_modules[8] = !b_modules[8];
GUI.color = b_modules[9] ? ColorSelected : Color.white; if(GUILayout.Button("Size by Speed", EditorStyles.toolbarButton, GUILayout.Width(120))) b_modules[9] = !b_modules[9];
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.color = b_modules[10] ? ColorSelected : Color.white; if(GUILayout.Button("Rotation over Lifetime", EditorStyles.toolbarButton, GUILayout.Width(120))) b_modules[10] = !b_modules[10];
GUI.color = b_modules[11] ? ColorSelected : Color.white; if(GUILayout.Button("Rotation by Speed", EditorStyles.toolbarButton, GUILayout.Width(120))) b_modules[11] = !b_modules[11];
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.color = b_modules[12] ? ColorSelected : Color.white; if(GUILayout.Button("Collision", EditorStyles.toolbarButton, GUILayout.Width(100))) b_modules[12] = !b_modules[12];
GUI.color = b_modules[13] ? ColorSelected : Color.white; if(GUILayout.Button("Sub Emitters", EditorStyles.toolbarButton, GUILayout.Width(100))) b_modules[13] = !b_modules[13];
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.color = b_modules[14] ? ColorSelected : Color.white; if(GUILayout.Button("Texture Animation", EditorStyles.toolbarButton, GUILayout.Width(110))) b_modules[14] = !b_modules[14];
GUI.color = b_modules[15] ? ColorSelected : Color.white; if(GUILayout.Button("Renderer", EditorStyles.toolbarButton, GUILayout.Width(90))) b_modules[15] = !b_modules[15];
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUI.color = Color.white;
GUILayout.Space(4);
if(GUILayout.Button("Copy properties to selected Object(s)"))
{
bool foundPs = false;
foreach(GameObject go in Selection.gameObjects)
{
ParticleSystem[] systems;
if(pref_IncludeChildren) systems = go.GetComponentsInChildren<ParticleSystem>(true);
else systems = go.GetComponents<ParticleSystem>();
if(systems.Length == 0) continue;
foundPs = true;
foreach(ParticleSystem system in systems) CopyModules(sourceObject, system);
}
if(!foundPs)
{
Debug.LogWarning("CartoonFX Easy Editor: No Particle System found in the selected GameObject(s)!");
}
}
}
//----------------------------------------------------------------
GUILayout.Space(8);
//Resize window
if(foldoutChanged && Event.current.type == EventType.Repaint)
{
foldoutChanged = false;
Rect r = GUILayoutUtility.GetLastRect();
this.minSize = new Vector2(300,r.y + 8);
this.maxSize = new Vector2(300,r.y + 8);
}
GUILayout.EndArea();
}
//Loop effects
private void loopEffect(bool setLoop)
{
foreach(GameObject go in Selection.gameObjects)
{
//Scale Shuriken Particles Values
ParticleSystem[] systems;
if(pref_IncludeChildren)
systems = go.GetComponentsInChildren<ParticleSystem>(true);
else
systems = go.GetComponents<ParticleSystem>();
foreach(ParticleSystem ps in systems)
{
SerializedObject so = new SerializedObject(ps);
so.FindProperty("looping").boolValue = setLoop;
so.ApplyModifiedProperties();
}
}
}
//Prewarm effects
private void prewarmEffect(bool setPrewarm)
{
foreach(GameObject go in Selection.gameObjects)
{
//Scale Shuriken Particles Values
ParticleSystem[] systems;
if(pref_IncludeChildren)
systems = go.GetComponentsInChildren<ParticleSystem>(true);
else
systems = go.GetComponents<ParticleSystem>();
foreach(ParticleSystem ps in systems)
{
SerializedObject so = new SerializedObject(ps);
so.FindProperty("prewarm").boolValue = setPrewarm;
so.ApplyModifiedProperties();
}
}
}
//Scale Size
private void applyScale()
{
foreach(GameObject go in Selection.gameObjects)
{
//Scale Shuriken Particles Values
ParticleSystem[] systems;
if(pref_IncludeChildren)
systems = go.GetComponentsInChildren<ParticleSystem>(true);
else
systems = go.GetComponents<ParticleSystem>();
foreach(ParticleSystem ps in systems)
{
ScaleParticleValues(ps, go);
}
//Scale Lights' range
Light[] lights = go.GetComponentsInChildren<Light>();
foreach(Light light in lights)
{
light.range *= ScalingValue;
light.transform.localPosition *= ScalingValue;
}
}
}
//Change Color
private void applyColor()
{
foreach(GameObject go in Selection.gameObjects)
{
ParticleSystem[] systems;
if(pref_IncludeChildren)
systems = go.GetComponentsInChildren<ParticleSystem>(true);
else
systems = go.GetComponents<ParticleSystem>();
foreach(ParticleSystem ps in systems)
{
SerializedObject psSerial = new SerializedObject(ps);
if(!AffectAlpha)
{
psSerial.FindProperty("InitialModule.startColor.maxColor").colorValue = new Color(ColorValue.r, ColorValue.g, ColorValue.b, psSerial.FindProperty("InitialModule.startColor.maxColor").colorValue.a);
psSerial.FindProperty("InitialModule.startColor.minColor").colorValue = new Color(ColorValue2.r, ColorValue2.g, ColorValue2.b, psSerial.FindProperty("InitialModule.startColor.minColor").colorValue.a);
}
else
{
psSerial.FindProperty("InitialModule.startColor.maxColor").colorValue = ColorValue;
psSerial.FindProperty("InitialModule.startColor.minColor").colorValue = ColorValue2;
}
psSerial.ApplyModifiedProperties();
}
}
}
//TINT COLORS ================================================================================================================================
private void tintColor()
{
if(!TintStartColor && !TintColorModule && !TintColorSpeedModule)
{
Debug.LogWarning("CartoonFX Easy Editor: You must toggle at least one of the three Color Modules to be able to tint anything!");
return;
}
float hue = HSLColor.FromRGBA(TintColorValue).h;
foreach(GameObject go in Selection.gameObjects)
{
ParticleSystem[] systems;
if(pref_IncludeChildren)
systems = go.GetComponentsInChildren<ParticleSystem>(true);
else
systems = go.GetComponents<ParticleSystem>();
foreach(ParticleSystem ps in systems)
{
SerializedObject psSerial = new SerializedObject(ps);
if(TintStartColor)
GenericTintColorProperty(psSerial.FindProperty("InitialModule.startColor"), hue);
if(TintColorModule)
GenericTintColorProperty(psSerial.FindProperty("ColorModule.gradient"), hue);
if(TintColorSpeedModule)
GenericTintColorProperty(psSerial.FindProperty("ColorBySpeedModule.gradient"), hue);
psSerial.ApplyModifiedProperties();
}
}
}
private void GenericTintColorProperty(SerializedProperty colorProperty, float hue)
{
int state = colorProperty.FindPropertyRelative("minMaxState").intValue;
switch(state)
{
//Constant Color
case 0:
colorProperty.FindPropertyRelative("maxColor").colorValue = HSLColor.FromRGBA(colorProperty.FindPropertyRelative("maxColor").colorValue).ColorWithHue(hue);
break;
//Gradient
case 1:
TintGradient(colorProperty.FindPropertyRelative("maxGradient"), hue);
break;
//Random between 2 Colors
case 2:
colorProperty.FindPropertyRelative("minColor").colorValue = HSLColor.FromRGBA(colorProperty.FindPropertyRelative("minColor").colorValue).ColorWithHue(hue);
colorProperty.FindPropertyRelative("maxColor").colorValue = HSLColor.FromRGBA(colorProperty.FindPropertyRelative("maxColor").colorValue).ColorWithHue(hue);
break;
//Random between 2 Gradients
case 3:
TintGradient(colorProperty.FindPropertyRelative("maxGradient"), hue);
TintGradient(colorProperty.FindPropertyRelative("minGradient"), hue);
break;
}
}
private void TintGradient(SerializedProperty gradientProperty, float hue)
{
gradientProperty.FindPropertyRelative("key0").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key0").colorValue).ColorWithHue(hue);
gradientProperty.FindPropertyRelative("key1").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key1").colorValue).ColorWithHue(hue);
gradientProperty.FindPropertyRelative("key2").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key2").colorValue).ColorWithHue(hue);
gradientProperty.FindPropertyRelative("key3").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key3").colorValue).ColorWithHue(hue);
gradientProperty.FindPropertyRelative("key4").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key4").colorValue).ColorWithHue(hue);
gradientProperty.FindPropertyRelative("key5").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key5").colorValue).ColorWithHue(hue);
gradientProperty.FindPropertyRelative("key6").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key6").colorValue).ColorWithHue(hue);
gradientProperty.FindPropertyRelative("key7").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key7").colorValue).ColorWithHue(hue);
}
//LIGHTNESS OFFSET ================================================================================================================================
private void addLightness(bool substract)
{
if(!TintStartColor && !TintColorModule && !TintColorSpeedModule)
{
Debug.LogWarning("CartoonFX Easy Editor: You must toggle at least one of the three Color Modules to be able to change lightness!");
return;
}
float lightness = (float)(LightnessStep/100f);
if(substract)
lightness *= -1f;
foreach(GameObject go in Selection.gameObjects)
{
ParticleSystem[] systems;
if(pref_IncludeChildren)
systems = go.GetComponentsInChildren<ParticleSystem>(true);
else
systems = go.GetComponents<ParticleSystem>();
foreach(ParticleSystem ps in systems)
{
SerializedObject psSerial = new SerializedObject(ps);
if(TintStartColor)
GenericAddLightness(psSerial.FindProperty("InitialModule.startColor"), lightness);
if(TintColorModule)
GenericAddLightness(psSerial.FindProperty("ColorModule.gradient"), lightness);
if(TintColorSpeedModule)
GenericAddLightness(psSerial.FindProperty("ColorBySpeedModule.gradient"), lightness);
psSerial.ApplyModifiedProperties();
psSerial.Update();
}
}
}
private void GenericAddLightness(SerializedProperty colorProperty, float lightness)
{
int state = colorProperty.FindPropertyRelative("minMaxState").intValue;
switch(state)
{
//Constant Color
case 0:
colorProperty.FindPropertyRelative("maxColor").colorValue = HSLColor.FromRGBA(colorProperty.FindPropertyRelative("maxColor").colorValue).ColorWithLightnessOffset(lightness);
break;
//Gradient
case 1:
AddLightnessGradient(colorProperty.FindPropertyRelative("maxGradient"), lightness);
break;
//Random between 2 Colors
case 2:
colorProperty.FindPropertyRelative("minColor").colorValue = HSLColor.FromRGBA(colorProperty.FindPropertyRelative("minColor").colorValue).ColorWithLightnessOffset(lightness);
colorProperty.FindPropertyRelative("maxColor").colorValue = HSLColor.FromRGBA(colorProperty.FindPropertyRelative("maxColor").colorValue).ColorWithLightnessOffset(lightness);
break;
//Random between 2 Gradients
case 3:
AddLightnessGradient(colorProperty.FindPropertyRelative("maxGradient"), lightness);
AddLightnessGradient(colorProperty.FindPropertyRelative("minGradient"), lightness);
break;
}
}
private void AddLightnessGradient(SerializedProperty gradientProperty, float lightness)
{
gradientProperty.FindPropertyRelative("key0").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key0").colorValue).ColorWithLightnessOffset(lightness);
gradientProperty.FindPropertyRelative("key1").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key1").colorValue).ColorWithLightnessOffset(lightness);
gradientProperty.FindPropertyRelative("key2").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key2").colorValue).ColorWithLightnessOffset(lightness);
gradientProperty.FindPropertyRelative("key3").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key3").colorValue).ColorWithLightnessOffset(lightness);
gradientProperty.FindPropertyRelative("key4").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key4").colorValue).ColorWithLightnessOffset(lightness);
gradientProperty.FindPropertyRelative("key5").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key5").colorValue).ColorWithLightnessOffset(lightness);
gradientProperty.FindPropertyRelative("key6").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key6").colorValue).ColorWithLightnessOffset(lightness);
gradientProperty.FindPropertyRelative("key7").colorValue = HSLColor.FromRGBA(gradientProperty.FindPropertyRelative("key7").colorValue).ColorWithLightnessOffset(lightness);
}
//RGB / HSL Conversions
private struct HSLColor
{
public float h;
public float s;
public float l;
public float a;
public HSLColor(float h, float s, float l, float a)
{
this.h = h;
this.s = s;
this.l = l;
this.a = a;
}
public HSLColor(float h, float s, float l)
{
this.h = h;
this.s = s;
this.l = l;
this.a = 1f;
}
public HSLColor(Color c)
{
HSLColor temp = FromRGBA(c);
h = temp.h;
s = temp.s;
l = temp.l;
a = temp.a;
}
public static HSLColor FromRGBA(Color c)
{
float h, s, l, a;
a = c.a;
float cmin = Mathf.Min(Mathf.Min(c.r, c.g), c.b);
float cmax = Mathf.Max(Mathf.Max(c.r, c.g), c.b);
l = (cmin + cmax) / 2f;
if (cmin == cmax)
{
s = 0;
h = 0;
}
else
{
float delta = cmax - cmin;
s = (l <= .5f) ? (delta / (cmax + cmin)) : (delta / (2f - (cmax + cmin)));
h = 0;
if (c.r == cmax)
{
h = (c.g - c.b) / delta;
}
else if (c.g == cmax)
{
h = 2f + (c.b - c.r) / delta;
}
else if (c.b == cmax)
{
h = 4f + (c.r - c.g) / delta;
}
h = Mathf.Repeat(h * 60f, 360f);
}
return new HSLColor(h, s, l, a);
}
public Color ToRGBA()
{
float r, g, b, a;
a = this.a;
float m1, m2;
m2 = (l <= .5f) ? (l * (1f + s)) : (l + s - l * s);
m1 = 2f * l - m2;
if (s == 0f)
{
r = g = b = l;
}
else
{
r = Value(m1, m2, h + 120f);
g = Value(m1, m2, h);
b = Value(m1, m2, h - 120f);
}
return new Color(r, g, b, a);
}
static float Value(float n1, float n2, float hue)
{
hue = Mathf.Repeat(hue, 360f);
if (hue < 60f)
{
return n1 + (n2 - n1) * hue / 60f;
}
else if (hue < 180f)
{
return n2;
}
else if (hue < 240f)
{
return n1 + (n2 - n1) * (240f - hue) / 60f;
}
else
{
return n1;
}
}
public Color VividColor()
{
this.l = 0.5f;
this.s = 1.0f;
return this.ToRGBA();
}
public Color ColorWithHue(float hue)
{
this.h = hue;
return this.ToRGBA();
}
public Color ColorWithLightnessOffset(float lightness)
{
this.l += lightness;
if(this.l > 1.0f) this.l = 1.0f;
else if(this.l < 0.0f) this.l = 0.0f;
return this.ToRGBA();
}
public static implicit operator HSLColor(Color src)
{
return FromRGBA(src);
}
public static implicit operator Color(HSLColor src)
{
return src.ToRGBA();
}
}
//Scale Lifetime only
private void applySpeed()
{
foreach(GameObject go in Selection.gameObjects)
{
ParticleSystem[] systems;
if(pref_IncludeChildren)
systems = go.GetComponentsInChildren<ParticleSystem>(true);
else
systems = go.GetComponents<ParticleSystem>();
//Scale Lifetime
foreach(ParticleSystem ps in systems)
{
ps.playbackSpeed = (100.0f/LTScalingValue);
}
}
}
//Set Duration
private void applyDuration()
{
foreach(GameObject go in Selection.gameObjects)
{
//Scale Shuriken Particles Values
ParticleSystem[] systems;
if(pref_IncludeChildren)
systems = go.GetComponentsInChildren<ParticleSystem>(true);
else
systems = go.GetComponents<ParticleSystem>();
foreach(ParticleSystem ps in systems)
{
SerializedObject so = new SerializedObject(ps);
so.FindProperty("lengthInSec").floatValue = DurationValue;
so.ApplyModifiedProperties();
}
}
}
//Change delay
private void applyDelay()
{
foreach(GameObject go in Selection.gameObjects)
{
ParticleSystem[] systems;
if(pref_IncludeChildren)
systems = go.GetComponentsInChildren<ParticleSystem>(true);
else
systems = go.GetComponents<ParticleSystem>();
//Scale Lifetime
foreach(ParticleSystem ps in systems)
{
ps.startDelay = DelayValue;
}
}
}
//Copy Selected Modules
private void CopyModules(ParticleSystem source, ParticleSystem dest)
{
if(source == null)
{
Debug.LogWarning("CartoonFX Easy Editor: Select a source Particle System to copy properties from first!");
return;
}
SerializedObject psSource = new SerializedObject(source);
SerializedObject psDest = new SerializedObject(dest);
//Inial Module
if(b_modules[0])
{
psDest.FindProperty("prewarm").boolValue = psSource.FindProperty("prewarm").boolValue;
psDest.FindProperty("lengthInSec").floatValue = psSource.FindProperty("lengthInSec").floatValue;
psDest.FindProperty("moveWithTransform").boolValue = psSource.FindProperty("moveWithTransform").boolValue;
GenericModuleCopy(psSource.FindProperty("InitialModule"), psDest.FindProperty("InitialModule"));
dest.startDelay = source.startDelay;
dest.loop = source.loop;
dest.playOnAwake = source.playOnAwake;
dest.playbackSpeed = source.playbackSpeed;
dest.emissionRate = source.emissionRate;
dest.startSpeed = source.startSpeed;
dest.startSize = source.startSize;
dest.startColor = source.startColor;
dest.startRotation = source.startRotation;
dest.startLifetime = source.startLifetime;
dest.gravityModifier = source.gravityModifier;
}
//Emission
if(b_modules[1]) GenericModuleCopy(psSource.FindProperty("EmissionModule"), psDest.FindProperty("EmissionModule"));
//Shape
if(b_modules[2]) GenericModuleCopy(psSource.FindProperty("ShapeModule"), psDest.FindProperty("ShapeModule"));
//Velocity
if(b_modules[3]) GenericModuleCopy(psSource.FindProperty("VelocityModule"), psDest.FindProperty("VelocityModule"));
//Velocity Clamp
if(b_modules[4]) GenericModuleCopy(psSource.FindProperty("ClampVelocityModule"), psDest.FindProperty("ClampVelocityModule"));
//Force
if(b_modules[5]) GenericModuleCopy(psSource.FindProperty("ForceModule"), psDest.FindProperty("ForceModule"));
//Color
if(b_modules[6]) GenericModuleCopy(psSource.FindProperty("ColorModule"), psDest.FindProperty("ColorModule"));
//Color Speed
if(b_modules[7]) GenericModuleCopy(psSource.FindProperty("ColorBySpeedModule"), psDest.FindProperty("ColorBySpeedModule"));
//Size
if(b_modules[8]) GenericModuleCopy(psSource.FindProperty("SizeModule"), psDest.FindProperty("SizeModule"));
//Size Speed
if(b_modules[9]) GenericModuleCopy(psSource.FindProperty("SizeBySpeedModule"), psDest.FindProperty("SizeBySpeedModule"));
//Rotation
if(b_modules[10]) GenericModuleCopy(psSource.FindProperty("RotationModule"), psDest.FindProperty("RotationModule"));
//Rotation Speed
if(b_modules[11]) GenericModuleCopy(psSource.FindProperty("RotationBySpeedModule"), psDest.FindProperty("RotationBySpeedModule"));
//Collision
if(b_modules[12]) GenericModuleCopy(psSource.FindProperty("CollisionModule"), psDest.FindProperty("CollisionModule"));
//Sub Emitters
if(b_modules[13]) SubModuleCopy(psSource, psDest);
//Texture Animation
if(b_modules[14]) GenericModuleCopy(psSource.FindProperty("UVModule"), psDest.FindProperty("UVModule"));
//Renderer
if(b_modules[15])
{
ParticleSystemRenderer rendSource = source.GetComponent<ParticleSystemRenderer>();
ParticleSystemRenderer rendDest = dest.GetComponent<ParticleSystemRenderer>();
psSource = new SerializedObject(rendSource);
psDest = new SerializedObject(rendDest);
SerializedProperty ss = psSource.GetIterator();
ss.Next(true);
SerializedProperty sd = psDest.GetIterator();
sd.Next(true);
GenericModuleCopy(ss, sd, false);
}
}
//Copy One Module's Values
private void GenericModuleCopy(SerializedProperty ss, SerializedProperty sd, bool depthBreak = true)
{
while(true)
{
//Next Property
if(!ss.NextVisible(true))
{
break;
}
sd.NextVisible(true);
//If end of module: break
if(depthBreak && ss.depth == 0)
{
break;
}
bool found = true;
switch(ss.propertyType)
{
case SerializedPropertyType.Boolean : sd.boolValue = ss.boolValue; break;
case SerializedPropertyType.Integer : sd.intValue = ss.intValue; break;
case SerializedPropertyType.Float : sd.floatValue = ss.floatValue; break;
case SerializedPropertyType.Color : sd.colorValue = ss.colorValue; break;
case SerializedPropertyType.Bounds : sd.boundsValue = ss.boundsValue; break;
case SerializedPropertyType.Enum : sd.enumValueIndex = ss.enumValueIndex; break;
case SerializedPropertyType.ObjectReference : sd.objectReferenceValue = ss.objectReferenceValue; break;
case SerializedPropertyType.Rect : sd.rectValue = ss.rectValue; break;
case SerializedPropertyType.String : sd.stringValue = ss.stringValue; break;
case SerializedPropertyType.Vector2 : sd.vector2Value = ss.vector2Value; break;
case SerializedPropertyType.Vector3 : sd.vector3Value = ss.vector3Value; break;
case SerializedPropertyType.AnimationCurve : sd.animationCurveValue = ss.animationCurveValue; break;
#if !UNITY_3_5
case SerializedPropertyType.Gradient : copyGradient(ss,sd); break;
#endif
default: found = false; break;
}
if(!found)
{
found = true;
switch(ss.type)
{
default: found = false; break;
}
}
}
//Apply Changes
sd.serializedObject.ApplyModifiedProperties();
ss.Dispose();
sd.Dispose();
}
#if !UNITY_3_5
private void copyGradient(SerializedProperty ss, SerializedProperty sd)
{
SerializedProperty gradient = ss.Copy();
SerializedProperty copyGrad = sd.Copy();
gradient.Next(true);
copyGrad.Next(true);
do
{
switch(gradient.propertyType)
{
case SerializedPropertyType.Color: copyGrad.colorValue = gradient.colorValue; break;
case SerializedPropertyType.Integer: copyGrad.intValue = gradient.intValue; break;
default: Debug.Log("CopyGradient: Unrecognized property type:" + gradient.propertyType); break;
}
gradient.Next(true);
copyGrad.Next(true);
}
while(gradient.depth > 2);
}
#endif
//Specific Copy for Sub Emitters Module (duplicate Sub Particle Systems)
private void SubModuleCopy(SerializedObject source, SerializedObject dest)
{
dest.FindProperty("SubModule.enabled").boolValue = source.FindProperty("SubModule.enabled").boolValue;
GameObject copy;
if(source.FindProperty("SubModule.subEmitterBirth").objectReferenceValue != null)
{
//Duplicate sub Particle Emitter
copy = (GameObject)Instantiate((source.FindProperty("SubModule.subEmitterBirth").objectReferenceValue as ParticleSystem).gameObject);
//Set as child of destination
Vector3 localPos = copy.transform.localPosition;
Vector3 localScale = copy.transform.localScale;
Vector3 localAngles = copy.transform.localEulerAngles;
copy.transform.parent = (dest.targetObject as ParticleSystem).transform;
copy.transform.localPosition = localPos;
copy.transform.localScale = localScale;
copy.transform.localEulerAngles = localAngles;
//Assign as sub Particle Emitter
dest.FindProperty("SubModule.subEmitterBirth").objectReferenceValue = copy;
}
if(source.FindProperty("SubModule.subEmitterDeath").objectReferenceValue != null)
{
//Duplicate sub Particle Emitter
copy = (GameObject)Instantiate((source.FindProperty("SubModule.subEmitterDeath").objectReferenceValue as ParticleSystem).gameObject);
//Set as child of destination
Vector3 localPos = copy.transform.localPosition;
Vector3 localScale = copy.transform.localScale;
Vector3 localAngles = copy.transform.localEulerAngles;
copy.transform.parent = (dest.targetObject as ParticleSystem).transform;
copy.transform.localPosition = localPos;
copy.transform.localScale = localScale;
copy.transform.localEulerAngles = localAngles;
//Assign as sub Particle Emitter
dest.FindProperty("SubModule.subEmitterDeath").objectReferenceValue = copy;
}
if(source.FindProperty("SubModule.subEmitterCollision").objectReferenceValue != null)
{
//Duplicate sub Particle Emitter
copy = (GameObject)Instantiate((source.FindProperty("SubModule.subEmitterCollision").objectReferenceValue as ParticleSystem).gameObject);
//Set as child of destination
Vector3 localPos = copy.transform.localPosition;
Vector3 localScale = copy.transform.localScale;
Vector3 localAngles = copy.transform.localEulerAngles;
copy.transform.parent = (dest.targetObject as ParticleSystem).transform;
copy.transform.localPosition = localPos;
copy.transform.localScale = localScale;
copy.transform.localEulerAngles = localAngles;
//Assign as sub Particle Emitter
dest.FindProperty("SubModule.subEmitterCollision").objectReferenceValue = copy;
}
//Apply Changes
dest.ApplyModifiedProperties();
}
//Scale System
private void ScaleParticleValues(ParticleSystem ps, GameObject parent)
{
//Particle System
ps.startSize *= ScalingValue;
ps.gravityModifier *= ScalingValue;
if(ps.startSpeed > 0.01f)
ps.startSpeed *= ScalingValue;
if(ps.gameObject != parent)
ps.transform.localPosition *= ScalingValue;
SerializedObject psSerial = new SerializedObject(ps);
//Scale Emission Rate if set on Distance
if(psSerial.FindProperty("EmissionModule.enabled").boolValue && psSerial.FindProperty("EmissionModule.m_Type").intValue == 1)
{
psSerial.FindProperty("EmissionModule.rate.scalar").floatValue /= ScalingValue;
}
//Scale Size By Speed Module
if(psSerial.FindProperty("SizeBySpeedModule.enabled").boolValue)
{
psSerial.FindProperty("SizeBySpeedModule.range.x").floatValue *= ScalingValue;
psSerial.FindProperty("SizeBySpeedModule.range.y").floatValue *= ScalingValue;
}
//Scale Velocity Module
if(psSerial.FindProperty("VelocityModule.enabled").boolValue)
{
psSerial.FindProperty("VelocityModule.x.scalar").floatValue *= ScalingValue;
IterateKeys(psSerial.FindProperty("VelocityModule.x.minCurve").animationCurveValue);
IterateKeys(psSerial.FindProperty("VelocityModule.x.maxCurve").animationCurveValue);
psSerial.FindProperty("VelocityModule.y.scalar").floatValue *= ScalingValue;
IterateKeys(psSerial.FindProperty("VelocityModule.y.minCurve").animationCurveValue);
IterateKeys(psSerial.FindProperty("VelocityModule.y.maxCurve").animationCurveValue);
psSerial.FindProperty("VelocityModule.z.scalar").floatValue *= ScalingValue;
IterateKeys(psSerial.FindProperty("VelocityModule.z.minCurve").animationCurveValue);
IterateKeys(psSerial.FindProperty("VelocityModule.z.maxCurve").animationCurveValue);
}
//Scale Limit Velocity Module
if(psSerial.FindProperty("ClampVelocityModule.enabled").boolValue)
{
psSerial.FindProperty("ClampVelocityModule.x.scalar").floatValue *= ScalingValue;
IterateKeys(psSerial.FindProperty("ClampVelocityModule.x.minCurve").animationCurveValue);
IterateKeys(psSerial.FindProperty("ClampVelocityModule.x.maxCurve").animationCurveValue);
psSerial.FindProperty("ClampVelocityModule.y.scalar").floatValue *= ScalingValue;
IterateKeys(psSerial.FindProperty("ClampVelocityModule.y.minCurve").animationCurveValue);
IterateKeys(psSerial.FindProperty("ClampVelocityModule.y.maxCurve").animationCurveValue);
psSerial.FindProperty("ClampVelocityModule.z.scalar").floatValue *= ScalingValue;
IterateKeys(psSerial.FindProperty("ClampVelocityModule.z.minCurve").animationCurveValue);
IterateKeys(psSerial.FindProperty("ClampVelocityModule.z.maxCurve").animationCurveValue);
psSerial.FindProperty("ClampVelocityModule.magnitude.scalar").floatValue *= ScalingValue;
IterateKeys(psSerial.FindProperty("ClampVelocityModule.magnitude.minCurve").animationCurveValue);
IterateKeys(psSerial.FindProperty("ClampVelocityModule.magnitude.maxCurve").animationCurveValue);
}
//Scale Force Module
if(psSerial.FindProperty("ForceModule.enabled").boolValue)
{
psSerial.FindProperty("ForceModule.x.scalar").floatValue *= ScalingValue;
IterateKeys(psSerial.FindProperty("ForceModule.x.minCurve").animationCurveValue);
IterateKeys(psSerial.FindProperty("ForceModule.x.maxCurve").animationCurveValue);
psSerial.FindProperty("ForceModule.y.scalar").floatValue *= ScalingValue;
IterateKeys(psSerial.FindProperty("ForceModule.y.minCurve").animationCurveValue);
IterateKeys(psSerial.FindProperty("ForceModule.y.maxCurve").animationCurveValue);
psSerial.FindProperty("ForceModule.z.scalar").floatValue *= ScalingValue;
IterateKeys(psSerial.FindProperty("ForceModule.z.minCurve").animationCurveValue);
IterateKeys(psSerial.FindProperty("ForceModule.z.maxCurve").animationCurveValue);
}
//Scale Shape Module
if(psSerial.FindProperty("ShapeModule.enabled").boolValue)
{
psSerial.FindProperty("ShapeModule.boxX").floatValue *= ScalingValue;
psSerial.FindProperty("ShapeModule.boxY").floatValue *= ScalingValue;
psSerial.FindProperty("ShapeModule.boxZ").floatValue *= ScalingValue;
psSerial.FindProperty("ShapeModule.radius").floatValue *= ScalingValue;
//Create a new scaled Mesh if there is a Mesh reference
//(ShapeModule.type 6 == Mesh)
if(psSerial.FindProperty("ShapeModule.type").intValue == 6)
{
Object obj = psSerial.FindProperty("ShapeModule.m_Mesh").objectReferenceValue;
if(obj != null)
{
Mesh mesh = (Mesh)obj;
string assetPath = AssetDatabase.GetAssetPath(mesh);
string name = assetPath.Substring(assetPath.LastIndexOf("/")+1);
//Mesh to use
Mesh meshToUse = null;
bool createScaledMesh = true;
float meshScale = ScalingValue;
//Mesh has already been scaled: extract scaling value and re-scale base effect
if(name.Contains("(scaled)"))
{
string scaleStr = name.Substring(name.LastIndexOf("x")+1);
scaleStr = scaleStr.Remove(scaleStr.IndexOf(" (scaled).asset"));
float oldScale = float.Parse(scaleStr);
if(oldScale != 0)
{
meshScale = oldScale * ScalingValue;
//Check if there's already a mesh with the correct scale
string unscaledName = assetPath.Substring(0, assetPath.LastIndexOf(" x"));
assetPath = unscaledName;
string newPath = assetPath + " x"+meshScale+" (scaled).asset";
Mesh alreadyScaledMesh = (Mesh)AssetDatabase.LoadAssetAtPath(newPath, typeof(Mesh));
if(alreadyScaledMesh != null)
{
meshToUse = alreadyScaledMesh;
createScaledMesh = false;
}
else
//Load original unscaled mesh
{
Mesh orgMesh = (Mesh)AssetDatabase.LoadAssetAtPath(assetPath, typeof(Mesh));
if(orgMesh != null)
{
mesh = orgMesh;
}
}
}
}
else
//Verify if original mesh has already been scaled to that value
{
string newPath = assetPath + " x"+meshScale+" (scaled).asset";
Mesh alreadyScaledMesh = (Mesh)AssetDatabase.LoadAssetAtPath(newPath, typeof(Mesh));
if(alreadyScaledMesh != null)
{
meshToUse = alreadyScaledMesh;
createScaledMesh = false;
}
}
//Duplicate and scale mesh vertices if necessary
if(createScaledMesh)
{
string newMeshPath = assetPath + " x"+meshScale+" (scaled).asset";
meshToUse = (Mesh)AssetDatabase.LoadAssetAtPath(newMeshPath, typeof(Mesh));
if(meshToUse == null)
{
meshToUse = DuplicateAndScaleMesh(mesh, meshScale);
AssetDatabase.CreateAsset(meshToUse, newMeshPath);
}
}
//Apply new Mesh
psSerial.FindProperty("ShapeModule.m_Mesh").objectReferenceValue = meshToUse;
}
}
}
//Apply Modified Properties
psSerial.ApplyModifiedProperties();
}
//Iterate and Scale Keys (Animation Curve)
private void IterateKeys(AnimationCurve curve)
{
for(int i = 0; i < curve.keys.Length; i++)
{
curve.keys[i].value *= ScalingValue;
}
}
//Create Scaled Mesh
private Mesh DuplicateAndScaleMesh(Mesh mesh, float Scale)
{
Mesh scaledMesh = new Mesh();
Vector3[] scaledVertices = new Vector3[mesh.vertices.Length];
for(int i = 0; i < scaledVertices.Length; i++)
{
scaledVertices[i] = mesh.vertices[i] * Scale;
}
scaledMesh.vertices = scaledVertices;
scaledMesh.normals = mesh.normals;
scaledMesh.tangents = mesh.tangents;
scaledMesh.triangles = mesh.triangles;
scaledMesh.uv = mesh.uv;
scaledMesh.uv2 = mesh.uv2;
scaledMesh.colors = mesh.colors;
return scaledMesh;
}
}
| |
// 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.Threading;
using System.ComponentModel;
using System.ComponentModel.Design;
namespace System.Timers
{
/// <summary>
/// Handles recurring events in an application.
/// </summary>
[DefaultProperty("Interval"), DefaultEvent("Elapsed")]
public partial class Timer : Component, ISupportInitialize
{
private double _interval;
private bool _enabled;
private bool _initializing;
private bool _delayedEnable;
private ElapsedEventHandler _onIntervalElapsed;
private bool _autoReset;
private ISynchronizeInvoke _synchronizingObject;
private bool _disposed;
private Threading.Timer _timer;
private TimerCallback _callback;
private object _cookie;
/// <summary>
/// Initializes a new instance of the <see cref='System.Timers.Timer'/> class, with the properties
/// set to initial values.
/// </summary>
public Timer() : base()
{
_interval = 100;
_enabled = false;
_autoReset = true;
_initializing = false;
_delayedEnable = false;
_callback = new TimerCallback(MyTimerCallback);
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Timers.Timer'/> class, setting the <see cref='System.Timers.Timer.Interval'/> property to the specified period.
/// </summary>
public Timer(double interval) : this()
{
if (interval <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(interval), interval));
}
double roundedInterval = Math.Ceiling(interval);
if (roundedInterval > int.MaxValue || roundedInterval <= 0)
{
throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(interval), interval));
}
_interval = (int)roundedInterval;
}
/// <summary>
/// Gets or sets a value indicating whether the Timer raises the Tick event each time the specified
/// Interval has elapsed, when Enabled is set to true.
/// </summary>
[TimersDescription(nameof(SR.TimerAutoReset), null), DefaultValue(true)]
public bool AutoReset
{
get => _autoReset;
set
{
if (DesignMode)
{
_autoReset = value;
}
else if (_autoReset != value)
{
_autoReset = value;
if (_timer != null)
{
UpdateTimer();
}
}
}
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref='System.Timers.Timer'/>
/// is able to raise events at a defined interval.
/// The default value by design is false, don't change it.
/// </summary>
[TimersDescription(nameof(SR.TimerEnabled), null), DefaultValue(false)]
public bool Enabled
{
get => _enabled;
set
{
if (DesignMode)
{
_delayedEnable = value;
_enabled = value;
}
else if (_initializing)
{
_delayedEnable = value;
}
else if (_enabled != value)
{
if (!value)
{
if (_timer != null)
{
_cookie = null;
_timer.Dispose();
_timer = null;
}
_enabled = value;
}
else
{
_enabled = value;
if (_timer == null)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
int i = (int)Math.Ceiling(_interval);
_cookie = new object();
_timer = new Threading.Timer(_callback, _cookie, Timeout.Infinite, Timeout.Infinite);
_timer.Change(i, _autoReset ? i : Timeout.Infinite);
}
else
{
UpdateTimer();
}
}
}
}
}
private void UpdateTimer()
{
int i = (int)Math.Ceiling(_interval);
_timer.Change(i, _autoReset ? i : Timeout.Infinite);
}
/// <summary>
/// Gets or sets the interval on which to raise events.
/// </summary>
[TimersDescription(nameof(SR.TimerInterval), null), DefaultValue(100d)]
public double Interval
{
get => _interval;
set
{
if (value <= 0)
{
throw new ArgumentException(SR.Format(SR.TimerInvalidInterval, value, 0));
}
_interval = value;
if (_timer != null)
{
UpdateTimer();
}
}
}
/// <summary>
/// Occurs when the <see cref='System.Timers.Timer.Interval'/> has
/// elapsed.
/// </summary>
[TimersDescription(nameof(SR.TimerIntervalElapsed), null)]
public event ElapsedEventHandler Elapsed
{
add => _onIntervalElapsed += value;
remove => _onIntervalElapsed -= value;
}
/// <summary>
/// Sets the enable property in design mode to true by default.
/// </summary>
public override ISite Site
{
get => base.Site;
set
{
base.Site = value;
if (DesignMode)
{
_enabled = true;
}
}
}
/// <summary>
/// Gets or sets the object used to marshal event-handler calls that are issued when
/// an interval has elapsed.
/// </summary>
[DefaultValue(null), TimersDescription(nameof(SR.TimerSynchronizingObject), null)]
public ISynchronizeInvoke SynchronizingObject
{
get
{
if (_synchronizingObject == null && DesignMode)
{
IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
object baseComponent = host?.RootComponent;
if (baseComponent != null && baseComponent is ISynchronizeInvoke)
{
_synchronizingObject = (ISynchronizeInvoke)baseComponent;
}
}
return _synchronizingObject;
}
set => _synchronizingObject = value;
}
/// <summary>
/// Notifies the object that initialization is beginning and tells it to stand by.
/// </summary>
public void BeginInit()
{
Close();
_initializing = true;
}
/// <summary>
/// Disposes of the resources (other than memory) used by
/// the <see cref='System.Timers.Timer'/>.
/// </summary>
public void Close()
{
_initializing = false;
_delayedEnable = false;
_enabled = false;
if (_timer != null)
{
_timer.Dispose();
_timer = null;
}
}
protected override void Dispose(bool disposing)
{
Close();
_disposed = true;
base.Dispose(disposing);
}
/// <summary>
/// Notifies the object that initialization is complete.
/// </summary>
public void EndInit()
{
_initializing = false;
Enabled = _delayedEnable;
}
/// <summary>
/// Starts the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='true'/>.
/// </summary>
public void Start() => Enabled = true;
/// <summary>
/// Stops the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='false'/>.
/// </summary>
public void Stop()
{
Enabled = false;
}
private void MyTimerCallback(object state)
{
// System.Threading.Timer will not cancel the work item queued before the timer is stopped.
// We don't want to handle the callback after a timer is stopped.
if (state != _cookie)
{
return;
}
if (!_autoReset)
{
_enabled = false;
}
ElapsedEventArgs elapsedEventArgs = new ElapsedEventArgs(DateTime.UtcNow.ToFileTime());
try
{
// To avoid race between remove handler and raising the event
ElapsedEventHandler intervalElapsed = _onIntervalElapsed;
if (intervalElapsed != null)
{
if (SynchronizingObject != null && SynchronizingObject.InvokeRequired)
SynchronizingObject.BeginInvoke(intervalElapsed, new object[] { this, elapsedEventArgs });
else
intervalElapsed(this, elapsedEventArgs);
}
}
catch
{
}
}
}
}
| |
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 settings4net.TestWebApp.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Teknik.StorageService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Teknik.Areas.Paste;
using Teknik.Areas.Users.Models;
using Teknik.Areas.Users.Utility;
using Teknik.Areas.Vault.Models;
using Teknik.Areas.Vault.ViewModels;
using Teknik.Attributes;
using Teknik.Configuration;
using Teknik.Controllers;
using Teknik.Data;
using Teknik.Filters;
using Teknik.Logging;
using Teknik.Models;
using Teknik.Utilities;
using Teknik.Utilities.Cryptography;
using Teknik.Utilities.Routing;
namespace Teknik.Areas.Vault.Controllers
{
[Authorize]
[Area("Vault")]
public class VaultController : DefaultController
{
public VaultController(ILogger<Logger> logger, Config config, TeknikEntities dbContext) : base(logger, config, dbContext) { }
[AllowAnonymous]
[TrackPageView]
public async Task<IActionResult> ViewVault(string id)
{
Models.Vault foundVault = _dbContext.Vaults.Where(v => v.Url == id).FirstOrDefault();
if (foundVault != null)
{
// Update view count
foundVault.Views += 1;
_dbContext.Entry(foundVault).State = EntityState.Modified;
_dbContext.SaveChanges();
ViewBag.Title = foundVault.Title + " | Vault";
VaultViewModel model = new VaultViewModel();
model.CurrentSub = Subdomain;
model.Url = foundVault.Url;
model.UserId = foundVault.UserId;
model.User = foundVault.User;
model.Title = foundVault.Title;
model.Description = foundVault.Description;
model.DateCreated = foundVault.DateCreated;
model.DateEdited = foundVault.DateEdited;
if (foundVault.VaultItems.Any())
{
foreach (VaultItem item in foundVault.VaultItems.OrderBy(v => v.Index))
{
if (item.GetType().BaseType == typeof(UploadVaultItem))
{
UploadVaultItem upload = (UploadVaultItem)item;
// Increment Views
upload.Upload.Downloads += 1;
_dbContext.Entry(upload.Upload).State = EntityState.Modified;
_dbContext.SaveChanges();
UploadItemViewModel uploadModel = new UploadItemViewModel();
uploadModel.VaultItemId = item.VaultItemId;
uploadModel.Title = item.Title;
uploadModel.Description = item.Description;
uploadModel.DateAdded = item.DateAdded;
uploadModel.Upload = upload.Upload;
model.Items.Add(uploadModel);
}
else if (item.GetType().BaseType == typeof(PasteVaultItem))
{
PasteVaultItem paste = (PasteVaultItem)item;
// Increment Views
paste.Paste.Views += 1;
_dbContext.Entry(paste.Paste).State = EntityState.Modified;
_dbContext.SaveChanges();
// Check Expiration
if (PasteHelper.CheckExpiration(paste.Paste))
{
_dbContext.Pastes.Remove(paste.Paste);
_dbContext.SaveChanges();
break;
}
PasteItemViewModel pasteModel = new PasteItemViewModel();
pasteModel.VaultItemId = item.VaultItemId;
pasteModel.Title = item.Title;
pasteModel.Description = item.Description;
pasteModel.DateAdded = item.DateAdded;
pasteModel.PasteId = paste.Paste.PasteId;
pasteModel.Url = paste.Paste.Url;
pasteModel.DatePosted = paste.Paste.DatePosted;
pasteModel.Syntax = paste.Paste.Syntax;
pasteModel.HasPassword = !string.IsNullOrEmpty(paste.Paste.HashedPassword);
if (!pasteModel.HasPassword)
{
// Read in the file
var storageService = StorageServiceFactory.GetStorageService(_config.PasteConfig.StorageConfig);
var fileStream = storageService.GetFile(paste.Paste.FileName);
if (fileStream == null)
continue;
byte[] ivBytes = Encoding.Unicode.GetBytes(paste.Paste.IV);
byte[] keyBytes = AesCounterManaged.CreateKey(paste.Paste.Key, ivBytes, paste.Paste.KeySize);
using (AesCounterStream cs = new AesCounterStream(fileStream, false, keyBytes, ivBytes))
using (StreamReader sr = new StreamReader(cs, Encoding.Unicode))
{
pasteModel.Content = await sr.ReadToEndAsync();
}
}
model.Items.Add(pasteModel);
}
}
}
return View(model);
}
return new StatusCodeResult(StatusCodes.Status404NotFound);
}
[HttpGet]
[AllowAnonymous]
[TrackPageView]
public IActionResult NewVault()
{
ViewBag.Title = "Create Vault";
ModifyVaultViewModel model = new ModifyVaultViewModel();
model.CurrentSub = Subdomain;
return View("~/Areas/Vault/Views/Vault/ModifyVault.cshtml", model);
}
[HttpGet]
[AllowAnonymous]
[TrackPageView]
public IActionResult NewVaultFromService(string type, string items)
{
ViewBag.Title = "Create Vault";
ModifyVaultViewModel model = new ModifyVaultViewModel();
model.CurrentSub = Subdomain;
string decodedItems = HttpUtility.UrlDecode(items);
string[] allURLs = decodedItems.Split(',');
int index = 0;
foreach (string url in allURLs)
{
string[] urlInfo = url.Split(':');
string uploadId = urlInfo[0];
string title = string.Empty;
if (urlInfo.GetUpperBound(0) >= 1)
{
// They also passed in the original filename, so let's use it as our title
title = urlInfo[1];
}
if (IsValidItem(type, uploadId))
{
ModifyVaultItemViewModel item = new ModifyVaultItemViewModel();
item.isTemplate = false;
item.index = index;
item.title = title;
item.url = uploadId;
item.type = type;
model.items.Add(item);
index++;
}
}
return View("~/Areas/Vault/Views/Vault/ModifyVault.cshtml", model);
}
[HttpGet]
[TrackPageView]
public IActionResult EditVault(string url, string type, string items)
{
ViewBag.Title = "Edit Vault";
Vault.Models.Vault foundVault = _dbContext.Vaults.Where(v => v.Url == url).FirstOrDefault();
if (foundVault != null)
{
if (foundVault.User.Username == User.Identity.Name)
{
ViewBag.Title = "Edit Vault | " + foundVault.Title;
ModifyVaultViewModel model = new ModifyVaultViewModel();
model.CurrentSub = Subdomain;
model.isEdit = true;
model.vaultId = foundVault.VaultId;
model.title = foundVault.Title;
model.description = foundVault.Description;
int index = 0;
// Add all their existing items for the vault
foreach (VaultItem item in foundVault.VaultItems.OrderBy(v => v.Index))
{
ModifyVaultItemViewModel itemModel = new ModifyVaultItemViewModel();
itemModel.index = index;
itemModel.isTemplate = false;
if (item.GetType().BaseType == typeof(UploadVaultItem))
{
UploadVaultItem upload = (UploadVaultItem)item;
itemModel.title = upload.Title;
itemModel.description = upload.Description;
itemModel.type = "Upload";
itemModel.url = upload.Upload.Url;
model.items.Add(itemModel);
index++;
}
else if (item.GetType().BaseType == typeof(PasteVaultItem))
{
PasteVaultItem paste = (PasteVaultItem)item;
itemModel.title = paste.Title;
itemModel.description = paste.Description;
itemModel.type = "Paste";
itemModel.url = paste.Paste.Url;
model.items.Add(itemModel);
index++;
}
}
// If they passed any new items in via the parameters, let's add them
if (!string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(items))
{
string decodedItems = HttpUtility.UrlDecode(items);
string[] allItems = decodedItems.Split(',');
foreach (string newItem in allItems)
{
string[] urlInfo = newItem.Split(':');
string itemId = urlInfo[0];
string title = string.Empty;
if (urlInfo.GetUpperBound(0) >= 1)
{
// They also passed in the original filename, so let's use it as our title
title = urlInfo[1];
}
if (IsValidItem(type, itemId))
{
ModifyVaultItemViewModel item = new ModifyVaultItemViewModel();
item.isTemplate = false;
item.index = index;
item.title = title;
item.url = itemId;
item.type = type;
model.items.Add(item);
index++;
}
}
}
return View("~/Areas/Vault/Views/Vault/ModifyVault.cshtml", model);
}
return new StatusCodeResult(StatusCodes.Status403Forbidden);
}
return new StatusCodeResult(StatusCodes.Status404NotFound);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult CreateVault(ModifyVaultViewModel model)
{
if (model != null)
{
if (!string.IsNullOrEmpty(model.title))
{
Models.Vault newVault = new Models.Vault();
// Create a new ID
string url = StringHelper.RandomString(_config.VaultConfig.UrlLength);
while (_dbContext.Vaults.Where(v => v.Url == url).FirstOrDefault() != null)
{
url = StringHelper.RandomString(_config.VaultConfig.UrlLength);
}
newVault.Url = url;
newVault.DateCreated = DateTime.Now;
newVault.Title = model.title;
newVault.Description = model.description;
if (User.Identity.IsAuthenticated)
{
User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
if (user != null)
{
newVault.UserId = user.UserId;
}
}
// Add/Verify items
if (model.items.Any())
{
int index = 0;
foreach (ModifyVaultItemViewModel item in model.items)
{
if (IsValidItem(item.type, item.url))
{
switch (item.type.ToLower())
{
case "upload":
UploadVaultItem newUpload = new UploadVaultItem();
newUpload.Index = index;
newUpload.DateAdded = DateTime.Now;
newUpload.Title = item.title;
newUpload.Description = item.description;
newUpload.UploadId = _dbContext.Uploads.Where(u => u.Url == item.url).FirstOrDefault().UploadId;
newVault.VaultItems.Add(newUpload);
index++;
break;
case "paste":
PasteVaultItem newPaste = new PasteVaultItem();
newPaste.Index = index;
newPaste.DateAdded = DateTime.Now;
newPaste.Title = item.title;
newPaste.Description = item.description;
newPaste.PasteId = _dbContext.Pastes.Where(p => p.Url == item.url).FirstOrDefault().PasteId;
newVault.VaultItems.Add(newPaste);
index++;
break;
default:
return Json(new { error = new { message = "You have an invalid item type: " + item.type } });
}
}
else
{
return Json(new { error = new { message = "You have an invalid item URL: " + item.url } });
}
}
}
// Add and save the new vault
_dbContext.Vaults.Add(newVault);
_dbContext.SaveChanges();
return Json(new { result = new { url = Url.SubRouteUrl("v", "Vault.ViewVault", new { id = url }) } });
}
return Json(new { error = new { message = "You must supply a Title" } });
}
return Json(new { error = new { message = "Invalid Parameters" } });
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult EditVault(ModifyVaultViewModel model)
{
if (model != null)
{
Vault.Models.Vault foundVault = _dbContext.Vaults.Where(v => v.VaultId == model.vaultId).FirstOrDefault();
if (foundVault != null)
{
if (foundVault.User.Username == User.Identity.Name)
{
foundVault.DateEdited = DateTime.Now;
foundVault.Title = model.title;
foundVault.Description = model.description;
// Clear previous items
List<VaultItem> vaultItems = _dbContext.VaultItems.Where(v => v.VaultId == foundVault.VaultId).ToList();
if (vaultItems != null)
{
foreach (VaultItem item in vaultItems)
{
_dbContext.VaultItems.Remove(item);
}
}
foundVault.VaultItems.Clear();
// Add/Verify items
if (model.items.Any())
{
int index = 0;
foreach (ModifyVaultItemViewModel item in model.items)
{
if (IsValidItem(item.type, item.url))
{
switch (item.type.ToLower())
{
case "upload":
UploadVaultItem newUpload = new UploadVaultItem();
newUpload.Index = index;
newUpload.DateAdded = DateTime.Now;
newUpload.Title = item.title;
newUpload.Description = item.description;
newUpload.UploadId = _dbContext.Uploads.Where(u => u.Url == item.url).FirstOrDefault().UploadId;
foundVault.VaultItems.Add(newUpload);
index++;
break;
case "paste":
PasteVaultItem newPaste = new PasteVaultItem();
newPaste.Index = index;
newPaste.DateAdded = DateTime.Now;
newPaste.Title = item.title;
newPaste.Description = item.description;
newPaste.PasteId = _dbContext.Pastes.Where(p => p.Url == item.url).FirstOrDefault().PasteId;
foundVault.VaultItems.Add(newPaste);
index++;
break;
default:
return Json(new { error = new { message = "You have an invalid item type: " + item.type } });
}
}
else
{
return Json(new { error = new { message = "You have an invalid item URL: " + item.url } });
}
}
}
_dbContext.Entry(foundVault).State = EntityState.Modified;
_dbContext.SaveChanges();
return Json(new { result = new { url = Url.SubRouteUrl("v", "Vault.ViewVault", new { id = foundVault.Url }) } });
}
return Json(new { error = new { message = "You do not have permission to edit this Vault" } });
}
return Json(new { error = new { message = "That Vault does not exist" } });
}
return Json(new { error = new { message = "Invalid Parameters" } });
}
[HttpPost]
[HttpOptions]
public IActionResult Delete(string id)
{
Vault.Models.Vault foundVault = _dbContext.Vaults.Where(v => v.Url == id).FirstOrDefault();
if (foundVault != null)
{
if (foundVault.User?.Username == User.Identity.Name ||
User.IsInRole("Admin"))
{
_dbContext.Vaults.Remove(foundVault);
_dbContext.SaveChanges();
return Json(new { result = new { url = Url.SubRouteUrl("vault", "Vault.CreateVault") } });
}
return Json(new { error = new { message = "You do not have permission to edit this Vault" } });
}
return Json(new { error = new { message = "That Vault does not exist" } });
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ValidateItem(string type, string url)
{
if (IsValidItem(type, url))
{
return Json(new { result = new { valid = true } });
}
else
{
return Json(new { error = new { message = "Invalid URL Id for this Item" } });
}
}
private bool IsValidItem(string type, string url)
{
bool valid = false;
if (!string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(url))
{
switch (type.ToLower())
{
case "upload":
Upload.Models.Upload foundUpload = _dbContext.Uploads.Where(u => u.Url == url).FirstOrDefault();
if (foundUpload != null)
{
valid = true;
}
break;
case "paste":
Paste.Models.Paste foundPaste = _dbContext.Pastes.Where(p => p.Url == url).FirstOrDefault();
if (foundPaste != null)
{
valid = true;
}
break;
}
}
return valid;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using L10NSharp;
using SIL.Reporting;
using SIL.Windows.Forms.Extensions;
namespace SIL.Windows.Forms.ImageToolbox.ImageGallery
{
public partial class ImageGalleryControl : UserControl, IImageToolboxControl
{
private ImageCollectionManager _imageCollectionManager;
private PalasoImage _previousImage;
public bool InSomeoneElesesDesignMode;
public ImageGalleryControl()
{
InitializeComponent();
_thumbnailViewer.CaptionMethod = ((s) => string.Empty);//don't show a caption
_thumbnailViewer.LoadComplete += ThumbnailViewerOnLoadComplete;
_searchResultStats.Text = "";
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
// For Linux, we can install the package if requested.
_downloadInstallerLink.Text = "Install the Art Of Reading package (this may be very slow)".Localize("ImageToolbox.InstallArtOfReading");
_downloadInstallerLink.URL = null;
_downloadInstallerLink.LinkClicked += InstallLinkClicked;
}
else
{
// Ensure that we can get localized text here.
_downloadInstallerLink.Text = "Download Art Of Reading Installer".Localize("ImageToolbox.DownloadArtOfReading");
}
_labelSearch.Text = "Image Galleries".Localize("ImageToolbox.ImageGalleries");
SearchLanguage = "en"; // until/unless the owner specifies otherwise explicitly
// Get rid of any trace of a border on the toolstrip.
toolStrip1.Renderer = new NoBorderToolStripRenderer();
// For some reason, setting these BackColor values in InitializeComponent() doesn't work.
// The BackColor gets set back to the standard control background color somewhere...
_downloadInstallerLink.BackColor = Color.White;
_messageLabel.BackColor = Color.White;
_messageLabel.SizeChanged += MessageLabelSizeChanged;
}
/// <summary>
/// use if the calling app already has some notion of what the user might be looking for (e.g. the definition in a dictionary program)
/// </summary>
/// <param name="searchTerm"></param>
public void SetIntialSearchTerm(string searchTerm)
{
_searchTermsBox.Text = searchTerm;
}
/// <summary>
/// Gets or sets the language used in searching for an image by words.
/// </summary>
public string SearchLanguage { get; set; }
void _thumbnailViewer_SelectedIndexChanged(object sender, EventArgs e)
{
if(ImageChanged!=null && _thumbnailViewer.HasSelection)
{
ImageChanged.Invoke(this, null);
}
}
private void _thumbnailViewer_DoubleClick(object sender, EventArgs e)
{
if (ImageChangedAndAccepted != null && _thumbnailViewer.HasSelection)
{
ImageChangedAndAccepted.Invoke(this, null);
}
}
private void _searchButton_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
_searchButton.Enabled = false;
try
{
_thumbnailViewer.Clear();
if (!string.IsNullOrWhiteSpace(_searchTermsBox.Text))
{
bool foundExactMatches;
// (avoid enumerating the returned IEnumerable<object> more than once by copying to a List.)
var results = _imageCollectionManager.GetMatchingImages(_searchTermsBox.Text, true, out foundExactMatches).ToList();
if (results.Any())
{
_messageLabel.Visible = false;
_downloadInstallerLink.Visible = false;
_thumbnailViewer.LoadItems(results);
var fmt = "Found {0} images".Localize("ImageToolbox.MatchingImages", "The {0} will be replaced by the number of matching images");
if (!foundExactMatches)
fmt = "Found {0} images with names close to \u201C{1}\u201D".Localize("ImageToolbox.AlmostMatchingImages", "The {0} will be replaced by the number of images found. The {1} will be replaced with the search string.");
_searchResultStats.Text = string.Format(fmt, results.Count, _searchTermsBox.Text);
_searchResultStats.ForeColor = foundExactMatches ? Color.Black : Color.FromArgb(0x34, 0x65, 0xA4); //#3465A4
_searchResultStats.Font = new Font("Segoe UI", 9F, foundExactMatches ? FontStyle.Regular : FontStyle.Bold);
}
else
{
_messageLabel.Visible = true;
if (!_searchLanguageMenu.Visible)
_downloadInstallerLink.Visible = true;
_searchResultStats.Text = "Found no matching images".Localize("ImageToolbox.NoMatchingImages");
_searchResultStats.ForeColor = Color.Black;
_searchResultStats.Font = new Font("Segoe UI", 9F, FontStyle.Regular);
}
}
}
catch (Exception)
{
}
_searchButton.Enabled = true;
//_okButton.Enabled = false;
}
private void ThumbnailViewerOnLoadComplete(object sender, EventArgs eventArgs)
{
Cursor.Current = Cursors.Default;
}
public string ChosenPath { get { return _thumbnailViewer.SelectedPath; } }
public bool HaveImageCollectionOnThisComputer
{
get { return _imageCollectionManager != null; }
}
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
_thumbnailViewer.Closing();
}
public void SetImage(PalasoImage image)
{
_previousImage = image;
if(ImageChanged!=null)
ImageChanged.Invoke(this,null);
}
public PalasoImage GetImage()
{
if(ChosenPath!=null && File.Exists(ChosenPath))
{
try
{
return PalasoImage.FromFile(ChosenPath);
}
catch (Exception error)
{
ErrorReport.ReportNonFatalExceptionWithMessage(error, "There was a problem choosing that image.");
return _previousImage;
}
}
return _previousImage;
}
public event EventHandler ImageChanged;
/// <summary>
/// happens when you double click an item
/// </summary>
public event EventHandler ImageChangedAndAccepted;
private void _searchTermsBox_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode ==Keys.Enter)
{
e.SuppressKeyPress = true;
_searchButton_Click(sender, null);
}
else
{
_searchResultStats.Text = "";
}
}
private new bool DesignMode
{
get
{
return (base.DesignMode || GetService(typeof(IDesignerHost)) != null) ||
(LicenseManager.UsageMode == LicenseUsageMode.Designtime);
}
}
private void ArtOfReadingChooser_Load(object sender, EventArgs e)
{
if (DesignMode)
return;
_imageCollectionManager = ImageCollectionManager.FromStandardLocations(SearchLanguage);
_collectionToolStrip.Visible = false;
if (_imageCollectionManager == null)
{
_messageLabel.Visible = true;
_messageLabel.Text = "This computer doesn't appear to have any galleries installed yet.".Localize("ImageToolbox.NoGalleries");
_downloadInstallerLink.Visible = true;
_searchTermsBox.Enabled = false;
_searchButton.Enabled = false;
}
else
{
#if DEBUG
// _searchTermsBox.Text = @"flower";
#endif
SetupSearchLanguageChoice();
_messageLabel.Visible = string.IsNullOrEmpty(_searchTermsBox.Text);
// Adjust size to avoid text truncation
_messageLabel.Height = 200;
SetMessageLabelText();
_thumbnailViewer.SelectedIndexChanged += new EventHandler(_thumbnailViewer_SelectedIndexChanged);
if (_imageCollectionManager.Collections.Count() > 1)
{
_collectionToolStrip.Visible = true;
_collectionDropDown.Visible = true;
_collectionDropDown.Text =
"Galleries".Localize("ImageToolbox.Galleries");
if(ImageToolboxSettings.Default.DisabledImageCollections == null)
{
ImageToolboxSettings.Default.DisabledImageCollections = new StringCollection();
}
foreach (var collection in _imageCollectionManager.Collections)
{
if(ImageToolboxSettings.Default.DisabledImageCollections.Contains(collection.FolderPath))
{
collection.Enabled = false;
}
var text = Path.GetFileNameWithoutExtension(collection.Name);
var item = new ToolStripMenuItem(text);
_collectionDropDown.DropDownItems.Add(item);
item.CheckOnClick = true;
item.CheckState = collection.Enabled ? CheckState.Checked : CheckState.Unchecked;
item.CheckedChanged += (o, args) =>
{
if(_collectionDropDown.DropDownItems.Cast<ToolStripMenuItem>().Count(x => x.Checked) == 0)
item.Checked = true; // tried to uncheck the last one, don't allow it.
else
{
collection.Enabled = item.Checked;
var disabledSettings = ImageToolboxSettings.Default.DisabledImageCollections;
if (disabledSettings == null)
ImageToolboxSettings.Default.DisabledImageCollections = disabledSettings = new StringCollection();
if (item.Checked && disabledSettings.Contains(collection.FolderPath))
disabledSettings.Remove(collection.FolderPath);
if (!item.Checked && !disabledSettings.Contains(collection.FolderPath))
disabledSettings.Add(collection.FolderPath);
ImageToolboxSettings.Default.Save();
}
};
}
}
else
{
// otherwise, just leave them all enabled
}
}
_messageLabel.Font = new Font(SystemFonts.DialogFont.FontFamily, 10);
#if DEBUG
//if (!HaveImageCollectionOnThisComputer)
// return;
//when just testing, I just want to see some choices.
// _searchTermsBox.Text = @"flower";
//_searchButton_Click(this,null);
#endif
}
private void SetMessageLabelText()
{
var msg = "In the box above, type what you are searching for, then press ENTER.".Localize("ImageToolbox.EnterSearchTerms");
// Allow for the old index that contained English and Indonesian together.
var searchLang = "English + Indonesian";
// If we have the new multilingual index, _searchLanguageMenu will be visible. Its tooltip
// contains both the native name of the current search language + its English name in
// parentheses if its in a nonRoman script or otherwise thought to be unguessable by a
// literate speaker of an European language. (The menu displays only the native name, and
// SearchLanguage stores only the ISO code.)
if (_searchLanguageMenu.Visible)
searchLang = _searchLanguageMenu.ToolTipText;
msg += Environment.NewLine + Environment.NewLine +
String.Format("The search box is currently set to {0}".Localize("ImageToolbox.SearchLanguage"), searchLang);
if (PlatformUtilities.Platform.IsWindows && !_searchLanguageMenu.Visible)
{
msg += Environment.NewLine + Environment.NewLine +
"Did you know that there is a new version of this collection which lets you search in Arabic, Bengali, Chinese, English, French, Indonesian, Hindi, Portuguese, Spanish, Thai, or Swahili? It is free and available for downloading."
.Localize("ImageToolbox.NewMultilingual");
_downloadInstallerLink.Visible = true;
_downloadInstallerLink.BackColor = Color.White;
}
// Restore alignment (from center) for messages. (See https://silbloom.myjetbrains.com/youtrack/issue/BL-2753.)
_messageLabel.TextAlign = _messageLabel.RightToLeft==RightToLeft.Yes ? HorizontalAlignment.Right : HorizontalAlignment.Left;
_messageLabel.Text = msg;
}
/// <summary>
/// Position the download link label properly whenever the size of the main message label changes,
/// whether due to changing its text or changing the overall dialog box size. (BL-2853)
/// </summary>
private void MessageLabelSizeChanged(object sender, EventArgs eventArgs)
{
if (_searchLanguageMenu.Visible || !PlatformUtilities.Platform.IsWindows || !_downloadInstallerLink.Visible)
return;
_downloadInstallerLink.Width = _messageLabel.Width; // not sure why this isn't automatic
if (_downloadInstallerLink.Location.Y != _messageLabel.Bottom + 5)
_downloadInstallerLink.Location = new Point(_downloadInstallerLink.Left, _messageLabel.Bottom + 5);
}
protected class LanguageChoice
{
static readonly List<string> idsOfRecognizableLanguages = new List<string> { "en", "fr", "es", "it", "tpi", "pt", "id" };
private readonly CultureInfo _info;
public LanguageChoice(CultureInfo ci)
{
_info = ci;
}
public string Id { get { return _info.Name == "zh-Hans" ? "zh" : _info.Name; } }
public string NativeName
{
get
{
if (_info.Name == "id" && _info.NativeName == "Indonesia")
return "Bahasa Indonesia"; // This is a known problem in Windows/.Net.
return _info.NativeName;
}
}
public override string ToString()
{
if (_info.NativeName == _info.EnglishName)
return NativeName; // English (English) looks rather silly...
if (idsOfRecognizableLanguages.Contains(Id))
return NativeName;
return String.Format("{0} ({1})", _info.NativeName, _info.EnglishName);
}
}
private void SetupSearchLanguageChoice()
{
var indexLangs = _imageCollectionManager.IndexLanguageIds;
if (indexLangs == null)
{
_searchLanguageMenu.Visible = false;
}
else
{
_searchLanguageMenu.Visible = true;
foreach (var id in indexLangs)
{
var ci = id == "zh" ? new CultureInfo("zh-Hans") : new CultureInfo(id);
var choice = new LanguageChoice(ci);
var item = _searchLanguageMenu.DropDownItems.Add(choice.ToString());
item.Tag = choice;
item.Click += SearchLanguageClick;
if (id == SearchLanguage)
{
_searchLanguageMenu.Text = choice.NativeName;
_searchLanguageMenu.ToolTipText = choice.ToString();
}
}
}
// The Mono renderer makes the toolstrip stick out. (This is a Mono bug that
// may not be worth spending time on.) Let's not poke the user in the eye
// with an empty toolstrip.
if (Environment.OSVersion.Platform == PlatformID.Unix)
toolStrip1.Visible = _searchLanguageMenu.Visible;
}
void SearchLanguageClick(object sender, EventArgs e)
{
var item = sender as ToolStripItem;
if (item != null)
{
var lang = item.Tag as LanguageChoice;
if (lang != null && SearchLanguage != lang.Id)
{
_searchLanguageMenu.Text = lang.NativeName;
_searchLanguageMenu.ToolTipText = lang.ToString();
SearchLanguage = lang.Id;
_imageCollectionManager.ChangeSearchLanguageAndReloadIndex(lang.Id);
SetMessageLabelText(); // Update with new language name.
}
}
}
/// <summary>
/// To actually focus on the search box, the Mono runtime library appears to
/// first need us to focus the search button, wait a bit, and then focus the
/// search box. Bizarre, unfortunate, but true. (One of those bugs that we
/// couldn't write code to do if we tried!)
/// See https://jira.sil.org/browse/BL-964.
/// </summary>
internal void FocusSearchBox()
{
_searchButton.GotFocus += _searchButtonGotSetupFocus;
_searchButton.Select();
}
private System.Windows.Forms.Timer _focusTimer1;
private void _searchButtonGotSetupFocus(object sender, EventArgs e)
{
_searchButton.GotFocus -= _searchButtonGotSetupFocus;
_focusTimer1 = new System.Windows.Forms.Timer(this.components);
_focusTimer1.Tick += new System.EventHandler(this._focusTimer1_Tick);
_focusTimer1.Interval = 100;
_focusTimer1.Enabled = true;
}
private void _focusTimer1_Tick(object sender, EventArgs e)
{
_focusTimer1.Enabled = false;
_focusTimer1.Dispose();
_focusTimer1 = null;
_searchTermsBox.TextBox.Focus();
}
/// <summary>
/// Try to install the artofreading package if possible. Use a GUI program if
/// possible, but if not, try the command-line program with a GUI password
/// dialog.
/// </summary>
/// <remarks>
/// On Windows, the link label opens a web page to let the user download the
/// installer. This is the analogous behavior for Linux, but is potentially
/// so slow (300MB download) that we fire off the program without waiting for
/// it to finish.
/// </remarks>
private void InstallLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (Environment.OSVersion.Platform != PlatformID.Unix)
return;
// Install the artofreading package if at all possible.
if (File.Exists("/usr/bin/software-center"))
{
using (var process = new Process())
{
process.StartInfo = new ProcessStartInfo {
FileName = "/usr/bin/python",
Arguments = "/usr/bin/software-center art-of-reading",
UseShellExecute = false,
RedirectStandardOutput = false,
CreateNoWindow = false
};
process.Start();
}
}
else if (File.Exists("/usr/bin/ssh-askpass"))
{
using (var process = new Process())
{
process.StartInfo = new ProcessStartInfo {
FileName = "/usr/bin/sudo",
Arguments = "-A /usr/bin/apt-get -y install art-of-reading",
UseShellExecute = false,
RedirectStandardOutput = false,
CreateNoWindow = false
};
process.StartInfo.EnvironmentVariables.Add("SUDO_ASKPASS", "/usr/bin/ssh-askpass");
process.Start();
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Sources.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Akka.Annotations;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation.Stages;
using Akka.Streams.Stage;
using Akka.Streams.Supervision;
using Akka.Streams.Util;
using Akka.Util;
namespace Akka.Streams.Implementation
{
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="TOut">TBD</typeparam>
[InternalApi]
public sealed class QueueSource<TOut> : GraphStageWithMaterializedValue<SourceShape<TOut>, ISourceQueueWithComplete<TOut>>
{
#region internal classes
/// <summary>
/// TBD
/// </summary>
public interface IInput { }
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
internal sealed class Offer<T> : IInput
{
/// <summary>
/// TBD
/// </summary>
/// <param name="element">TBD</param>
/// <param name="completionSource">TBD</param>
public Offer(T element, TaskCompletionSource<IQueueOfferResult> completionSource)
{
Element = element;
CompletionSource = completionSource;
}
/// <summary>
/// TBD
/// </summary>
public T Element { get; }
/// <summary>
/// TBD
/// </summary>
public TaskCompletionSource<IQueueOfferResult> CompletionSource { get; }
}
/// <summary>
/// TBD
/// </summary>
internal sealed class Completion : IInput
{
/// <summary>
/// TBD
/// </summary>
public static Completion Instance { get; } = new Completion();
private Completion()
{
}
}
/// <summary>
/// TBD
/// </summary>
internal sealed class Failure : IInput
{
/// <summary>
/// TBD
/// </summary>
/// <param name="ex">TBD</param>
public Failure(Exception ex)
{
Ex = ex;
}
/// <summary>
/// TBD
/// </summary>
public Exception Ex { get; }
}
#endregion
private sealed class Logic : GraphStageLogicWithCallbackWrapper<IInput>, IOutHandler
{
private readonly TaskCompletionSource<object> _completion;
private readonly QueueSource<TOut> _stage;
private IBuffer<TOut> _buffer;
private Offer<TOut> _pendingOffer;
private bool _terminating;
public Logic(QueueSource<TOut> stage, TaskCompletionSource<object> completion) : base(stage.Shape)
{
_completion = completion;
_stage = stage;
SetHandler(stage.Out, this);
}
public void OnPull()
{
if (_stage._maxBuffer == 0)
{
if (_pendingOffer != null)
{
Push(_stage.Out, _pendingOffer.Element);
_pendingOffer.CompletionSource.SetResult(QueueOfferResult.Enqueued.Instance);
_pendingOffer = null;
if (_terminating)
{
_completion.SetResult(new object());
CompleteStage();
}
}
}
else if (_buffer.NonEmpty)
{
Push(_stage.Out, _buffer.Dequeue());
if (_pendingOffer != null)
{
EnqueueAndSuccess(_pendingOffer);
_pendingOffer = null;
}
}
if (_terminating && _buffer.IsEmpty)
{
_completion.SetResult(new object());
CompleteStage();
}
}
public void OnDownstreamFinish()
{
if (_pendingOffer != null)
{
_pendingOffer.CompletionSource.SetResult(QueueOfferResult.QueueClosed.Instance);
_pendingOffer = null;
}
_completion.SetResult(new object());
CompleteStage();
}
public override void PreStart()
{
if (_stage._maxBuffer > 0)
_buffer = Buffer.Create<TOut>(_stage._maxBuffer, Materializer);
InitCallback(Callback());
}
public override void PostStop()
{
StopCallback(input =>
{
var offer = input as Offer<TOut>;
if (offer != null)
{
var promise = offer.CompletionSource;
promise.SetException(new IllegalStateException("Stream is terminated. SourceQueue is detached."));
}
});
}
private void EnqueueAndSuccess(Offer<TOut> offer)
{
_buffer.Enqueue(offer.Element);
offer.CompletionSource.SetResult(QueueOfferResult.Enqueued.Instance);
}
private void BufferElement(Offer<TOut> offer)
{
if (!_buffer.IsFull)
EnqueueAndSuccess(offer);
else
{
switch (_stage._overflowStrategy)
{
case OverflowStrategy.DropHead:
_buffer.DropHead();
EnqueueAndSuccess(offer);
break;
case OverflowStrategy.DropTail:
_buffer.DropTail();
EnqueueAndSuccess(offer);
break;
case OverflowStrategy.DropBuffer:
_buffer.Clear();
EnqueueAndSuccess(offer);
break;
case OverflowStrategy.DropNew:
offer.CompletionSource.SetResult(QueueOfferResult.Dropped.Instance);
break;
case OverflowStrategy.Fail:
var bufferOverflowException =
new BufferOverflowException($"Buffer overflow (max capacity was: {_stage._maxBuffer})!");
offer.CompletionSource.SetResult(new QueueOfferResult.Failure(bufferOverflowException));
_completion.SetException(bufferOverflowException);
FailStage(bufferOverflowException);
break;
case OverflowStrategy.Backpressure:
if (_pendingOffer != null)
offer.CompletionSource.SetException(
new IllegalStateException(
"You have to wait for previous offer to be resolved to send another request."));
else
_pendingOffer = offer;
break;
}
}
}
private Action<IInput> Callback()
{
return GetAsyncCallback<IInput>(
input =>
{
var offer = input as Offer<TOut>;
if (offer != null)
{
if (_stage._maxBuffer != 0)
{
BufferElement(offer);
if (IsAvailable(_stage.Out))
Push(_stage.Out, _buffer.Dequeue());
}
else if (IsAvailable(_stage.Out))
{
Push(_stage.Out, offer.Element);
offer.CompletionSource.SetResult(QueueOfferResult.Enqueued.Instance);
}
else if (_pendingOffer == null)
_pendingOffer = offer;
else
{
switch (_stage._overflowStrategy)
{
case OverflowStrategy.DropHead:
case OverflowStrategy.DropBuffer:
_pendingOffer.CompletionSource.SetResult(QueueOfferResult.Dropped.Instance);
_pendingOffer = offer;
break;
case OverflowStrategy.DropTail:
case OverflowStrategy.DropNew:
offer.CompletionSource.SetResult(QueueOfferResult.Dropped.Instance);
break;
case OverflowStrategy.Backpressure:
offer.CompletionSource.SetException(
new IllegalStateException(
"You have to wait for previous offer to be resolved to send another request"));
break;
case OverflowStrategy.Fail:
var bufferOverflowException =
new BufferOverflowException(
$"Buffer overflow (max capacity was: {_stage._maxBuffer})!");
offer.CompletionSource.SetResult(new QueueOfferResult.Failure(bufferOverflowException));
_completion.SetException(bufferOverflowException);
FailStage(bufferOverflowException);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
var completion = input as Completion;
if (completion != null)
{
if (_stage._maxBuffer != 0 && _buffer.NonEmpty || _pendingOffer != null)
_terminating = true;
else
{
_completion.SetResult(new object());
CompleteStage();
}
}
var failure = input as Failure;
if (failure != null)
{
_completion.SetException(failure.Ex);
FailStage(failure.Ex);
}
});
}
internal void Invoke(IInput offer) => InvokeCallbacks(offer);
}
/// <summary>
/// TBD
/// </summary>
public sealed class Materialized : ISourceQueueWithComplete<TOut>
{
private readonly Action<IInput> _invokeLogic;
private readonly TaskCompletionSource<object> _completion;
/// <summary>
/// TBD
/// </summary>
/// <param name="invokeLogic">TBD</param>
/// <param name="completion">TBD</param>
public Materialized(Action<IInput> invokeLogic, TaskCompletionSource<object> completion)
{
_invokeLogic = invokeLogic;
_completion = completion;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="element">TBD</param>
/// <returns>TBD</returns>
public Task<IQueueOfferResult> OfferAsync(TOut element)
{
var promise = new TaskCompletionSource<IQueueOfferResult>();
_invokeLogic(new Offer<TOut>(element, promise));
return promise.Task;
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public Task WatchCompletionAsync() => _completion.Task;
/// <summary>
/// TBD
/// </summary>
public void Complete() => _invokeLogic(Completion.Instance);
/// <summary>
/// TBD
/// </summary>
/// <param name="ex">TBD</param>
public void Fail(Exception ex) => _invokeLogic(new Failure(ex));
}
private readonly int _maxBuffer;
private readonly OverflowStrategy _overflowStrategy;
/// <summary>
/// TBD
/// </summary>
/// <param name="maxBuffer">TBD</param>
/// <param name="overflowStrategy">TBD</param>
public QueueSource(int maxBuffer, OverflowStrategy overflowStrategy)
{
_maxBuffer = maxBuffer;
_overflowStrategy = overflowStrategy;
Shape = new SourceShape<TOut>(Out);
}
/// <summary>
/// TBD
/// </summary>
public Outlet<TOut> Out { get; } = new Outlet<TOut>("queueSource.out");
/// <summary>
/// TBD
/// </summary>
public override SourceShape<TOut> Shape { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
public override ILogicAndMaterializedValue<ISourceQueueWithComplete<TOut>> CreateLogicAndMaterializedValue(Attributes inheritedAttributes)
{
var completion = new TaskCompletionSource<object>();
var logic = new Logic(this, completion);
return new LogicAndMaterializedValue<ISourceQueueWithComplete<TOut>>(logic, new Materialized(t => logic.Invoke(t), completion));
}
}
/// <summary>
/// INTERNAL API
/// </summary>
[InternalApi]
public sealed class UnfoldResourceSource<TOut, TSource> : GraphStage<SourceShape<TOut>>
{
#region Logic
private sealed class Logic : OutGraphStageLogic
{
private readonly UnfoldResourceSource<TOut, TSource> _stage;
private readonly Lazy<Decider> _decider;
private TSource _blockingStream;
private bool _open;
public Logic(UnfoldResourceSource<TOut, TSource> stage, Attributes inheritedAttributes) : base(stage.Shape)
{
_stage = stage;
_decider = new Lazy<Decider>(() =>
{
var strategy = inheritedAttributes.GetAttribute<ActorAttributes.SupervisionStrategy>(null);
return strategy != null ? strategy.Decider : Deciders.StoppingDecider;
});
SetHandler(stage.Out, this);
}
public override void OnPull()
{
var stop = false;
while (!stop)
{
try
{
var data = _stage._readData(_blockingStream);
if (data.HasValue)
Push(_stage.Out, data.Value);
else
CloseStage();
break;
}
catch (Exception ex)
{
var directive = _decider.Value(ex);
switch (directive)
{
case Directive.Stop:
_stage._close(_blockingStream);
FailStage(ex);
stop = true;
break;
case Directive.Restart:
RestartState();
break;
case Directive.Resume:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
public override void OnDownstreamFinish() => CloseStage();
public override void PreStart()
{
_blockingStream = _stage._create();
_open = true;
}
private void RestartState()
{
_stage._close(_blockingStream);
_blockingStream = _stage._create();
_open = true;
}
private void CloseStage()
{
try
{
_stage._close(_blockingStream);
_open = false;
CompleteStage();
}
catch (Exception ex)
{
FailStage(ex);
}
}
public override void PostStop()
{
if (_open)
_stage._close(_blockingStream);
}
}
#endregion
private readonly Func<TSource> _create;
private readonly Func<TSource, Option<TOut>> _readData;
private readonly Action<TSource> _close;
/// <summary>
/// TBD
/// </summary>
/// <param name="create">TBD</param>
/// <param name="readData">TBD</param>
/// <param name="close">TBD</param>
public UnfoldResourceSource(Func<TSource> create, Func<TSource, Option<TOut>> readData, Action<TSource> close)
{
_create = create;
_readData = readData;
_close = close;
Shape = new SourceShape<TOut>(Out);
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.UnfoldResourceSource;
/// <summary>
/// TBD
/// </summary>
public Outlet<TOut> Out { get; } = new Outlet<TOut>("UnfoldResourceSource.out");
/// <summary>
/// TBD
/// </summary>
public override SourceShape<TOut> Shape { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this, inheritedAttributes);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "UnfoldResourceSource";
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TSource">TBD</typeparam>
[InternalApi]
public sealed class UnfoldResourceSourceAsync<TOut, TSource> : GraphStage<SourceShape<TOut>>
{
#region Logic
private sealed class Logic : OutGraphStageLogic
{
private readonly UnfoldResourceSourceAsync<TOut, TSource> _source;
private readonly Lazy<Decider> _decider;
private TaskCompletionSource<TSource> _resource;
private Action<Either<Option<TOut>, Exception>> _createdCallback;
private Action<Tuple<Action, Task>> _closeCallback;
private bool _open;
public Logic(UnfoldResourceSourceAsync<TOut, TSource> source, Attributes inheritedAttributes) : base(source.Shape)
{
_source = source;
_resource = new TaskCompletionSource<TSource>();
Decider CreateDecider()
{
var strategy = inheritedAttributes.GetAttribute<ActorAttributes.SupervisionStrategy>(null);
return strategy != null ? strategy.Decider : Deciders.StoppingDecider;
}
_decider = new Lazy<Decider>(CreateDecider);
SetHandler(source.Out, this);
}
public override void OnPull()
{
void Ready(TSource source)
{
try
{
void Continune(Task<Option<TOut>> t)
{
if (!t.IsFaulted && !t.IsCanceled)
_createdCallback(new Left<Option<TOut>, Exception>(t.Result));
else
_createdCallback(new Right<Option<TOut>, Exception>(t.Exception));
}
_source._readData(source).ContinueWith(Continune);
}
catch (Exception ex)
{
ErrorHandler(ex);
}
}
OnResourceReady(Ready);
}
public override void OnDownstreamFinish() => CloseStage();
public override void PreStart()
{
CreateStream(false);
void CreatedHandler(Either<Option<TOut>, Exception> either)
{
if (either.IsLeft)
{
var element = either.ToLeft().Value;
if (element.HasValue)
Push(_source.Out, element.Value);
else
CloseStage();
}
else
ErrorHandler(either.ToRight().Value);
}
_createdCallback = GetAsyncCallback<Either<Option<TOut>, Exception>>(CreatedHandler);
void CloseHandler(Tuple<Action, Task> t)
{
if (t.Item2.IsCompleted && !t.Item2.IsFaulted)
{
_open = false;
t.Item1();
}
else
{
_open = false;
FailStage(t.Item2.Exception);
}
}
_closeCallback = GetAsyncCallback<Tuple<Action, Task>>(CloseHandler);
}
private void CreateStream(bool withPull)
{
void Handler(Either<TSource, Exception> either)
{
if (either.IsLeft)
{
_open = true;
_resource.SetResult(either.ToLeft().Value);
if (withPull)
OnPull();
}
else
FailStage(either.ToRight().Value);
}
var cb = GetAsyncCallback<Either<TSource, Exception>>(Handler);
try
{
void Continue(Task<TSource> t)
{
if (t.IsCanceled || t.IsFaulted)
cb(new Right<TSource, Exception>(t.Exception));
else
cb(new Left<TSource, Exception>(t.Result));
}
_source._create().ContinueWith(Continue);
}
catch (Exception ex)
{
FailStage(ex);
}
}
private void OnResourceReady(Action<TSource> action) => _resource.Task.ContinueWith(t =>
{
if (!t.IsFaulted && !t.IsCanceled)
action(t.Result);
});
private void ErrorHandler(Exception ex)
{
var directive = _decider.Value(ex);
switch (directive)
{
case Directive.Stop:
OnResourceReady(s => _source._close(s));
FailStage(ex);
break;
case Directive.Resume:
OnPull();
break;
case Directive.Restart:
RestartState();
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void CloseAndThen(Action action)
{
SetKeepGoing(true);
void Ready(TSource source)
{
try
{
_source._close(source).ContinueWith(t => _closeCallback(Tuple.Create(action, t)));
}
catch (Exception ex)
{
var fail = GetAsyncCallback(() => FailStage(ex));
fail();
}
finally
{
_open = false;
}
}
OnResourceReady(Ready);
}
private void RestartState()
{
void Restart()
{
_resource = new TaskCompletionSource<TSource>();
CreateStream(true);
}
CloseAndThen(Restart);
}
private void CloseStage() => CloseAndThen(CompleteStage);
public override void PostStop()
{
if (_open)
CloseStage();
}
}
#endregion
private readonly Func<Task<TSource>> _create;
private readonly Func<TSource, Task<Option<TOut>>> _readData;
private readonly Func<TSource, Task> _close;
/// <summary>
/// TBD
/// </summary>
/// <param name="create">TBD</param>
/// <param name="readData">TBD</param>
/// <param name="close">TBD</param>
public UnfoldResourceSourceAsync(Func<Task<TSource>> create, Func<TSource, Task<Option<TOut>>> readData, Func<TSource, Task> close)
{
_create = create;
_readData = readData;
_close = close;
Shape = new SourceShape<TOut>(Out);
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.UnfoldResourceSourceAsync;
/// <summary>
/// TBD
/// </summary>
public Outlet<TOut> Out { get; } = new Outlet<TOut>("UnfoldResourceSourceAsync.out");
/// <summary>
/// TBD
/// </summary>
public override SourceShape<TOut> Shape { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <returns>TBD</returns>
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this, inheritedAttributes);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => "UnfoldResourceSourceAsync";
}
/// <summary>
/// INTERNAL API
/// </summary>
[InternalApi]
public sealed class LazySource<TOut, TMat> : GraphStageWithMaterializedValue<SourceShape<TOut>, Task<TMat>>
{
#region Logic
private sealed class Logic : OutGraphStageLogic
{
private readonly LazySource<TOut, TMat> _stage;
private readonly TaskCompletionSource<TMat> _completion;
private readonly Attributes _inheritedAttributes;
public Logic(LazySource<TOut, TMat> stage, TaskCompletionSource<TMat> completion, Attributes inheritedAttributes) : base(stage.Shape)
{
_stage = stage;
_completion = completion;
_inheritedAttributes = inheritedAttributes;
SetHandler(stage.Out, this);
}
public override void OnDownstreamFinish()
{
_completion.SetException(new Exception("Downstream canceled without triggering lazy source materialization"));
CompleteStage();
}
public override void OnPull()
{
var source = _stage._sourceFactory();
var subSink = new SubSinkInlet<TOut>(this, "LazySource");
subSink.Pull();
SetHandler(_stage.Out, () => subSink.Pull(), () =>
{
subSink.Cancel();
CompleteStage();
});
subSink.SetHandler(new LambdaInHandler(() => Push(_stage.Out, subSink.Grab())));
try
{
var value = SubFusingMaterializer.Materialize(source.ToMaterialized(subSink.Sink, Keep.Left),
_inheritedAttributes);
_completion.SetResult(value);
}
catch (Exception e)
{
subSink.Cancel();
FailStage(e);
_completion.TrySetException(e);
}
}
public override void PostStop() => _completion.TrySetException(
new Exception("LazySource stopped without completing the materialized task"));
}
#endregion
private readonly Func<Source<TOut, TMat>> _sourceFactory;
/// <summary>
/// Creates a new <see cref="LazySource{TOut,TMat}"/>
/// </summary>
/// <param name="sourceFactory">The factory that generates the source when needed</param>
public LazySource(Func<Source<TOut, TMat>> sourceFactory)
{
_sourceFactory = sourceFactory;
Shape = new SourceShape<TOut>(Out);
}
/// <summary>
/// TBD
/// </summary>
public Outlet<TOut> Out { get; } = new Outlet<TOut>("LazySource.out");
/// <summary>
/// TBD
/// </summary>
public override SourceShape<TOut> Shape { get; }
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes { get; } = DefaultAttributes.LazySource;
/// <summary>
/// TBD
/// </summary>
public override ILogicAndMaterializedValue<Task<TMat>> CreateLogicAndMaterializedValue(Attributes inheritedAttributes)
{
var completion = new TaskCompletionSource<TMat>();
var logic = new Logic(this, completion, inheritedAttributes);
return new LogicAndMaterializedValue<Task<TMat>>(logic, completion.Task);
}
/// <summary>
/// Returns the string representation of the <see cref="LazySource{TOut,TMat}"/>
/// </summary>
public override string ToString() => "LazySource";
}
/// <summary>
/// API for the <see cref="LazySource{TOut,TMat}"/>
/// </summary>
public static class LazySource
{
/// <summary>
/// Creates a new <see cref="LazySource{TOut,TMat}"/> for the given <paramref name="create"/> factory
/// </summary>
public static LazySource<TOut, TMat> Create<TOut, TMat>(Func<Source<TOut, TMat>> create) =>
new LazySource<TOut, TMat>(create);
}
/// <summary>
/// INTERNAL API
/// </summary>
public sealed class EmptySource<TOut> : GraphStage<SourceShape<TOut>>
{
private sealed class Logic : OutGraphStageLogic
{
public Logic(EmptySource<TOut> stage) : base(stage.Shape) => SetHandler(stage.Out, this);
public override void OnPull() => CompleteStage();
public override void PreStart() => CompleteStage();
}
public EmptySource()
{
Shape = new SourceShape<TOut>(Out);
}
public Outlet<TOut> Out { get; } = new Outlet<TOut>("EmptySource.out");
public override SourceShape<TOut> Shape { get; }
protected override Attributes InitialAttributes => DefaultAttributes.LazySource;
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
public override string ToString() => "EmptySource";
}
/// <summary>
/// INTERNAL API
///
/// A graph stage that can be used to integrate Akka.Streams with .NET events.
/// </summary>
/// <typeparam name="TEventArgs"></typeparam>
/// <typeparam name="TDelegate">Delegate</typeparam>
[InternalApi]
public sealed class EventSourceStage<TDelegate, TEventArgs> : GraphStage<SourceShape<TEventArgs>>
{
#region logic
private class Logic : OutGraphStageLogic
{
private readonly EventSourceStage<TDelegate, TEventArgs> _stage;
private readonly LinkedList<TEventArgs> _buffer;
private readonly TDelegate _handler;
private readonly Action<TEventArgs> _onOverflow;
public Logic(EventSourceStage<TDelegate, TEventArgs> stage) : base(stage.Shape)
{
_stage = stage;
_buffer = new LinkedList<TEventArgs>();
var bufferCapacity = stage._maxBuffer;
var onEvent = GetAsyncCallback<TEventArgs>(e =>
{
if (IsAvailable(_stage.Out))
{
Push(_stage.Out, e);
}
else
{
if (_buffer.Count >= bufferCapacity) _onOverflow(e);
else Enqueue(e);
}
});
_handler = _stage._conversion(onEvent);
_onOverflow = SetupOverflowStrategy(stage._overflowStrategy);
SetHandler(stage.Out, this);
}
private void Enqueue(TEventArgs e) => _buffer.AddLast(e);
private TEventArgs Dequeue()
{
var element = _buffer.First.Value;
_buffer.RemoveFirst();
return element;
}
public override void OnPull()
{
if (_buffer.Count > 0)
{
var element = Dequeue();
Push(_stage.Out, element);
}
}
public override void PreStart()
{
base.PreStart();
_stage._addHandler(_handler);
}
public override void PostStop()
{
_stage._removeHandler(_handler);
_buffer.Clear();
base.PostStop();
}
private Action<TEventArgs> SetupOverflowStrategy(OverflowStrategy overflowStrategy)
{
switch (overflowStrategy)
{
case OverflowStrategy.DropHead:
return message =>
{
_buffer.RemoveFirst();
Enqueue(message);
};
case OverflowStrategy.DropTail:
return message =>
{
_buffer.RemoveLast();
Enqueue(message);
};
case OverflowStrategy.DropNew:
return message =>
{
// do nothing
};
case OverflowStrategy.DropBuffer:
return message => {
_buffer.Clear();
Enqueue(message);
};
case OverflowStrategy.Fail:
return message =>
{
FailStage(new BufferOverflowException($"{_stage.Out} buffer has been overflown"));
};
case OverflowStrategy.Backpressure:
return message =>
{
throw new NotSupportedException("OverflowStrategy.Backpressure is not supported");
};
default: throw new NotSupportedException($"Unknown option: {overflowStrategy}");
}
}
}
#endregion
private readonly Func<Action<TEventArgs>, TDelegate> _conversion;
private readonly Action<TDelegate> _addHandler;
private readonly Action<TDelegate> _removeHandler;
private readonly int _maxBuffer;
private readonly OverflowStrategy _overflowStrategy;
public Outlet<TEventArgs> Out { get; } = new Outlet<TEventArgs>("event.out");
/// <summary>
/// Creates a new instance of event source class.
/// </summary>
/// <param name="conversion">Function used to convert given event handler to delegate compatible with underlying .NET event.</param>
/// <param name="addHandler">Action which attaches given event handler to the underlying .NET event.</param>
/// <param name="removeHandler">Action which detaches given event handler to the underlying .NET event.</param>
/// <param name="maxBuffer">Maximum size of the buffer, used in situation when amount of emitted events is higher than current processing capabilities of the downstream.</param>
/// <param name="overflowStrategy">Overflow strategy used, when buffer (size specified by <paramref name="maxBuffer"/>) has been overflown.</param>
public EventSourceStage(Action<TDelegate> addHandler, Action<TDelegate> removeHandler, Func<Action<TEventArgs>, TDelegate> conversion, int maxBuffer, OverflowStrategy overflowStrategy)
{
_conversion = conversion ?? throw new ArgumentNullException(nameof(conversion));
_addHandler = addHandler ?? throw new ArgumentNullException(nameof(addHandler));
_removeHandler = removeHandler ?? throw new ArgumentNullException(nameof(removeHandler));
_maxBuffer = maxBuffer;
_overflowStrategy = overflowStrategy;
Shape = new SourceShape<TEventArgs>(Out);
}
public override SourceShape<TEventArgs> Shape { get; }
protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
}
| |
//
// SearchEntry.cs
//
// Author:
// Aaron Bockover <[email protected]>
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
namespace Banshee.Widgets
{
public class SearchEntry : EventBox
{
private HBox box;
private Entry entry;
private HoverImageButton filter_button;
private HoverImageButton clear_button;
private Menu menu;
private int active_filter_id = -1;
private uint changed_timeout_id = 0;
private string empty_message;
private bool ready = false;
private event EventHandler filter_changed;
private event EventHandler entry_changed;
public event EventHandler Changed {
add { entry_changed += value; }
remove { entry_changed -= value; }
}
public event EventHandler Activated {
add { entry.Activated += value; }
remove { entry.Activated -= value; }
}
public event EventHandler FilterChanged {
add { filter_changed += value; }
remove { filter_changed -= value; }
}
public uint ChangeTimeoutMs { get; set; }
public Menu Menu {
get { return menu; }
}
protected SearchEntry (IntPtr raw) : base (raw)
{
}
public SearchEntry()
{
ChangeTimeoutMs = 25;
AppPaintable = true;
BuildWidget();
BuildMenu();
NoShowAll = true;
}
private void BuildWidget()
{
box = new HBox();
entry = new FramelessEntry(this);
filter_button = new HoverImageButton(IconSize.Menu, new string [] { "edit-find", Stock.Find });
clear_button = new HoverImageButton(IconSize.Menu, new string [] { "edit-clear", Stock.Clear });
clear_button.TooltipText = Mono.Unix.Catalog.GetString ("Clear search");
box.PackStart(filter_button, false, false, 0);
box.PackStart(entry, true, true, 0);
box.PackStart(clear_button, false, false, 0);
Add(box);
box.ShowAll();
entry.StyleSet += OnInnerEntryStyleSet;
entry.StateChanged += OnInnerEntryStateChanged;
entry.FocusInEvent += OnInnerEntryFocusEvent;
entry.FocusOutEvent += OnInnerEntryFocusEvent;
entry.Changed += OnInnerEntryChanged;
filter_button.Image.Xpad = 2;
clear_button.Image.Xpad = 2;
filter_button.CanFocus = false;
clear_button.CanFocus = false;
filter_button.ButtonReleaseEvent += OnButtonReleaseEvent;
clear_button.ButtonReleaseEvent += OnButtonReleaseEvent;
clear_button.Clicked += OnClearButtonClicked;
filter_button.Visible = false;
clear_button.Visible = false;
}
private void BuildMenu()
{
menu = new Menu();
menu.Deactivated += OnMenuDeactivated;
}
private void ShowMenu(uint time)
{
if(menu.Children.Length > 0) {
menu.Popup(null, null, OnPositionMenu, 0, time);
menu.ShowAll();
}
}
private void ShowHideButtons()
{
clear_button.Visible = entry.Text.Length > 0;
filter_button.Visible = menu != null && menu.Children.Length > 0;
}
private void OnPositionMenu(Menu menu, out int x, out int y, out bool push_in)
{
int origin_x, origin_y, tmp;
filter_button.GdkWindow.GetOrigin(out origin_x, out tmp);
GdkWindow.GetOrigin(out tmp, out origin_y);
x = origin_x + filter_button.Allocation.X;
y = origin_y + SizeRequest().Height;
push_in = true;
}
private void OnMenuDeactivated(object o, EventArgs args)
{
filter_button.QueueDraw();
}
private bool toggling = false;
private void OnMenuItemToggled(object o, EventArgs args)
{
if(toggling || !(o is FilterMenuItem)) {
return;
}
toggling = true;
FilterMenuItem item = (FilterMenuItem)o;
foreach(MenuItem child_item in menu) {
if(!(child_item is FilterMenuItem)) {
continue;
}
FilterMenuItem filter_child = (FilterMenuItem)child_item;
if(filter_child != item) {
filter_child.Active = false;
}
}
item.Active = true;
ActiveFilterID = item.ID;
toggling = false;
}
private void OnInnerEntryChanged(object o, EventArgs args)
{
ShowHideButtons();
if(changed_timeout_id > 0) {
GLib.Source.Remove(changed_timeout_id);
}
if (Ready)
changed_timeout_id = GLib.Timeout.Add(ChangeTimeoutMs, OnChangedTimeout);
}
private bool OnChangedTimeout()
{
OnChanged();
return false;
}
private void UpdateStyle ()
{
Gdk.Color color = entry.Style.Base (entry.State);
filter_button.ModifyBg (entry.State, color);
clear_button.ModifyBg (entry.State, color);
box.BorderWidth = (uint)entry.Style.XThickness;
}
private void OnInnerEntryStyleSet (object o, StyleSetArgs args)
{
UpdateStyle ();
}
private void OnInnerEntryStateChanged (object o, EventArgs args)
{
UpdateStyle ();
}
private void OnInnerEntryFocusEvent(object o, EventArgs args)
{
QueueDraw();
}
private void OnButtonReleaseEvent(object o, ButtonReleaseEventArgs args)
{
if(args.Event.Button != 1) {
return;
}
entry.HasFocus = true;
if(o == filter_button) {
ShowMenu(args.Event.Time);
}
}
private void OnClearButtonClicked(object o, EventArgs args)
{
active_filter_id = 0;
entry.Text = String.Empty;
}
protected override bool OnKeyPressEvent (Gdk.EventKey evnt)
{
if (evnt.Key == Gdk.Key.Escape) {
active_filter_id = 0;
entry.Text = String.Empty;
return true;
}
return base.OnKeyPressEvent (evnt);
}
protected override bool OnExposeEvent(Gdk.EventExpose evnt)
{
Style.PaintFlatBox (entry.Style, GdkWindow, State, ShadowType.None, evnt.Area, this,
"entry_bg", 0, 0, Allocation.Width, Allocation.Height);
PropagateExpose(Child, evnt);
Style.PaintShadow(entry.Style, GdkWindow, StateType.Normal,
ShadowType.In, evnt.Area, entry, "entry",
0, 0, Allocation.Width, Allocation.Height);
return true;
}
protected override void OnShown()
{
base.OnShown();
ShowHideButtons();
}
protected virtual void OnChanged()
{
if(!Ready) {
return;
}
EventHandler handler = entry_changed;
if(handler != null) {
handler(this, EventArgs.Empty);
}
}
protected virtual void OnFilterChanged()
{
EventHandler handler = filter_changed;
if(handler != null) {
handler(this, EventArgs.Empty);
}
if(IsQueryAvailable) {
OnInnerEntryChanged(this, EventArgs.Empty);
}
}
public void AddFilterOption(int id, string label)
{
if(id < 0) {
throw new ArgumentException("id", "must be >= 0");
}
FilterMenuItem item = new FilterMenuItem(id, label);
item.Toggled += OnMenuItemToggled;
menu.Append(item);
if(ActiveFilterID < 0) {
item.Toggle();
}
filter_button.Visible = true;
}
public void AddFilterSeparator()
{
menu.Append(new SeparatorMenuItem());
}
public void RemoveFilterOption(int id)
{
FilterMenuItem item = FindFilterMenuItem(id);
if(item != null) {
menu.Remove(item);
}
}
public void ActivateFilter(int id)
{
FilterMenuItem item = FindFilterMenuItem(id);
if(item != null) {
item.Toggle();
}
}
private FilterMenuItem FindFilterMenuItem(int id)
{
foreach(MenuItem item in menu) {
if(item is FilterMenuItem && ((FilterMenuItem)item).ID == id) {
return (FilterMenuItem)item;
}
}
return null;
}
public string GetLabelForFilterID(int id)
{
FilterMenuItem item = FindFilterMenuItem(id);
if(item == null) {
return null;
}
return item.Label;
}
public void CancelSearch()
{
entry.Text = String.Empty;
ActivateFilter(0);
}
public int ActiveFilterID {
get { return active_filter_id; }
private set {
if(value == active_filter_id) {
return;
}
active_filter_id = value;
OnFilterChanged();
}
}
public string EmptyMessage {
get {
return entry.Sensitive ? empty_message : String.Empty;
}
set {
empty_message = value;
entry.QueueDraw();
}
}
public string Query {
get { return entry.Text.Trim(); }
set { entry.Text = String.IsNullOrEmpty (value) ? String.Empty : value.Trim (); }
}
public bool IsQueryAvailable {
get { return Query != null && Query != String.Empty; }
}
public bool Ready {
get { return ready; }
set { ready = value; }
}
public new bool HasFocus {
get { return entry.HasFocus; }
set { entry.HasFocus = true; }
}
public Entry InnerEntry {
get { return entry; }
}
protected override void OnStateChanged (Gtk.StateType previous_state)
{
base.OnStateChanged (previous_state);
entry.Sensitive = State != StateType.Insensitive;
filter_button.Sensitive = State != StateType.Insensitive;
clear_button.Sensitive = State != StateType.Insensitive;
}
private class FilterMenuItem : MenuItem /*CheckMenuItem*/
{
private int id;
private string label;
public FilterMenuItem(int id, string label) : base(label)
{
this.id = id;
this.label = label;
//DrawAsRadio = true;
}
public int ID {
get { return id; }
}
public string Label {
get { return label; }
}
// FIXME: Remove when restored to CheckMenuItem
private bool active;
public bool Active {
get { return active; }
set { active = value; }
}
public new event EventHandler Toggled;
protected override void OnActivated ()
{
base.OnActivated ();
if (Toggled != null) {
Toggled (this, EventArgs.Empty);
}
}
}
private class FramelessEntry : Entry
{
private Gdk.Window text_window;
private SearchEntry parent;
private Pango.Layout layout;
private Gdk.GC text_gc;
public FramelessEntry(SearchEntry parent) : base()
{
this.parent = parent;
HasFrame = false;
parent.StyleSet += OnParentStyleSet;
WidthChars = 1;
}
private void OnParentStyleSet(object o, EventArgs args)
{
RefreshGC();
QueueDraw();
}
private void RefreshGC()
{
if(text_window == null) {
return;
}
text_gc = new Gdk.GC(text_window);
text_gc.Copy(Style.TextGC(StateType.Normal));
Gdk.Color color_a = parent.Style.Base(StateType.Normal);
Gdk.Color color_b = parent.Style.Text(StateType.Normal);
text_gc.RgbFgColor = Hyena.Gui.GtkUtilities.ColorBlend(color_a, color_b);
}
protected override bool OnExposeEvent(Gdk.EventExpose evnt)
{
// The Entry's GdkWindow is the top level window onto which
// the frame is drawn; the actual text entry is drawn into a
// separate window, so we can ensure that for themes that don't
// respect HasFrame, we never ever allow the base frame drawing
// to happen
if(evnt.Window == GdkWindow) {
return true;
}
bool ret = base.OnExposeEvent(evnt);
if(text_gc == null || evnt.Window != text_window) {
text_window = evnt.Window;
RefreshGC();
}
if(Text.Length > 0 || HasFocus || parent.EmptyMessage == null) {
return ret;
}
if (layout == null) {
layout = new Pango.Layout(PangoContext);
layout.FontDescription = PangoContext.FontDescription;
}
int width, height;
layout.SetMarkup(parent.EmptyMessage);
layout.GetPixelSize(out width, out height);
evnt.Window.DrawLayout(text_gc, 2, (SizeRequest().Height - height) / 2, layout);
return ret;
}
}
}
}
| |
using System.Drawing;
namespace YAF.Pages.Admin
{
#region Using
using System;
using System.Data;
using System.Web.UI.WebControls;
using VZF.Data.Common;
using YAF.Core;
using YAF.Types;
using YAF.Types.Constants;
using YAF.Types.Flags;
using YAF.Types.Interfaces;
using VZF.Utils;
using VZF.Utils.Helpers;
#endregion
/// <summary>
/// Summary description for ranks.
/// </summary>
public partial class ranks : AdminPage
{
#region Methods
/// <summary>
/// Format string color.
/// </summary>
/// <param name="item">
/// The item.
/// </param>
/// <returns>
/// Set values are rendered green if true, and if not red
/// </returns>
protected Color GetItemColorString(string item)
{
// show enabled flag red
return item.IsSet() ? Color.Green : Color.Red;
}
/// <summary>
/// Format access mask setting color formatting.
/// </summary>
/// <param name="enabled">
/// The enabled.
/// </param>
/// <returns>
/// Set access mask flags are rendered green if true, and if not red
/// </returns>
protected Color GetItemColor(bool enabled)
{
// show enabled flag red
return enabled ? Color.Green : Color.Red;
}
/// <summary>
/// Get a user friendly item name.
/// </summary>
/// <param name="enabled">
/// The enabled.
/// </param>
/// <returns>
/// Item Name.
/// </returns>
protected string GetItemName(bool enabled)
{
return enabled ? this.GetText("DEFAULT", "YES") : this.GetText("DEFAULT", "NO");
}
/// <summary>
/// The bit set.
/// </summary>
/// <param name="_o">
/// The _o.
/// </param>
/// <param name="bitmask">
/// The bitmask.
/// </param>
/// <returns>
/// The bit set.
/// </returns>
protected bool BitSet([NotNull] object _o, int bitmask)
{
var i = (int)_o;
return (i & bitmask) != 0;
}
/// <summary>
/// The delete_ load.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void Delete_Load([NotNull] object sender, [NotNull] EventArgs e)
{
ControlHelper.AddOnClickConfirmDialog(sender, this.GetText("ADMIN_RANKS", "CONFIRM_DELETE"));
}
/// <summary>
/// The ladder info.
/// </summary>
/// <param name="_o">
/// The _o.
/// </param>
/// <returns>
/// The ladder info.
/// </returns>
protected string LadderInfo([NotNull] object _o)
{
var dr = (DataRowView)_o;
// object IsLadder,object MinPosts
// Eval( "IsLadder"),Eval( "MinPosts")
bool isLadder = dr["Flags"].BinaryAnd(RankFlags.Flags.IsLadder);
return isLadder
? "{0} ({1} {2})".FormatWith(GetItemName(true), dr["MinPosts"], this.GetText("ADMIN_RANKS", "POSTS"))
: GetItemName(false);
}
/// <summary>
/// The new rank_ click.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void NewRank_Click([NotNull] object sender, [NotNull] EventArgs e)
{
YafBuildLink.Redirect(ForumPages.admin_editrank);
}
/// <summary>
/// The page_ load.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
{
if (this.IsPostBack)
{
return;
}
this.PageLinks.AddLink(this.PageContext.BoardSettings.Name, YafBuildLink.GetLink(ForumPages.forum));
this.PageLinks.AddLink(this.GetText("ADMIN_ADMIN", "Administration"), YafBuildLink.GetLink(ForumPages.admin_admin));
this.PageLinks.AddLink(this.GetText("ADMIN_RANKS", "TITLE"), string.Empty);
this.Page.Header.Title = "{0} - {1}".FormatWith(
this.GetText("ADMIN_ADMIN", "Administration"),
this.GetText("ADMIN_RANKS", "TITLE"));
this.NewRank.Text = this.GetText("ADMIN_RANKS", "NEW_RANK");
this.BindData();
}
/// <summary>
/// The rank list_ item command.
/// </summary>
/// <param name="source">
/// The source.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void RankList_ItemCommand([NotNull] object source, [NotNull] RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "edit":
YafBuildLink.Redirect(ForumPages.admin_editrank, "r={0}", e.CommandArgument);
break;
case "delete":
CommonDb.rank_delete(PageContext.PageModuleID, e.CommandArgument);
this.BindData();
break;
}
}
/// <summary>
/// The bind data.
/// </summary>
private void BindData()
{
this.RankList.DataSource = CommonDb.rank_list(PageContext.PageModuleID, this.PageContext.PageBoardID);
this.DataBind();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.Threading.Tasks.Tests
{
public class AsyncTaskMethodBuilderTests
{
// Test captured sync context with successful completion (SetResult)
[Fact]
public static void VoidMethodBuilder_TrackedContext()
{
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
var trackedContext = new TrackOperationsSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(trackedContext);
// TrackedCount should increase as Create() is called, and decrease as SetResult() is called.
// Completing in opposite order as created.
var avmb1 = AsyncVoidMethodBuilder.Create();
Assert.Equal(1, trackedContext.TrackedCount);
var avmb2 = AsyncVoidMethodBuilder.Create();
Assert.Equal(2, trackedContext.TrackedCount);
avmb2.SetResult();
Assert.Equal(1, trackedContext.TrackedCount);
avmb1.SetResult();
Assert.Equal(0, trackedContext.TrackedCount);
// Completing in same order as created
avmb1 = AsyncVoidMethodBuilder.Create();
Assert.Equal(1, trackedContext.TrackedCount);
avmb2 = AsyncVoidMethodBuilder.Create();
Assert.Equal(2, trackedContext.TrackedCount);
avmb1.SetResult();
Assert.Equal(1, trackedContext.TrackedCount);
avmb2.SetResult();
Assert.Equal(0, trackedContext.TrackedCount);
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
// Test not having a sync context with successful completion (SetResult)
[Fact]
public static void VoidMethodBuilder_NoContext()
{
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
// Make sure not having a sync context doesn't cause us to blow up
SynchronizationContext.SetSynchronizationContext(null);
var avmb = AsyncVoidMethodBuilder.Create();
avmb.SetResult();
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
// AsyncTaskMethodBuilder
[Fact]
public static void TaskMethodBuilder_Basic()
{
// Creating a task builder, building it, completing it successfully
{
var atmb = AsyncTaskMethodBuilder.Create();
var t = atmb.Task;
Assert.Equal(TaskStatus.WaitingForActivation, t.Status);
atmb.SetResult();
Assert.Equal(TaskStatus.RanToCompletion, t.Status);
}
}
[Fact]
public static void TaskMethodBuilder_DoesNotTouchSyncContext()
{
// Verify that AsyncTaskMethodBuilder is not touching sync context
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
var trackedContext = new TrackOperationsSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(trackedContext);
var atmb = AsyncTaskMethodBuilder.Create();
Assert.Equal(0, trackedContext.TrackedCount);
atmb.SetResult();
Assert.Equal(0, trackedContext.TrackedCount);
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
// AsyncTaskMethodBuilder<T>
[Fact]
public static void TaskMethodBuilderT_Basic()
{
// Creating a task builder, building it, completing it successfully
var atmb = AsyncTaskMethodBuilder<int>.Create();
var t = atmb.Task;
Assert.Equal(TaskStatus.WaitingForActivation, t.Status);
atmb.SetResult(43);
Assert.Equal(TaskStatus.RanToCompletion, t.Status);
Assert.Equal(43, t.Result);
}
[Fact]
public static void TaskMethodBuilderT_DoesNotTouchSyncContext()
{
// Verify that AsyncTaskMethodBuilder<T> is not touching sync context
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
var trackedContext = new TrackOperationsSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(trackedContext);
var atmb = AsyncTaskMethodBuilder<string>.Create();
Assert.Equal(0, trackedContext.TrackedCount);
atmb.SetResult("async");
Assert.Equal(0, trackedContext.TrackedCount);
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
// Incorrect usage for AsyncTaskMethodBuilder
[Fact]
public static void TaskMethodBuilder_IncorrectUsage()
{
var atmb = new AsyncTaskMethodBuilder();
Assert.Throws<ArgumentNullException>(() => { atmb.SetException(null); });
}
// Incorrect usage for AsyncVoidMethodBuilder
[Fact]
public static void VoidMethodBuilder_IncorrectUsage()
{
var avmb = AsyncVoidMethodBuilder.Create();
Assert.Throws<ArgumentNullException>(() => { avmb.SetException(null); });
avmb.SetResult();
}
// Creating a task builder, building it, completing it successfully, and making sure it can't be reset
[Fact]
public static void TaskMethodBuilder_CantBeReset()
{
var atmb = AsyncTaskMethodBuilder.Create();
atmb.SetResult();
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
// Incorrect usage for AsyncTaskMethodBuilder<T>
[Fact]
public static void TaskMethodBuilderT_IncorrectUsage()
{
var atmb = new AsyncTaskMethodBuilder<int>();
Assert.Throws<ArgumentNullException>(() => { atmb.SetException(null); });
}
// Creating a task builder <T>, building it, completing it successfully, and making sure it can't be reset
[Fact]
public static void TaskMethodBuilderT_CantBeReset()
{
var atmb = AsyncTaskMethodBuilder<int>.Create();
atmb.SetResult(43);
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(44); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
// Creating a task builder, building it, completing it faulted, and making sure it can't be reset
[Fact]
public static void TaskMethodBuilder_SetException_CantBeReset0()
{
var atmb = AsyncTaskMethodBuilder.Create();
var t = atmb.Task;
Assert.Equal(TaskStatus.WaitingForActivation, t.Status);
atmb.SetException(new InvalidCastException());
Assert.Equal(TaskStatus.Faulted, t.Status);
Assert.True(t.Exception.InnerException is InvalidCastException, "Wrong exception found in builder (ATMB, build then fault)");
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
// Creating a task builder, completing it faulted, building it, and making sure it can't be reset
[Fact]
public static void TaskMethodBuilder_SetException_CantBeReset1()
{
var atmb = AsyncTaskMethodBuilder.Create();
atmb.SetException(new InvalidCastException());
var t = atmb.Task;
Assert.Equal(TaskStatus.Faulted, t.Status);
Assert.True(t.Exception.InnerException is InvalidCastException, "Wrong exception found in builder (ATMB, fault then build)");
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
// Test cancellation
[Fact]
public static void TaskMethodBuilder_Cancellation()
{
var atmb = AsyncTaskMethodBuilder.Create();
var oce = new OperationCanceledException();
atmb.SetException(oce);
var t = atmb.Task;
Assert.Equal(TaskStatus.Canceled, t.Status);
OperationCanceledException caught = Assert.Throws<OperationCanceledException>(() =>
{
t.GetAwaiter().GetResult();
});
Assert.Same(oce, caught);
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
[Fact]
public static void AsyncMethodBuilderCreate_SetExceptionTest2()
{
// Test captured sync context with exceptional completion
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
var trackedContext = new TrackOperationsSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(trackedContext);
// Completing in opposite order as created
var avmb1 = AsyncVoidMethodBuilder.Create();
Assert.Equal(1, trackedContext.TrackedCount);
var avmb2 = AsyncVoidMethodBuilder.Create();
Assert.Equal(2, trackedContext.TrackedCount);
avmb2.SetException(new InvalidOperationException("uh oh 1"));
Assert.Equal(1, trackedContext.TrackedCount);
avmb1.SetException(new InvalidCastException("uh oh 2"));
Assert.Equal(0, trackedContext.TrackedCount);
Assert.Equal(2, trackedContext.PostExceptions.Count);
Assert.IsType<InvalidOperationException>(trackedContext.PostExceptions[0]);
Assert.IsType<InvalidCastException>(trackedContext.PostExceptions[1]);
// Completing in same order as created
var avmb3 = AsyncVoidMethodBuilder.Create();
Assert.Equal(1, trackedContext.TrackedCount);
var avmb4 = AsyncVoidMethodBuilder.Create();
Assert.Equal(2, trackedContext.TrackedCount);
avmb3.SetException(new InvalidOperationException("uh oh 3"));
Assert.Equal(1, trackedContext.TrackedCount);
avmb4.SetException(new InvalidCastException("uh oh 4"));
Assert.Equal(0, trackedContext.TrackedCount);
Assert.Equal(4, trackedContext.PostExceptions.Count);
Assert.IsType<InvalidOperationException>(trackedContext.PostExceptions[2]);
Assert.IsType<InvalidCastException>(trackedContext.PostExceptions[3]);
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
// Creating a task builder, building it, completing it faulted, and making sure it can't be reset
[Fact]
public static void TaskMethodBuilderT_SetExceptionTest0()
{
var atmb = AsyncTaskMethodBuilder<int>.Create();
var t = atmb.Task;
Assert.Equal(TaskStatus.WaitingForActivation, t.Status);
atmb.SetException(new InvalidCastException());
Assert.Equal(TaskStatus.Faulted, t.Status);
Assert.IsType<InvalidCastException>(t.Exception.InnerException);
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(44); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
// Creating a task builder, completing it faulted, building it, and making sure it can't be reset
[Fact]
public static void TaskMethodBuilderT_SetExceptionTest1()
{
var atmb = AsyncTaskMethodBuilder<int>.Create();
atmb.SetException(new InvalidCastException());
var t = atmb.Task;
Assert.Equal(TaskStatus.Faulted, t.Status);
Assert.IsType<InvalidCastException>(t.Exception.InnerException);
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(44); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
// Test cancellation
[Fact]
public static void TaskMethodBuilderT_Cancellation()
{
var atmb = AsyncTaskMethodBuilder<int>.Create();
var oce = new OperationCanceledException();
atmb.SetException(oce);
var t = atmb.Task;
Assert.Equal(TaskStatus.Canceled, t.Status);
OperationCanceledException e = Assert.Throws<OperationCanceledException>(() =>
{
t.GetAwaiter().GetResult();
});
Assert.Same(oce, e);
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(44); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
[Fact]
public static void TaskMethodBuilder_TaskIsCached()
{
var atmb = new AsyncTaskMethodBuilder();
var t1 = atmb.Task;
var t2 = atmb.Task;
Assert.NotNull(t1);
Assert.NotNull(t2);
Assert.Same(t1, t2);
}
[Fact]
public static void TaskMethodBuilderT_TaskIsCached()
{
var atmb = new AsyncTaskMethodBuilder<int>();
var t1 = atmb.Task;
var t2 = atmb.Task;
Assert.NotNull(t1);
Assert.NotNull(t2);
Assert.Same(t1, t2);
}
[Fact]
public static void TaskMethodBuilder_UsesCompletedCache()
{
var atmb1 = new AsyncTaskMethodBuilder();
var atmb2 = new AsyncTaskMethodBuilder();
atmb1.SetResult();
atmb2.SetResult();
Assert.Same(atmb1.Task, atmb2.Task);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void TaskMethodBuilderBoolean_UsesCompletedCache(bool result)
{
TaskMethodBuilderT_UsesCompletedCache(result, true);
}
[Theory]
[InlineData(0, true)]
[InlineData(5, true)]
[InlineData(-5, false)]
[InlineData(42, false)]
public static void TaskMethodBuilderInt32_UsesCompletedCache(int result, bool shouldBeCached)
{
TaskMethodBuilderT_UsesCompletedCache(result, shouldBeCached);
}
[Theory]
[InlineData((string)null, true)]
[InlineData("test", false)]
public static void TaskMethodBuilderRef_UsesCompletedCache(string result, bool shouldBeCached)
{
TaskMethodBuilderT_UsesCompletedCache(result, shouldBeCached);
}
private static void TaskMethodBuilderT_UsesCompletedCache<T>(T result, bool shouldBeCached)
{
var atmb1 = new AsyncTaskMethodBuilder<T>();
var atmb2 = new AsyncTaskMethodBuilder<T>();
atmb1.SetResult(result);
atmb2.SetResult(result);
Assert.Equal(shouldBeCached, object.ReferenceEquals(atmb1.Task, atmb2.Task));
}
[Fact]
public static void Tcs_ValidateFaultedTask()
{
var tcs = new TaskCompletionSource<int>();
try { throw new InvalidOperationException(); }
catch (Exception e) { tcs.SetException(e); }
ValidateFaultedTask(tcs.Task);
}
[Fact]
public static void TaskMethodBuilder_ValidateFaultedTask()
{
var atmb = AsyncTaskMethodBuilder.Create();
try { throw new InvalidOperationException(); }
catch (Exception e) { atmb.SetException(e); }
ValidateFaultedTask(atmb.Task);
}
[Fact]
public static void TaskMethodBuilderT_ValidateFaultedTask()
{
var atmbtr = AsyncTaskMethodBuilder<object>.Create();
try { throw new InvalidOperationException(); }
catch (Exception e) { atmbtr.SetException(e); }
ValidateFaultedTask(atmbtr.Task);
}
[Fact]
public static void TrackedSyncContext_ValidateException()
{
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
var tosc = new TrackOperationsSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(tosc);
var avmb = AsyncVoidMethodBuilder.Create();
try { throw new InvalidOperationException(); }
catch (Exception exc) { avmb.SetException(exc); }
Assert.NotEmpty(tosc.PostExceptions);
ValidateException(tosc.PostExceptions[0]);
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
// Running tasks with exceptions.
[Fact]
public static void FaultedTaskExceptions()
{
var twa1 = Task.Run(() => { throw new Exception("uh oh"); });
var twa2 = Task.Factory.StartNew(() => { throw new Exception("uh oh"); });
var tasks = new Task[]
{
Task.Run(() => { throw new Exception("uh oh"); }),
Task.Factory.StartNew<int>(() => { throw new Exception("uh oh"); }),
Task.WhenAll(Task.Run(() => { throw new Exception("uh oh"); }), Task.Run(() => { throw new Exception("uh oh"); })),
Task.WhenAll<int>(Task.Run(new Func<int>(() => { throw new Exception("uh oh"); })), Task.Run(new Func<int>(() => { throw new Exception("uh oh"); }))),
Task.WhenAny(twa1, twa2).Unwrap(),
Task.WhenAny<int>(Task.Run(new Func<Task<int>>(() => { throw new Exception("uh oh"); }))).Unwrap(),
Task.Factory.StartNew(() => Task.Factory.StartNew(() => { throw new Exception("uh oh"); })).Unwrap(),
Task.Factory.StartNew<Task<int>>(() => Task.Factory.StartNew<int>(() => { throw new Exception("uh oh"); })).Unwrap(),
Task.Run(() => Task.Run(() => { throw new Exception("uh oh"); })),
Task.Run(() => Task.Run(new Func<int>(() => { throw new Exception("uh oh"); }))),
Task.Run(new Func<Task>(() => { throw new Exception("uh oh"); })),
Task.Run(new Func<Task<int>>(() => { throw new Exception("uh oh"); }))
};
for (int i = 0; i < tasks.Length; i++)
{
ValidateFaultedTask(tasks[i]);
}
((IAsyncResult)twa1).AsyncWaitHandle.WaitOne();
((IAsyncResult)twa2).AsyncWaitHandle.WaitOne();
Exception ignored = twa1.Exception;
ignored = twa2.Exception;
}
// Test that OCEs don't result in the unobserved event firing
[Fact]
public static void CancellationDoesntResultInEventFiring()
{
var cts = new CancellationTokenSource();
var oce = new OperationCanceledException(cts.Token);
// A Task that throws an exception to cancel
var b = new Barrier(2);
Task t1 = Task.Factory.StartNew(() =>
{
b.SignalAndWait();
b.SignalAndWait();
throw oce;
}, cts.Token);
b.SignalAndWait(); // make sure task is started before we cancel
cts.Cancel();
b.SignalAndWait(); // release task to complete
// This test may be run concurrently with other tests in the suite,
// which can be problematic as TaskScheduler.UnobservedTaskException
// is global state. The handler is carefully written to be non-problematic
// if it happens to be set during the execution of another test that has
// an unobserved exception.
EventHandler<UnobservedTaskExceptionEventArgs> handler =
(s, e) => Assert.DoesNotContain(oce, e.Exception.InnerExceptions);
TaskScheduler.UnobservedTaskException += handler;
((IAsyncResult)t1).AsyncWaitHandle.WaitOne();
t1 = null;
for (int i = 0; i < 10; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
TaskScheduler.UnobservedTaskException -= handler;
}
#region Helper Methods / Classes
private static void ValidateFaultedTask(Task t)
{
((IAsyncResult)t).AsyncWaitHandle.WaitOne();
Assert.True(t.IsFaulted);
Exception e = Assert.ThrowsAny<Exception>(() =>
{
t.GetAwaiter().GetResult();
});
ValidateException(e);
}
private static void ValidateException(Exception e)
{
Assert.NotNull(e);
Assert.NotNull(e.StackTrace);
Assert.Contains("End of stack trace", e.StackTrace);
}
private class TrackOperationsSynchronizationContext : SynchronizationContext
{
private int _trackedCount;
private int _postCount;
//ConcurrentQueue
private List<Exception> _postExceptions = new List<Exception>();
public int TrackedCount { get { return _trackedCount; } }
public List<Exception> PostExceptions
{
get
{
List<Exception> returnValue;
lock (_postExceptions)
{
returnValue = new List<Exception>(_postExceptions);
return returnValue;
}
}
}
public int PostCount { get { return _postCount; } }
public override void OperationStarted() { Interlocked.Increment(ref _trackedCount); }
public override void OperationCompleted() { Interlocked.Decrement(ref _trackedCount); }
public override void Post(SendOrPostCallback callback, object state)
{
try
{
Interlocked.Increment(ref _postCount);
callback(state);
}
catch (Exception exc)
{
lock (_postExceptions)
{
_postExceptions.Add(exc);
}
}
}
}
#endregion
}
}
| |
using System;
using System.Reflection;
using Invio.Extensions.Reflection;
namespace Invio.Immutable {
/// <summary>
/// This is the base <see cref="IPropertyHandler" /> for all implementations
/// to guarantee consistent validation and exception messaging. It defers
/// all appropriate implementation-specific behavior to the inheriting class.
/// </summary>
/// <typeparam name="TProperty">
/// A type that can reliably be assigned to values that are stored in the
/// injected property.
/// </typeparam>
public abstract class PropertyHandlerBase<TProperty> : IPropertyHandler {
public const Int32 NullValueHashCode = 37;
/// <summary>
/// The name of the abstracted property that exists on the value object.
/// </summary>
public virtual String PropertyName { get; }
/// <summary>
/// The type of the abstracted property that exists on the value object.
/// </summary>
public virtual Type PropertyType { get; }
// This is made lazy because, according to the documentation made available in
// Invio.Reflection.Extensions, creating these caching delegates is expensive.
private Lazy<Func<object, object>> getter { get; }
/// <summary>
/// Creates an instance of <see cref="PropertyHandlerBase{TProperty}" /> that
/// will use consistent null and type checking on the value objects being
/// provided to its methods.
/// </summary>
/// <param name="property">
/// A <see cref="PropertyInfo" /> on a value object that will potentially
/// have its native equality comparison and hash code generation by the
/// inheriting class.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="property" /> is null.
/// </exception>
protected PropertyHandlerBase(PropertyInfo property) {
if (property == null) {
throw new ArgumentNullException(nameof(property));
} else if (!property.PropertyType.IsDerivativeOf(typeof(TProperty))) {
throw new ArgumentException(
$"The '{property.Name}' property is not of type " +
$"'{typeof(TProperty).GetNameWithGenericParameters()}'.",
nameof(property)
);
}
this.PropertyName = property.Name;
this.PropertyType = property.PropertyType;
this.getter = new Lazy<Func<object, object>>(
() => property.CreateGetter()
);
}
/// <summary>
/// Determines whether the values for the abstracted property are equal
/// on two value objects that contain them.
/// </summary>
/// <param name="leftParent">
/// A value object that contains the abstracted property.
/// </param>
/// <param name="rightParent">
/// A value object that contains the abstracted property.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="leftParent" /> or
/// <paramref name="rightParent" /> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when either <paramref name="leftParent" /> or
/// <paramref name="rightParent" /> does not contains the abstracted property.
/// </exception>
/// <returns>
/// Whether or not the values for the abstracted property are
/// equal for the two value objects provided that contain them.
/// </returns>
public virtual bool ArePropertyValuesEqual(object leftParent, object rightParent) {
if (leftParent == null) {
throw new ArgumentNullException(nameof(leftParent));
} else if (rightParent == null) {
throw new ArgumentNullException(nameof(rightParent));
}
var leftPropertyValue =
this.GetPropertyValueImplOrThrow(leftParent, nameof(leftParent));
var rightPropertyValue =
this.GetPropertyValueImplOrThrow(rightParent, nameof(rightParent));
if (Object.ReferenceEquals(leftPropertyValue, null)) {
return Object.ReferenceEquals(rightPropertyValue, null);
}
if (Object.ReferenceEquals(rightPropertyValue, null)) {
return false;
}
return this.ArePropertyValuesEqualImpl(leftPropertyValue, rightPropertyValue);
}
/// <summary>
/// An implementation specific equality comparison that is deferred to the
/// class that inherits from this <see cref="PropertyHandlerBase{TProperty}" />
/// implementation. By default, this uses the native
/// <see cref="Object.Equals(object)" /> implementation.
/// </summary>
/// <param name="leftPropertyValue">
/// A non-null property value extracted from a value object that contains the
/// <see cref="PropertyInfo" /> injected into the constructor.
/// </param>
/// <param name="rightPropertyValue">
/// A non-null property value extracted from a value object that contains the
/// <see cref="PropertyInfo" /> injected into the constructor.
/// </param>
/// <returns>
/// Whether or not the values provided via <paramref name="leftPropertyValue" />
/// and <paramref name="rightPropertyValue" /> should be considered equal.
/// </returns>
protected virtual bool ArePropertyValuesEqualImpl(
TProperty leftPropertyValue,
TProperty rightPropertyValue) {
return leftPropertyValue.Equals(rightPropertyValue);
}
/// <summary>
/// Generates a hash code for the value of the abstracted property using the
/// value stored on the value object provided via <paramref name="parent" />.
/// </summary>
/// <remarks>
/// If the property value is <c>null</c>, attempting to use the native hash
/// code generation would result in a <see cref="NullReferenceException" />.
/// To avoid this edge case, a constant of <c>37</c> is used instead whenever
/// the property's value is <c>null</c>.
/// </remarks>
/// <param name="parent">
/// A value object that contains the abstracted property.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="parent" /> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="parent" /> does not contain the abstracted property.
/// </exception>
/// <returns>
/// An appropriate hash code for the value of the abstracted property
/// found on the value object provided via <paramref name="parent" />.
/// </returns>
public virtual int GetPropertyValueHashCode(object parent) {
if (parent == null) {
throw new ArgumentNullException(nameof(parent));
}
var propertyValue = this.GetPropertyValueImplOrThrow(parent, nameof(parent));
if (propertyValue == null) {
// Arbitrary (but prime!) number for null.
return NullValueHashCode;
}
return this.GetPropertyValueHashCodeImpl(propertyValue);
}
/// <summary>
/// An implementation specific hash code generator that can be
/// deferred to the class that inherits from this
/// <see cref="PropertyHandlerBase{TProperty}" /> implementation.
/// By default, this uses the native <see cref="Object.GetHashCode" />
/// implementation.
/// </summary>
/// <param name="propertyValue">
/// A non-null property value extracted from a value object that contains the
/// <see cref="PropertyInfo" /> injected into the constructor.
/// </param>
/// <returns>
/// An appropriate hash code for the value provided via the
/// <paramref name="propertyValue" /> parameter.
/// </returns>
protected virtual int GetPropertyValueHashCodeImpl(TProperty propertyValue) {
return propertyValue.GetHashCode();
}
/// <summary>
/// Gets the value for the injected <see cref="PropertyInfo" /> off
/// of the provided <paramref name="parent" />.
/// </summary>
/// <param name="parent">
/// A value object that contains the injected <see cref="PropertyInfo" />.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="parent" /> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="parent" /> does not contain
/// the injected <see cref="PropertyInfo" />.
/// </exception>
/// <returns>
/// The value of the injected <see cref="PropertyInfo" />
/// found on the value object provided via <paramref name="parent" />.
/// </returns>
public virtual object GetPropertyValue(object parent) {
if (parent == null) {
throw new ArgumentNullException(nameof(parent));
}
return this.GetPropertyValueImplOrThrow(parent, nameof(parent));
}
protected TProperty GetPropertyValueImplOrThrow(object parent, string paramName) {
try {
return (TProperty)this.getter.Value(parent);
} catch (InvalidCastException exception) {
throw new ArgumentException(
$"The value object provided is of type {parent.GetType().Name}, " +
$"which does not contains the {this.PropertyName} property.",
paramName,
exception
);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ProtectionContainerRefreshOperationResultsOperations operations.
/// </summary>
internal partial class ProtectionContainerRefreshOperationResultsOperations : IServiceOperations<RecoveryServicesBackupClient>, IProtectionContainerRefreshOperationResultsOperations
{
/// <summary>
/// Initializes a new instance of the ProtectionContainerRefreshOperationResultsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ProtectionContainerRefreshOperationResultsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Provides the result of the refresh operation triggered by the BeginRefresh
/// operation.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the container.
/// </param>
/// <param name='operationId'>
/// Operation ID associated with the operation whose result needs to be
/// fetched.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string operationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fabricName");
}
if (operationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "operationId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("operationId", operationId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/operationResults/{operationId}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
_url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//This is UnityEditor only for the time being...
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UMA;
using UMA.CharacterSystem;
namespace UMA.CharacterSystem.Examples
{
//UPDATED For CharacterSystem.
//Takes photos of the character based on the Wardrobe slots.
//HUGE MemoryLeak or infinite loop in this somewhere...
public class PhotoBooth : MonoBehaviour
{
public RenderTexture bodyRenderTexture;
public RenderTexture outfitRenderTexture;
public RenderTexture headRenderTexture;
public RenderTexture chestRenderTexture;
public RenderTexture handsRenderTexture;
public RenderTexture legsRenderTexture;
public RenderTexture feetRenderTexture;
public DynamicCharacterAvatar avatarToPhoto;
public enum renderTextureOpts { BodyRenderTexture, OutfitRenderTexture, HeadRenderTexture, ChestRenderTexture, HandsRenderTexture, LegsRenderTexture, FeetRenderTexture };
public string photoName;
public bool freezeAnimation;
public float animationFreezeFrame = 1.8f;
public string destinationFolder;//non-serialized?
[Tooltip("If true will automatically take all possible wardrobe photos for the current character. Otherwise photographs character in its current state.")]
public bool autoPhotosEnabled = true;
[Tooltip("In mnual mode use this to select the RenderTexture you wish to Photo")]
public renderTextureOpts textureToPhoto = renderTextureOpts.BodyRenderTexture;
[Tooltip("If true will dim everything but the target wardrobe recipe (AutoPhotosEnabled only)")]
public bool dimAllButTarget = false;
public Color dimToColor = new Color(0, 0, 0, 1);
public Color dimToMetallic = new Color(0, 0, 0, 1);
[Tooltip("If true will set the colors for the target wardrobe recipe to the neuttal color (AutoPhotosEnabled only)")]
public bool neutralizeTargetColors = false;
public Color neutralizeToColor = new Color(1, 1, 1, 1);
public Color neutralizeToMetallic = new Color(0, 0, 0, 1);
[Tooltip("If true will attempt to find an underwear wardrobe slot to apply when taking the base race photo (AutoPhotosEnabled only)")]
public bool addUnderwearToBasePhoto = true;
public bool overwriteExistingPhotos = true;
public bool doingTakePhoto = false;
bool canTakePhoto = true;
RenderTexture renderTextureToUse;
List<UMATextRecipe> wardrobeRecipeToPhoto = new List<UMATextRecipe>();
Dictionary<int, Dictionary<int, Color>> originalColors = new Dictionary<int, Dictionary<int, Color>>();
DynamicCharacterSystem dcs;
bool basePhotoTaken;
void Start()
{
destinationFolder = "";
}
public void TakePhotos()
{
if (doingTakePhoto == false)
{
doingTakePhoto = true;
if (avatarToPhoto == null)
{
Debug.Log("You need to set the Avatar to photo in the inspector!");
doingTakePhoto = false;
return;
}
if (destinationFolder == "")
{
Debug.Log("You need to set a DestinationFolder in the inspector!");
doingTakePhoto = false;
return;
}
dcs = UMAContext.Instance.dynamicCharacterSystem as DynamicCharacterSystem;
if (!autoPhotosEnabled)
{
bool canPhoto = SetBestRenderTexture();
if (canPhoto)
{
photoName = photoName == "" ? avatarToPhoto.activeRace.name + Path.GetRandomFileName().Replace(".", "") : photoName;
StartCoroutine(TakePhotoCoroutine());
}
else
{
Debug.Log("Unknown RenderTexture Error...");
doingTakePhoto = false;
return;
}
}
else
{
Dictionary<string, List<UMATextRecipe>> recipesToPhoto = dcs.Recipes[avatarToPhoto.activeRace.name];
basePhotoTaken = false;
StartCoroutine(TakePhotosCoroutine(recipesToPhoto));
}
}
}
IEnumerator TakePhotosCoroutine(Dictionary<string, List<UMATextRecipe>> recipesToPhoto)
{
yield return null;
wardrobeRecipeToPhoto.Clear();
if (!basePhotoTaken)
{
Debug.Log("Gonna take base Photo...");
avatarToPhoto.ClearSlots();
if (addUnderwearToBasePhoto)
{
foreach (KeyValuePair<string, List<UMATextRecipe>> kp in recipesToPhoto)
{
if (kp.Key.IndexOf("Underwear") > -1 || kp.Key.IndexOf("underwear") > -1)
{
avatarToPhoto.SetSlot(kp.Value[0]);
}
}
}
bool renderTextureFound = SetBestRenderTexture("Body");
if (!renderTextureFound)
{
Debug.Log("No suitable RenderTexture found for Base Photo..");
doingTakePhoto = false;
yield break;
}
photoName = avatarToPhoto.activeRace.name;
canTakePhoto = false;
avatarToPhoto.CharacterUpdated.AddListener(SetCharacterReady);
avatarToPhoto.BuildCharacter(true);
while (!canTakePhoto)
{
yield return new WaitForSeconds(1f);
}
yield return StartCoroutine("TakePhotoCoroutine");
Debug.Log("Took base Photo...");
StopCoroutine("TakePhotoCoroutine");
//really we need photos for each area of the body (i.e. from each renderTexture/Cam) with no clothes on so we can have a 'None' image
//so we'll need head, chest, hands, legs, feet, full outfit...
Debug.Log("Now taking the Base Photos for body parts...");
List<string> emptySlotsToPhoto = new List<string> { "Head", "Chest", "Hands", "Legs", "Feet", "Outfit" };
//if dimming and neutralizing is on do it
if (dimAllButTarget && neutralizeTargetColors)
{
canTakePhoto = false;
avatarToPhoto.CharacterUpdated.AddListener(SetCharacterReadyAfterColorChange);
DoDimmingAndNeutralizing();
while (!canTakePhoto)
{
yield return new WaitForSeconds(1f);
}
}
foreach (string emptySlotToPhoto in emptySlotsToPhoto)
{
photoName = avatarToPhoto.activeRace.name + emptySlotToPhoto + "None";
renderTextureFound = SetBestRenderTexture(emptySlotToPhoto);
if (!renderTextureFound)
{
Debug.Log("No suitable RenderTexture found for " + emptySlotToPhoto + " Photo..");
continue;
}
yield return StartCoroutine("TakePhotoCoroutine");
Debug.Log("Took base " + emptySlotToPhoto + " Photo...");
StopCoroutine("TakePhotoCoroutine");
}
basePhotoTaken = true;
Debug.Log("Now taking the rest...");
StartCoroutine(TakePhotosCoroutine(recipesToPhoto));
yield break;
}
else
{
Debug.Log("Gonna take other wardrobe photos...");
if (originalColors.Count > 0)
{
avatarToPhoto.CharacterUpdated.RemoveListener(SetCharacterReadyAfterColorChange);
UndoDimmingAnNeutralizing();
}
var numKeys = recipesToPhoto.Count;
int slotsDone = 0;
foreach (string wardrobeSlot in recipesToPhoto.Keys)
{
Debug.Log("Gonna take photos for " + wardrobeSlot);
bool renderTextureFound = SetBestRenderTexture(wardrobeSlot);
if (!renderTextureFound)
{
Debug.Log("No suitable RenderTexture found for " + wardrobeSlot + " Photo..");
doingTakePhoto = false;
yield break;
}
foreach (UMATextRecipe wardrobeRecipe in recipesToPhoto[wardrobeSlot])
{
Debug.Log("Gonna take photos for " + wardrobeRecipe.name + " in " + wardrobeSlot);
photoName = wardrobeRecipe.name;
var path = destinationFolder + "/" + photoName + ".png";
if (!overwriteExistingPhotos && File.Exists(Application.dataPath + "/" + path))
{
Debug.Log("Photo already existed for " + photoName + ". Turn on overwrite photos to replace existig ones");
continue;
}
wardrobeRecipeToPhoto.Clear();
wardrobeRecipeToPhoto.Add(wardrobeRecipe);
avatarToPhoto.ClearSlots();
if (addUnderwearToBasePhoto)
{
foreach (KeyValuePair<string, List<UMATextRecipe>> kp in recipesToPhoto)
{
if (kp.Key.IndexOf("Underwear") > -1 || kp.Key.IndexOf("underwear") > -1)
{
avatarToPhoto.SetSlot(kp.Value[0]);
break;
}
}
}
avatarToPhoto.SetSlot(wardrobeRecipe);
canTakePhoto = false;
avatarToPhoto.CharacterUpdated.AddListener(SetCharacterReady);
avatarToPhoto.BuildCharacter(true);
while (!canTakePhoto)
{
Debug.Log("Waiting to take photo...");
yield return new WaitForSeconds(1f);
}
yield return StartCoroutine("TakePhotoCoroutine");
StopCoroutine("TakePhotoCoroutine");
}
slotsDone++;
if (slotsDone == numKeys)
{
ResetCharacter();
doingTakePhoto = false;
StopAllCoroutines();
yield break;
}
}
}
}
private void ResetCharacter()
{
Debug.Log("Doing Final Reset");
if (originalColors.Count > 0)
{
avatarToPhoto.CharacterUpdated.RemoveListener(SetCharacterReadyAfterColorChange);
UndoDimmingAnNeutralizing();
}
if (freezeAnimation)
{
avatarToPhoto.umaData.animator.speed = 1f;
avatarToPhoto.umaData.gameObject.GetComponent<UMA.PoseTools.UMAExpressionPlayer>().enableBlinking = true;
avatarToPhoto.umaData.gameObject.GetComponent<UMA.PoseTools.UMAExpressionPlayer>().enableSaccades = true;
}
avatarToPhoto.LoadDefaultWardrobe();
avatarToPhoto.BuildCharacter(true);
}
public void SetCharacterReady(UMAData umaData)
{
avatarToPhoto.CharacterUpdated.RemoveListener(SetCharacterReady);
if ((dimAllButTarget || neutralizeTargetColors) /*&& wardrobeRecipeToPhoto != null*/)//should we be making it possible to dim the base slot photos too?
{
if (originalColors.Count > 0)
{
avatarToPhoto.CharacterUpdated.RemoveListener(SetCharacterReadyAfterColorChange);
UndoDimmingAnNeutralizing();//I think this is causing character updates maybe?
}
avatarToPhoto.CharacterUpdated.AddListener(SetCharacterReadyAfterColorChange);
DoDimmingAndNeutralizing();
}
else
{
if (freezeAnimation)
{
SetAnimationFrame();
}
canTakePhoto = true;
}
}
public void SetCharacterReadyAfterColorChange(UMAData umaData)
{
avatarToPhoto.CharacterUpdated.RemoveListener(SetCharacterReadyAfterColorChange);
if (freezeAnimation)
{
SetAnimationFrame();
}
canTakePhoto = true;
}
private void SetAnimationFrame()
{
var thisAnimatonClip = avatarToPhoto.umaData.animationController.animationClips[0];
avatarToPhoto.umaData.animator.Play(thisAnimatonClip.name, 0, animationFreezeFrame);
avatarToPhoto.umaData.animator.speed = 0f;
avatarToPhoto.umaData.gameObject.GetComponent<UMA.PoseTools.UMAExpressionPlayer>().enableBlinking = false;
avatarToPhoto.umaData.gameObject.GetComponent<UMA.PoseTools.UMAExpressionPlayer>().enableSaccades = false;
}
IEnumerator TakePhotoCoroutine()
{
canTakePhoto = false;
Debug.Log("Taking Photo...");
if (!autoPhotosEnabled)
{
if (dimAllButTarget && neutralizeTargetColors)
{
canTakePhoto = false;
avatarToPhoto.CharacterUpdated.AddListener(SetCharacterReadyAfterColorChange);
wardrobeRecipeToPhoto.Clear();
foreach (KeyValuePair<string, UMATextRecipe> kp in avatarToPhoto.WardrobeRecipes)
{
wardrobeRecipeToPhoto.Add(kp.Value);
}
DoDimmingAndNeutralizing();
while (!canTakePhoto)
{
yield return new WaitForSeconds(1f);
}
}
}
var path = destinationFolder + "/" + photoName + ".png";
if (!overwriteExistingPhotos && File.Exists(path))
{
Debug.Log("could not overwrite existing Photo. Turn on Overwrite Existing Photos if you want to allow this");
canTakePhoto = true;
doingTakePhoto = false;
if (!autoPhotosEnabled)
{
ResetCharacter();
}
yield return true;
}
else
{
Texture2D texToSave = new Texture2D(renderTextureToUse.width, renderTextureToUse.height);
RenderTexture prev = RenderTexture.active;
RenderTexture.active = renderTextureToUse;
texToSave.ReadPixels(new Rect(0, 0, renderTextureToUse.width, renderTextureToUse.height), 0, 0, true);
texToSave.Apply();
byte[] texToSavePNG = texToSave.EncodeToPNG();
//path must be inside assets
File.WriteAllBytes(path, texToSavePNG);
RenderTexture.active = prev;
var relativePath = path;
if (path.StartsWith(Application.dataPath))
{
relativePath = "Assets" + path.Substring(Application.dataPath.Length);
}
AssetDatabase.ImportAsset(relativePath, ImportAssetOptions.ForceUncompressedImport);
TextureImporter textureImporter = AssetImporter.GetAtPath(relativePath) as TextureImporter;
textureImporter.textureType = TextureImporterType.Sprite;
textureImporter.mipmapEnabled = false;
textureImporter.maxTextureSize = 256;
AssetDatabase.ImportAsset(relativePath, ImportAssetOptions.ForceUpdate);
canTakePhoto = true;
doingTakePhoto = false;
if (!autoPhotosEnabled)
{
ResetCharacter();
}
yield return true;
}
}
private void UndoDimmingAnNeutralizing()
{
int numSlots = avatarToPhoto.umaData.GetSlotArraySize();
for (int i = 0; i < numSlots; i++)
{
if (avatarToPhoto.umaData.GetSlot(i))
{
var thisSlot = avatarToPhoto.umaData.GetSlot(i);
var thisSlotOverlays = thisSlot.GetOverlayList();
for (int ii = 0; ii < thisSlotOverlays.Count; ii++)
{
if (originalColors.ContainsKey(i))
{
if (originalColors[i].ContainsKey(ii))
{
thisSlotOverlays[ii].SetColor(0, originalColors[i][ii]);
}
}
}
}
}
}
private void DoDimmingAndNeutralizing()
{
if (wardrobeRecipeToPhoto.Count > 0)
Debug.Log("Doing Dimming And Neutralizing for " + wardrobeRecipeToPhoto[0].name);
else
Debug.Log("Doing Dimming And Neutralizing for Body shots");
int numAvatarSlots = avatarToPhoto.umaData.GetSlotArraySize();
originalColors.Clear();
List<string> slotsInRecipe = new List<string>();
List<string> overlaysInRecipe = new List<string>();
foreach (UMATextRecipe utr in wardrobeRecipeToPhoto)
{
UMAData.UMARecipe tempLoadedRecipe = new UMAData.UMARecipe();
utr.Load(tempLoadedRecipe, avatarToPhoto.context);
foreach (SlotData slot in tempLoadedRecipe.slotDataList)
{
if (slot != null)
{
slotsInRecipe.Add(slot.asset.name);
foreach (OverlayData wOverlay in slot.GetOverlayList())
{
if (!overlaysInRecipe.Contains(wOverlay.asset.name))
overlaysInRecipe.Add(wOverlay.asset.name);
}
}
}
}
//Deal with skin color first if we are dimming
if (dimAllButTarget)
{
OverlayColorData[] sharedColors = avatarToPhoto.umaData.umaRecipe.sharedColors;
for (int i = 0; i < sharedColors.Length; i++)
{
if (sharedColors[i].name == "Skin" || sharedColors[i].name == "skin")
{
sharedColors[i].color = dimToColor;
if (sharedColors[i].channelAdditiveMask.Length >= 3)
{
sharedColors[i].channelAdditiveMask[2] = dimToMetallic;
}
}
}
}
for (int i = 0; i < numAvatarSlots; i++)
{
if (avatarToPhoto.umaData.GetSlot(i) != null)
{
var overlaysInAvatarSlot = avatarToPhoto.umaData.GetSlot(i).GetOverlayList();
if (slotsInRecipe.Contains(avatarToPhoto.umaData.GetSlot(i).asset.name))
{
if (neutralizeTargetColors || dimAllButTarget)
{
for (int ii = 0; ii < overlaysInAvatarSlot.Count; ii++)
{
//there is a problem here where if the recipe also contains replacement body slots (like my toon CapriPants_LEGS) these also get set to white
//so we need to check if the overlay contains any body part names I think
bool overlayIsBody = false;
var thisOverlayName = overlaysInAvatarSlot[ii].asset.name;
if (thisOverlayName.IndexOf("Face", StringComparison.OrdinalIgnoreCase) > -1
// || thisOverlayName.IndexOf("Torso", StringComparison.OrdinalIgnoreCase) > -1
|| thisOverlayName.IndexOf("Arms", StringComparison.OrdinalIgnoreCase) > -1
|| thisOverlayName.IndexOf("Hands", StringComparison.OrdinalIgnoreCase) > -1
|| thisOverlayName.IndexOf("Legs", StringComparison.OrdinalIgnoreCase) > -1
|| thisOverlayName.IndexOf("Feet", StringComparison.OrdinalIgnoreCase) > -1
|| thisOverlayName.IndexOf("Body", StringComparison.OrdinalIgnoreCase) > -1)
{
overlayIsBody = true;
}
if (overlaysInRecipe.Contains(overlaysInAvatarSlot[ii].asset.name) && overlayIsBody == false)
{
if (!originalColors.ContainsKey(i))
{
originalColors.Add(i, new Dictionary<int, Color>());
}
if (!originalColors[i].ContainsKey(ii))
originalColors[i].Add(ii, overlaysInAvatarSlot[ii].colorData.color);
overlaysInAvatarSlot[ii].colorData.color = neutralizeToColor;
if (overlaysInAvatarSlot[ii].colorData.channelAdditiveMask.Length >= 3)
{
overlaysInAvatarSlot[ii].colorData.channelAdditiveMask[2] = neutralizeToMetallic;
}
}
else
{
if (dimAllButTarget)
{
if (!originalColors.ContainsKey(i))
{
originalColors.Add(i, new Dictionary<int, Color>());
}
if (!originalColors[i].ContainsKey(ii))
originalColors[i].Add(ii, overlaysInAvatarSlot[ii].colorData.color);
overlaysInAvatarSlot[ii].colorData.color = dimToColor;
if (overlaysInAvatarSlot[ii].colorData.channelAdditiveMask.Length >= 3)
{
overlaysInAvatarSlot[ii].colorData.channelAdditiveMask[2] = dimToMetallic;
}
}
}
}
}
}
else
{
if (dimAllButTarget)
{
for (int ii = 0; ii < overlaysInAvatarSlot.Count; ii++)
{
if (!overlaysInRecipe.Contains(overlaysInAvatarSlot[ii].asset.name))
{
if (!originalColors.ContainsKey(i))
{
originalColors.Add(i, new Dictionary<int, Color>());
}
if (!originalColors[i].ContainsKey(ii))
originalColors[i].Add(ii, overlaysInAvatarSlot[ii].colorData.color);
overlaysInAvatarSlot[ii].colorData.color = dimToColor;
if (overlaysInAvatarSlot[ii].colorData.channelAdditiveMask.Length >= 3)
{
overlaysInAvatarSlot[ii].colorData.channelAdditiveMask[2] = dimToMetallic;
}
}
}
}
}
}
}
avatarToPhoto.umaData.dirty = false;
avatarToPhoto.umaData.Dirty(false, true, false);
}
private bool SetBestRenderTexture(string wardrobeSlot = "")
{
if (wardrobeSlot == "Body" || (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.BodyRenderTexture))
{
if (bodyRenderTexture == null)
{
Debug.Log("You need to set the Body Render Texture in the inspector!");
return false;
}
else
{
renderTextureToUse = bodyRenderTexture;
return true;
}
}
else if (wardrobeSlot.IndexOf("Hair", StringComparison.OrdinalIgnoreCase) > -1
|| wardrobeSlot.IndexOf("Face", StringComparison.OrdinalIgnoreCase) > -1
|| wardrobeSlot.IndexOf("Head", StringComparison.OrdinalIgnoreCase) > -1
|| wardrobeSlot.IndexOf("Helmet", StringComparison.OrdinalIgnoreCase) > -1
|| wardrobeSlot.IndexOf("Complexion", StringComparison.OrdinalIgnoreCase) > -1
|| wardrobeSlot.IndexOf("Eyebrows", StringComparison.OrdinalIgnoreCase) > -1
|| wardrobeSlot.IndexOf("Beard", StringComparison.OrdinalIgnoreCase) > -1
|| wardrobeSlot.IndexOf("Ears", StringComparison.OrdinalIgnoreCase) > -1
|| (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.HeadRenderTexture))
{
if (headRenderTexture == null)
{
Debug.Log("You need to set the Head Render Texture in the inspector!");
return false;
}
else
{
renderTextureToUse = headRenderTexture;
return true;
}
}
else if (wardrobeSlot.IndexOf("Shoulders", StringComparison.OrdinalIgnoreCase) > -1
|| wardrobeSlot.IndexOf("Chest", StringComparison.OrdinalIgnoreCase) > -1
|| wardrobeSlot.IndexOf("Arms", StringComparison.OrdinalIgnoreCase) > -1
|| (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.ChestRenderTexture)
)
{
if (chestRenderTexture == null)
{
Debug.Log("You need to set the Chest Render Texture in the inspector!");
return false;
}
else
{
renderTextureToUse = chestRenderTexture;
return true;
}
}
else if (wardrobeSlot.IndexOf("Hands", StringComparison.OrdinalIgnoreCase) > -1 || (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.HandsRenderTexture))
{
if (handsRenderTexture == null)
{
Debug.Log("You need to set the Hands Render Texture in the inspector!");
return false;
}
else
{
renderTextureToUse = handsRenderTexture;
return true;
}
}
else if (wardrobeSlot.IndexOf("Waist", StringComparison.OrdinalIgnoreCase) > -1
|| wardrobeSlot.IndexOf("Legs", StringComparison.OrdinalIgnoreCase) > -1
|| (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.LegsRenderTexture))
{
if (legsRenderTexture == null)
{
Debug.Log("You need to set the Legs Render Texture in the inspector!");
return false;
}
else
{
renderTextureToUse = legsRenderTexture;
return true;
}
}
else if (wardrobeSlot.IndexOf("Feet", StringComparison.OrdinalIgnoreCase) > -1 || (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.FeetRenderTexture))
{
if (feetRenderTexture == null)
{
Debug.Log("You need to set the Feet Render Texture in the inspector!");
return false;
}
else
{
renderTextureToUse = feetRenderTexture;
return true;
}
}
else if (wardrobeSlot.IndexOf("Outfit", StringComparison.OrdinalIgnoreCase) > -1
|| wardrobeSlot.IndexOf("Underwear", StringComparison.OrdinalIgnoreCase) > -1
|| (!autoPhotosEnabled && textureToPhoto == renderTextureOpts.OutfitRenderTexture))
{
if (outfitRenderTexture == null)
{
Debug.Log("You need to set the Outfit Render Texture in the inspector!");
return false;
}
else
{
renderTextureToUse = outfitRenderTexture;
return true;
}
}
else
{
Debug.Log("No suitable render texture found for " + wardrobeSlot + " using Body rendertexture");
renderTextureToUse = bodyRenderTexture;
return true;
}
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
namespace System.Linq.Expressions.Tests
{
partial class ExpressionCatalog
{
private static IEnumerable<Expression> Block()
{
yield return Expression.Block(Expression.Constant(1));
yield return Expression.Block(Expression.Constant("bar"), Expression.Constant(2));
yield return Expression.Block(Expression.Constant("bar"), Expression.Constant(false), Expression.Constant(3));
yield return Expression.Block(typeof(int), Expression.Constant(1));
yield return Expression.Block(typeof(int), Expression.Constant("bar"), Expression.Constant(2));
yield return Expression.Block(typeof(int), Expression.Constant("bar"), Expression.Constant(false), Expression.Constant(3));
yield return Expression.Block(typeof(object), Expression.Constant("bar"));
yield return Expression.Block(typeof(object), Expression.Constant(2), Expression.Constant("bar"));
yield return Expression.Block(typeof(object), Expression.Constant(false), Expression.Constant(3), Expression.Constant("bar"));
yield return Expression.Block(typeof(int), new[] { Expression.Parameter(typeof(int)) }, Expression.Constant(1));
yield return Expression.Block(typeof(int), new[] { Expression.Parameter(typeof(int)) }, Expression.Constant("bar"), Expression.Constant(2));
yield return Expression.Block(typeof(int), new[] { Expression.Parameter(typeof(int)) }, Expression.Constant("bar"), Expression.Constant(false), Expression.Constant(3));
yield return Expression.Block(typeof(object), new[] { Expression.Parameter(typeof(int)) }, Expression.Constant("bar"));
yield return Expression.Block(typeof(object), new[] { Expression.Parameter(typeof(int)) }, Expression.Constant(2), Expression.Constant("bar"));
yield return Expression.Block(typeof(object), new[] { Expression.Parameter(typeof(int)) }, Expression.Constant(false), Expression.Constant(3), Expression.Constant("bar"));
}
private static IEnumerable<KeyValuePair<ExpressionType, Expression>> Block_WithLog()
{
yield return WithLog(ExpressionType.Block, (log, summary) =>
{
return Expression.Block(
log(Expression.Constant("A")),
log(Expression.Constant("B")),
log(Expression.Constant("C")),
summary
);
});
}
private static IEnumerable<KeyValuePair<ExpressionType, Expression>> Block_Primes()
{
var to = Expression.Parameter(typeof(int), "to");
var res = Expression.Variable(typeof(List<int>), "res");
var n = Expression.Variable(typeof(int), "n");
var found = Expression.Variable(typeof(bool), "found");
var d = Expression.Variable(typeof(int), "d");
var breakOuter = Expression.Label();
var breakInner = Expression.Label();
var getPrimes =
// Func<int, List<int>> getPrimes =
Expression.Lambda<Func<int, List<int>>>(
// {
Expression.Block(
// List<int> res;
new[] { res },
// res = new List<int>();
Expression.Assign(
res,
Expression.New(typeof(List<int>))
),
// {
Expression.Block(
// int n;
new[] { n },
// n = 2;
Expression.Assign(
n,
Expression.Constant(2)
),
// while (true)
Expression.Loop(
// {
Expression.Block(
// if
Expression.IfThen(
// (!
Expression.Not(
// (n <= to)
Expression.LessThanOrEqual(
n,
to
)
// )
),
// break;
Expression.Break(breakOuter)
),
// {
Expression.Block(
// bool found;
new[] { found },
// found = false;
Expression.Assign(
found,
Expression.Constant(false)
),
// {
Expression.Block(
// int d;
new[] { d },
// d = 2;
Expression.Assign(
d,
Expression.Constant(2)
),
// while (true)
Expression.Loop(
// {
Expression.Block(
// if
Expression.IfThen(
// (!
Expression.Not(
// d <= Math.Sqrt(n)
Expression.LessThanOrEqual(
d,
Expression.Convert(
Expression.Call(
null,
typeof(Math).GetTypeInfo().GetDeclaredMethod("Sqrt"),
Expression.Convert(
n,
typeof(double)
)
),
typeof(int)
)
)
// )
),
// break;
Expression.Break(breakInner)
),
// {
Expression.Block(
// if (n % d == 0)
Expression.IfThen(
Expression.Equal(
Expression.Modulo(
n,
d
),
Expression.Constant(0)
),
// {
Expression.Block(
// found = true;
Expression.Assign(
found,
Expression.Constant(true)
),
// break;
Expression.Break(breakInner)
// }
)
)
// }
),
// d++;
Expression.PostIncrementAssign(d)
// }
),
breakInner
)
),
// if
Expression.IfThen(
// (!found)
Expression.Not(found),
// res.Add(n);
Expression.Call(
res,
typeof(List<int>).GetTypeInfo().GetDeclaredMethod("Add"),
n
)
)
),
// n++;
Expression.PostIncrementAssign(n)
// }
),
breakOuter
)
),
res
),
to
// }
);
var joinTemplate = (Expression<Func<List<int>, string>>)(xs => string.Join(", ", xs));
var expr = Expression.Invoke(joinTemplate, Expression.Invoke(getPrimes, Expression.Constant(100)));
yield return new KeyValuePair<ExpressionType, Expression>(ExpressionType.Block, expr);
}
private static IEnumerable<KeyValuePair<ExpressionType, Expression>> Block_Primes_WithLog()
{
var joinTemplate = (Expression<Func<List<int>, string>>)(xs => string.Join(", ", xs));
var concatTemplate = (Expression<Func<string, string, string>>)((s1, s2) => s1 + s2);
var to = Expression.Parameter(typeof(int), "to");
var res = Expression.Variable(typeof(List<int>), "res");
var n = Expression.Variable(typeof(int), "n");
var found = Expression.Variable(typeof(bool), "found");
var d = Expression.Variable(typeof(int), "d");
var breakOuter = Expression.Label();
var breakInner = Expression.Label();
var expr =
WithLog((log, summary) =>
{
var body =
// {
Expression.Block(
// List<int> res;
new[] { res, to },
// to = 100;
Expression.Assign(
to,
Expression.Constant(100)
),
// res = new List<int>();
Expression.Assign(
res,
Expression.New(typeof(List<int>))
),
// {
Expression.Block(
// int n;
new[] { n },
// n = 2;
Expression.Assign(
n,
Expression.Constant(2)
),
// while (true)
Expression.Loop(
// {
Expression.Block(
// if
Expression.IfThen(
// (!
Expression.Not(
// (n <= to)
Expression.LessThanOrEqual(
n,
to
)
// )
),
// break;
Expression.Break(breakOuter)
),
// {
Expression.Block(
// bool found;
new[] { found },
// found = false;
Expression.Assign(
found,
Expression.Constant(false)
),
// {
Expression.Block(
// int d;
new[] { d },
// d = 2;
Expression.Assign(
d,
Expression.Constant(2)
),
// while (true)
Expression.Loop(
// {
Expression.Block(
// if
Expression.IfThen(
// (!
Expression.Not(
// d <= Math.Sqrt(n)
Expression.LessThanOrEqual(
d,
Expression.Convert(
Expression.Call(
null,
typeof(Math).GetTypeInfo().GetDeclaredMethod("Sqrt"),
Expression.Convert(
n,
typeof(double)
)
),
typeof(int)
)
)
// )
),
// break;
Expression.Break(breakInner)
),
// {
Expression.Block(
// if (n % d == 0)
Expression.IfThen(
Expression.Equal(
Expression.Modulo(
n,
d
),
Expression.Constant(0)
),
// {
Expression.Block(
// found = true;
Expression.Assign(
found,
Expression.Constant(true)
),
// break;
Expression.Break(breakInner)
// }
)
)
// }
),
// d++;
Expression.PostIncrementAssign(d)
// }
),
breakInner
)
),
// if
Expression.IfThen(
// (!found)
Expression.Not(found),
// res.Add(n);
Expression.Call(
res,
typeof(List<int>).GetTypeInfo().GetDeclaredMethod("Add"),
n
)
)
),
// n++;
Expression.PostIncrementAssign(n)
// }
),
breakOuter
)
),
Expression.Invoke(
concatTemplate,
Expression.Invoke(joinTemplate, res),
summary
)
);
return new InstrumentWithLog(log).Visit(body);
});
yield return new KeyValuePair<ExpressionType, Expression>(ExpressionType.Block, expr);
}
class InstrumentWithLog : ExpressionVisitor
{
private readonly Func<Expression, Expression> _log;
private int _n;
public InstrumentWithLog(Func<Expression, Expression> log)
{
_log = log;
}
protected override Expression VisitBlock(BlockExpression node)
{
var exprs = node.Expressions.SelectMany(e => new Expression[] { _log(Expression.Constant("S" + _n++)), Visit(e) }).ToList();
return node.Update(node.Variables, exprs);
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// NetworkAccessProfileResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Supersim.V1
{
public class NetworkAccessProfileResource : Resource
{
private static Request BuildCreateRequest(CreateNetworkAccessProfileOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Supersim,
"/v1/NetworkAccessProfiles",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Create a new Network Access Profile
/// </summary>
/// <param name="options"> Create NetworkAccessProfile parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of NetworkAccessProfile </returns>
public static NetworkAccessProfileResource Create(CreateNetworkAccessProfileOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Create a new Network Access Profile
/// </summary>
/// <param name="options"> Create NetworkAccessProfile parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of NetworkAccessProfile </returns>
public static async System.Threading.Tasks.Task<NetworkAccessProfileResource> CreateAsync(CreateNetworkAccessProfileOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Create a new Network Access Profile
/// </summary>
/// <param name="uniqueName"> An application-defined string that uniquely identifies the resource </param>
/// <param name="networks"> List of Network SIDs that this Network Access Profile will allow connections to </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of NetworkAccessProfile </returns>
public static NetworkAccessProfileResource Create(string uniqueName = null,
List<string> networks = null,
ITwilioRestClient client = null)
{
var options = new CreateNetworkAccessProfileOptions(){UniqueName = uniqueName, Networks = networks};
return Create(options, client);
}
#if !NET35
/// <summary>
/// Create a new Network Access Profile
/// </summary>
/// <param name="uniqueName"> An application-defined string that uniquely identifies the resource </param>
/// <param name="networks"> List of Network SIDs that this Network Access Profile will allow connections to </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of NetworkAccessProfile </returns>
public static async System.Threading.Tasks.Task<NetworkAccessProfileResource> CreateAsync(string uniqueName = null,
List<string> networks = null,
ITwilioRestClient client = null)
{
var options = new CreateNetworkAccessProfileOptions(){UniqueName = uniqueName, Networks = networks};
return await CreateAsync(options, client);
}
#endif
private static Request BuildFetchRequest(FetchNetworkAccessProfileOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Supersim,
"/v1/NetworkAccessProfiles/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch a Network Access Profile instance from your account.
/// </summary>
/// <param name="options"> Fetch NetworkAccessProfile parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of NetworkAccessProfile </returns>
public static NetworkAccessProfileResource Fetch(FetchNetworkAccessProfileOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch a Network Access Profile instance from your account.
/// </summary>
/// <param name="options"> Fetch NetworkAccessProfile parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of NetworkAccessProfile </returns>
public static async System.Threading.Tasks.Task<NetworkAccessProfileResource> FetchAsync(FetchNetworkAccessProfileOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch a Network Access Profile instance from your account.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of NetworkAccessProfile </returns>
public static NetworkAccessProfileResource Fetch(string pathSid, ITwilioRestClient client = null)
{
var options = new FetchNetworkAccessProfileOptions(pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch a Network Access Profile instance from your account.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of NetworkAccessProfile </returns>
public static async System.Threading.Tasks.Task<NetworkAccessProfileResource> FetchAsync(string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchNetworkAccessProfileOptions(pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildUpdateRequest(UpdateNetworkAccessProfileOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Supersim,
"/v1/NetworkAccessProfiles/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Updates the given properties of a Network Access Profile in your account.
/// </summary>
/// <param name="options"> Update NetworkAccessProfile parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of NetworkAccessProfile </returns>
public static NetworkAccessProfileResource Update(UpdateNetworkAccessProfileOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Updates the given properties of a Network Access Profile in your account.
/// </summary>
/// <param name="options"> Update NetworkAccessProfile parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of NetworkAccessProfile </returns>
public static async System.Threading.Tasks.Task<NetworkAccessProfileResource> UpdateAsync(UpdateNetworkAccessProfileOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Updates the given properties of a Network Access Profile in your account.
/// </summary>
/// <param name="pathSid"> The SID of the resource to update </param>
/// <param name="uniqueName"> The new unique name of the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of NetworkAccessProfile </returns>
public static NetworkAccessProfileResource Update(string pathSid,
string uniqueName = null,
ITwilioRestClient client = null)
{
var options = new UpdateNetworkAccessProfileOptions(pathSid){UniqueName = uniqueName};
return Update(options, client);
}
#if !NET35
/// <summary>
/// Updates the given properties of a Network Access Profile in your account.
/// </summary>
/// <param name="pathSid"> The SID of the resource to update </param>
/// <param name="uniqueName"> The new unique name of the resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of NetworkAccessProfile </returns>
public static async System.Threading.Tasks.Task<NetworkAccessProfileResource> UpdateAsync(string pathSid,
string uniqueName = null,
ITwilioRestClient client = null)
{
var options = new UpdateNetworkAccessProfileOptions(pathSid){UniqueName = uniqueName};
return await UpdateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadNetworkAccessProfileOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Supersim,
"/v1/NetworkAccessProfiles",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of Network Access Profiles from your account.
/// </summary>
/// <param name="options"> Read NetworkAccessProfile parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of NetworkAccessProfile </returns>
public static ResourceSet<NetworkAccessProfileResource> Read(ReadNetworkAccessProfileOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<NetworkAccessProfileResource>.FromJson("network_access_profiles", response.Content);
return new ResourceSet<NetworkAccessProfileResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of Network Access Profiles from your account.
/// </summary>
/// <param name="options"> Read NetworkAccessProfile parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of NetworkAccessProfile </returns>
public static async System.Threading.Tasks.Task<ResourceSet<NetworkAccessProfileResource>> ReadAsync(ReadNetworkAccessProfileOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<NetworkAccessProfileResource>.FromJson("network_access_profiles", response.Content);
return new ResourceSet<NetworkAccessProfileResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of Network Access Profiles from your account.
/// </summary>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of NetworkAccessProfile </returns>
public static ResourceSet<NetworkAccessProfileResource> Read(int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadNetworkAccessProfileOptions(){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of Network Access Profiles from your account.
/// </summary>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of NetworkAccessProfile </returns>
public static async System.Threading.Tasks.Task<ResourceSet<NetworkAccessProfileResource>> ReadAsync(int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadNetworkAccessProfileOptions(){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<NetworkAccessProfileResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<NetworkAccessProfileResource>.FromJson("network_access_profiles", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<NetworkAccessProfileResource> NextPage(Page<NetworkAccessProfileResource> page,
ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Supersim)
);
var response = client.Request(request);
return Page<NetworkAccessProfileResource>.FromJson("network_access_profiles", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<NetworkAccessProfileResource> PreviousPage(Page<NetworkAccessProfileResource> page,
ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Supersim)
);
var response = client.Request(request);
return Page<NetworkAccessProfileResource>.FromJson("network_access_profiles", response.Content);
}
/// <summary>
/// Converts a JSON string into a NetworkAccessProfileResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> NetworkAccessProfileResource object represented by the provided JSON </returns>
public static NetworkAccessProfileResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<NetworkAccessProfileResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// An application-defined string that uniquely identifies the resource
/// </summary>
[JsonProperty("unique_name")]
public string UniqueName { get; private set; }
/// <summary>
/// The SID of the Account that the Network Access Profile belongs to
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The absolute URL of the resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The links
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private NetworkAccessProfileResource()
{
}
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Lucene.Net.Index
{
/*
* 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 Directory = Lucene.Net.Store.Directory;
using IBits = Lucene.Net.Util.IBits;
using InfoStream = Lucene.Net.Util.InfoStream;
using MonotonicAppendingInt64Buffer = Lucene.Net.Util.Packed.MonotonicAppendingInt64Buffer;
/// <summary>
/// Holds common state used during segment merging.
/// <para/>
/// @lucene.experimental
/// </summary>
public class MergeState
{
/// <summary>
/// Remaps docids around deletes during merge
/// </summary>
public abstract class DocMap
{
internal DocMap()
{
}
/// <summary>
/// Returns the mapped docID corresponding to the provided one. </summary>
public abstract int Get(int docID);
/// <summary>
/// Returns the total number of documents, ignoring
/// deletions.
/// </summary>
public abstract int MaxDoc { get; }
/// <summary>
/// Returns the number of not-deleted documents. </summary>
public int NumDocs => MaxDoc - NumDeletedDocs;
/// <summary>
/// Returns the number of deleted documents. </summary>
public abstract int NumDeletedDocs { get; }
/// <summary>
/// Returns <c>true</c> if there are any deletions. </summary>
public virtual bool HasDeletions => NumDeletedDocs > 0;
/// <summary>
/// Creates a <see cref="DocMap"/> instance appropriate for
/// this reader.
/// </summary>
public static DocMap Build(AtomicReader reader)
{
int maxDoc = reader.MaxDoc;
if (!reader.HasDeletions)
{
return new NoDelDocMap(maxDoc);
}
IBits liveDocs = reader.LiveDocs;
return Build(maxDoc, liveDocs);
}
internal static DocMap Build(int maxDoc, IBits liveDocs)
{
if (Debugging.AssertsEnabled) Debugging.Assert(liveDocs != null);
MonotonicAppendingInt64Buffer docMap = new MonotonicAppendingInt64Buffer();
int del = 0;
for (int i = 0; i < maxDoc; ++i)
{
docMap.Add(i - del);
if (!liveDocs.Get(i))
{
++del;
}
}
docMap.Freeze();
int numDeletedDocs = del;
if (Debugging.AssertsEnabled) Debugging.Assert(docMap.Count == maxDoc);
return new DocMapAnonymousClass(maxDoc, liveDocs, docMap, numDeletedDocs);
}
private class DocMapAnonymousClass : DocMap
{
private readonly int maxDoc;
private readonly IBits liveDocs;
private readonly MonotonicAppendingInt64Buffer docMap;
private readonly int numDeletedDocs;
public DocMapAnonymousClass(int maxDoc, IBits liveDocs, MonotonicAppendingInt64Buffer docMap, int numDeletedDocs)
{
this.maxDoc = maxDoc;
this.liveDocs = liveDocs;
this.docMap = docMap;
this.numDeletedDocs = numDeletedDocs;
}
public override int Get(int docID)
{
if (!liveDocs.Get(docID))
{
return -1;
}
return (int)docMap.Get(docID);
}
public override int MaxDoc => maxDoc;
public override int NumDeletedDocs => numDeletedDocs;
}
}
private sealed class NoDelDocMap : DocMap
{
private readonly int maxDoc;
internal NoDelDocMap(int maxDoc)
{
this.maxDoc = maxDoc;
}
public override int Get(int docID)
{
return docID;
}
public override int MaxDoc => maxDoc;
public override int NumDeletedDocs => 0;
}
/// <summary>
/// <see cref="Index.SegmentInfo"/> of the newly merged segment. </summary>
public SegmentInfo SegmentInfo { get; private set; }
/// <summary>
/// <see cref="Index.FieldInfos"/> of the newly merged segment. </summary>
public FieldInfos FieldInfos { get; set; }
/// <summary>
/// Readers being merged. </summary>
public IList<AtomicReader> Readers { get; private set; }
/// <summary>
/// Maps docIDs around deletions. </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public DocMap[] DocMaps { get; set; }
/// <summary>
/// New docID base per reader. </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public int[] DocBase { get; set; }
/// <summary>
/// Holds the <see cref="Index.CheckAbort"/> instance, which is invoked
/// periodically to see if the merge has been aborted.
/// </summary>
public CheckAbort CheckAbort { get; private set; }
/// <summary>
/// <see cref="Util.InfoStream"/> for debugging messages. </summary>
public InfoStream InfoStream { get; private set; }
// TODO: get rid of this? it tells you which segments are 'aligned' (e.g. for bulk merging)
// but is this really so expensive to compute again in different components, versus once in SM?
/// <summary>
/// <see cref="SegmentReader"/>s that have identical field
/// name/number mapping, so their stored fields and term
/// vectors may be bulk merged.
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public SegmentReader[] MatchingSegmentReaders { get; set; }
/// <summary>
/// How many <see cref="MatchingSegmentReaders"/> are set. </summary>
public int MatchedCount { get; set; }
/// <summary>
/// Sole constructor. </summary>
internal MergeState(IList<AtomicReader> readers, SegmentInfo segmentInfo, InfoStream infoStream, CheckAbort checkAbort)
{
this.Readers = readers;
this.SegmentInfo = segmentInfo;
this.InfoStream = infoStream;
this.CheckAbort = checkAbort;
}
}
/// <summary>
/// Class for recording units of work when merging segments.
/// </summary>
public class CheckAbort // LUCENENET Specific: De-nested this class to fix CLS naming issue
{
private double workCount;
private readonly MergePolicy.OneMerge merge;
private readonly Directory dir;
/// <summary>
/// Creates a <see cref="CheckAbort"/> instance. </summary>
public CheckAbort(MergePolicy.OneMerge merge, Directory dir)
{
this.merge = merge;
this.dir = dir;
}
/// <summary>
/// Records the fact that roughly units amount of work
/// have been done since this method was last called.
/// When adding time-consuming code into <see cref="SegmentMerger"/>,
/// you should test different values for units to ensure
/// that the time in between calls to merge.CheckAborted
/// is up to ~ 1 second.
/// </summary>
public virtual void Work(double units)
{
workCount += units;
if (workCount >= 10000.0)
{
merge.CheckAborted(dir);
workCount = 0;
}
}
/// <summary>
/// If you use this: IW.Dispose(false) cannot abort your merge!
/// <para/>
/// @lucene.internal
/// </summary>
public static readonly CheckAbort NONE = new CheckAbortAnonymousClass();
private class CheckAbortAnonymousClass : CheckAbort
{
public CheckAbortAnonymousClass()
: base(null, null)
{
}
public override void Work(double units)
{
// do nothing
}
}
}
}
| |
using System;
using System.Text;
namespace Gearman.Packets.Worker
{
public class CanDo : RequestPacket
{
public string functionName;
public CanDo(string function)
{
this.type = PacketType.CAN_DO;
this.functionName = function;
this.size = functionName.Length;
}
public CanDo(byte[] pktdata) : base(pktdata)
{
int pOff = 0;
pOff = parseString(pOff, ref functionName);
}
override public byte[] ToByteArray()
{
byte[] result = new byte[this.size + 12];
byte[] functionbytes = new ASCIIEncoding().GetBytes(functionName);
Array.Copy(this.Header, result, this.Header.Length);
Array.Copy(functionbytes, 0, result, this.Header.Length, functionbytes.Length);
return result;
}
}
public class CanDoTimeout : RequestPacket {
public string functionName;
public CanDoTimeout(string function)
{
this.functionName = function;
this.size = function.Length;
this.type = PacketType.CAN_DO_TIMEOUT;
}
override public byte[] ToByteArray()
{
byte[] result = new byte[this.size + 12];
byte[] functionbytes = new ASCIIEncoding().GetBytes(functionName);
Array.Copy(this.Header, result, this.Header.Length);
Array.Copy(functionbytes, 0, result, this.Header.Length, functionbytes.Length);
return result;
}
}
public class CantDo : RequestPacket {
public string functionName;
public CantDo(string function)
{
this.functionName = function;
this.size = function.Length;
this.type = PacketType.CANT_DO;
}
override public byte[] ToByteArray()
{
byte[] result = new byte[this.size + 12];
byte[] functionbytes = new ASCIIEncoding().GetBytes(functionName);
Array.Copy(this.Header, result, this.Header.Length);
Array.Copy(functionbytes, 0, result, this.Header.Length, functionbytes.Length);
return result;
}
}
public class ResetAbilities : RequestPacket {
public ResetAbilities()
{
this.type = PacketType.RESET_ABILITIES;
}
}
public class PreSleep : RequestPacket {
public PreSleep()
{
this.type = PacketType.PRE_SLEEP;
}
}
public class GrabJob : RequestPacket {
public GrabJob()
{
this.type = PacketType.GRAB_JOB;
}
}
public class GrabJobUniq : RequestPacket {
public GrabJobUniq()
{
this.type = PacketType.GRAB_JOB_UNIQ;
}
}
public class WorkData : RequestPacket {
public String jobhandle;
public byte[] data;
public WorkData()
{
this.type = PacketType.WORK_DATA;
}
public WorkData(String jobhandle, byte[] data)
{
this.jobhandle = jobhandle;
this.data = data;
this.size = jobhandle.Length + 1 + data.Length;
this.type = PacketType.WORK_DATA;
}
public WorkData(byte[] pktdata) : base(pktdata)
{
int pOff = 0;
pOff = parseString(pOff, ref jobhandle);
data = rawdata.Slice(pOff, rawdata.Length);
}
override public byte[] ToByteArray()
{
byte[] result = new byte[this.size + 12];
byte[] header = base.ToByteArray();
byte[] jhbytes = new ASCIIEncoding().GetBytes(jobhandle + '\0');
Array.Copy(header, result, header.Length);
Array.Copy(jhbytes, 0, result, header.Length, jhbytes.Length);
Array.Copy(data, 0, result, header.Length + jhbytes.Length, data.Length);
return result;
}
}
public class WorkWarning : WorkData
{
public WorkWarning(String jobhandle, byte[] data) : base(jobhandle, data)
{
this.type = PacketType.WORK_WARNING;
}
public WorkWarning(byte[] pktdata) : base(pktdata)
{
this.type = PacketType.WORK_WARNING;
}
}
public class WorkComplete : WorkData
{
public WorkComplete(String jobhandle, byte[] data) : base(jobhandle, data)
{
this.type = PacketType.WORK_COMPLETE;
}
public WorkComplete(byte[] pktdata) : base(pktdata)
{
this.type = PacketType.WORK_COMPLETE;
}
}
public class WorkFail : RequestPacket
{
public string jobhandle;
public WorkFail(String jobhandle)
{
this.jobhandle = jobhandle;
this.size = jobhandle.Length;
this.type = PacketType.WORK_FAIL;
}
public WorkFail(byte[] pktdata) : base(pktdata)
{
int pOff = 0;
pOff = parseString(pOff, ref jobhandle);
}
override public byte[] ToByteArray()
{
byte[] result = new byte[this.size + 12];
byte[] header = base.ToByteArray();
byte[] jhbytes = new ASCIIEncoding().GetBytes(jobhandle);
Array.Copy(header, result, header.Length);
Array.Copy(jhbytes, 0, result, header.Length, jhbytes.Length);
return result;
}
}
public class WorkException : RequestPacket
{
public string jobhandle;
public byte[] exception;
public WorkException(string jobhandle, byte[] exception)
{
this.jobhandle = jobhandle;
this.exception = exception;
this.size = jobhandle.Length + 1 + exception.Length;
this.type = PacketType.WORK_EXCEPTION;
}
public WorkException(byte[] pktdata) : base(pktdata)
{
int pOff = 0;
pOff = parseString(pOff, ref jobhandle);
exception = pktdata.Slice(pOff, rawdata.Length);
}
}
public class WorkStatus : RequestPacket
{
public string jobhandle;
public int completenumerator;
public int completedenominator;
public WorkStatus()
{ }
public WorkStatus(string jobhandle, int numerator, int denominator)
{
this.jobhandle = jobhandle;
this.completenumerator = numerator;
this.completedenominator = denominator;
this.type = PacketType.WORK_STATUS;
this.size = jobhandle.Length + 1 + completenumerator.ToString().Length + 1 + completedenominator.ToString().Length;
}
public WorkStatus(byte[] pktdata) : base(pktdata)
{
int pOff = 0;
string numerator = "", denominator = "";
pOff = parseString(pOff, ref jobhandle);
pOff = parseString(pOff, ref numerator);
pOff = parseString(pOff, ref denominator);
completedenominator = Int32.Parse(denominator);
completenumerator = Int32.Parse(numerator);
}
override public byte[] ToByteArray()
{
byte[] result = new byte[this.size + 12];
byte[] header = base.ToByteArray();
byte[] msgdata = new ASCIIEncoding().GetBytes(jobhandle + '\0' + completenumerator + '\0' + completedenominator);
Array.Copy(header, result, header.Length);
Array.Copy(msgdata, 0, result, header.Length, msgdata.Length);
return result;
}
}
public class SetClientID : RequestPacket
{
public string instanceid;
public SetClientID(string instanceid)
{
this.instanceid = instanceid;
this.type = PacketType.SET_CLIENT_ID;
}
public SetClientID(byte[] pktdata) : base(pktdata)
{
int pOff = 0;
pOff = parseString(pOff, ref instanceid);
}
}
/* Responses */
public class NoOp : ResponsePacket
{
public NoOp()
{
this.type = PacketType.NOOP;
}
}
public class NoJob : ResponsePacket
{
public NoJob()
{
this.type = PacketType.NO_JOB;
}
}
public class JobAssign : ResponsePacket
{
public string jobhandle;
public string taskname;
public byte[] data;
public JobAssign()
{
this.type = PacketType.JOB_ASSIGN;
}
public JobAssign(string jobhandle, string taskname, byte[] data)
{
this.jobhandle = jobhandle;
this.taskname = taskname;
this.data = data;
this.type = PacketType.JOB_ASSIGN;
this.size = taskname.Length + 1 + jobhandle.Length + 1 + data.Length;
}
public JobAssign(byte[] pktdata) : base(pktdata)
{
int pOff = 0;
pOff = parseString(pOff, ref jobhandle);
pOff = parseString(pOff, ref taskname);
data = rawdata.Slice(pOff, rawdata.Length);
}
override public byte[] ToByteArray()
{
byte[] result = new byte[this.size + 12];
byte[] metadata = new ASCIIEncoding().GetBytes(jobhandle + '\0' + taskname + '\0');
Array.Copy(this.Header, result, this.Header.Length);
Array.Copy(metadata, 0, result, this.Header.Length, metadata.Length);
Array.Copy(data, 0, result, Header.Length + metadata.Length, data.Length);
return result;
}
}
public class JobAssignUniq : ResponsePacket
{
public string jobhandle, taskname, unique_id;
public byte[] data;
public JobAssignUniq()
{
this.type = PacketType.JOB_ASSIGN_UNIQ;
}
public JobAssignUniq(byte[] pktdata) : base (pktdata)
{
int pOff = 0;
pOff = parseString(pOff, ref jobhandle);
pOff = parseString(pOff, ref taskname);
pOff = parseString(pOff, ref unique_id);
data = pktdata.Slice(pOff, pktdata.Length);
}
}
public class SubmitJob : RequestPacket
{
public string taskname, unique_id, epochstring;
public byte[] data;
public bool background;
public SubmitJob()
{
}
public SubmitJob(byte[] pktdata) : base (pktdata)
{
int pOff = 0;
pOff = parseString(pOff, ref taskname);
pOff = parseString(pOff, ref unique_id);
if (this.type == PacketType.SUBMIT_JOB_EPOCH)
{
pOff = parseString(pOff, ref epochstring);
}
if (this.type == PacketType.SUBMIT_JOB_HIGH_BG || this.type == PacketType.SUBMIT_JOB_LOW_BG || this.type == PacketType.SUBMIT_JOB_BG)
{
this.background = true;
}
data = pktdata.Slice(pOff, pktdata.Length);
}
public SubmitJob(string function, string unique_id, byte[] data, bool background)
{
this.taskname = function;
this.unique_id = unique_id;
this.data = data;
this.size = function.Length + 1 + unique_id.Length + 1 + data.Length;
if(background)
{
this.type = PacketType.SUBMIT_JOB_BG;
} else {
this.type = PacketType.SUBMIT_JOB;
}
}
public SubmitJob(string function, string unique_id, byte[] data, bool background, Gearman.Client.JobPriority priority) : this(function, unique_id, data, background)
{
switch (priority)
{
case Gearman.Client.JobPriority.HIGH:
this.type = background ? PacketType.SUBMIT_JOB_HIGH_BG : PacketType.SUBMIT_JOB_HIGH;
break;
case Gearman.Client.JobPriority.NORMAL:
this.type = background ? PacketType.SUBMIT_JOB_BG : PacketType.SUBMIT_JOB;
break;
case Gearman.Client.JobPriority.LOW:
this.type = background ? PacketType.SUBMIT_JOB_LOW_BG : PacketType.SUBMIT_JOB_LOW;
break;
default:
break;
}
}
public DateTime when
{
get
{
try
{
var unixepoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return unixepoch.AddSeconds(Convert.ToInt64(epochstring));
}
catch (Exception e)
{
return new DateTime(0);
}
}
}
override public byte[] ToByteArray()
{
byte[] result = new byte[this.size + 12];
byte[] metadata = new ASCIIEncoding().GetBytes(taskname + '\0' + unique_id + '\0');
Array.Copy(this.Header, result, this.Header.Length);
Array.Copy(metadata, 0, result, this.Header.Length, metadata.Length);
Array.Copy(data, 0, result, Header.Length + metadata.Length, data.Length);
return result;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: HttpWebRequest.cs
//
// 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.IO;
using System.Net.Cache;
using Android.Net.Http;
using Android.Util;
using Org.Apache.Http;
using Org.Apache.Http.Client.Methods;
using Org.Apache.Http.Client.Params;
using Org.Apache.Http.Entity;
using Org.Apache.Http.Message;
using Org.Apache.Http.Params;
namespace System.Net
{
/// <summary>
/// Provides an HTTP-specific implementation of the WebRequest class.
/// </summary>
public class HttpWebRequest : WebRequest
{
private Uri _requestUri;
private Uri _address;
private Stream _requestStream;
private HttpRequestBase _request;
static HttpWebRequest()
{
DefaultMaximumErrorResponseLength = -1;
}
internal HttpWebRequest(Uri requestUri)
{
_requestUri = requestUri;
Headers = new WebHeaderCollection();
MaximumAutomaticRedirections = 50;
AllowAutoRedirect = true;
AllowWriteStreamBuffering = true;
Timeout = 100000; //(100 Seconds)
Method = "GET";
ProtocolVersion = HttpVersion.Version11;
}
/// <summary>
/// Gets or sets the value of the Accept HTTP header.
/// </summary>
public string Accept
{
get { return Headers[HttpRequestHeader.Accept]; }
set { Headers[HttpRequestHeader.Accept ] = value; }
}
/// <summary>
/// Gets the Uniform Resource Identifier (URI) of the Internet resource that actually responds to the request.
/// </summary>
public Uri Address { get { return _address; } }
/// <summary>
/// Whether the request should follow redirection responses (default is true).
/// </summary>
public bool AllowAutoRedirect { get; set; }
/// <summary>
/// Whether to buffer the data sent to the Internet resource (default is true).
/// </summary>
public bool AllowWriteStreamBuffering { get; set; }
/// <summary>
/// The type of decompression that is used.
/// </summary>
public DecompressionMethods AutomaticDecompression { get; set; }
/*
/// <summary>
/// The collection of security certificates that are associated with this request.
/// </summary>
public X509CertificateCollection ClientCertificates { get; set; }
*/
/// <summary>
/// The value of the Connection HTTP header.
/// </summary>
public string Connection
{
get { return Headers[HttpRequestHeader.Connection]; }
set { Headers[HttpRequestHeader.Connection] = value; }
}
/// <summary>
/// the name of the connection group for the request (default = null).
/// </summary>
public override string ConnectionGroupName { get; set; }
/// <summary>
/// The Content-length HTTP header (default = -1, meaning no request data to send).
/// </summary>
public override long ContentLength
{
get
{
var contentLength = Headers[HttpRequestHeader.ContentLength];
if (string.IsNullOrEmpty(contentLength)) return -1L;
return long.Parse(contentLength);
}
set { Headers.Set(HttpRequestHeader.ContentLength, value.ToString()); }
}
/// <summary>
/// he value of the Content-type HTTP header (default = null).
/// </summary>
public override string ContentType
{
get { return Headers[HttpRequestHeader.ContentType]; }
set { Headers[HttpRequestHeader.ContentType] = value; }
}
/// <summary>
/// The delegate method called when an HTTP 100-continue response is received from the Internet resource.
/// </summary>
public HttpContinueDelegate ContinueDelegate { get; set; }
/*
/// <summary>
/// The cookies associated with the request.
/// </summary>
public CookieContainer CookieContainer { get; set; }
*/
/// <summary>
/// The authentication information for the request (default = null).
/// </summary>
public override ICredentials Credentials { get; set; }
/// <summary>
/// The Date HTTP header value to use in an HTTP request.
/// </summary>
public DateTime Date
{
get
{
var date = Headers[HttpRequestHeader.Date];
if (string.IsNullOrEmpty(date)) return DateTime.MinValue;
return DateTime.Parse(date);
}
set { Headers[HttpRequestHeader.Date] = value.ToString(); }
}
/// <summary>
/// The default cache policy for this request.
/// </summary>
public static RequestCachePolicy DefaultCachePolicy { get; set; }
/// <summary>
/// The default maximum length of an HTTP error response (defualt is -1, meaning unlimited).
/// </summary>
public static int DefaultMaximumErrorResponseLength { get; set; }
/// <summary>
/// The default for the MaximumResponseHeadersLength property.
/// </summary>
public static int DefaultMaximumResponseHeadersLength { get; set; }
/// <summary>
/// The value of the Expect HTTP header.
/// </summary>
public string Expect
{
get { return Headers[HttpRequestHeader.Expect]; }
set { Headers[HttpRequestHeader.Expect] = value; }
}
/// <summary>
/// Whether a response has been received from an Internet resource.
/// </summary>
public bool HaveResponse
{
get { return _address != null; }
}
/// <summary>
/// Specifies a collection of the name/value pairs that make up the HTTP headers.
/// </summary>
public override WebHeaderCollection Headers { get; set; }
/// <summary>
/// The Host header value to use in an HTTP request independent from the request URI.
/// </summary>
public string Host { get; set; }
/// <summary>
/// The value of the If-Modified-Since HTTP header (default is current).
/// </summary>
public DateTime IfModifiedSince
{
get
{
var date = Headers[HttpRequestHeader.Date];
if (string.IsNullOrEmpty(date)) return DateTime.Now;
return DateTime.Parse(date);
}
set { Headers[HttpRequestHeader.Date] = value.ToString(); }
}
/// <summary>
/// Whether to make a persistent connection to the Internet resource (default = true).
/// </summary>
public bool KeepAlive
{
get
{
var keepAlive = Headers[HttpRequestHeader.KeepAlive];
if (string.IsNullOrEmpty(keepAlive)) return true;
return bool.Parse(keepAlive);
}
set { Headers[HttpRequestHeader.Date] = value.ToString(); }
}
/// <summary>
/// The maximum number of redirects that the request follows (default = 50).
/// </summary>
public int MaximumAutomaticRedirections { get; set; }
/// <summary>
/// the maximum allowed length of the response headers (in kilobytes; default = -1)
/// </summary>
public int MaximumResponseHeadersLength { get; set; }
/// <summary>
/// The media type of the request.
/// </summary>
public string MediaType { get; set; }
/// <summary>
/// The method for the request (default = GET).
/// </summary>
public override string Method { get; set; }
/// <summary>
/// whether to pipeline the request to the Internet resource.
/// </summary>
public bool Pipelined { get; set; }
/// <summary>
/// Whether to send an Authorization header with the request.
/// </summary>
public override bool PreAuthenticate { get; set; }
/// <summary>
/// The version of HTTP to use for the request (default = Version 1.1)
/// </summary>
public Version ProtocolVersion { get; set; }
/// <summary>
/// Proxy information for the request.
/// </summary>
public override IWebProxy Proxy { get; set; }
/// <summary>
/// The time-out in milliseconds when writing to or reading from a stream (default = 300.000 [5 min]).
/// </summary>
public int ReadWriteTimeout { get; set; }
/// <summary>
/// The value of the Referer HTTP header (default = null).
/// </summary>
public string Referer
{
get { return Headers[HttpRequestHeader.Referer]; }
set { Headers[HttpRequestHeader.Referer] = value; }
}
//
// Summary:
// Gets the original Uniform Resource Identifier (URI) of the request.
//
// Returns:
// A System.Uri that contains the URI of the Internet resource passed to the
// System.Net.WebRequest.Create(System.String) method.
public override Uri RequestUri
{
get { return _requestUri; }
}
/// <summary>
/// Whether to send data in segments to the Internet resource (default = false).
/// </summary>
public bool SendChunked { get; set; }
/*
/// <summary>
/// The service point to use for the request.
/// </summary>
public ServicePoint ServicePoint { get; }
*/
/// <summary>
/// the time-out value in milliseconds for the GetResponse() GetRequestStream() methods (default = 100,000 [100 seconds]).
/// </summary>
public override int Timeout { get; set; }
/// <summary>
/// The value of the Transfer-encoding HTTP header.
/// </summary>
public string TransferEncoding
{
get { return Headers[HttpRequestHeader.TransferEncoding]; }
set { Headers[HttpRequestHeader.TransferEncoding] = value; }
}
/// <summary>
/// Whether to allow high-speed NTLM-authenticated connection sharing.
/// </summary>
public bool UnsafeAuthenticatedConnectionSharing { get; set; }
/// <summary>
/// Whether default credentials are sent with requests (default = false).
/// </summary>
public override bool UseDefaultCredentials { get; set; }
/// <summary>
/// The value of the User-agent HTTP header.
/// </summary>
public string UserAgent
{
get { return Headers[HttpRequestHeader.UserAgent]; }
set { Headers[HttpRequestHeader.UserAgent ] = value; }
}
/// <summary>
/// Cancels a request to an Internet resource.
/// </summary>
public override void Abort()
{
if (_request != null) _request.Abort();
}
/// <summary>
/// Adds a byte range header to a request for a specific range from the beginning or end of the requested data.
/// </summary>
/// <param name="range"></param>
public void AddRange(int range)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a byte range header to a request for a specific range from the beginning or end of the requested data.
/// </summary>
/// <param name="range"></param>
public void AddRange(long range)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a byte range header to the request for a specified range.
/// </summary>
public void AddRange(int from, int to)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a byte range header to the request for a specified range.
/// </summary>
public void AddRange(long from, long to)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a Range header to a request for a specific range from the beginning or end of the requested data.
/// </summary>
public void AddRange(string rangeSpecifier, int range)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a Range header to a request for a specific range from the beginning or end of the requested data.
/// </summary>
/// <param name="rangeSpecifier"></param>
/// <param name="range"></param>
public void AddRange(string rangeSpecifier, long range)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a range header to a request for a specified range.
/// </summary>
/// <param name="rangeSpecifier"></param>
/// <param name="from"></param>
/// <param name="to"></param>
public void AddRange(string rangeSpecifier, int from, int to)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds a range header to a request for a specified range.
/// </summary>
public void AddRange(string rangeSpecifier, long from, long to)
{
throw new NotImplementedException();
}
/// <summary>
/// Begins an asynchronous request for a System.IO.Stream object to use to write data.
/// </summary>
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
{
throw new NotImplementedException();
}
/// <summary>
/// Begins an asynchronous request to an Internet resource.
/// </summary>
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
throw new NotImplementedException();
}
/// <summary>
/// Ends an asynchronous request for a Stream object to use to write data.
/// </summary>
public override Stream EndGetRequestStream(IAsyncResult asyncResult)
{
throw new NotImplementedException();
}
/*
/// <summary>
/// Ends an asynchronous request to an Internet resource and outputs the context.
/// </summary>
public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext context);
*/
/// <summary>
/// Ends an asynchronous request to an Internet resource.
/// </summary>
public override WebResponse EndGetResponse(IAsyncResult asyncResult)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets a Stream object to use to write request data.
/// </summary>
public override Stream GetRequestStream()
{
return _requestStream ?? (_requestStream = new MemoryStream());
}
/*
/// <summary>
/// Gets a Stream object to use to write request data and outputs the context.
/// </summary>
public Stream GetRequestStream(out TransportContext context);
*/
/// <summary>
/// Returns a response from an Internet resource.
/// </summary>
/// <remarks>
/// You must close the returned response to avoid socket and memory leaks.
/// </remarks>
public override WebResponse GetResponse()
{
#if ANDROID_8P
var method = this.Method.ToLower();
switch (method)
{
case "get":
_request = new HttpGet();
break;
case "post":
_request = new HttpPost();
break;
case "put":
_request = new HttpPut();
break;
case "delete":
_request = new HttpDelete();
break;
default: //the switch below is to prevent a C# compiler bug with 7 case statements.
switch (method)
{
case "options":
_request = new HttpOptions();
break;
case "head":
_request = new HttpHead();
break;
case "trace":
_request = new HttpTrace();
break;
default:
throw new NotSupportedException(string.Format("Unsupported Method: {0}", this.Method));
}
break;
}
_request.SetURI(_requestUri);
if (ContentLength != -1)
{
var entityRequest = _request as HttpEntityEnclosingRequestBase;
if (entityRequest == null)
throw new NotSupportedException(string.Format("Method: {0} does not support a request stream",
this.Method));
if (_requestStream.Length < ContentLength)
throw new ArgumentException(
string.Format("ContentLength={0}, however the request stream contains only {1} bytes",
ContentLength, _requestStream.Length));
_requestStream.Seek(0L, SeekOrigin.Begin);
entityRequest.Entity = new InputStreamEntity(_requestStream, ContentLength);
}
if (Headers != null)
{
var count = Headers.Count;
for (var i = 0; i < count; i++)
{
var key = Headers.GetKey(i);
if (key != "content-length") //The content length is set above.
_request.AddHeader(key, Headers.Get(i));
}
}
AndroidHttpClient client = null;
try
{
client = AndroidHttpClient.NewInstance(UserAgent);
HttpClientParams.SetRedirecting(client.Params, this.AllowAutoRedirect);
var response = client.Execute(_request);
if (response == null)
{
throw new Exception("Response is null");
}
var header = response.GetFirstHeader(WebHeaderCollection.HeaderToString(HttpResponseHeader.Location));
var uri = header != null ? header.Value : null;
_address = new Uri(!string.IsNullOrEmpty(uri) ? uri : _requestUri.ToString());
var result = new HttpWebResponse(this, response, client);
client = null; // So we won't release it, HttpWebResponse should now release it.
return result;
}
finally
{
if(client != null) client.Close();
}
#else
throw new NotSupportedException("The HttpWebRequest is not supported on Android v2.1, but available as of v2.2");
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using MongoDB.Connections;
using MongoDB.Protocol;
using MongoDB.Serialization;
using System.Linq;
using MongoDB.Util;
using MongoDB.Configuration.Mapping;
namespace MongoDB
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public class Cursor<T> : ICursor<T> where T : class
{
private readonly Connection _connection;
private readonly string _databaseName;
private readonly Document _specOpts = new Document();
private object _spec;
private object _fields;
private int _limit;
private QueryOptions _options;
private ReplyMessage<T> _reply;
private int _skip;
private bool _keepCursor;
private readonly ISerializationFactory _serializationFactory;
private readonly IMappingStore _mappingStore;
/// <summary>
/// Initializes a new instance of the <see cref="Cursor<T>"/> class.
/// </summary>
/// <param name="serializationFactory">The serialization factory.</param>
/// <param name="mappingStore">The mapping store.</param>
/// <param name="connection">The conn.</param>
/// <param name="databaseName">Name of the database.</param>
/// <param name="collectionName">Name of the collection.</param>
internal Cursor(ISerializationFactory serializationFactory, IMappingStore mappingStore, Connection connection, string databaseName, string collectionName)
{
//Todo: add public constrcutor for users to call
IsModifiable = true;
_connection = connection;
_databaseName = databaseName;
FullCollectionName = databaseName + "." + collectionName;
_serializationFactory = serializationFactory;
_mappingStore = mappingStore;
}
/// <summary>
/// Initializes a new instance of the <see cref="Cursor<T>"/> class.
/// </summary>
/// <param name="serializationFactory">The serialization factory.</param>
/// <param name="mappingStore">The mapping store.</param>
/// <param name="connection">The conn.</param>
/// <param name="databaseName">Name of the database.</param>
/// <param name="collectionName">Name of the collection.</param>
/// <param name="spec">The spec.</param>
/// <param name="limit">The limit.</param>
/// <param name="skip">The skip.</param>
/// <param name="fields">The fields.</param>
internal Cursor(ISerializationFactory serializationFactory, IMappingStore mappingStore, Connection connection, string databaseName, string collectionName, object spec, int limit, int skip, object fields)
: this(serializationFactory, mappingStore, connection, databaseName, collectionName)
{
//Todo: add public constrcutor for users to call
if (spec == null)
spec = new Document();
_spec = spec;
_limit = limit;
_skip = skip;
_fields = fields;
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="Cursor<T>"/> is reclaimed by garbage collection.
/// </summary>
~Cursor(){
Dispose(false);
}
/// <summary>
/// Gets or sets the full name of the collection.
/// </summary>
/// <value>The full name of the collection.</value>
public string FullCollectionName { get; private set; }
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
public long Id { get; private set; }
/// <summary>
/// Specs the specified spec.
/// </summary>
/// <param name="spec">The spec.</param>
/// <returns></returns>
public ICursor<T> Spec(object spec){
TryModify();
_spec = spec;
return this;
}
/// <summary>
/// Limits the specified limit.
/// </summary>
/// <param name="limit">The limit.</param>
/// <returns></returns>
public ICursor<T> Limit(int limit){
TryModify();
_limit = limit;
return this;
}
/// <summary>
/// Skips the specified skip.
/// </summary>
/// <param name="skip">The skip.</param>
/// <returns></returns>
public ICursor<T> Skip(int skip){
TryModify();
_skip = skip;
return this;
}
/// <summary>
/// Fieldses the specified fields.
/// </summary>
/// <param name="fields">The fields.</param>
/// <returns></returns>
public ICursor<T> Fields(object fields){
TryModify();
_fields = fields;
return this;
}
/// <summary>
/// Sorts the specified field.
/// </summary>
/// <param name = "field">The field.</param>
/// <returns></returns>
public ICursor<T> Sort(string field){
return Sort(field, IndexOrder.Ascending);
}
/// <summary>
/// Sorts the specified field.
/// </summary>
/// <param name = "field">The field.</param>
/// <param name = "order">The order.</param>
/// <returns></returns>
public ICursor<T> Sort(string field, IndexOrder order){
return Sort(new Document().Add(field, order));
}
/// <summary>
/// Sorts the specified fields.
/// </summary>
/// <param name="fields">The fields.</param>
/// <returns></returns>
public ICursor<T> Sort(object fields){
TryModify();
AddOrRemoveSpecOpt("$orderby", fields);
return this;
}
/// <summary>
/// Hints the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
public ICursor<T> Hint(object index){
TryModify();
AddOrRemoveSpecOpt("$hint", index);
return this;
}
/// <summary>
/// Keeps the cursor open.
/// </summary>
/// <param name="value">if set to <c>true</c> [value].</param>
/// <returns></returns>
/// <remarks>
/// By default cursors are closed automaticly after documents
/// are Enumerated.
/// </remarks>
public ICursor<T> KeepCursor(bool value)
{
_keepCursor = value;
return this;
}
/// <summary>
/// Snapshots the specified index.
/// </summary>
public ICursor<T> Snapshot(){
TryModify();
AddOrRemoveSpecOpt("$snapshot", true);
return this;
}
/// <summary>
/// Explains this instance.
/// </summary>
/// <returns></returns>
public Document Explain(){
TryModify();
var savedLimit = _limit;
_specOpts["$explain"] = true;
_limit = _limit * -1;
var explainResult = RetrieveData<Document>();
try
{
var explain = explainResult.Documents.FirstOrDefault();
if(explain==null)
throw new InvalidOperationException("Explain failed. No documents where returned.");
return explain;
}
finally
{
if(explainResult.CursorId > 0)
KillCursor(explainResult.CursorId);
_limit = savedLimit;
}
}
/// <summary>
/// Gets a value indicating whether this <see cref = "Cursor<T>" /> is modifiable.
/// </summary>
/// <value><c>true</c> if modifiable; otherwise, <c>false</c>.</value>
public bool IsModifiable { get; private set; }
/// <summary>
/// Gets the documents.
/// </summary>
/// <value>The documents.</value>
public IEnumerable<T> Documents {
get
{
do
{
_reply = RetrieveData<T>();
if(_reply == null)
throw new InvalidOperationException("Expecting reply but get null");
if(_limit > 0 && CursorPosition > _limit)
{
foreach(var document in _reply.Documents.Take(_limit - _reply.StartingFrom))
yield return document;
yield break;
}
foreach(var document in _reply.Documents)
yield return document;
}
while(Id > 0);
if(!_keepCursor)
Dispose(true);
}
}
/// <summary>
/// Gets the cursor position.
/// </summary>
/// <value>The cursor position.</value>
public int CursorPosition
{
get
{
if(_reply == null)
return 0;
return _reply.StartingFrom + _reply.NumberReturned;
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if(Id == 0 || !_connection.IsConnected) //All server side resources disposed of.
return;
KillCursor(Id);
}
/// <summary>
/// Optionses the specified options.
/// </summary>
/// <param name = "options">The options.</param>
/// <returns></returns>
public ICursor<T> Options(QueryOptions options){
TryModify();
_options = options;
return this;
}
/// <summary>
/// Kills the cursor.
/// </summary>
private void KillCursor(long cursorId)
{
var killCursorsMessage = new KillCursorsMessage(cursorId);
try {
_connection.SendMessage(killCursorsMessage,_databaseName);
Id = 0;
} catch (IOException exception) {
throw new MongoConnectionException("Could not read data, communication failure", _connection, exception);
}
}
/// <summary>
/// Retrieves the data.
/// </summary>
/// <typeparam name="TReply">The type of the reply.</typeparam>
/// <returns></returns>
private ReplyMessage<TReply> RetrieveData<TReply>() where TReply : class
{
IsModifiable = false;
IRequestMessage message;
if(Id <= 0)
{
var writerSettings = _serializationFactory.GetBsonWriterSettings(typeof(T));
message = new QueryMessage(writerSettings)
{
FullCollectionName = FullCollectionName,
Query = BuildSpec(),
NumberToReturn = _limit,
NumberToSkip = _skip,
Options = _options,
ReturnFieldSelector = ConvertFieldSelectorToDocument(_fields)
};
}
else
{
message = new GetMoreMessage(FullCollectionName, Id, _limit);
}
var readerSettings = _serializationFactory.GetBsonReaderSettings(typeof(T));
try
{
var reply = _connection.SendTwoWayMessage<TReply>(message, readerSettings, _databaseName);
Id = reply.CursorId;
if((reply.ResponseFlag & ResponseFlags.QueryFailure)!=0)
{
var error = "Review server log to get the error.";
if(reply.Documents.Length > 0)
{
var document = reply.Documents[0] as Document;
if(document != null)
error = Convert.ToString(document["$err"]);
}
throw new MongoException("The query failed on server. "+error);
}
return reply;
}
catch(IOException exception)
{
throw new MongoConnectionException("Could not read data, communication failure", _connection, exception);
}
}
/// <summary>
/// Tries the modify.
/// </summary>
private void TryModify(){
if(!IsModifiable)
throw new InvalidOperationException("Cannot modify a cursor that has already returned documents.");
}
/// <summary>
/// Adds the or remove spec opt.
/// </summary>
/// <param name = "key">The key.</param>
/// <param name = "doc">The doc.</param>
private void AddOrRemoveSpecOpt(string key, object doc){
if (doc == null)
_specOpts.Remove(key);
else
_specOpts[key] = doc;
}
/// <summary>
/// Builds the spec.
/// </summary>
/// <returns></returns>
private object BuildSpec(){
if (_specOpts.Count == 0)
return _spec;
var document = new Document();
_specOpts.CopyTo(document);
document["$query"] = _spec;
return document;
}
private Document ConvertFieldSelectorToDocument(object document)
{
Document doc;
if (document == null)
doc = new Document();
else
doc = ConvertExampleToDocument(document) as Document;
if (doc == null)
throw new NotSupportedException("An entity type is not supported in field selection. Use either a document or an anonymous type.");
var classMap = _mappingStore.GetClassMap(typeof(T));
if (doc.Count > 0 && (classMap.IsPolymorphic || classMap.IsSubClass))
doc[classMap.DiscriminatorAlias] = true;
return doc.Count == 0 ? null : doc;
}
private object ConvertExampleToDocument(object document)
{
if (document == null)
return null;
Document doc = document as Document;
if (doc != null)
return doc;
doc = new Document();
if (!(document is T)) //some type that is being used as an example
{
foreach (var prop in document.GetType().GetProperties())
{
if (!prop.CanRead)
continue;
object value = prop.GetValue(document, null);
if (!TypeHelper.IsNativeToMongo(prop.PropertyType))
value = ConvertExampleToDocument(value);
doc[prop.Name] = value;
}
}
return doc;
}
}
}
| |
//
// EqualizerView.cs
//
// Authors:
// Aaron Bockover <[email protected]>
// Ivan N. Zlatev <contact i-nZ.net>
// Alexander Hixon <[email protected]>
//
// Copyright 2006-2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using Gtk;
using Gdk;
using Mono.Unix;
using Hyena;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
namespace Banshee.Equalizer.Gui
{
public class EqualizerView : HBox
{
private HBox band_box;
private uint [] frequencies;
private EqualizerBandScale [] band_scales;
private EqualizerBandScale amplifier_scale;
private EqualizerSetting active_eq;
private int [] range = new int[3];
private bool loading;
public event EqualizerChangedEventHandler EqualizerChanged;
public event AmplifierChangedEventHandler AmplifierChanged;
public EqualizerView () : base ()
{
BuildWidget ();
}
private void BuildWidget ()
{
Spacing = 10;
int [] br = ((IEqualizer)ServiceManager.PlayerEngine.ActiveEngine).BandRange;
int mid = (br[0] + br[1]) / 2;
range[0] = br[0];
range[1] = mid;
range[2] = br[1];
amplifier_scale = new EqualizerBandScale (0, range[1] * 10, range[0] * 10, range[2] * 10,
Catalog.GetString ("Preamp"));
amplifier_scale.ValueChanged += OnAmplifierValueChanged;
amplifier_scale.Show ();
PackStart (amplifier_scale, false, false, 0);
EqualizerLevelsBox eq_levels = new EqualizerLevelsBox (
FormatDecibelString (range[2]),
FormatDecibelString (range[1]),
FormatDecibelString (range[0])
);
eq_levels.Show ();
PackStart (eq_levels, false, false, 0);
band_box = new HBox ();
band_box.Homogeneous = true;
band_box.Show ();
PackStart (band_box, true, true, 0);
BuildBands ();
}
private string FormatDecibelString (int db)
{
// Translators: {0} is a numerical value, and dB is the Decibel symbol
if (db > 0) {
return String.Format (Catalog.GetString ("+{0} dB"), db);
} else {
return String.Format (Catalog.GetString ("{0} dB"), db);
}
}
private void BuildBands ()
{
foreach (Widget widget in band_box.Children) {
band_box.Remove (widget);
}
if (frequencies == null || frequencies.Length <= 0) {
frequencies = new uint[0];
band_scales = new EqualizerBandScale[0];
return;
}
band_scales = new EqualizerBandScale[10];
for (uint i = 0; i < 10; i++) {
// Translators: {0} is a numerical value, Hz and kHz are Hertz unit symbols
string label = frequencies[i] < 1000 ?
String.Format (Catalog.GetString ("{0} Hz"), frequencies[i]) :
String.Format (Catalog.GetString ("{0} kHz"), (int)Math.Round (frequencies[i] / 1000.0));
band_scales[i] = new EqualizerBandScale (i, range[1] * 10, range[0] * 10, range[2] * 10, label);
band_scales[i].ValueChanged += OnEqualizerValueChanged;
band_scales[i].Show ();
band_box.PackStart (band_scales[i], true, true, 0);
}
}
private void OnEqualizerValueChanged (object o, EventArgs args)
{
if (loading) {
return;
}
EqualizerBandScale scale = o as EqualizerBandScale;
if (active_eq != null) {
active_eq.SetGain (scale.Band, (double)scale.Value / 10, true);
}
if (EqualizerChanged != null) {
EqualizerChanged (this, new EqualizerChangedEventArgs (scale.Band, scale.Value));
}
}
private void OnAmplifierValueChanged (object o, EventArgs args)
{
if (loading) {
return;
}
EqualizerBandScale scale = o as EqualizerBandScale;
if (active_eq != null) {
active_eq.AmplifierLevel = (double) (scale.Value / 10.0);
}
if (AmplifierChanged != null) {
AmplifierChanged (this, new EventArgs<int> (scale.Value));
}
}
public uint [] Frequencies {
get { return (uint [])frequencies.Clone (); }
set {
frequencies = (uint [])value.Clone ();
BuildBands ();
}
}
public int [] Preset {
get {
int [] result = new int[band_scales.Length];
for (int i = 0; i < band_scales.Length; i++) {
result[i] = (int) band_scales[i].Value;
}
return result;
}
set {
for (int i = 0; i < value.Length; i++) {
band_scales[i].Value = value[i];
}
}
}
public void SetBand (uint band, double value)
{
band_scales[band].Value = (int) (value * 10);
}
public double AmplifierLevel {
get { return (double) amplifier_scale.Value / 10; }
set { amplifier_scale.Value = (int) (value * 10); }
}
public EqualizerSetting EqualizerSetting {
get { return active_eq; }
set {
if (active_eq == value) {
return;
}
loading = true;
active_eq = value;
if (active_eq == null) {
AmplifierLevel = 0;
loading = false;
return;
}
amplifier_scale.Sensitive = !value.IsReadOnly;
AmplifierLevel = active_eq.AmplifierLevel;
for (uint i = 0; i < active_eq.BandCount; i++) {
band_scales[i].Sensitive = !value.IsReadOnly;
SetBand (i, active_eq[i]);
}
loading = false;
}
}
}
public delegate void EqualizerChangedEventHandler (object o, EqualizerChangedEventArgs args);
public delegate void AmplifierChangedEventHandler (object o, EventArgs<int> args);
public sealed class EqualizerChangedEventArgs : EventArgs
{
private uint band;
private int value;
public EqualizerChangedEventArgs (uint band, int value)
{
this.band = band;
this.value = value;
}
public uint Band {
get { return this.band; }
}
public int Value {
get { return this.value; }
}
}
}
| |
using System;
using ClosedXML.Excel;
namespace ClosedXML_Examples.Misc
{
public class DataTypes : IXLExample
{
#region Variables
// Public
// Private
#endregion
#region Properties
// Public
// Private
// Override
#endregion
#region Events
// Public
// Private
// Override
#endregion
#region Methods
// Public
public void Create(String filePath)
{
var workbook = new XLWorkbook();
var ws = workbook.Worksheets.Add("Data Types");
var co = 2;
var ro = 1;
ws.Cell(++ro, co).Value = "Plain Text:";
ws.Cell(ro, co + 1).Value = "Hello World.";
ws.Cell(++ro, co).Value = "Plain Date:";
ws.Cell(ro, co + 1).Value = new DateTime(2010, 9, 2);
ws.Cell(++ro, co).Value = "Plain DateTime:";
ws.Cell(ro, co + 1).Value = new DateTime(2010, 9, 2, 13, 45, 22);
ws.Cell(++ro, co).Value = "Plain Boolean:";
ws.Cell(ro, co + 1).Value = true;
ws.Cell(++ro, co).Value = "Plain Number:";
ws.Cell(ro, co + 1).Value = 123.45;
ws.Cell(++ro, co).Value = "TimeSpan:";
ws.Cell(ro, co + 1).Value = new TimeSpan(33, 45, 22);
ro++;
ws.Cell(++ro, co).Value = "Decimal Number:";
ws.Cell(ro, co + 1).Value = 123.45m;
ws.Cell(++ro, co).Value = "Float Number:";
ws.Cell(ro, co + 1).Value = 123.45f;
ws.Cell(++ro, co).Value = "Double Number:";
ws.Cell(ro, co + 1).Value = 123.45d;
ro++;
ws.Cell(++ro, co).Value = "Explicit Text:";
ws.Cell(ro, co + 1).Value = "'Hello World.";
ws.Cell(++ro, co).Value = "Date as Text:";
ws.Cell(ro, co + 1).Value = "'" + new DateTime(2010, 9, 2).ToString();
ws.Cell(++ro, co).Value = "DateTime as Text:";
ws.Cell(ro, co + 1).Value = "'" + new DateTime(2010, 9, 2, 13, 45, 22).ToString();
ws.Cell(++ro, co).Value = "Boolean as Text:";
ws.Cell(ro, co + 1).Value = "'" + true.ToString();
ws.Cell(++ro, co).Value = "Number as Text:";
ws.Cell(ro, co + 1).Value = "'123.45";
ws.Cell(++ro, co).Value = "Number with @ format:";
ws.Cell(ro, co + 1).Style.NumberFormat.Format = "@";
ws.Cell(ro, co + 1).Value = 123.45;
ws.Cell(++ro, co).Value = "Format number with @:";
ws.Cell(ro, co + 1).Value = 123.45;
ws.Cell(ro, co + 1).Style.NumberFormat.Format = "@";
ws.Cell(++ro, co).Value = "TimeSpan as Text:";
ws.Cell(ro, co + 1).Value = "'" + new TimeSpan(33, 45, 22).ToString();
ro++;
ws.Cell(++ro, co).Value = "Changing Data Types:";
ro++;
ws.Cell(++ro, co).Value = "Date to Text:";
ws.Cell(ro, co + 1).Value = new DateTime(2010, 9, 2);
ws.Cell(ro, co + 1).DataType = XLCellValues.Text;
ws.Cell(++ro, co).Value = "DateTime to Text:";
ws.Cell(ro, co + 1).Value = new DateTime(2010, 9, 2, 13, 45, 22);
ws.Cell(ro, co + 1).DataType = XLCellValues.Text;
ws.Cell(++ro, co).Value = "Boolean to Text:";
ws.Cell(ro, co + 1).Value = true;
ws.Cell(ro, co + 1).DataType = XLCellValues.Text;
ws.Cell(++ro, co).Value = "Number to Text:";
ws.Cell(ro, co + 1).Value = 123.45;
ws.Cell(ro, co + 1).DataType = XLCellValues.Text;
ws.Cell(++ro, co).Value = "TimeSpan to Text:";
ws.Cell(ro, co + 1).Value = new TimeSpan(33, 45, 22);
ws.Cell(ro, co + 1).DataType = XLCellValues.Text;
ws.Cell(++ro, co).Value = "Text to Date:";
ws.Cell(ro, co + 1).Value = "'" + new DateTime(2010, 9, 2).ToString();
ws.Cell(ro, co + 1).DataType = XLCellValues.DateTime;
ws.Cell(++ro, co).Value = "Text to DateTime:";
ws.Cell(ro, co + 1).Value = "'" + new DateTime(2010, 9, 2, 13, 45, 22).ToString();
ws.Cell(ro, co + 1).DataType = XLCellValues.DateTime;
ws.Cell(++ro, co).Value = "Text to Boolean:";
ws.Cell(ro, co + 1).Value = "'" + true.ToString();
ws.Cell(ro, co + 1).DataType = XLCellValues.Boolean;
ws.Cell(++ro, co).Value = "Text to Number:";
ws.Cell(ro, co + 1).Value = "'123.45";
ws.Cell(ro, co + 1).DataType = XLCellValues.Number;
ws.Cell(++ro, co).Value = "@ format to Number:";
ws.Cell(ro, co + 1).Style.NumberFormat.Format = "@";
ws.Cell(ro, co + 1).Value = 123.45;
ws.Cell(ro, co + 1).DataType = XLCellValues.Number;
ws.Cell(++ro, co).Value = "Text to TimeSpan:";
ws.Cell(ro, co + 1).Value = "'" + new TimeSpan(33, 45, 22).ToString();
ws.Cell(ro, co + 1).DataType = XLCellValues.TimeSpan;
ro++;
ws.Cell(++ro, co).Value = "Formatted Date to Text:";
ws.Cell(ro, co + 1).Value = new DateTime(2010, 9, 2);
ws.Cell(ro, co + 1).Style.DateFormat.Format = "yyyy-MM-dd";
ws.Cell(ro, co + 1).DataType = XLCellValues.Text;
ws.Cell(++ro, co).Value = "Formatted Number to Text:";
ws.Cell(ro, co + 1).Value = 12345.6789;
ws.Cell(ro, co + 1).Style.NumberFormat.Format = "#,##0.00";
ws.Cell(ro, co + 1).DataType = XLCellValues.Text;
ro++;
ws.Cell(++ro, co).Value = "Blank Text:";
ws.Cell(ro, co + 1).Value = 12345.6789;
ws.Cell(ro, co + 1).Style.NumberFormat.Format = "#,##0.00";
ws.Cell(ro, co + 1).DataType = XLCellValues.Text;
ws.Cell(ro, co + 1).Value = "";
ro++;
// Using inline strings (few users will ever need to use this feature)
//
// By default all strings are stored as shared so one block of text
// can be reference by multiple cells.
// You can override this by setting the .ShareString property to false
ws.Cell(++ro, co).Value = "Inline String:";
var cell = ws.Cell(ro, co + 1);
cell.Value = "Not Shared";
cell.ShareString = false;
// To view all shared strings (all texts in the workbook actually), use the following:
// workbook.GetSharedStrings()
ws.Cell(++ro, co)
.SetDataType(XLCellValues.Text)
.SetDataType(XLCellValues.Boolean)
.SetDataType(XLCellValues.DateTime)
.SetDataType(XLCellValues.Number)
.SetDataType(XLCellValues.TimeSpan)
.SetDataType(XLCellValues.Text)
.SetDataType(XLCellValues.TimeSpan)
.SetDataType(XLCellValues.Number)
.SetDataType(XLCellValues.DateTime)
.SetDataType(XLCellValues.Boolean)
.SetDataType(XLCellValues.Text);
ws.Columns(2, 3).AdjustToContents();
workbook.SaveAs(filePath);
}
// Private
// Override
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using System.Windows.Forms;
namespace Simbiosis
{
/// <summary>
/// This is the panel of the submarine
/// </summary>
class SubPanel : Panel
{
SubCam owner = null; // The camera ship that owns me
// Resources for writing to the radar display on the SubBot widget
private SolidBrush navBrush = null; // foreground brush for fonts etc.
private SolidBrush navFill = null; // background brush for fills
private Pen navPen = null; // foreground pen for lines etc. (same colour as .brush)
private System.Drawing.Font navFont = null; // body text font
private Meter depthMeter = null; // sub's depth
private Meter hdgMeter = null; // sub's bearing
private Meter trkMeter = null; // tracked object's bearing
private Meter labMeter = null; // Research ship's bearing
private Knob bouyancy = null; // controls bouyancy
private SafetyButton hatch = null; // "leave ship"
public SubPanel(SubCam owner)
: base()
{
// Store the camera ship for callbacks etc.
this.owner = owner;
// Create the backdrop and widgets
widgetList.Add(new Widget("SubPanel", false, 1024, 768, 0, 0)); // top panel
//widgetList.Add(new Widget("SubBot", true, 1024, 168, 0, 768 - 168)); // bottom panel (and radar)
//widgetList.Add(new Widget("SubLeft", false, 128, 500, 0, 100)); // left panel
//widgetList.Add(new Widget("SubRight", false, 50, 500, 1024 - 50, 100)); // right panel
// Spotlight switch
Switch switch1 = new Switch("toggleswitch", 48, 67, 860, 30, Keys.L);
widgetList.Add(switch1);
switch1.OnChange += new ChangeEventHandler(owner.Switch1Changed);
// Depth meter
depthMeter = new Meter("LabNeedle", 8, 48, 90, 58, (float)Math.PI * 0.75f, 4, 40, -4, 4, false);
widgetList.Add(depthMeter);
// Compass bearing
hdgMeter = new Meter("CompassRose", 104, 104, 42, 646, (float)Math.PI, 52, 52, 0, 0, false); // no shadow; don't slew, or it'll spin when wrapping
widgetList.Add(hdgMeter);
// Bearing to tracked object
trkMeter = new Meter("LabNeedle", 8, 48, 90, 674, (float)Math.PI, 4, 40, -4, 4, false);
widgetList.Add(trkMeter);
// Bearing to lab ship
labMeter = new Meter("SmallNeedle", 8, 32, 90, 682, (float)Math.PI, 4, 25, -4, 4, false);
widgetList.Add(labMeter);
bouyancy = new Knob("KnobMedium", 64, 75, 950, 170, 32F, 32F, Keys.PageUp, Keys.PageDown, (float)(Math.PI * 0.5));
bouyancy.Value = 0.5f;
bouyancy.OnChange += new ChangeEventHandler(bouyancy_OnChange);
widgetList.Add(bouyancy);
hatch = new SafetyButton("SafetySwitch", 80, 92, 940, 265, Keys.None, 0.3f);
hatch.OnChange += new ChangeEventHandler(hatch_OnChange);
widgetList.Add(hatch);
// Set up the Display widget for the navigation display
SetupNavDisplay();
}
/// <summary>
/// Return the dimensions of the porthole through which the scene will be visible.
/// </summary>
/// <returns>Porthole dimensions in BASE coordinates</returns>
public override Rectangle GetPorthole()
{
return new Rectangle(180, 50, 670, 670);
}
/// <summary>
/// Refresh navigation display and other slow-changing widgets
/// </summary>
public override void SlowUpdate()
{
DrawNavDisplay(); // draw the navigation display
}
/// <summary>
/// Refresh fast-changing widgets
/// </summary>
public override void FastUpdate()
{
float bearing = 0;
// Set the depth meter
float depth = (Water.WATERLEVEL - Camera.Position.Y) / Water.WATERLEVEL;
if (depth < 0) depth = 0;
else if (depth > 1.0f) depth = 1.0f;
depthMeter.Value = depth;
// Set the compass
hdgMeter.Value = 1.0f - ((Camera.bearing / (float)Math.PI / 2.0f) % 1.0f);
// Show the bearing of the tracked object, if any
if (Lab.TrackedOrg != null)
{
bearing = (float)Math.Atan2(Lab.TrackedOrg.Location.X - owner.Location.X, Lab.TrackedOrg.Location.Z - owner.Location.Z);
bearing -= Camera.bearing; // show relative to current heading
bearing = bearing / (float)Math.PI / 2f + 0.5f;
trkMeter.Value = bearing;
}
// Show the bearing of the research vessel
Organism lab = (Organism)CameraShip.GetLab();
bearing = (float)Math.Atan2(lab.Location.X - owner.Location.X, lab.Location.Z - owner.Location.Z);
bearing -= Camera.bearing; // show relative to current heading
bearing = bearing / (float)Math.PI / 2f + 0.5f;
labMeter.Value = bearing;
}
/// <summary>
/// Create the resources for drawing onto the navigation display (subbot)
/// </summary>
private void SetupNavDisplay()
{
// Create the fonts, brushes and pens
navFont = new System.Drawing.Font(FontFamily.GenericMonospace, 12, FontStyle.Bold);
navBrush = new SolidBrush(Color.FromArgb(150, Color.LightGreen));
navFill = new SolidBrush(Color.FromArgb(64, Color.DarkGreen));
navPen = new Pen(navBrush, 2);
}
/// <summary>
/// Draw text/graphics onto the navigation display inside the SubBot widget
/// </summary>
private void DrawNavDisplay()
{
//const float left = 580; // top-left edge of radar disp
//const float top = 120;
//Graphics g = widgetList[1].BeginDrawing();
//// TEMP: ----------- Draw debug info ----------------
//g.DrawString(Map.HUDInfo + " " + Engine.Framework.FPS.ToString("###") + "fps", navFont, Brushes.Red, 480, 48);
//float hdg = Camera.bearing / (float)Math.PI * 180.0f;
//if (hdg < 0) hdg += 360;
//// Draw the navigation text
//g.DrawString(String.Format("locn: {0:0000}E hdg: {1:000}deg",
// Camera.Position.X, hdg),
// navFont, navBrush, left + 48, top + 8);
//g.DrawString(String.Format(" {0:0000}N depth: {1:000}m",
// Camera.Position.Z, Water.WATERLEVEL - Camera.Position.Y),
// navFont, navBrush, left + 48, top + 24);
//widgetList[1].EndDrawing();
}
/// <summary>
/// Bouyancy knob has been moved. Send a command through to root cell's physiology
/// </summary>
/// <param name="sender"></param>
/// <param name="value"></param>
void bouyancy_OnChange(Widget sender, object value)
{
owner.Command("buoyancy", value);
}
/// <summary>
/// Hatch button has been pressed - jump to survey ship / lab
/// </summary>
/// <param name="sender"></param>
/// <param name="value"></param>
void hatch_OnChange(Widget sender, object value)
{
hatch.Frame = 0; // reset switch
CameraShip.SwitchCameraShip(); // change to next (specific???) camera ship
}
/// <summary>
/// Left mouse click - may be a 3D pick.
/// Picking is used to select an organism to track.
/// </summary>
/// <param name="screenX">mouse position when click occurred</param>
/// <returns>true if the click was handled</returns>
public override bool LeftClick(float screenX, float screenY)
{
// First check to see if it is a 3D pick of a cell
JointFrame socket;
Cell cell = Camera.MousePick(screenX, screenY, out socket); // get the selected cell and/or socket
if (cell != null)
{
if (!(cell.Owner is CameraShip)) // if it isn't a camera ship
Lab.TrackedOrg = cell.Owner; // set it to the source for tracking and any future tractor beam
return true;
}
// If not, pass it back to the base class to distribute to our widgets
return base.LeftClick(screenX, screenY);
}
}
/// <summary>
/// Secondary panel: Clear view of scene without any backdrop or instruments
/// </summary>
class SubPanel2 : Panel
{
SubCam owner = null; // The camera ship that owns me
public SubPanel2(SubCam owner)
: base()
{
// Store the camera ship for callbacks etc.
this.owner = owner;
}
/// <summary>
/// Refresh any HUD Display widgets, etc.
/// </summary>
public override void SlowUpdate()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.SqlSyntax;
namespace Umbraco.Core.Persistence.Migrations.Initial
{
/// <summary>
/// Represents the initial database schema creation by running CreateTable for all DTOs against the db.
/// </summary>
internal class DatabaseSchemaCreation
{
#region Private Members
private readonly Database _database;
private static readonly Dictionary<int, Type> OrderedTables = new Dictionary<int, Type>
{
{0, typeof (NodeDto)},
{1, typeof (TemplateDto)},
{2, typeof (ContentDto)},
{3, typeof (ContentVersionDto)},
{4, typeof (DocumentDto)},
{5, typeof (ContentTypeDto)},
{6, typeof (DocumentTypeDto)},
{7, typeof (DataTypeDto)},
{8, typeof (DataTypePreValueDto)},
{9, typeof (DictionaryDto)},
{10, typeof (LanguageTextDto)},
{11, typeof (LanguageDto)},
{12, typeof (DomainDto)},
{13, typeof (LogDto)},
{14, typeof (MacroDto)},
{15, typeof (MacroPropertyDto)},
{16, typeof (MemberTypeDto)},
{17, typeof (MemberDto)},
{18, typeof (Member2MemberGroupDto)},
{19, typeof (ContentXmlDto)},
{20, typeof (PreviewXmlDto)},
{21, typeof (PropertyTypeGroupDto)},
{22, typeof (PropertyTypeDto)},
{23, typeof (PropertyDataDto)},
{24, typeof (RelationTypeDto)},
{25, typeof (RelationDto)},
{26, typeof (StylesheetDto)},
{27, typeof (StylesheetPropertyDto)},
{28, typeof (TagDto)},
{29, typeof (TagRelationshipDto)},
{30, typeof (UserLoginDto)},
{31, typeof (UserTypeDto)},
{32, typeof (UserDto)},
{33, typeof (TaskTypeDto)},
{34, typeof (TaskDto)},
{35, typeof (ContentType2ContentTypeDto)},
{36, typeof (ContentTypeAllowedContentTypeDto)},
{37, typeof (User2AppDto)},
{38, typeof (User2NodeNotifyDto)},
{39, typeof (User2NodePermissionDto)},
{40, typeof (ServerRegistrationDto)}
};
#endregion
/// <summary>
/// Drops all Umbraco tables in the db
/// </summary>
internal void UninstallDatabaseSchema()
{
LogHelper.Info<DatabaseSchemaCreation>("Start UninstallDatabaseSchema");
foreach (var item in OrderedTables.OrderByDescending(x => x.Key))
{
var tableNameAttribute = item.Value.FirstAttribute<TableNameAttribute>();
string tableName = tableNameAttribute == null ? item.Value.Name : tableNameAttribute.Value;
LogHelper.Info<DatabaseSchemaCreation>("Uninstall" + tableName);
try
{
if (_database.TableExist(tableName))
{
_database.DropTable(tableName);
}
}
catch (Exception ex)
{
//swallow this for now, not sure how best to handle this with diff databases... though this is internal
// and only used for unit tests. If this fails its because the table doesn't exist... generally!
LogHelper.Error<DatabaseSchemaCreation>("Could not drop table " + tableName, ex);
}
}
}
public DatabaseSchemaCreation(Database database)
{
_database = database;
}
/// <summary>
/// Initialize the database by creating the umbraco db schema
/// </summary>
public void InitializeDatabaseSchema()
{
var e = new DatabaseCreationEventArgs();
FireBeforeCreation(e);
if (!e.Cancel)
{
foreach (var item in OrderedTables.OrderBy(x => x.Key))
{
_database.CreateTable(false, item.Value);
}
}
FireAfterCreation(e);
}
/// <summary>
/// Validates the schema of the current database
/// </summary>
public DatabaseSchemaResult ValidateSchema()
{
var result = new DatabaseSchemaResult();
//get the db index defs
result.DbIndexDefinitions = SqlSyntaxContext.SqlSyntaxProvider.GetDefinedIndexes(_database)
.Select(x => new DbIndexDefinition()
{
TableName = x.Item1,
IndexName = x.Item2,
ColumnName = x.Item3,
IsUnique = x.Item4
}).ToArray();
foreach (var item in OrderedTables.OrderBy(x => x.Key))
{
var tableDefinition = DefinitionFactory.GetTableDefinition(item.Value);
result.TableDefinitions.Add(tableDefinition);
}
ValidateDbTables(result);
ValidateDbColumns(result);
ValidateDbIndexes(result);
ValidateDbConstraints(result);
return result;
}
private void ValidateDbConstraints(DatabaseSchemaResult result)
{
//MySql doesn't conform to the "normal" naming of constraints, so there is currently no point in doing these checks.
//TODO: At a later point we do other checks for MySql, but ideally it should be necessary to do special checks for different providers.
// ALso note that to get the constraints for MySql we have to open a connection which we currently have not.
if (SqlSyntaxContext.SqlSyntaxProvider is MySqlSyntaxProvider)
return;
//Check constraints in configured database against constraints in schema
var constraintsInDatabase = SqlSyntaxContext.SqlSyntaxProvider.GetConstraintsPerColumn(_database).DistinctBy(x => x.Item3).ToList();
var foreignKeysInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("FK_")).Select(x => x.Item3).ToList();
var primaryKeysInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("PK_")).Select(x => x.Item3).ToList();
var indexesInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("IX_")).Select(x => x.Item3).ToList();
var indexesInSchema = result.TableDefinitions.SelectMany(x => x.Indexes.Select(y => y.Name)).ToList();
var unknownConstraintsInDatabase =
constraintsInDatabase.Where(
x =>
x.Item3.InvariantStartsWith("FK_") == false && x.Item3.InvariantStartsWith("PK_") == false &&
x.Item3.InvariantStartsWith("IX_") == false).Select(x => x.Item3).ToList();
var foreignKeysInSchema = result.TableDefinitions.SelectMany(x => x.ForeignKeys.Select(y => y.Name)).ToList();
var primaryKeysInSchema = result.TableDefinitions.SelectMany(x => x.Columns.Select(y => y.PrimaryKeyName))
.Where(x => x.IsNullOrWhiteSpace() == false).ToList();
//Add valid and invalid foreign key differences to the result object
// We'll need to do invariant contains with case insensitivity because foreign key, primary key, and even index naming w/ MySQL is not standardized
// In theory you could have: FK_ or fk_ ...or really any standard that your development department (or developer) chooses to use.
foreach (var unknown in unknownConstraintsInDatabase)
{
if (foreignKeysInSchema.InvariantContains(unknown) || primaryKeysInSchema.InvariantContains(unknown) || indexesInSchema.InvariantContains(unknown))
{
result.ValidConstraints.Add(unknown);
}
else
{
result.Errors.Add(new Tuple<string, string>("Unknown", unknown));
}
}
//Foreign keys:
var validForeignKeyDifferences = foreignKeysInDatabase.Intersect(foreignKeysInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var foreignKey in validForeignKeyDifferences)
{
result.ValidConstraints.Add(foreignKey);
}
var invalidForeignKeyDifferences =
foreignKeysInDatabase.Except(foreignKeysInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(foreignKeysInSchema.Except(foreignKeysInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var foreignKey in invalidForeignKeyDifferences)
{
result.Errors.Add(new Tuple<string, string>("Constraint", foreignKey));
}
//Primary keys:
//Add valid and invalid primary key differences to the result object
var validPrimaryKeyDifferences = primaryKeysInDatabase.Intersect(primaryKeysInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var primaryKey in validPrimaryKeyDifferences)
{
result.ValidConstraints.Add(primaryKey);
}
var invalidPrimaryKeyDifferences =
primaryKeysInDatabase.Except(primaryKeysInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(primaryKeysInSchema.Except(primaryKeysInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var primaryKey in invalidPrimaryKeyDifferences)
{
result.Errors.Add(new Tuple<string, string>("Constraint", primaryKey));
}
//Constaints:
//NOTE: SD: The colIndex checks above should really take care of this but I need to keep this here because it was here before
// and some schema validation checks might rely on this data remaining here!
//Add valid and invalid index differences to the result object
var validIndexDifferences = indexesInDatabase.Intersect(indexesInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var index in validIndexDifferences)
{
result.ValidConstraints.Add(index);
}
var invalidIndexDifferences =
indexesInDatabase.Except(indexesInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(indexesInSchema.Except(indexesInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var index in invalidIndexDifferences)
{
result.Errors.Add(new Tuple<string, string>("Constraint", index));
}
}
private void ValidateDbColumns(DatabaseSchemaResult result)
{
//Check columns in configured database against columns in schema
var columnsInDatabase = SqlSyntaxContext.SqlSyntaxProvider.GetColumnsInSchema(_database);
var columnsPerTableInDatabase = columnsInDatabase.Select(x => string.Concat(x.TableName, ",", x.ColumnName)).ToList();
var columnsPerTableInSchema = result.TableDefinitions.SelectMany(x => x.Columns.Select(y => string.Concat(y.TableName, ",", y.Name))).ToList();
//Add valid and invalid column differences to the result object
var validColumnDifferences = columnsPerTableInDatabase.Intersect(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var column in validColumnDifferences)
{
result.ValidColumns.Add(column);
}
var invalidColumnDifferences =
columnsPerTableInDatabase.Except(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(columnsPerTableInSchema.Except(columnsPerTableInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var column in invalidColumnDifferences)
{
result.Errors.Add(new Tuple<string, string>("Column", column));
}
}
private void ValidateDbTables(DatabaseSchemaResult result)
{
//Check tables in configured database against tables in schema
var tablesInDatabase = SqlSyntaxContext.SqlSyntaxProvider.GetTablesInSchema(_database).ToList();
var tablesInSchema = result.TableDefinitions.Select(x => x.Name).ToList();
//Add valid and invalid table differences to the result object
var validTableDifferences = tablesInDatabase.Intersect(tablesInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var tableName in validTableDifferences)
{
result.ValidTables.Add(tableName);
}
var invalidTableDifferences =
tablesInDatabase.Except(tablesInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(tablesInSchema.Except(tablesInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var tableName in invalidTableDifferences)
{
result.Errors.Add(new Tuple<string, string>("Table", tableName));
}
}
private void ValidateDbIndexes(DatabaseSchemaResult result)
{
//These are just column indexes NOT constraints or Keys
//var colIndexesInDatabase = result.DbIndexDefinitions.Where(x => x.IndexName.InvariantStartsWith("IX_")).Select(x => x.IndexName).ToList();
var colIndexesInDatabase = result.DbIndexDefinitions.Select(x => x.IndexName).ToList();
var indexesInSchema = result.TableDefinitions.SelectMany(x => x.Indexes.Select(y => y.Name)).ToList();
//Add valid and invalid index differences to the result object
var validColIndexDifferences = colIndexesInDatabase.Intersect(indexesInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var index in validColIndexDifferences)
{
result.ValidIndexes.Add(index);
}
var invalidColIndexDifferences =
colIndexesInDatabase.Except(indexesInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(indexesInSchema.Except(colIndexesInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var index in invalidColIndexDifferences)
{
result.Errors.Add(new Tuple<string, string>("Index", index));
}
}
#region Events
/// <summary>
/// The save event handler
/// </summary>
internal delegate void DatabaseEventHandler(DatabaseCreationEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
internal static event DatabaseEventHandler BeforeCreation;
/// <summary>
/// Raises the <see cref="BeforeCreation"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected internal virtual void FireBeforeCreation(DatabaseCreationEventArgs e)
{
if (BeforeCreation != null)
{
BeforeCreation(e);
}
}
/// <summary>
/// Occurs when [after save].
/// </summary>
internal static event DatabaseEventHandler AfterCreation;
/// <summary>
/// Raises the <see cref="AfterCreation"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterCreation(DatabaseCreationEventArgs e)
{
if (AfterCreation != null)
{
AfterCreation(e);
}
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Positioning.dll
// Description: A library for managing GPS connections.
// ********************************************************************************************************
//
// The Original Code is from http://geoframework.codeplex.com/ version 2.0
//
// The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup)
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// -------------------------------------------------------------------------------------------------------
// | Developer | Date | Comments
// |--------------------------|------------|--------------------------------------------------------------
// | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GeoFrameworks 2.0
// | Shade1974 (Ted Dunsford) | 10/21/2010 | Added file headers reviewed formatting with resharper.
// ********************************************************************************************************
using System;
using System.Globalization;
#if !PocketPC || DesignTime
using System.ComponentModel;
#endif
namespace DotSpatial.Positioning
{
#if !PocketPC || DesignTime
/// <summary>
/// Represents a two-dimensional rectangular area.
/// </summary>
/// <remarks>Instances of this class are guaranteed to be thread-safe because the class is
/// immutable (it's properties can only be set via constructors).</remarks>
[TypeConverter("DotSpatial.Positioning.Design.GeographicSizeConverter, DotSpatial.Positioning.Design, Culture=neutral, Version=1.0.0.0, PublicKeyToken=b4b0b185210c9dae")]
#endif
public struct GeographicSize : IFormattable, IEquatable<GeographicSize>
{
/// <summary>
///
/// </summary>
private readonly Distance _width;
/// <summary>
///
/// </summary>
private readonly Distance _height;
#region Fields
/// <summary>
/// Represents a size with no value.
/// </summary>
public static readonly GeographicSize Empty = new GeographicSize(Distance.Empty, Distance.Empty);
/// <summary>
/// Represents a size with no value.
/// </summary>
public static readonly GeographicSize Minimum = new GeographicSize(Distance.Minimum, Distance.Minimum);
/// <summary>
/// Represents the largest possible size on Earth's surface.
/// </summary>
public static readonly GeographicSize Maximum = new GeographicSize(Distance.Maximum, Distance.Maximum);
/// <summary>
/// Represents an invalid geographic size.
/// </summary>
public static readonly GeographicSize Invalid = new GeographicSize(Distance.Invalid, Distance.Invalid);
#endregion Fields
#region Constructors
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public GeographicSize(Distance width, Distance height)
{
_width = width;
_height = height;
}
/// <summary>
/// Creates a new instance from the specified string.
/// </summary>
/// <param name="value">The value.</param>
public GeographicSize(string value)
: this(value, CultureInfo.CurrentCulture)
{ }
/// <summary>
/// Creates a new instance from the specified string in the specified culture.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="culture">The culture.</param>
/// <remarks>This method will attempt to split the specified string into two values, then parse each value
/// as an Distance object. The string must contain two numbers separated by a comma (or other character depending
/// on the culture).</remarks>
public GeographicSize(string value, CultureInfo culture)
{
// Split out the values
string[] values = value.Split(culture.TextInfo.ListSeparator.ToCharArray());
// There should only be two of them
switch (values.Length)
{
case 2:
_width = Distance.Parse(values[0], culture);
_height = Distance.Parse(values[1], culture);
break;
default:
throw new ArgumentException("A GeographicSize could not be created from a string because the string was not in an identifiable format. The format should be \"(w, h)\" where \"w\" represents a width in degrees, and \"h\" represents a height in degrees. The values should be separated by a comma (or other character depending on the current culture).");
}
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Returns the ratio of the size's width to its height.
/// </summary>
public float AspectRatio
{
get
{
return Convert.ToSingle(_width.ToMeters().Value / _height.ToMeters().Value);
}
}
/// <summary>
/// Returns the left-to-right size.
/// </summary>
public Distance Width
{
get
{
return _width;
}
}
/// <summary>
/// Returns the top-to-bottom size.
/// </summary>
public Distance Height
{
get
{
return _height;
}
}
/// <summary>
/// Indicates if the size has zero values.
/// </summary>
public bool IsEmpty
{
get
{
return (_width.IsEmpty && _height.IsEmpty);
}
}
/// <summary>
/// Returns whether the current instance has invalid values.
/// </summary>
public bool IsInvalid
{
get
{
return _width.IsInvalid && _height.IsInvalid;
}
}
#endregion Public Properties
#region Public Methods
/// <summary>
/// Toes the aspect ratio.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <returns></returns>
public GeographicSize ToAspectRatio(Distance width, Distance height)
{
// Calculate the aspect ratio
return ToAspectRatio(Convert.ToSingle(width.Divide(height).Value));
}
/// <summary>
/// Toes the aspect ratio.
/// </summary>
/// <param name="aspectRatio">The aspect ratio.</param>
/// <returns></returns>
public GeographicSize ToAspectRatio(float aspectRatio)
{
float currentAspect = AspectRatio;
// Do the values already match?
if (currentAspect == aspectRatio)
return this;
// Convert to meters first
Distance widthMeters = _width.ToMeters();
Distance heightMeters = _height.ToMeters();
// Is the new ratio higher or lower?
if (aspectRatio > currentAspect)
{
// Inflate the GeographicRectDistance to the new height minus the current height
return new GeographicSize(
widthMeters.Add(heightMeters.Multiply(aspectRatio).Subtract(widthMeters)),
heightMeters);
}
// Inflate the GeographicRectDistance to the new height minus the current height
return new GeographicSize(
widthMeters,
heightMeters.Add(widthMeters.Divide(aspectRatio).Subtract(heightMeters)));
}
/// <summary>
/// Adds the specified size to the current instance.
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
public GeographicSize Add(GeographicSize size)
{
return new GeographicSize(_width.Add(size.Width), _height.Add(size.Height));
}
/// <summary>
/// Subtracts the specified size from the current instance.
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
public GeographicSize Subtract(GeographicSize size)
{
return new GeographicSize(_width.Subtract(size.Width), _height.Subtract(size.Height));
}
/// <summary>
/// Multiplies the width and height by the specified size.
/// </summary>
/// <param name="size">A <strong>GeographicSize</strong> specifying how to much to multiply the width and height.</param>
/// <returns>A <strong>GeographicSize</strong> representing the product of the current instance with the specified size.</returns>
public GeographicSize Multiply(GeographicSize size)
{
return new GeographicSize(_width.Multiply(size.Width), _height.Multiply(size.Height));
}
/// <summary>
/// Divides the width and height by the specified size.
/// </summary>
/// <param name="size">The size.</param>
/// <returns></returns>
public GeographicSize Divide(GeographicSize size)
{
return new GeographicSize(_width.Divide(size.Width), _height.Divide(size.Height));
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
#endregion Public Methods
#region Overrides
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
if (obj is GeographicSize)
return Equals((GeographicSize)obj);
return false;
}
/// <summary>
/// Returns a unique code based on the object's value.
/// </summary>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
return _width.GetHashCode() ^ _height.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
#endregion Overrides
#region Static Methods
/// <summary>
/// Returns a GeographicSize whose value matches the specified string.
/// </summary>
/// <param name="value">A <strong>String</strong> describing a width, followed by a height.</param>
/// <returns>A <strong>GeographicSize</strong> whose Width and Height properties match the specified string.</returns>
public static GeographicSize Parse(string value)
{
return Parse(value, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a GeographicSize whose value matches the specified string.
/// </summary>
/// <param name="value">A <strong>String</strong> describing a width, followed by a height.</param>
/// <param name="culture">A <strong>CultureInfo</strong> object describing how to parse the specified string.</param>
/// <returns>A <strong>GeographicSize</strong> whose Width and Height properties match the specified string.</returns>
public static GeographicSize Parse(string value, CultureInfo culture)
{
return new GeographicSize(value, culture);
}
#endregion Static Methods
#region Conversions
/// <summary>
/// Performs an explicit conversion from <see cref="System.String"/> to <see cref="DotSpatial.Positioning.GeographicSize"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator GeographicSize(string value)
{
return new GeographicSize(value, CultureInfo.CurrentCulture);
}
/// <summary>
/// Performs an explicit conversion from <see cref="DotSpatial.Positioning.GeographicSize"/> to <see cref="System.String"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator string(GeographicSize value)
{
return value.ToString();
}
#endregion Conversions
#region IEquatable<GeographicSize> Members
/// <summary>
/// Compares the value of the current instance to the specified GeographicSize.
/// </summary>
/// <param name="value">A <strong>GeographicSize</strong> object to compare against.</param>
/// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values of both objects are precisely the same.</returns>
public bool Equals(GeographicSize value)
{
return Width.Equals(value.Width)
&& Height.Equals(value.Height);
}
/// <summary>
/// Compares the value of the current instance to the specified GeographicSize, to the specified number of decimals.
/// </summary>
/// <param name="value">A <strong>GeographicSize</strong> object to compare against.</param>
/// <param name="decimals">An <strong>Integer</strong> describing how many decimals the values are rounded to before comparison.</param>
/// <returns>A <strong>Boolean</strong>, <strong>True</strong> if the values of both objects are the same out to the number of decimals specified.</returns>
public bool Equals(GeographicSize value, int decimals)
{
return _width.Equals(value.Width, decimals)
&& _height.Equals(value.Height, decimals);
}
#endregion IEquatable<GeographicSize> Members
#region IFormattable Members
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format to use.-or- A null reference (Nothing in Visual Basic) to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.</param>
/// <param name="formatProvider">The provider to use to format the value.-or- A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
CultureInfo culture = (CultureInfo)formatProvider ?? CultureInfo.CurrentCulture;
if (string.IsNullOrEmpty(format))
format = "G";
return _width.ToString(format, culture)
+ culture.TextInfo.ListSeparator + " "
+ _height.ToString(format, culture);
}
#endregion IFormattable Members
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.WebsiteBuilder.DataAccess;
using Frapid.WebsiteBuilder.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.WebsiteBuilder.Api.Tests
{
public class EmailSubscriptionTests
{
public static EmailSubscriptionController Fixture()
{
EmailSubscriptionController controller = new EmailSubscriptionController(new EmailSubscriptionRepository(), "", new LoginView());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.WebsiteBuilder.Entities.EmailSubscription emailSubscription = Fixture().Get(new System.Guid());
Assert.NotNull(emailSubscription);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.WebsiteBuilder.Entities.EmailSubscription emailSubscription = Fixture().GetFirst();
Assert.NotNull(emailSubscription);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.WebsiteBuilder.Entities.EmailSubscription emailSubscription = Fixture().GetPrevious(new System.Guid());
Assert.NotNull(emailSubscription);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.WebsiteBuilder.Entities.EmailSubscription emailSubscription = Fixture().GetNext(new System.Guid());
Assert.NotNull(emailSubscription);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.WebsiteBuilder.Entities.EmailSubscription emailSubscription = Fixture().GetLast();
Assert.NotNull(emailSubscription);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.WebsiteBuilder.Entities.EmailSubscription> emailSubscriptions = Fixture().Get(new System.Guid[] { });
Assert.NotNull(emailSubscriptions);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(new System.Guid(), null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(new System.Guid());
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// Specialized producer/consumer queues.
//
//
// ************<IMPORTANT NOTE>*************
//
// src\ndp\clr\src\bcl\system\threading\tasks\producerConsumerQueue.cs
// src\ndp\fx\src\dataflow\system\threading\tasks\dataflow\internal\producerConsumerQueue.cs
// Keep both of them consistent by changing the other file when you change this one, also avoid:
// 1- To reference interneal types in mscorlib
// 2- To reference any dataflow specific types
// This should be fixed post Dev11 when this class becomes public.
//
// ************</IMPORTANT NOTE>*************
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
namespace System.Threading.Tasks
{
/// <summary>Represents a producer/consumer queue used internally by dataflow blocks.</summary>
/// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam>
internal interface IProducerConsumerQueue<T> : IEnumerable<T>
{
/// <summary>Enqueues an item into the queue.</summary>
/// <param name="item">The item to enqueue.</param>
/// <remarks>This method is meant to be thread-safe subject to the particular nature of the implementation.</remarks>
void Enqueue(T item);
/// <summary>Attempts to dequeue an item from the queue.</summary>
/// <param name="result">The dequeued item.</param>
/// <returns>true if an item could be dequeued; otherwise, false.</returns>
/// <remarks>This method is meant to be thread-safe subject to the particular nature of the implementation.</remarks>
bool TryDequeue([MaybeNullWhen(false)] out T result);
/// <summary>Gets whether the collection is currently empty.</summary>
/// <remarks>This method may or may not be thread-safe.</remarks>
bool IsEmpty { get; }
/// <summary>Gets the number of items in the collection.</summary>
/// <remarks>In many implementations, this method will not be thread-safe.</remarks>
int Count { get; }
}
/// <summary>
/// Provides a producer/consumer queue safe to be used by any number of producers and consumers concurrently.
/// </summary>
/// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam>
[DebuggerDisplay("Count = {Count}")]
internal sealed class MultiProducerMultiConsumerQueue<T> : ConcurrentQueue<T>, IProducerConsumerQueue<T>
{
/// <summary>Enqueues an item into the queue.</summary>
/// <param name="item">The item to enqueue.</param>
void IProducerConsumerQueue<T>.Enqueue(T item) { base.Enqueue(item); }
/// <summary>Attempts to dequeue an item from the queue.</summary>
/// <param name="result">The dequeued item.</param>
/// <returns>true if an item could be dequeued; otherwise, false.</returns>
bool IProducerConsumerQueue<T>.TryDequeue([MaybeNullWhen(false)] out T result) { return base.TryDequeue(out result); }
/// <summary>Gets whether the collection is currently empty.</summary>
bool IProducerConsumerQueue<T>.IsEmpty { get { return base.IsEmpty; } }
/// <summary>Gets the number of items in the collection.</summary>
int IProducerConsumerQueue<T>.Count { get { return base.Count; } }
}
/// <summary>
/// Provides a producer/consumer queue safe to be used by only one producer and one consumer concurrently.
/// </summary>
/// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(SingleProducerSingleConsumerQueue<>.SingleProducerSingleConsumerQueue_DebugView))]
internal sealed class SingleProducerSingleConsumerQueue<T> : IProducerConsumerQueue<T>
{
// Design:
//
// SingleProducerSingleConsumerQueue (SPSCQueue) is a concurrent queue designed to be used
// by one producer thread and one consumer thread. SPSCQueue does not work correctly when used by
// multiple producer threads concurrently or multiple consumer threads concurrently.
//
// SPSCQueue is based on segments that behave like circular buffers. Each circular buffer is represented
// as an array with two indexes: m_first and m_last. m_first is the index of the array slot for the consumer
// to read next, and m_last is the slot for the producer to write next. The circular buffer is empty when
// (m_first == m_last), and full when ((m_last+1) % m_array.Length == m_first).
//
// Since m_first is only ever modified by the consumer thread and m_last by the producer, the two indices can
// be updated without interlocked operations. As long as the queue size fits inside a single circular buffer,
// enqueues and dequeues simply advance the corresponding indices around the circular buffer. If an enqueue finds
// that there is no room in the existing buffer, however, a new circular buffer is allocated that is twice as big
// as the old buffer. From then on, the producer will insert values into the new buffer. The consumer will first
// empty out the old buffer and only then follow the producer into the new (larger) buffer.
//
// As described above, the enqueue operation on the fast path only modifies the m_first field of the current segment.
// However, it also needs to read m_last in order to verify that there is room in the current segment. Similarly, the
// dequeue operation on the fast path only needs to modify m_last, but also needs to read m_first to verify that the
// queue is non-empty. This results in true cache line sharing between the producer and the consumer.
//
// The cache line sharing issue can be mitigating by having a possibly stale copy of m_first that is owned by the producer,
// and a possibly stale copy of m_last that is owned by the consumer. So, the consumer state is described using
// (m_first, m_lastCopy) and the producer state using (m_firstCopy, m_last). The consumer state is separated from
// the producer state by padding, which allows fast-path enqueues and dequeues from hitting shared cache lines.
// m_lastCopy is the consumer's copy of m_last. Whenever the consumer can tell that there is room in the buffer
// simply by observing m_lastCopy, the consumer thread does not need to read m_last and thus encounter a cache miss. Only
// when the buffer appears to be empty will the consumer refresh m_lastCopy from m_last. m_firstCopy is used by the producer
// in the same way to avoid reading m_first on the hot path.
/// <summary>The initial size to use for segments (in number of elements).</summary>
private const int INIT_SEGMENT_SIZE = 32; // must be a power of 2
/// <summary>The maximum size to use for segments (in number of elements).</summary>
private const int MAX_SEGMENT_SIZE = 0x1000000; // this could be made as large as int.MaxValue / 2
/// <summary>The head of the linked list of segments.</summary>
private volatile Segment m_head;
/// <summary>The tail of the linked list of segments.</summary>
private volatile Segment m_tail;
/// <summary>Initializes the queue.</summary>
internal SingleProducerSingleConsumerQueue()
{
// Validate constants in ctor rather than in an explicit cctor that would cause perf degradation
Debug.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0.");
Debug.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2");
Debug.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum.");
Debug.Assert(MAX_SEGMENT_SIZE < int.MaxValue / 2, "Max segment size * 2 must be < int.MaxValue, or else overflow could occur.");
// Initialize the queue
m_head = m_tail = new Segment(INIT_SEGMENT_SIZE);
}
/// <summary>Enqueues an item into the queue.</summary>
/// <param name="item">The item to enqueue.</param>
public void Enqueue(T item)
{
Segment segment = m_tail;
var array = segment.m_array;
int last = segment.m_state.m_last; // local copy to avoid multiple volatile reads
// Fast path: there's obviously room in the current segment
int tail2 = (last + 1) & (array.Length - 1);
if (tail2 != segment.m_state.m_firstCopy)
{
array[last] = item;
segment.m_state.m_last = tail2;
}
// Slow path: there may not be room in the current segment.
else EnqueueSlow(item, ref segment);
}
/// <summary>Enqueues an item into the queue.</summary>
/// <param name="item">The item to enqueue.</param>
/// <param name="segment">The segment in which to first attempt to store the item.</param>
private void EnqueueSlow(T item, ref Segment segment)
{
Debug.Assert(segment != null, "Expected a non-null segment.");
if (segment.m_state.m_firstCopy != segment.m_state.m_first)
{
segment.m_state.m_firstCopy = segment.m_state.m_first;
Enqueue(item); // will only recur once for this enqueue operation
return;
}
int newSegmentSize = m_tail.m_array.Length << 1; // double size
Debug.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow.");
if (newSegmentSize > MAX_SEGMENT_SIZE) newSegmentSize = MAX_SEGMENT_SIZE;
var newSegment = new Segment(newSegmentSize);
newSegment.m_array[0] = item;
newSegment.m_state.m_last = 1;
newSegment.m_state.m_lastCopy = 1;
try { }
finally
{
// Finally block to protect against corruption due to a thread abort
// between setting m_next and setting m_tail.
Volatile.Write(ref m_tail.m_next, newSegment); // ensure segment not published until item is fully stored
m_tail = newSegment;
}
}
/// <summary>Attempts to dequeue an item from the queue.</summary>
/// <param name="result">The dequeued item.</param>
/// <returns>true if an item could be dequeued; otherwise, false.</returns>
public bool TryDequeue([MaybeNullWhen(false)] out T result)
{
Segment segment = m_head;
var array = segment.m_array;
int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads
// Fast path: there's obviously data available in the current segment
if (first != segment.m_state.m_lastCopy)
{
result = array[first];
array[first] = default!; // Clear the slot to release the element
segment.m_state.m_first = (first + 1) & (array.Length - 1);
return true;
}
// Slow path: there may not be data available in the current segment
else return TryDequeueSlow(ref segment, ref array, out result);
}
/// <summary>Attempts to dequeue an item from the queue.</summary>
/// <param name="array">The array from which the item was dequeued.</param>
/// <param name="segment">The segment from which the item was dequeued.</param>
/// <param name="result">The dequeued item.</param>
/// <returns>true if an item could be dequeued; otherwise, false.</returns>
private bool TryDequeueSlow(ref Segment segment, ref T[] array, [MaybeNullWhen(false)] out T result)
{
Debug.Assert(segment != null, "Expected a non-null segment.");
Debug.Assert(array != null, "Expected a non-null item array.");
if (segment.m_state.m_last != segment.m_state.m_lastCopy)
{
segment.m_state.m_lastCopy = segment.m_state.m_last;
return TryDequeue(out result); // will only recur once for this dequeue operation
}
if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last)
{
segment = segment.m_next;
array = segment.m_array;
m_head = segment;
}
var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads
if (first == segment.m_state.m_last)
{
result = default!;
return false;
}
result = array[first];
array[first] = default!; // Clear the slot to release the element
segment.m_state.m_first = (first + 1) & (segment.m_array.Length - 1);
segment.m_state.m_lastCopy = segment.m_state.m_last; // Refresh m_lastCopy to ensure that m_first has not passed m_lastCopy
return true;
}
/// <summary>Gets whether the collection is currently empty.</summary>
/// <remarks>WARNING: This should not be used concurrently without further vetting.</remarks>
public bool IsEmpty
{
// This implementation is optimized for calls from the consumer.
get
{
var head = m_head;
if (head.m_state.m_first != head.m_state.m_lastCopy) return false; // m_first is volatile, so the read of m_lastCopy cannot get reordered
if (head.m_state.m_first != head.m_state.m_last) return false;
return head.m_next == null;
}
}
/// <summary>Gets an enumerable for the collection.</summary>
/// <remarks>WARNING: This should only be used for debugging purposes. It is not safe to be used concurrently.</remarks>
public IEnumerator<T> GetEnumerator()
{
for (Segment? segment = m_head; segment != null; segment = segment.m_next)
{
for (int pt = segment.m_state.m_first;
pt != segment.m_state.m_last;
pt = (pt + 1) & (segment.m_array.Length - 1))
{
yield return segment.m_array[pt];
}
}
}
/// <summary>Gets an enumerable for the collection.</summary>
/// <remarks>WARNING: This should only be used for debugging purposes. It is not safe to be used concurrently.</remarks>
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
/// <summary>Gets the number of items in the collection.</summary>
/// <remarks>WARNING: This should only be used for debugging purposes. It is not meant to be used concurrently.</remarks>
public int Count
{
get
{
int count = 0;
for (Segment? segment = m_head; segment != null; segment = segment.m_next)
{
int arraySize = segment.m_array.Length;
int first, last;
while (true) // Count is not meant to be used concurrently, but this helps to avoid issues if it is
{
first = segment.m_state.m_first;
last = segment.m_state.m_last;
if (first == segment.m_state.m_first) break;
}
count += (last - first) & (arraySize - 1);
}
return count;
}
}
/// <summary>A segment in the queue containing one or more items.</summary>
[StructLayout(LayoutKind.Sequential)]
private sealed class Segment
{
/// <summary>The next segment in the linked list of segments.</summary>
internal Segment? m_next;
/// <summary>The data stored in this segment.</summary>
internal readonly T[] m_array;
/// <summary>Details about the segment.</summary>
internal SegmentState m_state; // separated out to enable StructLayout attribute to take effect
/// <summary>Initializes the segment.</summary>
/// <param name="size">The size to use for this segment.</param>
internal Segment(int size)
{
Debug.Assert((size & (size - 1)) == 0, "Size must be a power of 2");
m_array = new T[size];
}
}
/// <summary>Stores information about a segment.</summary>
[StructLayout(LayoutKind.Sequential)] // enforce layout so that padding reduces false sharing
private struct SegmentState
{
/// <summary>Padding to reduce false sharing between the segment's array and m_first.</summary>
internal Internal.PaddingFor32 m_pad0;
/// <summary>The index of the current head in the segment.</summary>
internal volatile int m_first;
/// <summary>A copy of the current tail index.</summary>
internal int m_lastCopy; // not volatile as read and written by the producer, except for IsEmpty, and there m_lastCopy is only read after reading the volatile m_first
/// <summary>Padding to reduce false sharing between the first and last.</summary>
internal Internal.PaddingFor32 m_pad1;
/// <summary>A copy of the current head index.</summary>
internal int m_firstCopy; // not voliatle as only read and written by the consumer thread
/// <summary>The index of the current tail in the segment.</summary>
internal volatile int m_last;
/// <summary>Padding to reduce false sharing with the last and what's after the segment.</summary>
internal Internal.PaddingFor32 m_pad2;
}
/// <summary>Debugger type proxy for a SingleProducerSingleConsumerQueue of T.</summary>
private sealed class SingleProducerSingleConsumerQueue_DebugView
{
/// <summary>The queue being visualized.</summary>
private readonly SingleProducerSingleConsumerQueue<T> m_queue;
/// <summary>Initializes the debug view.</summary>
/// <param name="queue">The queue being debugged.</param>
public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue<T> queue)
{
Debug.Assert(queue != null, "Expected a non-null queue.");
m_queue = queue;
}
}
}
}
| |
// 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.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Represents an Azure Batch JobManager task.
/// </summary>
/// <remarks>
/// Batch will retry tasks when a recovery operation is triggered on a compute node. Examples of recovery operations
/// include (but are not limited to) when an unhealthy compute node is rebooted or a compute node disappeared due to
/// host failure. Retries due to recovery operations are independent of and are not counted against the <see cref="TaskConstraints.MaxTaskRetryCount"
/// />. Even if the <see cref="TaskConstraints.MaxTaskRetryCount" /> is 0, an internal retry due to a recovery operation
/// may occur. Because of this, all tasks should be idempotent. This means tasks need to tolerate being interrupted and
/// restarted without causing any corruption or duplicate data. The best practice for long running tasks is to use some
/// form of checkpointing.
/// </remarks>
public partial class JobManagerTask : ITransportObjectProvider<Models.JobManagerTask>, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<bool?> AllowLowPriorityNodeProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<AuthenticationTokenSettings> AuthenticationTokenSettingsProperty;
public readonly PropertyAccessor<string> CommandLineProperty;
public readonly PropertyAccessor<TaskConstraints> ConstraintsProperty;
public readonly PropertyAccessor<TaskContainerSettings> ContainerSettingsProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<bool?> KillJobOnCompletionProperty;
public readonly PropertyAccessor<IList<OutputFile>> OutputFilesProperty;
public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty;
public readonly PropertyAccessor<bool?> RunExclusiveProperty;
public readonly PropertyAccessor<UserIdentity> UserIdentityProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AllowLowPriorityNodeProperty = this.CreatePropertyAccessor<bool?>(nameof(AllowLowPriorityNode), BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write);
this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor<AuthenticationTokenSettings>(nameof(AuthenticationTokenSettings), BindingAccess.Read | BindingAccess.Write);
this.CommandLineProperty = this.CreatePropertyAccessor<string>(nameof(CommandLine), BindingAccess.Read | BindingAccess.Write);
this.ConstraintsProperty = this.CreatePropertyAccessor<TaskConstraints>(nameof(Constraints), BindingAccess.Read | BindingAccess.Write);
this.ContainerSettingsProperty = this.CreatePropertyAccessor<TaskContainerSettings>(nameof(ContainerSettings), BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>(nameof(EnvironmentSettings), BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write);
this.KillJobOnCompletionProperty = this.CreatePropertyAccessor<bool?>(nameof(KillJobOnCompletion), BindingAccess.Read | BindingAccess.Write);
this.OutputFilesProperty = this.CreatePropertyAccessor<IList<OutputFile>>(nameof(OutputFiles), BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>(nameof(ResourceFiles), BindingAccess.Read | BindingAccess.Write);
this.RunExclusiveProperty = this.CreatePropertyAccessor<bool?>(nameof(RunExclusive), BindingAccess.Read | BindingAccess.Write);
this.UserIdentityProperty = this.CreatePropertyAccessor<UserIdentity>(nameof(UserIdentity), BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.JobManagerTask protocolObject) : base(BindingState.Bound)
{
this.AllowLowPriorityNodeProperty = this.CreatePropertyAccessor(
protocolObject.AllowLowPriorityNode,
nameof(AllowLowPriorityNode),
BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences),
nameof(ApplicationPackageReferences),
BindingAccess.Read | BindingAccess.Write);
this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AuthenticationTokenSettings, o => new AuthenticationTokenSettings(o)),
nameof(AuthenticationTokenSettings),
BindingAccess.Read | BindingAccess.Write);
this.CommandLineProperty = this.CreatePropertyAccessor(
protocolObject.CommandLine,
nameof(CommandLine),
BindingAccess.Read | BindingAccess.Write);
this.ConstraintsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new TaskConstraints(o)),
nameof(Constraints),
BindingAccess.Read | BindingAccess.Write);
this.ContainerSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ContainerSettings, o => new TaskContainerSettings(o).Freeze()),
nameof(ContainerSettings),
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
nameof(DisplayName),
BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollection(protocolObject.EnvironmentSettings),
nameof(EnvironmentSettings),
BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
nameof(Id),
BindingAccess.Read | BindingAccess.Write);
this.KillJobOnCompletionProperty = this.CreatePropertyAccessor(
protocolObject.KillJobOnCompletion,
nameof(KillJobOnCompletion),
BindingAccess.Read | BindingAccess.Write);
this.OutputFilesProperty = this.CreatePropertyAccessor(
OutputFile.ConvertFromProtocolCollection(protocolObject.OutputFiles),
nameof(OutputFiles),
BindingAccess.Read | BindingAccess.Write);
this.ResourceFilesProperty = this.CreatePropertyAccessor(
ResourceFile.ConvertFromProtocolCollection(protocolObject.ResourceFiles),
nameof(ResourceFiles),
BindingAccess.Read | BindingAccess.Write);
this.RunExclusiveProperty = this.CreatePropertyAccessor(
protocolObject.RunExclusive,
nameof(RunExclusive),
BindingAccess.Read | BindingAccess.Write);
this.UserIdentityProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.UserIdentity, o => new UserIdentity(o)),
nameof(UserIdentity),
BindingAccess.Read | BindingAccess.Write);
}
}
private readonly PropertyContainer propertyContainer;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="JobManagerTask"/> class.
/// </summary>
/// <param name='id'>The id of the task.</param>
/// <param name='commandLine'>The command line of the task.</param>
public JobManagerTask(
string id,
string commandLine)
{
this.propertyContainer = new PropertyContainer();
this.Id = id;
this.CommandLine = commandLine;
}
internal JobManagerTask(Models.JobManagerTask protocolObject)
{
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region JobManagerTask
/// <summary>
/// Gets or sets whether the Job Manager task may run on a low-priority compute node. If omitted, the default is
/// true.
/// </summary>
public bool? AllowLowPriorityNode
{
get { return this.propertyContainer.AllowLowPriorityNodeProperty.Value; }
set { this.propertyContainer.AllowLowPriorityNodeProperty.Value = value; }
}
/// <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>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <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.
/// </remarks>
public AuthenticationTokenSettings AuthenticationTokenSettings
{
get { return this.propertyContainer.AuthenticationTokenSettingsProperty.Value; }
set { this.propertyContainer.AuthenticationTokenSettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the command line of the task.
/// </summary>
/// <remarks>
/// 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. If the command line
/// refers to file paths, it should use a relative path (relative to the task working directory), or use the Batch
/// provided environment variables (https://docs.microsoft.com/en-us/azure/batch/batch-compute-node-environment-variables).
/// </remarks>
public string CommandLine
{
get { return this.propertyContainer.CommandLineProperty.Value; }
set { this.propertyContainer.CommandLineProperty.Value = value; }
}
/// <summary>
/// Gets or sets the execution constraints for this JobManager task.
/// </summary>
public TaskConstraints Constraints
{
get { return this.propertyContainer.ConstraintsProperty.Value; }
set { this.propertyContainer.ConstraintsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the settings for the container under which the task runs.
/// </summary>
/// <remarks>
/// If the pool that will run this task has <see cref="VirtualMachineConfiguration.ContainerConfiguration"/> set,
/// this must be set as well. If the pool that will run this task doesn't have <see cref="VirtualMachineConfiguration.ContainerConfiguration"/>
/// set, this must not be set. When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR
/// (the root of Azure Batch directories on the node) are mapped into the container, all task environment variables
/// are mapped into the container, and the task command line is executed in the container.
/// </remarks>
public TaskContainerSettings ContainerSettings
{
get { return this.propertyContainer.ContainerSettingsProperty.Value; }
set { this.propertyContainer.ContainerSettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the display name of the JobManager task.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets or sets a set of environment settings for the JobManager task.
/// </summary>
public IList<EnvironmentSetting> EnvironmentSettings
{
get { return this.propertyContainer.EnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the id of the task.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets or sets a value that indicates whether to terminate all tasks in the job and complete the job when the job
/// manager task completes.
/// </summary>
public bool? KillJobOnCompletion
{
get { return this.propertyContainer.KillJobOnCompletionProperty.Value; }
set { this.propertyContainer.KillJobOnCompletionProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will upload from the compute node after running the command
/// line.
/// </summary>
public IList<OutputFile> OutputFiles
{
get { return this.propertyContainer.OutputFilesProperty.Value; }
set
{
this.propertyContainer.OutputFilesProperty.Value = ConcurrentChangeTrackedModifiableList<OutputFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets a list of files that the Batch service will download to the compute node before running the command
/// line.
/// </summary>
public IList<ResourceFile> ResourceFiles
{
get { return this.propertyContainer.ResourceFilesProperty.Value; }
set
{
this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets whether the Job Manager task requires exclusive use of the compute node where it runs.
/// </summary>
public bool? RunExclusive
{
get { return this.propertyContainer.RunExclusiveProperty.Value; }
set { this.propertyContainer.RunExclusiveProperty.Value = value; }
}
/// <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>
public UserIdentity UserIdentity
{
get { return this.propertyContainer.UserIdentityProperty.Value; }
set { this.propertyContainer.UserIdentityProperty.Value = value; }
}
#endregion // JobManagerTask
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.JobManagerTask ITransportObjectProvider<Models.JobManagerTask>.GetTransportObject()
{
Models.JobManagerTask result = new Models.JobManagerTask()
{
AllowLowPriorityNode = this.AllowLowPriorityNode,
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
AuthenticationTokenSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.AuthenticationTokenSettings, (o) => o.GetTransportObject()),
CommandLine = this.CommandLine,
Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()),
ContainerSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.ContainerSettings, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings),
Id = this.Id,
KillJobOnCompletion = this.KillJobOnCompletion,
OutputFiles = UtilitiesInternal.ConvertToProtocolCollection(this.OutputFiles),
ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles),
RunExclusive = this.RunExclusive,
UserIdentity = UtilitiesInternal.CreateObjectWithNullCheck(this.UserIdentity, (o) => o.GetTransportObject()),
};
return result;
}
#endregion // Internal/private methods
}
}
| |
using UnityEngine;
using System.Collections;
using ForieroEngine.MIDIUnified;
public static class MidiExtensions {
#region int
public static int ToInt(this System.Enum enumValue){
return System.Convert.ToInt32(enumValue);
}
public static int ToRawMidiCommand(int command, int channel){
return channel + command;
}
public static int ToMidiCommand(this int i){
return i & 0xF0;
}
public static int ToMidiChannel(this int i){
return i & 0x0F;
}
public static Color ToMidiColor(this int i){
return MidiConversion.GetToneColorFromMidiIndex(i);
}
public static bool IsNoteON(this int i){
return (ToMidiCommand(i) == (int)CommandEnum.NoteOn);
}
public static bool IsNoteOFF(this int i){
return (ToMidiCommand(i) == (int)CommandEnum.NoteOff);
}
public static int ShiftL(this int i, int bits){
return i << bits;
}
public static int ShiftR(this int i, int bits){
return i >> bits;
}
public static int WriteBit(this int i, byte bit, bool bitValue){
if(bitValue) return (1 << bit) | i;
else return i & ~(1 << bit);
}
public static bool ReadBit(this int i, byte bit){
return ((1 << bit) & i) == (1 << bit);
}
public static bool IsInByteRange(this int i){
return (i >= 0 && i <= byte.MaxValue);
}
public static bool IsInMidiRange(this int pitch)
{
return pitch >= 0 && pitch <= 127;
}
public static int Octave(this int i)
{
return (i < 0 ? (i - 11) / 12 : i / 12) - 1;
}
public static int PositionInOctave(this int i)
{
return i < 0 ? 11 - ((-i - 1) % 12) : i % 12;
}
public static bool IsInChannelRange(this int i){
return i >= 0 && i<=15;
}
public static bool IsWhiteKey(this int i){
switch(i.BaseMidiIndex()){
case 0: return true;
case 1: return false;
case 2: return true;
case 3: return false;
case 4: return true;
case 5: return true;
case 6: return false;
case 7: return true;
case 8: return false;
case 9: return true;
case 10: return false;
case 11: return true;
default : return true;
}
}
public static bool IsBlackKey(this int i){
switch(i.BaseMidiIndex()){
case 0: return false;
case 1: return true;
case 2: return false;
case 3: return true;
case 4: return false;
case 5: return false;
case 6: return true;
case 7: return false;
case 8: return true;
case 9: return false;
case 10: return true;
case 11: return false;
default : return true;
}
}
public static int BaseMidiIndex(this int i){
return MidiConversion.BaseMidiIndex(i);
}
public static int PrevWhiteKey(this int i){
i--;
while(!i.IsWhiteKey()){
i--;
}
return i;
}
public static int NextWhiteKey(this int i){
i++;
while(!i.IsWhiteKey()){
i++;
}
return i;
}
public static int PrevBlackKey(this int i){
i--;
while(!i.IsBlackKey()){
i--;
}
return i;
}
public static int NextBlackKey(this int i){
i++;
while(!i.IsBlackKey()){
i++;
}
return i;
}
#endregion
#region byte
public static byte ToRawMidiCommand(byte command, byte channel){
return (byte)(channel + command);
}
public static byte ToMidiCommand(this byte i){
return (byte)(i & 0xF0);
}
public static byte ToMidiChannel(this byte i){
return (byte)(i & 0x0F);
}
public static Color ToMidiColor(this byte i){
return MidiConversion.GetToneColorFromMidiIndex(i);
}
public static bool IsNoteON(this byte i){
return (ToMidiCommand(i) == (byte)CommandEnum.NoteOn);
}
public static bool IsNoteOFF(this byte i){
return (ToMidiCommand(i) == (byte)CommandEnum.NoteOff);
}
public static byte ShiftL(this byte i, int bits){
return (byte)(i << bits);
}
public static byte ShiftR(this byte i, int bits){
return (byte)(i >> bits);
}
public static bool IsInByteRange(this byte i){
return (i >= 0 && i <= byte.MaxValue);
}
public static bool IsInMidiRange(this byte pitch)
{
return pitch >= 0 && pitch <= 127;
}
public static byte Octave(this byte i)
{
return (byte)((i < 0 ? (i - 11) / 12 : i / 12) - 1);
}
public static byte PositionInOctave(this byte i)
{
return (byte)(i < 0 ? 11 - ((-i - 1) % 12) : i % 12);
}
public static bool IsInChannelRange(this byte i){
return i >= 0 && i<=15;
}
public static bool IsWhiteKey(this byte i){
switch(i.BaseMidiIndex()){
case 0: return true;
case 1: return false;
case 2: return true;
case 3: return false;
case 4: return true;
case 5: return true;
case 6: return false;
case 7: return true;
case 8: return false;
case 9: return true;
case 10: return false;
case 11: return true;
default : return true;
}
}
public static bool IsBlackKey(this byte i){
switch(i.BaseMidiIndex()){
case 0: return false;
case 1: return true;
case 2: return false;
case 3: return true;
case 4: return false;
case 5: return false;
case 6: return true;
case 7: return false;
case 8: return true;
case 9: return false;
case 10: return true;
case 11: return false;
default : return true;
}
}
public static byte BaseMidiIndex(this byte i){
return (byte)MidiConversion.BaseMidiIndex(i);
}
public static byte PrevWhiteKey(this byte i){
i--;
while(!i.IsWhiteKey()){
i--;
}
return i;
}
public static byte NextWhiteKey(this byte i){
i++;
while(!i.IsWhiteKey()){
i++;
}
return i;
}
public static byte PrevBlackKey(this byte i){
i--;
while(!i.IsBlackKey()){
i--;
}
return i;
}
public static byte NextBlackKey(this byte i){
i++;
while(!i.IsBlackKey()){
i++;
}
return i;
}
#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.
/*============================================================
**
**
**
**
**
** Purpose: Abstract base class for Text-only Writers.
** Subclasses will include StreamWriter & StringWriter.
**
**
===========================================================*/
using System;
using System.Text;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Security.Permissions;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
namespace System.IO {
// This abstract base class represents a writer that can write a sequential
// stream of characters. A subclass must minimally implement the
// Write(char) method.
//
// This class is intended for character output, not bytes.
// There are methods on the Stream class for writing bytes.
[Serializable]
[ComVisible(true)]
#if FEATURE_REMOTING
public abstract class TextWriter : MarshalByRefObject, IDisposable {
#else // FEATURE_REMOTING
public abstract class TextWriter : IDisposable {
#endif // FEATURE_REMOTING
public static readonly TextWriter Null = new NullTextWriter();
// This should be initialized to Environment.NewLine, but
// to avoid loading Environment unnecessarily so I've duplicated
// the value here.
#if !PLATFORM_UNIX
private const String InitialNewLine = "\r\n";
protected char[] CoreNewLine = new char[] { '\r', '\n' };
#else
private const String InitialNewLine = "\n";
protected char[] CoreNewLine = new char[] {'\n'};
#endif // !PLATFORM_UNIX
// Can be null - if so, ask for the Thread's CurrentCulture every time.
private IFormatProvider InternalFormatProvider;
protected TextWriter()
{
InternalFormatProvider = null; // Ask for CurrentCulture all the time.
}
protected TextWriter(IFormatProvider formatProvider)
{
InternalFormatProvider = formatProvider;
}
public virtual IFormatProvider FormatProvider {
get {
if (InternalFormatProvider == null)
return Thread.CurrentThread.CurrentCulture;
else
return InternalFormatProvider;
}
}
// Closes this TextWriter and releases any system resources associated with the
// TextWriter. Following a call to Close, any operations on the TextWriter
// may raise exceptions. This default method is empty, but descendant
// classes can override the method to provide the appropriate
// functionality.
public virtual void Close() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Clears all buffers for this TextWriter and causes any buffered data to be
// written to the underlying device. This default method is empty, but
// descendant classes can override the method to provide the appropriate
// functionality.
public virtual void Flush() {
}
public abstract Encoding Encoding {
get;
}
// Returns the line terminator string used by this TextWriter. The default line
// terminator string is a carriage return followed by a line feed ("\r\n").
//
// Sets the line terminator string for this TextWriter. The line terminator
// string is written to the text stream whenever one of the
// WriteLine methods are called. In order for text written by
// the TextWriter to be readable by a TextReader, only one of the following line
// terminator strings should be used: "\r", "\n", or "\r\n".
//
public virtual String NewLine {
get { return new String(CoreNewLine); }
set {
if (value == null)
value = InitialNewLine;
CoreNewLine = value.ToCharArray();
}
}
[HostProtection(Synchronization=true)]
public static TextWriter Synchronized(TextWriter writer) {
if (writer==null)
throw new ArgumentNullException("writer");
Contract.Ensures(Contract.Result<TextWriter>() != null);
Contract.EndContractBlock();
if (writer is SyncTextWriter)
return writer;
return new SyncTextWriter(writer);
}
// Writes a character to the text stream. This default method is empty,
// but descendant classes can override the method to provide the
// appropriate functionality.
//
public virtual void Write(char value) {
}
// Writes a character array to the text stream. This default method calls
// Write(char) for each of the characters in the character array.
// If the character array is null, nothing is written.
//
public virtual void Write(char[] buffer) {
if (buffer != null) Write(buffer, 0, buffer.Length);
}
// Writes a range of a character array to the text stream. This method will
// write count characters of data into this TextWriter from the
// buffer character array starting at position index.
//
public virtual void Write(char[] buffer, int index, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
for (int i = 0; i < count; i++) Write(buffer[index + i]);
}
// Writes the text representation of a boolean to the text stream. This
// method outputs either Boolean.TrueString or Boolean.FalseString.
//
public virtual void Write(bool value) {
Write(value ? Boolean.TrueLiteral : Boolean.FalseLiteral);
}
// Writes the text representation of an integer to the text stream. The
// text representation of the given value is produced by calling the
// Int32.ToString() method.
//
public virtual void Write(int value) {
Write(value.ToString(FormatProvider));
}
// Writes the text representation of an integer to the text stream. The
// text representation of the given value is produced by calling the
// UInt32.ToString() method.
//
[CLSCompliant(false)]
public virtual void Write(uint value) {
Write(value.ToString(FormatProvider));
}
// Writes the text representation of a long to the text stream. The
// text representation of the given value is produced by calling the
// Int64.ToString() method.
//
public virtual void Write(long value) {
Write(value.ToString(FormatProvider));
}
// Writes the text representation of an unsigned long to the text
// stream. The text representation of the given value is produced
// by calling the UInt64.ToString() method.
//
[CLSCompliant(false)]
public virtual void Write(ulong value) {
Write(value.ToString(FormatProvider));
}
// Writes the text representation of a float to the text stream. The
// text representation of the given value is produced by calling the
// Float.toString(float) method.
//
public virtual void Write(float value) {
Write(value.ToString(FormatProvider));
}
// Writes the text representation of a double to the text stream. The
// text representation of the given value is produced by calling the
// Double.toString(double) method.
//
public virtual void Write(double value) {
Write(value.ToString(FormatProvider));
}
public virtual void Write(Decimal value) {
Write(value.ToString(FormatProvider));
}
// Writes a string to the text stream. If the given string is null, nothing
// is written to the text stream.
//
public virtual void Write(String value) {
if (value != null) Write(value.ToCharArray());
}
// Writes the text representation of an object to the text stream. If the
// given object is null, nothing is written to the text stream.
// Otherwise, the object's ToString method is called to produce the
// string representation, and the resulting string is then written to the
// output stream.
//
public virtual void Write(Object value) {
if (value != null) {
IFormattable f = value as IFormattable;
if (f != null)
Write(f.ToString(null, FormatProvider));
else
Write(value.ToString());
}
}
#if false
// // Converts the wchar * to a string and writes this to the stream.
// //
// __attribute NonCLSCompliantAttribute()
// public void Write(wchar *value) {
// Write(new String(value));
// }
// // Treats the byte* as a LPCSTR, converts it to a string, and writes it to the stream.
// //
// __attribute NonCLSCompliantAttribute()
// public void Write(byte *value) {
// Write(new String(value));
// }
#endif
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write(String format, Object arg0)
{
Write(String.Format(FormatProvider, format, arg0));
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write(String format, Object arg0, Object arg1)
{
Write(String.Format(FormatProvider, format, arg0, arg1));
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write(String format, Object arg0, Object arg1, Object arg2)
{
Write(String.Format(FormatProvider, format, arg0, arg1, arg2));
}
// Writes out a formatted string. Uses the same semantics as
// String.Format.
//
public virtual void Write(String format, params Object[] arg)
{
Write(String.Format(FormatProvider, format, arg));
}
// Writes a line terminator to the text stream. The default line terminator
// is a carriage return followed by a line feed ("\r\n"), but this value
// can be changed by setting the NewLine property.
//
public virtual void WriteLine() {
Write(CoreNewLine);
}
// Writes a character followed by a line terminator to the text stream.
//
public virtual void WriteLine(char value) {
Write(value);
WriteLine();
}
// Writes an array of characters followed by a line terminator to the text
// stream.
//
public virtual void WriteLine(char[] buffer) {
Write(buffer);
WriteLine();
}
// Writes a range of a character array followed by a line terminator to the
// text stream.
//
public virtual void WriteLine(char[] buffer, int index, int count) {
Write(buffer, index, count);
WriteLine();
}
// Writes the text representation of a boolean followed by a line
// terminator to the text stream.
//
public virtual void WriteLine(bool value) {
Write(value);
WriteLine();
}
// Writes the text representation of an integer followed by a line
// terminator to the text stream.
//
public virtual void WriteLine(int value) {
Write(value);
WriteLine();
}
// Writes the text representation of an unsigned integer followed by
// a line terminator to the text stream.
//
[CLSCompliant(false)]
public virtual void WriteLine(uint value) {
Write(value);
WriteLine();
}
// Writes the text representation of a long followed by a line terminator
// to the text stream.
//
public virtual void WriteLine(long value) {
Write(value);
WriteLine();
}
// Writes the text representation of an unsigned long followed by
// a line terminator to the text stream.
//
[CLSCompliant(false)]
public virtual void WriteLine(ulong value) {
Write(value);
WriteLine();
}
// Writes the text representation of a float followed by a line terminator
// to the text stream.
//
public virtual void WriteLine(float value) {
Write(value);
WriteLine();
}
// Writes the text representation of a double followed by a line terminator
// to the text stream.
//
public virtual void WriteLine(double value) {
Write(value);
WriteLine();
}
public virtual void WriteLine(decimal value) {
Write(value);
WriteLine();
}
// Writes a string followed by a line terminator to the text stream.
//
public virtual void WriteLine(String value) {
if (value==null) {
WriteLine();
}
else {
// We'd ideally like WriteLine to be atomic, in that one call
// to WriteLine equals one call to the OS (ie, so writing to
// console while simultaneously calling printf will guarantee we
// write out a string and new line chars, without any interference).
// Additionally, we need to call ToCharArray on Strings anyways,
// so allocating a char[] here isn't any worse than what we were
// doing anyways. We do reduce the number of calls to the
// backing store this way, potentially.
int vLen = value.Length;
int nlLen = CoreNewLine.Length;
char[] chars = new char[vLen+nlLen];
value.CopyTo(0, chars, 0, vLen);
// CoreNewLine will almost always be 2 chars, and possibly 1.
if (nlLen == 2) {
chars[vLen] = CoreNewLine[0];
chars[vLen+1] = CoreNewLine[1];
}
else if (nlLen == 1)
chars[vLen] = CoreNewLine[0];
else
Buffer.InternalBlockCopy(CoreNewLine, 0, chars, vLen * 2, nlLen * 2);
Write(chars, 0, vLen + nlLen);
}
/*
Write(value); // We could call Write(String) on StreamWriter...
WriteLine();
*/
}
// Writes the text representation of an object followed by a line
// terminator to the text stream.
//
public virtual void WriteLine(Object value) {
if (value==null) {
WriteLine();
}
else {
// Call WriteLine(value.ToString), not Write(Object), WriteLine().
// This makes calls to WriteLine(Object) atomic.
IFormattable f = value as IFormattable;
if (f != null)
WriteLine(f.ToString(null, FormatProvider));
else
WriteLine(value.ToString());
}
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine(String format, Object arg0)
{
WriteLine(String.Format(FormatProvider, format, arg0));
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine (String format, Object arg0, Object arg1)
{
WriteLine(String.Format(FormatProvider, format, arg0, arg1));
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine (String format, Object arg0, Object arg1, Object arg2)
{
WriteLine(String.Format(FormatProvider, format, arg0, arg1, arg2));
}
// Writes out a formatted string and a new line. Uses the same
// semantics as String.Format.
//
public virtual void WriteLine (String format, params Object[] arg)
{
WriteLine(String.Format(FormatProvider, format, arg));
}
#region Task based Async APIs
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(char value)
{
var tuple = new Tuple<TextWriter, char>(this, value);
return Task.Factory.StartNew(state =>
{
var t = (Tuple<TextWriter, char>)state;
t.Item1.Write(t.Item2);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(String value)
{
var tuple = new Tuple<TextWriter, string>(this, value);
return Task.Factory.StartNew(state =>
{
var t = (Tuple<TextWriter, string>)state;
t.Item1.Write(t.Item2);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteAsync(char[] buffer)
{
if (buffer == null) return Task.CompletedTask;
return WriteAsync(buffer, 0, buffer.Length);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(char[] buffer, int index, int count)
{
var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
return Task.Factory.StartNew(state =>
{
var t = (Tuple<TextWriter, char[], int, int>)state;
t.Item1.Write(t.Item2, t.Item3, t.Item4);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(char value)
{
var tuple = new Tuple<TextWriter, char>(this, value);
return Task.Factory.StartNew(state =>
{
var t = (Tuple<TextWriter, char>)state;
t.Item1.WriteLine(t.Item2);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(String value)
{
var tuple = new Tuple<TextWriter, string>(this, value);
return Task.Factory.StartNew(state =>
{
var t = (Tuple<TextWriter, string>)state;
t.Item1.WriteLine(t.Item2);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteLineAsync(char[] buffer)
{
if (buffer == null) return Task.CompletedTask;
return WriteLineAsync(buffer, 0, buffer.Length);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync(char[] buffer, int index, int count)
{
var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
return Task.Factory.StartNew(state =>
{
var t = (Tuple<TextWriter, char[], int, int>)state;
t.Item1.WriteLine(t.Item2, t.Item3, t.Item4);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteLineAsync()
{
return WriteAsync(CoreNewLine);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task FlushAsync()
{
return Task.Factory.StartNew(state =>
{
((TextWriter)state).Flush();
},
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
#endregion
[Serializable]
private sealed class NullTextWriter : TextWriter
{
internal NullTextWriter(): base(CultureInfo.InvariantCulture) {
}
public override Encoding Encoding {
get { return Encoding.Default; }
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void Write(char[] buffer, int index, int count) {
}
public override void Write(String value) {
}
// Not strictly necessary, but for perf reasons
public override void WriteLine() {
}
// Not strictly necessary, but for perf reasons
public override void WriteLine(String value) {
}
public override void WriteLine(Object value) {
}
}
[Serializable]
internal sealed class SyncTextWriter : TextWriter, IDisposable
{
private TextWriter _out;
internal SyncTextWriter(TextWriter t): base(t.FormatProvider) {
_out = t;
}
public override Encoding Encoding {
get { return _out.Encoding; }
}
public override IFormatProvider FormatProvider {
get { return _out.FormatProvider; }
}
public override String NewLine {
[MethodImplAttribute(MethodImplOptions.Synchronized)]
get { return _out.NewLine; }
[MethodImplAttribute(MethodImplOptions.Synchronized)]
set { _out.NewLine = value; }
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Close() {
// So that any overriden Close() gets run
_out.Close();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing) {
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_out).Dispose();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Flush() {
_out.Flush();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(char value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(char[] buffer) {
_out.Write(buffer);
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(char[] buffer, int index, int count) {
_out.Write(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(bool value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(int value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(uint value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(long value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(ulong value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(float value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(double value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(Decimal value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(String value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(Object value) {
_out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(String format, Object arg0) {
_out.Write(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(String format, Object arg0, Object arg1) {
_out.Write(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(String format, Object arg0, Object arg1, Object arg2) {
_out.Write(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Write(String format, Object[] arg) {
_out.Write(format, arg);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine() {
_out.WriteLine();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(char value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(decimal value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(char[] buffer) {
_out.WriteLine(buffer);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(char[] buffer, int index, int count) {
_out.WriteLine(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(bool value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(int value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(uint value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(long value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(ulong value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(float value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(double value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(String value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(Object value) {
_out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(String format, Object arg0) {
_out.WriteLine(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(String format, Object arg0, Object arg1) {
_out.WriteLine(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(String format, Object arg0, Object arg1, Object arg2) {
_out.WriteLine(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void WriteLine(String format, Object[] arg) {
_out.WriteLine(format, arg);
}
//
// On SyncTextWriter all APIs should run synchronously, even the async ones.
//
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task WriteAsync(char value)
{
Write(value);
return Task.CompletedTask;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task WriteAsync(String value)
{
Write(value);
return Task.CompletedTask;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task WriteAsync(char[] buffer, int index, int count)
{
Write(buffer, index, count);
return Task.CompletedTask;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task WriteLineAsync(char value)
{
WriteLine(value);
return Task.CompletedTask;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task WriteLineAsync(String value)
{
WriteLine(value);
return Task.CompletedTask;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
WriteLine(buffer, index, count);
return Task.CompletedTask;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
[ComVisible(false)]
public override Task FlushAsync()
{
Flush();
return Task.CompletedTask;
}
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System.Collections.Generic;
using Xunit;
public class AsyncTargetWrapperTests : NLogTestBase
{
[Fact]
public void AsyncTargetWrapperInitTest()
{
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper(myTarget, 300, AsyncTargetWrapperOverflowAction.Grow);
Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, targetWrapper.OverflowAction);
Assert.Equal(300, targetWrapper.QueueLimit);
Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches);
Assert.Equal(200, targetWrapper.BatchSize);
}
[Fact]
public void AsyncTargetWrapperInitTest2()
{
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper()
{
WrappedTarget = myTarget,
};
Assert.Equal(AsyncTargetWrapperOverflowAction.Discard, targetWrapper.OverflowAction);
Assert.Equal(10000, targetWrapper.QueueLimit);
Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches);
Assert.Equal(200, targetWrapper.BatchSize);
}
/// <summary>
/// Test Fix for https://github.com/NLog/NLog/issues/1069
/// </summary>
[Fact]
public void AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero()
{
LogManager.ThrowConfigExceptions = true;
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper() {
WrappedTarget = myTarget,
TimeToSleepBetweenBatches = 0,
BatchSize = 4,
QueueLimit = 2, // Will make it "sleep" between every second write
OverflowAction = AsyncTargetWrapperOverflowAction.Block
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
int flushCounter = 0;
AsyncContinuation flushHandler = (ex) => { ++flushCounter; };
List<KeyValuePair<LogEventInfo, AsyncContinuation>> itemPrepareList = new List<KeyValuePair<LogEventInfo, AsyncContinuation>>(500);
List<int> itemWrittenList = new List<int>(itemPrepareList.Capacity);
for (int i = 0; i< itemPrepareList.Capacity; ++i)
{
var logEvent = new LogEventInfo();
int sequenceID = logEvent.SequenceID;
itemPrepareList.Add(new KeyValuePair<LogEventInfo, AsyncContinuation>(logEvent, (ex) => itemWrittenList.Add(sequenceID)));
}
long startTicks = Environment.TickCount;
for (int i = 0; i < itemPrepareList.Count; ++i)
{
var logEvent = itemPrepareList[i].Key;
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(itemPrepareList[i].Value));
}
targetWrapper.Flush(flushHandler);
for (int i = 0; i < itemPrepareList.Count * 2 && itemWrittenList.Count != itemPrepareList.Count; ++i)
System.Threading.Thread.Sleep(1);
long elapsedMilliseconds = Environment.TickCount - startTicks;
Assert.Equal(itemPrepareList.Count, itemWrittenList.Count);
int prevSequenceID = 0;
for (int i = 0; i < itemWrittenList.Count; ++i)
{
Assert.True(prevSequenceID < itemWrittenList[i]);
prevSequenceID = itemWrittenList[i];
}
if (!IsAppVeyor())
Assert.True(elapsedMilliseconds < 750); // Skip timing test when running within OpenCover.Console.exe
targetWrapper.Flush(flushHandler);
for (int i = 0; i < 2000 && flushCounter != 2; ++i)
System.Threading.Thread.Sleep(1);
Assert.Equal(2, flushCounter);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperSyncTest1()
{
var myTarget = new MyTarget();
var targetWrapper = new AsyncTargetWrapper
{
WrappedTarget = myTarget,
Name = "AsyncTargetWrapperSyncTest1_Wrapper",
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
var logEvent = new LogEventInfo();
Exception lastException = null;
ManualResetEvent continuationHit = new ManualResetEvent(false);
Thread continuationThread = null;
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationThread = Thread.CurrentThread;
continuationHit.Set();
};
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
// continuation was not hit
Assert.True(continuationHit.WaitOne(2000));
Assert.NotSame(continuationThread, Thread.CurrentThread);
Assert.Null(lastException);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotSame(continuationThread, Thread.CurrentThread);
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperAsyncTest1()
{
var myTarget = new MyAsyncTarget();
var targetWrapper = new AsyncTargetWrapper(myTarget) { Name = "AsyncTargetWrapperAsyncTest1_Wrapper" };
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit.WaitOne());
Assert.Null(lastException);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperAsyncWithExceptionTest1()
{
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true,
};
var targetWrapper = new AsyncTargetWrapper(myTarget) {Name = "AsyncTargetWrapperAsyncWithExceptionTest1_Wrapper"};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit.WaitOne());
Assert.NotNull(lastException);
Assert.IsType<InvalidOperationException>(lastException);
// no flush on exception
Assert.Equal(0, myTarget.FlushCount);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
lastException = null;
targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotNull(lastException);
Assert.IsType<InvalidOperationException>(lastException);
Assert.Equal(0, myTarget.FlushCount);
Assert.Equal(2, myTarget.WriteCount);
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperFlushTest()
{
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true
};
var targetWrapper = new AsyncTargetWrapper(myTarget)
{
Name = "AsyncTargetWrapperFlushTest_Wrapper",
OverflowAction = AsyncTargetWrapperOverflowAction.Grow
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
try
{
List<Exception> exceptions = new List<Exception>();
int eventCount = 5000;
for (int i = 0; i < eventCount; ++i)
{
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(
ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
}
}));
}
Exception lastException = null;
ManualResetEvent mre = new ManualResetEvent(false);
string internalLog = RunAndCaptureInternalLog(
() =>
{
targetWrapper.Flush(
cont =>
{
try
{
// by this time all continuations should be completed
Assert.Equal(eventCount, exceptions.Count);
// with just 1 flush of the target
Assert.Equal(1, myTarget.FlushCount);
// and all writes should be accounted for
Assert.Equal(eventCount, myTarget.WriteCount);
}
catch (Exception ex)
{
lastException = ex;
}
finally
{
mre.Set();
}
});
Assert.True(mre.WaitOne());
},
LogLevel.Trace);
if (lastException != null)
{
Assert.True(false, lastException.ToString() + "\r\n" + internalLog);
}
}
finally
{
myTarget.Close();
targetWrapper.Close();
}
}
[Fact]
public void AsyncTargetWrapperCloseTest()
{
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true
};
var targetWrapper = new AsyncTargetWrapper(myTarget)
{
OverflowAction = AsyncTargetWrapperOverflowAction.Grow,
TimeToSleepBetweenBatches = 1000,
Name = "AsyncTargetWrapperCloseTest_Wrapper",
};
targetWrapper.Initialize(null);
myTarget.Initialize(null);
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));
// quickly close the target before the timer elapses
targetWrapper.Close();
}
[Fact]
public void AsyncTargetWrapperExceptionTest()
{
var targetWrapper = new AsyncTargetWrapper
{
OverflowAction = AsyncTargetWrapperOverflowAction.Grow,
TimeToSleepBetweenBatches = 500,
WrappedTarget = new DebugTarget(),
Name = "AsyncTargetWrapperExceptionTest_Wrapper"
};
LogManager.ThrowExceptions = false;
targetWrapper.Initialize(null);
// null out wrapped target - will cause exception on the timer thread
targetWrapper.WrappedTarget = null;
string internalLog = RunAndCaptureInternalLog(
() =>
{
targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));
targetWrapper.Close();
},
LogLevel.Trace);
Assert.True(internalLog.Contains("AsyncWrapper 'AsyncTargetWrapperExceptionTest_Wrapper': WrappedTarget is NULL"), internalLog);
}
[Fact]
public void FlushingMultipleTimesSimultaneous()
{
var asyncTarget = new AsyncTargetWrapper
{
TimeToSleepBetweenBatches = 1000,
WrappedTarget = new DebugTarget(),
Name = "FlushingMultipleTimesSimultaneous_Wrapper"
};
asyncTarget.Initialize(null);
try
{
asyncTarget.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { }));
var firstContinuationCalled = false;
var secondContinuationCalled = false;
var firstContinuationResetEvent = new ManualResetEvent(false);
var secondContinuationResetEvent = new ManualResetEvent(false);
asyncTarget.Flush(ex =>
{
firstContinuationCalled = true;
firstContinuationResetEvent.Set();
});
asyncTarget.Flush(ex =>
{
secondContinuationCalled = true;
secondContinuationResetEvent.Set();
});
firstContinuationResetEvent.WaitOne();
secondContinuationResetEvent.WaitOne();
Assert.True(firstContinuationCalled);
Assert.True(secondContinuationCalled);
}
finally
{
asyncTarget.Close();
}
}
class MyAsyncTarget : Target
{
private readonly NLog.Internal.AsyncOperationCounter pendingWriteCounter = new NLog.Internal.AsyncOperationCounter();
public int FlushCount;
public int WriteCount;
protected override void Write(LogEventInfo logEvent)
{
throw new NotSupportedException();
}
protected override void Write(AsyncLogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
pendingWriteCounter.BeginOperation();
ThreadPool.QueueUserWorkItem(
s =>
{
try
{
Interlocked.Increment(ref this.WriteCount);
if (this.ThrowExceptions)
{
logEvent.Continuation(new InvalidOperationException("Some problem!"));
logEvent.Continuation(new InvalidOperationException("Some problem!"));
}
else
{
logEvent.Continuation(null);
logEvent.Continuation(null);
}
}
finally
{
pendingWriteCounter.CompleteOperation(null);
}
});
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
Interlocked.Increment(ref this.FlushCount);
var wrappedContinuation = pendingWriteCounter.RegisterCompletionNotification(asyncContinuation);
ThreadPool.QueueUserWorkItem(
s =>
{
wrappedContinuation(null);
});
}
public bool ThrowExceptions { get; set; }
}
class MyTarget : Target
{
public int FlushCount { get; set; }
public int WriteCount { get; set; }
protected override void Write(LogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
this.WriteCount++;
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
this.FlushCount++;
asyncContinuation(null);
}
}
}
}
| |
using System;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Scintilla;
using Scintilla.Enums;
using Scintilla.Configuration;
namespace Scintilla.Configuration.SciTE
{
/// <summary>
/// A class that encapsulates the properties
/// Justin Greenwood - [email protected]
/// </summary>
public class SciTEProperties : IScintillaConfigProvider
{
private static Regex regExFindVars = new Regex(@"[\$][\(](?<varname>.*?)[\)]", RegexOptions.Compiled);
private static Regex regExKeyValPairs = new Regex(@"[\s]*(?:(?<key>[^,]*?)[\s]*:[\s]*(?<value>[^,^:]*[,]*?)|(?<single>[^,^:]*[,]*?))[\s]*", RegexOptions.Compiled);
private Dictionary<string, string> properties = new Dictionary<string, string>();
private Dictionary<string, string> extentionLanguages = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
private Dictionary<string, string> languageExtentions = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
private List<string> languageNames = new List<string>();
/// <summary>
///
/// </summary>
public SciTEProperties()
{
// these variables are used in the properties files from Scite for the two different versions.
properties["PLAT_WIN"] = Boolean.TrueString;
properties["PLAT_GTK"] = Boolean.FalseString;
}
public void Load(FileInfo globalConfigFile)
{
s_props = this;
PropertiesReader.Read(globalConfigFile, PropertyRead);
}
/// <summary>
///
/// </summary>
public Dictionary<string, string>.KeyCollection Keys
{
get { return properties.Keys; }
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string this[string key]
{
get
{
return properties[key];
}
set
{
if (key.IndexOf("$(") == -1)
properties[key] = value;
else
properties[Evaluate(key)] = value;
}
}
/// <summary>
///
/// </summary>
/// <param name="ext"></param>
/// <param name="f"></param>
public void AddFileExtentionMapping(string extensionList, string languageName)
{
if (!languageNames.Contains(languageName))
languageNames.Add(languageName);
languageExtentions[languageName] = extensionList;
string[] exts = extensionList.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string ext in exts)
{
string trimExt = ext.TrimStart('*', '.');
if (!extentionLanguages.ContainsKey(trimExt))
{
extentionLanguages[trimExt] = languageName;
}
}
}
public void AddLanguageNames(params string[] names)
{
this.languageNames.AddRange(names);
}
/// <summary>
///
/// </summary>
/// <param name="ext"></param>
/// <returns></returns>
public string GetLanguageFromExtension(string ext)
{
string lang = null;
if (extentionLanguages.ContainsKey(ext))
{
lang = extentionLanguages[ext];
}
return lang;
}
/// <summary>
///
/// </summary>
/// <param name="language"></param>
/// <returns></returns>
public string GetExtensionListFromLanguage(string language)
{
string extList = null;
if (languageExtentions.ContainsKey(language))
{
extList = languageExtentions[language];
}
return extList;
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool ContainsKey(string key)
{
return this.properties.ContainsKey(key);
}
public string GetByKey(string key)
{
return this[key];
}
#region Populate ScintillaConfig data structure
/// <summary>
/// Apply the lexer style according to the scite config files
/// </summary>
/// <param name="config"></param>
public bool PopulateScintillaConfig(IScintillaConfig config, string filepattern)
{
string key, val, lang;
int? valInt;
bool? valBool;
// Menu Items in the format: (menuString|fileExtension|key|)*
key = "menu.language";
if (properties.ContainsKey(key))
{
val = this.Evaluate(properties[key]);
string[] menuItems = val.Split('|');
for (int i = 2; i < menuItems.Length; i += 3)
{
lang = this.GetLanguageFromExtension(menuItems[i - 1]);
MenuItemConfig menuItem = new MenuItemConfig();
menuItem.Text = menuItems[i - 2];
menuItem.Value = (lang == null) ? menuItems[i - 1] : lang;
menuItem.ShortcutKeys = GetKeys(menuItems[i]);
config.LanguageMenuItems.Add(menuItem);
}
}
valInt = GetInt("code.page");
if (valInt.HasValue) config.CodePage = valInt.Value;
valInt = GetInt("selection.alpha");
if (valInt.HasValue) config.SelectionAlpha = valInt;
config.SelectionBackColor = GetColor("selection.back", config.SelectionBackColor);
config.FileOpenFilter = GetString("open.filter", config.FileOpenFilter);
config.DefaultFileExtention = GetString("default.file.ext", config.DefaultFileExtention);
valInt = GetInt("tab.size", filepattern);
if(!valInt.HasValue)
{
valInt = GetInt("tabsize");
if (valInt.HasValue) config.TabSize = valInt;
}
valInt = GetInt("indent.size", filepattern);
if (valInt.HasValue) config.IndentSize = valInt;
valBool = GetBool("use.tabs", filepattern);
if (valBool.HasValue) config.UseTabs = valBool;
valBool = GetBool("fold");
if (valBool.HasValue) config.Fold = valBool.Value;
valBool = GetBool("fold.compact");
if (valBool.HasValue) config.FoldCompact = valBool.Value;
valBool = GetBool("fold.symbols");
if (valBool.HasValue) config.FoldSymbols = valBool.Value;
valBool = GetBool("fold.comment");
if (valBool.HasValue) config.FoldComment = valBool.Value;
valBool = GetBool("fold.on.open");
if (valBool.HasValue) config.FoldOnOpen = valBool.Value;
valBool = GetBool("fold.preprocessor");
if (valBool.HasValue) config.FoldPreprocessor = valBool.Value;
valBool = GetBool("fold.html");
if (valBool.HasValue) config.FoldHTML = valBool.Value;
valBool = GetBool("fold.html.preprocessor");
if (valBool.HasValue) config.FoldHTMLPreprocessor = valBool.Value;
valInt = GetInt("fold.flags");
if (valInt.HasValue) config.FoldFlags = valInt;
valInt = GetInt("fold.margin.width");
if (valInt.HasValue) config.FoldMarginWidth = valInt;
config.FoldMarginColor = GetColor("fold.margin.colour", config.FoldMarginColor);
config.FoldMarginHighlightColor = GetColor("fold.margin.highlight.colour", config.FoldMarginHighlightColor);
//tabsize=8
//indent.size=8
//default.file.ext=.cxx
//open.filter
//code.page
//selection.alpha=30
//selection.back=#000000
//fold=1
//fold.compact=1
//fold.flags=16
//fold.symbols=1
//#fold.on.open=1
//fold.comment=1
//fold.preprocessor=1
// there are a ton of generic scintilla properties - we will eventually implement them here
//#fold.margin.width=16
//#fold.margin.colour=#FF0000
//#fold.margin.highlight.colour=#0000FF
//fold.quotes.python
//fold.perl.package
//fold.perl.pod
return true;
}
/// <summary>
///
/// </summary>
/// <param name="config"></param>
public bool PopulateLexerConfig(ILexerConfig config)
{
/*--------------------------------------- styles ---------------------------------------
The lexers determine a style number for each lexical type, such as keyword, comment or number. These settings
determine the visual style to be used for each style number of each lexer.
The value of each setting is a set of ',' separated fields, some of which have a subvalue after a ':'. The fields
are font, size, fore, back, italics, notitalics, bold, notbold, eolfilled, noteolfilled, underlined,
notunderlined, and case. The font field has a subvalue which is the name of the font, the fore and back
have colour subvalues, the size field has a numeric size subvalue, the case field has a subvalue of 'm',
'u', or 'l' for mixed, upper or lower case, and the bold, italics and eolfilled fields have no subvalue.
The value "fore:#FF0000,font:Courier,size:14" represents 14 point, red Courier text.
A global style can be set up using style.*.stylenumber. Any style options set in the global style will be
inherited by each lexer style unless overridden.
----------------------------------------------------------------------------------------*/
string key, s, lexer = config.LexerName.ToLower();
ILexerStyle style;
bool dataIsFound = false;
Dictionary<string, string> dict;
for (int i = 0; i < 128; i++)
{
if (config.Styles.ContainsKey(i))
style = config.Styles[i];
else
style = new LexerStyle(i);
dataIsFound = true;
foreach (string lang in new string[] { "*", lexer })
{
key = string.Format("style.{0}.{1}", lang, i);
if (properties.ContainsKey(key))
{
dataIsFound = true;
s = this.Evaluate(properties[key]);
dict = PropertiesReader.GetKeyValuePairs(s);
foreach (string styleKey in dict.Keys)
{
s = dict[styleKey];
switch (styleKey)
{
case "font":
style.FontName = s;
break;
case "size":
style.FontSize = Convert.ToInt32(s);
break;
case "fore":
style.ForeColor = ColorTranslator.FromHtml(s);
break;
case "back":
style.BackColor = ColorTranslator.FromHtml(s);
break;
case "italics":
style.Italics = true;
break;
case "notitalics":
style.Italics = false;
break;
case "bold":
style.Bold = true;
break;
case "notbold":
style.Bold = false;
break;
case "eolfilled":
style.EOLFilled = true;
break;
case "noteolfilled":
style.EOLFilled = false;
break;
case "underlined":
style.Underline = true;
break;
case "notunderlined":
style.Underline = false;
break;
case "case":
style.CaseVisibility = ((s == "m") ? CaseVisible.Mixed : ((s == "u") ? CaseVisible.Upper : CaseVisible.Lower));
break;
}
}
}
}
if (dataIsFound) config.Styles[i] = style;
}
return true;
}
/// <summary>
///
/// </summary>
/// <param name="config"></param>
public bool PopulateLanguageConfig(ILanguageConfig config, ILexerConfigCollection lexers)
{
bool success = true;
string key, s,
language = config.Name.ToLower(),
extList = GetExtensionListFromLanguage(language);
if (extList == null)
{
extList = "*." + language;
languageExtentions[language] = extList;
}
config.ExtensionList = extList;
key = string.Format("lexer.{0}", extList);
if (properties.ContainsKey(key))
{
config.Lexer = lexers[this.Evaluate(properties[key])];
}
if (config.Lexer == null) success = false;
/*--------------------------------------- keywords ---------------------------------------
Most of the lexers differentiate between names and keywords and use the keywords variables to do so.
To avoid repeating the keyword list for each file extension, where several file extensions are
used for one language, a keywordclass variable is defined in the distributed properties file
although this is just a convention. Some lexers define a second set of keywords which will be
displayed in a different style to the first set of keywords. This is used in the HTML lexer
to display JavaScript keywords in a different style to HTML tags and attributes.
----------------------------------------------------------------------------------------*/
for (int i = 0; i <= 8; i++)
{
s = (i == 0) ? string.Empty : i.ToString();
key = string.Format("keywords{0}.{1}", s, extList);
s = GetString(key);
if (s != null) config.KeywordLists[i] = s;
}
/*--------------------------------------- word characters ---------------------------------------
Defines which characters can be parts of words. The default value here is all the alphabetic and
numeric characters and the underscore which is a reasonable value for languages such as C++.
----------------------------------------------------------------------------------------*/
key = string.Format("word.characters.{0}", extList);
config.WordCharacters = GetString(key);
/*--------------------------------------- whitespace characters ---------------------------------------
Defines which characters are considered whitespace. The default value is that initially set up by Scintilla,
which is space and all chars less than 0x20. Setting this property allows you to force Scintilla to consider other
characters as whitespace (e.g. punctuation) during such activities as cursor navigation (ctrl+left/right).
----------------------------------------------------------------------------------------*/
key = string.Format("whitespace.characters.{0}", extList);
config.WhitespaceCharacters = GetString(key);
return success;
}
#endregion
#region Helper Methods for pulling data out of the scite config files
private System.Windows.Forms.Keys GetKeys(string data)
{
System.Windows.Forms.Keys shortcutKeys = System.Windows.Forms.Keys.None;
if (!string.IsNullOrEmpty(data))
{
string[] keys = data.Split(new char[] {'+'}, StringSplitOptions.RemoveEmptyEntries);
foreach (string key in keys)
{
shortcutKeys = shortcutKeys | (System.Windows.Forms.Keys)Enum.Parse(
typeof(System.Windows.Forms.Keys),
(key.Equals("Ctrl",StringComparison.CurrentCultureIgnoreCase) ? "Control" : key),
true);
}
}
return shortcutKeys;
}
private string GetString(string key)
{
return GetString(key, null);
}
private string GetString(string key, string nullValue)
{
string val = nullValue;
if (properties.ContainsKey(key))
{
val = this.Evaluate(properties[key]);
}
return val;
}
private Color GetColor(string key, Color colorIfNull)
{
Color val = colorIfNull;
string sval = GetString(key);
if (sval != null) val = ColorTranslator.FromHtml(sval);
return val;
}
private int? GetInt(string key, string filepattern)
{
int? result = filepattern == null ? null : GetInt(key + "." + filepattern);
if (!result.HasValue)
result = GetInt(key);
return result;
}
private int? GetInt(string key)
{
int? val = null;
string sval = GetString(key);
if (sval != null) val = Convert.ToInt32(sval);
return val;
}
private bool? GetBool(string key, string filepattern)
{
bool? result = filepattern == null ? null : GetBool(key + "." + filepattern);
if (!result.HasValue)
result = GetBool(key);
return result;
}
private bool? GetBool(string key)
{
bool? val = null;
string sval = GetString(key);
if (sval != null)
{
sval = sval.ToLower();
switch (sval)
{
case "1":
case "y":
case "t":
case "yes":
case "true":
val = true;
break;
default:
val = false;
break;
}
}
return val;
}
#endregion
#region Evaluate String with embedded variables
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string Evaluate(string str)
{
return PropertiesReader.Evaluate(str, this.GetByKey, this.ContainsKey);
}
#endregion
#region Special Debug Methods for testing (will delete later)
#if DEBUG
/// <summary>
/// This is a method I am using to test the properties file parser
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
string val;
foreach (string key in this.properties.Keys)
{
val = properties[key];
sb.Append(key).Append(" = ").AppendLine(val);
sb.Append('\t').Append(Evaluate(key)).Append(" = ").AppendLine(Evaluate(val));
}
return sb.ToString();
}
#endif
#endregion
#region Static Property Reader Methods
protected static SciTEProperties s_props = null;
protected static bool s_supressImports = false;
/// <summary>
///
/// </summary>
/// <param name="file"></param>
/// <param name="propertyType"></param>
/// <param name="keyQueue"></param>
/// <param name="key"></param>
/// <param name="data"></param>
/// <returns></returns>
protected static bool PropertyRead(FileInfo file, PropertyType propertyType, Queue<string> keyQueue, string key, string var)
{
bool success = false;
string filePatternPrefix = "file.patterns.";
string languageNameListPrefix = "language.names";
string lang, extList;
if (s_props != null)
{
switch (propertyType)
{
case PropertyType.Property:
success = true;
s_props[key] = var;
if (key.StartsWith(languageNameListPrefix))
{
extList = s_props.Evaluate(var);
s_props.AddLanguageNames(var.Split(' '));
}
else if (key.StartsWith(filePatternPrefix))
{
lang = key.Substring(filePatternPrefix.Length);
if (lang.LastIndexOf('.') == -1)
{
extList = s_props.Evaluate(var);
s_props.AddFileExtentionMapping(extList, lang);
}
}
break;
case PropertyType.If:
if (s_props.ContainsKey(var))
{
success = !Convert.ToBoolean(s_props[var]);
}
break;
case PropertyType.Import:
if (!s_supressImports)
{
FileInfo fileToImport = new FileInfo(string.Format(@"{0}\{1}.properties", file.Directory.FullName, var));
success = fileToImport.Exists;
}
break;
}
}
return success;
}
#endregion
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace ZXing.QRCode.Internal
{
/// <summary>
///
/// </summary>
/// <author>Satoru Takabayashi</author>
/// <author>Daniel Switkin</author>
/// <author>Sean Owen</author>
public static class MaskUtil
{
// Penalty weights from section 6.8.2.1
private const int N1 = 3;
private const int N2 = 3;
private const int N3 = 40;
private const int N4 = 10;
/// <summary>
/// Apply mask penalty rule 1 and return the penalty. Find repetitive cells with the same color and
/// give penalty to them. Example: 00000 or 11111.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns></returns>
public static int applyMaskPenaltyRule1(ByteMatrix matrix)
{
return applyMaskPenaltyRule1Internal(matrix, true) + applyMaskPenaltyRule1Internal(matrix, false);
}
/// <summary>
/// Apply mask penalty rule 2 and return the penalty. Find 2x2 blocks with the same color and give
/// penalty to them. This is actually equivalent to the spec's rule, which is to find MxN blocks and give a
/// penalty proportional to (M-1)x(N-1), because this is the number of 2x2 blocks inside such a block.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns></returns>
public static int applyMaskPenaltyRule2(ByteMatrix matrix)
{
int penalty = 0;
var array = matrix.Array;
int width = matrix.Width;
int height = matrix.Height;
for (int y = 0; y < height - 1; y++)
{
for (int x = 0; x < width - 1; x++)
{
int value = array[y][x];
if (value == array[y][x + 1] && value == array[y + 1][x] && value == array[y + 1][x + 1])
{
penalty++;
}
}
}
return N2 * penalty;
}
/// <summary>
/// Apply mask penalty rule 3 and return the penalty. Find consecutive cells of 00001011101 or
/// 10111010000, and give penalty to them. If we find patterns like 000010111010000, we give
/// penalties twice (i.e. 40 * 2).
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns></returns>
public static int applyMaskPenaltyRule3(ByteMatrix matrix)
{
int numPenalties = 0;
byte[][] array = matrix.Array;
int width = matrix.Width;
int height = matrix.Height;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
byte[] arrayY = array[y]; // We can at least optimize this access
if (x + 6 < width &&
arrayY[x] == 1 &&
arrayY[x + 1] == 0 &&
arrayY[x + 2] == 1 &&
arrayY[x + 3] == 1 &&
arrayY[x + 4] == 1 &&
arrayY[x + 5] == 0 &&
arrayY[x + 6] == 1 &&
(isWhiteHorizontal(arrayY, x - 4, x) || isWhiteHorizontal(arrayY, x + 7, x + 11)))
{
numPenalties++;
}
if (y + 6 < height &&
array[y][x] == 1 &&
array[y + 1][x] == 0 &&
array[y + 2][x] == 1 &&
array[y + 3][x] == 1 &&
array[y + 4][x] == 1 &&
array[y + 5][x] == 0 &&
array[y + 6][x] == 1 &&
(isWhiteVertical(array, x, y - 4, y) || isWhiteVertical(array, x, y + 7, y + 11)))
{
numPenalties++;
}
}
}
return numPenalties * N3;
}
private static bool isWhiteHorizontal(byte[] rowArray, int from, int to)
{
for (int i = from; i < to; i++)
{
if (i >= 0 && i < rowArray.Length && rowArray[i] == 1)
{
return false;
}
}
return true;
}
private static bool isWhiteVertical(byte[][] array, int col, int from, int to)
{
for (int i = from; i < to; i++)
{
if (i >= 0 && i < array.Length && array[i][col] == 1)
{
return false;
}
}
return true;
}
/// <summary>
/// Apply mask penalty rule 4 and return the penalty. Calculate the ratio of dark cells and give
/// penalty if the ratio is far from 50%. It gives 10 penalty for 5% distance.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns></returns>
public static int applyMaskPenaltyRule4(ByteMatrix matrix)
{
int numDarkCells = 0;
var array = matrix.Array;
int width = matrix.Width;
int height = matrix.Height;
for (int y = 0; y < height; y++)
{
var arrayY = array[y];
for (int x = 0; x < width; x++)
{
if (arrayY[x] == 1)
{
numDarkCells++;
}
}
}
var numTotalCells = matrix.Height * matrix.Width;
var darkRatio = (double)numDarkCells / numTotalCells;
var fivePercentVariances = (int)(Math.Abs(darkRatio - 0.5) * 20.0); // * 100.0 / 5.0
return fivePercentVariances * N4;
}
/// <summary>
/// Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask
/// pattern conditions.
/// </summary>
/// <param name="maskPattern">The mask pattern.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <returns></returns>
public static bool getDataMaskBit(int maskPattern, int x, int y)
{
int intermediate, temp;
switch (maskPattern)
{
case 0:
intermediate = (y + x) & 0x1;
break;
case 1:
intermediate = y & 0x1;
break;
case 2:
intermediate = x % 3;
break;
case 3:
intermediate = (y + x) % 3;
break;
case 4:
intermediate = (((int)((uint)y >> 1)) + (x / 3)) & 0x1;
break;
case 5:
temp = y * x;
intermediate = (temp & 0x1) + (temp % 3);
break;
case 6:
temp = y * x;
intermediate = (((temp & 0x1) + (temp % 3)) & 0x1);
break;
case 7:
temp = y * x;
intermediate = (((temp % 3) + ((y + x) & 0x1)) & 0x1);
break;
default:
throw new ArgumentException("Invalid mask pattern: " + maskPattern);
}
return intermediate == 0;
}
/// <summary>
/// Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both
/// vertical and horizontal orders respectively.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <param name="isHorizontal">if set to <c>true</c> [is horizontal].</param>
/// <returns></returns>
private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix, bool isHorizontal)
{
int penalty = 0;
int iLimit = isHorizontal ? matrix.Height : matrix.Width;
int jLimit = isHorizontal ? matrix.Width : matrix.Height;
var array = matrix.Array;
for (int i = 0; i < iLimit; i++)
{
int numSameBitCells = 0;
int prevBit = -1;
for (int j = 0; j < jLimit; j++)
{
int bit = isHorizontal ? array[i][j] : array[j][i];
if (bit == prevBit)
{
numSameBitCells++;
}
else
{
if (numSameBitCells >= 5)
{
penalty += N1 + (numSameBitCells - 5);
}
numSameBitCells = 1; // Include the cell itself.
prevBit = bit;
}
}
if (numSameBitCells >= 5)
{
penalty += N1 + (numSameBitCells - 5);
}
}
return penalty;
}
}
}
| |
/**
* Copyright (C) 2007-2010 Nicholas Berardi, Managed Fusion, LLC ([email protected])
*
* <author>Nicholas Berardi</author>
* <author_email>[email protected]</author_email>
* <company>Managed Fusion, LLC</company>
* <product>Url Rewriter and Reverse Proxy</product>
* <license>Microsoft Public License (Ms-PL)</license>
* <agreement>
* This software, as defined above in <product />, is copyrighted by the <author /> and the <company />, all defined above.
*
* For all binary distributions the <product /> is licensed for use under <license />.
* For all source distributions please contact the <author /> at <author_email /> for a commercial license.
*
* This copyright notice may not be removed and if this <product /> or any parts of it are used any other
* packaged software, attribution needs to be given to the author, <author />. This can be in the form of a textual
* message at program startup or in documentation (online or textual) provided with the packaged software.
* </agreement>
* <product_url>http://www.managedfusion.com/products/url-rewriter/</product_url>
* <license_url>http://www.managedfusion.com/products/url-rewriter/license.aspx</license_url>
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Hosting;
using System.Security.Permissions;
using Talifun.AcceptanceTestProxy.UrlRewriter.Rules;
using log4net;
namespace Talifun.AcceptanceTestProxy.UrlRewriter
{
/// <summary>
///
/// </summary>
public abstract class RuleSet
{
private static readonly ILog Logger = LogManager.GetLogger(typeof(RuleSet));
private static readonly string DefaultLogFileName;
/// <summary>
/// Initializes the <see cref="RuleSet"/> class.
/// </summary>
static RuleSet()
{
DefaultLogFileName = "url-rewrite-log.txt";
}
private IList<IRule> _rules;
private IList<IRule> _outputRules;
/// <summary>
/// Initializes a new instance of the <see cref="RuleSet"/> class.
/// </summary>
public RuleSet()
{
// create list of rules
_rules = new List<IRule>();
_outputRules = new List<IRule>();
// the defaults for hte properties
MaxInternalTransfers = 10;
EngineEnabled = true;
}
/// <summary>
/// Gets or sets a value indicating whether [engine enabled].
/// </summary>
/// <value>
/// <see langword="true"/> if [engine enabled]; otherwise, <see langword="false"/>.
/// </value>
public bool EngineEnabled
{
get;
protected set;
}
/// <summary>
/// Gets or sets the log level.
/// </summary>
/// <value>The log level.</value>
public int LogLevel
{
get;
protected set;
}
/// <summary>
/// Gets or sets the log location.
/// </summary>
/// <value>The log location.</value>
public string LogLocation
{
get;
protected set;
}
/// <summary>
/// Gets or set the physical base.
/// </summary>
public string PhysicalBase
{
get;
protected set;
}
/// <summary>
/// Gets or sets the base.
/// </summary>
/// <value>The base.</value>
public string VirtualBase
{
get;
protected set;
}
/// <summary>
/// Gets or sets the max internal transfers allowed.
/// </summary>
/// <remarks>In order to prevent endless loops of internal transfers issued by rewrite requests in IIS7 or above, the ruleset
/// aborts the request after reaching a maximum number of such redirects and responds with an 500 Internal Server Error.
/// If you really need more internal redirects than 10 per request, you may increase the default to the desired value.</remarks>
public int MaxInternalTransfers
{
get;
protected set;
}
/// <summary>
/// Adds the rule.
/// </summary>
/// <param name="rule">The rule.</param>
public void AddRule(IRule rule)
{
_rules.Add(rule);
}
/// <summary>
/// Adds the output rule.
/// </summary>
/// <param name="rule">The rule.</param>
public void AddOutputRule(IRule rule)
{
_outputRules.Add(rule);
}
/// <summary>
/// Adds the rules.
/// </summary>
/// <param name="rules">The rules.</param>
public void AddRules(IEnumerable<IRule> rules)
{
foreach (IRule rule in rules)
{
AddRule(rule);
}
}
/// <summary>
/// Adds the output rules.
/// </summary>
/// <param name="rules">The rules.</param>
public void AddOutputRules(IEnumerable<IRule> rules)
{
foreach (IRule rule in rules)
{
AddOutputRule(rule);
}
}
/// <summary>
/// Clears the rules.
/// </summary>
public void ClearRules()
{
_rules.Clear();
_outputRules.Clear();
}
/// <summary>
/// Gets the rule count.
/// </summary>
public int RuleCount
{
get { return _rules.Count; }
}
/// <summary>
/// Gets the output rule count.
/// </summary>
public int OutputRuleCount
{
get { return _outputRules.Count; }
}
#region Refresh Actions
/// <summary>
/// Normalizes the log location.
/// </summary>
/// <param name="path">The path.</param>
/// <returns></returns>
protected string NormalizeLogLocation(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
var pathRoot = Path.GetPathRoot(path);
// if the path root is empty then add a root to it
if (string.IsNullOrEmpty(pathRoot))
{
pathRoot = Path.DirectorySeparatorChar.ToString();
path = pathRoot + path;
}
// if the log path is not rooted to the drive then we need to path the path according to
// our web application root directory
if (pathRoot == Path.DirectorySeparatorChar.ToString())
{
path = HostingEnvironment.MapPath(path);
}
// if the path is a directory then add our default filename to it
if (string.IsNullOrEmpty(Path.GetFileName(path)))
{
path = Path.Combine(path, DefaultLogFileName);
}
// normalize the path in case anything wacky is in there
path = Path.GetFullPath(path);
// verify write access is granted to the path
new FileIOPermission(FileIOPermissionAccess.Write, path).Demand();
return path;
}
#endregion
#region Run Actions
/// <summary>
/// Determines whether [is internal transfer] [the specified context].
/// </summary>
/// <param name="context">The context.</param>
/// <returns>
/// <see langword="true"/> if [is internal transfer] [the specified context]; otherwise, <see langword="false"/>.
/// </returns>
private bool IsInternalTransfer(HttpContextBase context)
{
return !string.IsNullOrEmpty(context.Request.Headers["X-Rewriter-Transfer"]);
}
/// <summary>
/// Gets the total count of internal transfers that have occured.
/// </summary>
/// <param name="context">The context.</param>
/// <returns>Returns the count of internal transfers that have occured.</returns>
private int InternalTransferCount(HttpContextBase context)
{
int transferCount;
var transferCountHeader = context.Request.Headers["X-Rewriter-Transfer"];
if (string.IsNullOrEmpty(transferCountHeader) || !Int32.TryParse(transferCountHeader, out transferCount))
{
transferCount = 0;
}
return transferCount;
}
/// <summary>
/// Removes the base.
/// </summary>
/// <param name="baseFrom">The base from.</param>
/// <param name="url">The URL.</param>
/// <returns></returns>
private Uri RemoveBase(string baseFrom, Uri url)
{
var urlPath = url.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped);
if (urlPath.StartsWith(baseFrom))
{
urlPath = urlPath.Remove(0, baseFrom.Length);
}
if (!urlPath.StartsWith("/"))
{
urlPath = "/" + urlPath;
}
return new Uri(url, urlPath);
}
/// <summary>
/// Adds the base.
/// </summary>
/// <param name="baseFrom">The base from.</param>
/// <param name="url">The URL.</param>
/// <returns></returns>
private Uri AddBase(string baseFrom, Uri url)
{
var urlPath = url.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped);
if (!urlPath.StartsWith(baseFrom))
{
urlPath = baseFrom + urlPath;
}
while (urlPath.Contains("//"))
{
urlPath = urlPath.Replace("//", "/");
}
return new Uri(url, urlPath);
}
/// <summary>
/// Runs the rules.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="url">The URL.</param>
/// <returns>
/// Returns a rewritten <see cref="System.Uri"/>, or a value of <see langword="null"/> if no rewriting was done to <paramref name="url"/>.
/// </returns>
public Uri RunRules(HttpContextBase httpContext, Uri url)
{
var context = new RuleSetContext(this, url, httpContext);
var currentUrl = url;
if (!EngineEnabled)
{
Logger.Info("Rewrite Engine Is DISABLED");
}
if (_rules.Count > 0 && EngineEnabled)
{
Logger.InfoFormat("Input: " + currentUrl);
// check if max number of internal transfers have been exceeded
if (InternalTransferCount(httpContext) > MaxInternalTransfers)
{
string message = "Exceeded the max number of internal transfers.";
throw new HttpException(500, message);
}
IRuleFlagProcessor temporyFlags = null;
var skipNextChain = false;
var initialUrl = currentUrl;
if (!string.IsNullOrEmpty(VirtualBase) && VirtualBase != "/")
{
currentUrl = RemoveBase(VirtualBase, currentUrl);
}
// process rules according to their settings
for (var i = 0; i < _rules.Count; i++)
{
var ruleContext = new RuleContext(i, context, currentUrl, _rules[i]);
temporyFlags = _rules[i].Flags;
// continue if this rule shouldn't be processed because it doesn't allow internal transfer requests
if (RuleFlagsProcessor.HasNotForInternalSubRequests(temporyFlags) && IsInternalTransfer(httpContext))
{
continue;
}
var containsChain = RuleFlagsProcessor.HasChain(_rules[i].Flags);
var previousContainsChain = RuleFlagsProcessor.HasChain(_rules[Math.Max(0, i - 1)].Flags);
// if the previous rule doesn't contain a chain flag then set the initial URL
// this will be used to reset a chain if one of the chain rules fail
if (!previousContainsChain)
{
initialUrl = currentUrl;
}
// skip if the current rule or the last rule has a chain flag
// and if the skip next chain is set
if (skipNextChain && (previousContainsChain || containsChain))
{
continue;
}
else
{
skipNextChain = false;
}
if (_rules[i].TryExecute(ruleContext))
{
var flagResponse = temporyFlags.Apply(ruleContext);
currentUrl = ruleContext.SubstitutedUrl;
i = ruleContext.RuleIndex ?? -1;
var breakLoop = false;
// apply the flags to the rules, and only do special processing
// for the flag responses listed in the switch statement below
switch (flagResponse)
{
case RuleFlagProcessorResponse.ExitRuleSet:
return null;
case RuleFlagProcessorResponse.LastRule:
breakLoop = true;
break;
}
// break the loop because we have reached the last rule as indicated by a flag
if (breakLoop)
{
break;
}
}
else if (containsChain)
{
skipNextChain = true;
// reset the current URL back to the initial URL from the start of the chain
currentUrl = initialUrl;
}
else if (previousContainsChain)
{
// reset the current URL back to the initial URL from the start of the chain
currentUrl = initialUrl;
}
}
if (!string.IsNullOrEmpty(VirtualBase) && VirtualBase != "/")
{
currentUrl = AddBase(VirtualBase, currentUrl);
}
Logger.InfoFormat("Output: {0}", currentUrl);
}
// if the http request url matches for both the request and the rewrite no work was done so the url should be null
if (Uri.Compare(currentUrl, url, UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase) == 0)
{
currentUrl = null;
}
return currentUrl;
}
#endregion
#region Run Output Actions
/// <summary>
///
/// </summary>
/// <param name="httpContext"></param>
/// <param name="content"></param>
/// <returns></returns>
public byte[] RunOutputRules(HttpContextBase httpContext, byte[] content)
{
var context = new RuleSetContext(this, content, httpContext);
var currentContent = content;
if (!EngineEnabled)
{
Logger.Info("Rewrite Engine Is DISABLED");
}
if (_outputRules.Count > 0 && EngineEnabled)
{
IRuleFlagProcessor temporyFlags = null;
var skipNextChain = false;
var initialContent = currentContent;
// process rules according to their settings
for (var i = 0; i < _outputRules.Count; i++)
{
var ruleContext = new RuleContext(i, context, currentContent, _outputRules[i]);
temporyFlags = _outputRules[i].Flags;
var containsChain = RuleFlagsProcessor.HasChain(_outputRules[i].Flags);
var previousContainsChain = RuleFlagsProcessor.HasChain(_outputRules[Math.Max(0, i - 1)].Flags);
// if the previous rule doesn't contain a chain flag then set the initial URL
// this will be used to reset a chain if one of the chain rules fail
if (!previousContainsChain)
{
initialContent = currentContent;
}
// skip if the current rule or the last rule has a chain flag
// and if the skip next chain is set
if (skipNextChain && (previousContainsChain || containsChain))
{
continue;
}
else
{
skipNextChain = false;
}
if (_outputRules[i].TryExecute(ruleContext))
{
var flagResponse = temporyFlags.Apply(ruleContext);
currentContent = ruleContext.SubstitutedContent;
i = ruleContext.RuleIndex ?? -1;
var breakLoop = false;
// apply the flags to the rules, and only do special processing
// for the flag responses listed in the switch statement below
switch (flagResponse)
{
case RuleFlagProcessorResponse.ExitRuleSet:
return null;
case RuleFlagProcessorResponse.LastRule:
breakLoop = true;
break;
}
// break the loop because we have reached the last rule as indicated by a flag
if (breakLoop)
{
break;
}
}
else if (containsChain)
{
skipNextChain = true;
// reset the current URL back to the initial URL from the start of the chain
currentContent = initialContent;
}
else if (previousContainsChain)
{
// reset the current URL back to the initial URL from the start of the chain
currentContent = initialContent;
}
}
}
return currentContent;
}
#endregion
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
namespace UnitTests.ActivationsLifeCycleTests
{
public class GrainActivateDeactivateTests : HostedTestClusterEnsureDefaultStarted, IDisposable
{
private IActivateDeactivateWatcherGrain watcher;
public GrainActivateDeactivateTests()
{
watcher = GrainClient.GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
watcher.Clear().Wait();
}
public void Dispose()
{
watcher.Clear().Wait();
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")]
public async Task WatcherGrain_GetGrain()
{
IActivateDeactivateWatcherGrain grain = GrainClient.GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(1);
await grain.Clear();
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Activate_Simple()
{
int id = random.Next();
ISimpleActivateDeactivateTestGrain grain = GrainClient.GrainFactory.GetGrain<ISimpleActivateDeactivateTestGrain>(id);
string activation = await grain.DoSomething();
await CheckNumActivateDeactivateCalls(1, 0, activation, "After activation");
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Deactivate_Simple()
{
int id = random.Next();
ISimpleActivateDeactivateTestGrain grain = GrainClient.GrainFactory.GetGrain<ISimpleActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Reactivate_Simple()
{
int id = random.Next();
ISimpleActivateDeactivateTestGrain grain = GrainClient.GrainFactory.GetGrain<ISimpleActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
// Reactivate
string activation2 = await grain.DoSomething();
Assert.NotEqual(activation, activation2); // New activation created after re-activate
await CheckNumActivateDeactivateCalls(2, 1, new[] { activation, activation2 }, "After reactivation");
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Activate_TailCall()
{
int id = random.Next();
ITailCallActivateDeactivateTestGrain grain = GrainClient.GrainFactory.GetGrain<ITailCallActivateDeactivateTestGrain>(id);
string activation = await grain.DoSomething();
await CheckNumActivateDeactivateCalls(1, 0, activation, "After activation");
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Deactivate_TailCall()
{
int id = random.Next();
ITailCallActivateDeactivateTestGrain grain = GrainClient.GrainFactory.GetGrain<ITailCallActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Reactivate_TailCall()
{
int id = random.Next();
ITailCallActivateDeactivateTestGrain grain = GrainClient.GrainFactory.GetGrain<ITailCallActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
// Reactivate
string activation2 = await grain.DoSomething();
Assert.NotEqual(activation, activation2); // New activation created after re-activate
await CheckNumActivateDeactivateCalls(2, 1, new[] { activation, activation2 }, "After reactivation");
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("Reentrancy")]
public async Task LongRunning_Deactivate()
{
int id = random.Next();
ILongRunningActivateDeactivateTestGrain grain = GrainClient.GrainFactory.GetGrain<ILongRunningActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
await CheckNumActivateDeactivateCalls(1, 0, activation, "Before deactivation");
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
// Reactivate
string activation2 = await grain.DoSomething();
Assert.NotEqual(activation, activation2); // New activation created after re-activate;
await CheckNumActivateDeactivateCalls(2, 1, new[] { activation, activation2 }, "After reactivation");
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task BadActivate_Await()
{
try
{
int id = random.Next();
IBadActivateDeactivateTestGrain grain = GrainClient.GrainFactory.GetGrain<IBadActivateDeactivateTestGrain>(id);
await grain.ThrowSomething();
Assert.True(false, "Expected ThrowSomething call to fail as unable to Activate grain");
}
catch (Exception exc)
{
AssertIsNotInvalidOperationException(exc, "Application-OnActivateAsync");
}
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task BadActivate_GetValue()
{
try
{
int id = random.Next();
IBadActivateDeactivateTestGrain grain = GrainClient.GrainFactory.GetGrain<IBadActivateDeactivateTestGrain>(id);
long key = await grain.GetKey();
Assert.True(false, "Expected ThrowSomething call to fail as unable to Activate grain, but returned " + key);
}
catch (Exception exc)
{
AssertIsNotInvalidOperationException(exc, "Application-OnActivateAsync");
}
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task BadActivate_Await_ViaOtherGrain()
{
try
{
int id = random.Next();
ICreateGrainReferenceTestGrain grain = GrainClient.GrainFactory.GetGrain<ICreateGrainReferenceTestGrain>(id);
await grain.ForwardCall(GrainClient.GrainFactory.GetGrain<IBadActivateDeactivateTestGrain>(id));
Assert.True(false, "Expected ThrowSomething call to fail as unable to Activate grain");
}
catch (Exception exc)
{
AssertIsNotInvalidOperationException(exc, "Application-OnActivateAsync");
}
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Constructor_Bad_Await()
{
try
{
int id = random.Next();
IBadConstructorTestGrain grain = GrainClient.GrainFactory.GetGrain<IBadConstructorTestGrain>(id);
await grain.DoSomething();
Assert.True(false, "Expected ThrowSomething call to fail as unable to Activate grain");
}
catch (TimeoutException te)
{
Console.WriteLine("Received timeout: " + te);
throw; // Fail test
}
catch (Exception exc)
{
AssertIsNotInvalidOperationException(exc, "Constructor");
}
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task Constructor_CreateGrainReference()
{
int id = random.Next();
ICreateGrainReferenceTestGrain grain = GrainClient.GrainFactory.GetGrain<ICreateGrainReferenceTestGrain>(id);
string activation = await grain.DoSomething();
Assert.NotNull(activation);
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task TaskAction_Deactivate()
{
int id = random.Next();
ITaskActionActivateDeactivateTestGrain grain = GrainClient.GrainFactory.GetGrain<ITaskActionActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation.ToString());
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public async Task DeactivateOnIdleWhileActivate()
{
int id = random.Next();
IDeactivatingWhileActivatingTestGrain grain = GrainClient.GrainFactory.GetGrain<IDeactivatingWhileActivatingTestGrain>(id);
try
{
string activation = await grain.DoSomething();
Assert.True(false, "Should have thrown.");
}
catch(Exception exc)
{
logger.Info("Thrown as expected:", exc);
Exception e = exc.GetBaseException();
Assert.True(e.Message.Contains("Forwarding failed"),
"Did not get expected exception message returned: " + e.Message);
}
}
private async Task CheckNumActivateDeactivateCalls(
int expectedActivateCalls,
int expectedDeactivateCalls,
string forActivation,
string when = null)
{
await CheckNumActivateDeactivateCalls(
expectedActivateCalls,
expectedDeactivateCalls,
new string[] { forActivation },
when )
;
}
private async Task CheckNumActivateDeactivateCalls(
int expectedActivateCalls,
int expectedDeactivateCalls,
string[] forActivations,
string when = null)
{
string[] activateCalls = await watcher.GetActivateCalls();
Assert.Equal(expectedActivateCalls, activateCalls.Length);
string[] deactivateCalls = await watcher.GetDeactivateCalls();
Assert.Equal(expectedDeactivateCalls, deactivateCalls.Length);
for (int i = 0; i < expectedActivateCalls; i++)
{
Assert.Equal(forActivations[i], activateCalls[i]);
}
for (int i = 0; i < expectedDeactivateCalls; i++)
{
Assert.Equal(forActivations[i], deactivateCalls[i]);
}
}
private static void AssertIsNotInvalidOperationException(Exception thrownException, string expectedMessageSubstring)
{
Console.WriteLine("Received exception: " + thrownException);
Exception e = thrownException.GetBaseException();
Console.WriteLine("Nested exception type: " + e.GetType().FullName);
Console.WriteLine("Nested exception message: " + e.Message);
Assert.IsAssignableFrom<Exception>(e);
Assert.False(e is InvalidOperationException);
Assert.True(e.Message.Contains(expectedMessageSubstring), "Did not get expected exception message returned: " + e.Message);
}
}
}
| |
/*
* Vericred API
*
* Vericred's API allows you to search for Health Plans that a specific doctor
accepts.
## Getting Started
Visit our [Developer Portal](https://developers.vericred.com) to
create an account.
Once you have created an account, you can create one Application for
Production and another for our Sandbox (select the appropriate Plan when
you create the Application).
## SDKs
Our API follows standard REST conventions, so you can use any HTTP client
to integrate with us. You will likely find it easier to use one of our
[autogenerated SDKs](https://github.com/vericred/?query=vericred-),
which we make available for several common programming languages.
## Authentication
To authenticate, pass the API Key you created in the Developer Portal as
a `Vericred-Api-Key` header.
`curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"`
## Versioning
Vericred's API default to the latest version. However, if you need a specific
version, you can request it with an `Accept-Version` header.
The current version is `v3`. Previous versions are `v1` and `v2`.
`curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"`
## Pagination
Endpoints that accept `page` and `per_page` parameters are paginated. They expose
four additional fields that contain data about your position in the response,
namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988).
For example, to display 5 results per page and view the second page of a
`GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`.
## Sideloading
When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s
we sideload the associated data. In this example, we would provide an Array of
`State`s and a `state_id` for each provider. This is done primarily to reduce the
payload size since many of the `Provider`s will share a `State`
```
{
providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }],
states: [{ id: 1, code: 'NY' }]
}
```
If you need the second level of the object graph, you can just match the
corresponding id.
## Selecting specific data
All endpoints allow you to specify which fields you would like to return.
This allows you to limit the response to contain only the data you need.
For example, let's take a request that returns the following JSON by default
```
{
provider: {
id: 1,
name: 'John',
phone: '1234567890',
field_we_dont_care_about: 'value_we_dont_care_about'
},
states: [{
id: 1,
name: 'New York',
code: 'NY',
field_we_dont_care_about: 'value_we_dont_care_about'
}]
}
```
To limit our results to only return the fields we care about, we specify the
`select` query string parameter for the corresponding fields in the JSON
document.
In this case, we want to select `name` and `phone` from the `provider` key,
so we would add the parameters `select=provider.name,provider.phone`.
We also want the `name` and `code` from the `states` key, so we would
add the parameters `select=states.name,staes.code`. The id field of
each document is always returned whether or not it is requested.
Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code`
The response would be
```
{
provider: {
id: 1,
name: 'John',
phone: '1234567890'
},
states: [{
id: 1,
name: 'New York',
code: 'NY'
}]
}
```
## Benefits summary format
Benefit cost-share strings are formatted to capture:
* Network tiers
* Compound or conditional cost-share
* Limits on the cost-share
* Benefit-specific maximum out-of-pocket costs
**Example #1**
As an example, we would represent [this Summary of Benefits & Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as:
* **Hospital stay facility fees**:
- Network Provider: `$400 copay/admit plus 20% coinsurance`
- Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance`
- Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible`
* **Rehabilitation services:**
- Network Provider: `20% coinsurance`
- Out-of-Network Provider: `50% coinsurance`
- Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.`
- Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period`
**Example #2**
In [this other Summary of Benefits & Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies.
* **Specialty drugs:**
- Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply`
- Out-of-Network Provider `Not covered`
- Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%`
**BNF**
Here's a description of the benefits summary string, represented as a context-free grammar:
```
<cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit>
<tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:"
<opt-num-prefix> ::= "first" <num> <unit> | ""
<unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)"
<value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable"
<compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible>
<copay> ::= "$" <num>
<coinsurace> ::= <num> "%"
<ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited"
<opt-per-unit> ::= "per day" | "per visit" | "per stay" | ""
<deductible> ::= "before deductible" | "after deductible" | ""
<tier-limit> ::= ", " <limit> | ""
<benefit-limit> ::= <limit> | ""
```
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace IO.Vericred.Model
{
/// <summary>
/// CountyBulk
/// </summary>
[DataContract]
public partial class CountyBulk : IEquatable<CountyBulk>
{
/// <summary>
/// Initializes a new instance of the <see cref="CountyBulk" /> class.
/// </summary>
/// <param name="Id">FIPs code for the county.</param>
/// <param name="Name">Name of the county.</param>
/// <param name="StateId">State code.</param>
/// <param name="RatingAreaCount">Count of unique rating areas in the county.</param>
/// <param name="ServiceAreaCount">Count of unique service areas in the county.</param>
public CountyBulk(string Id = null, string Name = null, string StateId = null, string RatingAreaCount = null, string ServiceAreaCount = null)
{
this.Id = Id;
this.Name = Name;
this.StateId = StateId;
this.RatingAreaCount = RatingAreaCount;
this.ServiceAreaCount = ServiceAreaCount;
}
/// <summary>
/// FIPs code for the county
/// </summary>
/// <value>FIPs code for the county</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// Name of the county
/// </summary>
/// <value>Name of the county</value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// State code
/// </summary>
/// <value>State code</value>
[DataMember(Name="state_id", EmitDefaultValue=false)]
public string StateId { get; set; }
/// <summary>
/// Count of unique rating areas in the county
/// </summary>
/// <value>Count of unique rating areas in the county</value>
[DataMember(Name="rating_area_count", EmitDefaultValue=false)]
public string RatingAreaCount { get; set; }
/// <summary>
/// Count of unique service areas in the county
/// </summary>
/// <value>Count of unique service areas in the county</value>
[DataMember(Name="service_area_count", EmitDefaultValue=false)]
public string ServiceAreaCount { 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 CountyBulk {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" StateId: ").Append(StateId).Append("\n");
sb.Append(" RatingAreaCount: ").Append(RatingAreaCount).Append("\n");
sb.Append(" ServiceAreaCount: ").Append(ServiceAreaCount).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 CountyBulk);
}
/// <summary>
/// Returns true if CountyBulk instances are equal
/// </summary>
/// <param name="other">Instance of CountyBulk to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CountyBulk other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.StateId == other.StateId ||
this.StateId != null &&
this.StateId.Equals(other.StateId)
) &&
(
this.RatingAreaCount == other.RatingAreaCount ||
this.RatingAreaCount != null &&
this.RatingAreaCount.Equals(other.RatingAreaCount)
) &&
(
this.ServiceAreaCount == other.ServiceAreaCount ||
this.ServiceAreaCount != null &&
this.ServiceAreaCount.Equals(other.ServiceAreaCount)
);
}
/// <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.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.StateId != null)
hash = hash * 59 + this.StateId.GetHashCode();
if (this.RatingAreaCount != null)
hash = hash * 59 + this.RatingAreaCount.GetHashCode();
if (this.ServiceAreaCount != null)
hash = hash * 59 + this.ServiceAreaCount.GetHashCode();
return hash;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Services.Connectors.Friends;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using OpenMetaverse;
using log4net;
using Nini.Config;
namespace OpenSim.Services.HypergridService
{
/// <summary>
/// W2W social networking
/// </summary>
public class HGFriendsService : IHGFriendsService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
static bool m_Initialized = false;
protected static IGridUserService m_GridUserService;
protected static IGridService m_GridService;
protected static IGatekeeperService m_GatekeeperService;
protected static IFriendsService m_FriendsService;
protected static IPresenceService m_PresenceService;
protected static IUserAccountService m_UserAccountService;
protected static IFriendsSimConnector m_FriendsLocalSimConnector; // standalone, points to HGFriendsModule
protected static FriendsSimConnector m_FriendsSimConnector; // grid
private static string m_ConfigName = "HGFriendsService";
public HGFriendsService(IConfigSource config, String configName, IFriendsSimConnector localSimConn)
{
if (m_FriendsLocalSimConnector == null)
m_FriendsLocalSimConnector = localSimConn;
if (!m_Initialized)
{
m_Initialized = true;
if (configName != String.Empty)
m_ConfigName = configName;
Object[] args = new Object[] { config };
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null)
throw new Exception(String.Format("No section {0} in config file", m_ConfigName));
string theService = serverConfig.GetString("FriendsService", string.Empty);
if (theService == String.Empty)
throw new Exception("No FriendsService in config file " + m_ConfigName);
m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(theService, args);
theService = serverConfig.GetString("UserAccountService", string.Empty);
if (theService == String.Empty)
throw new Exception("No UserAccountService in " + m_ConfigName);
m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(theService, args);
theService = serverConfig.GetString("GridService", string.Empty);
if (theService == String.Empty)
throw new Exception("No GridService in " + m_ConfigName);
m_GridService = ServerUtils.LoadPlugin<IGridService>(theService, args);
theService = serverConfig.GetString("PresenceService", string.Empty);
if (theService == String.Empty)
throw new Exception("No PresenceService in " + m_ConfigName);
m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(theService, args);
m_FriendsSimConnector = new FriendsSimConnector();
m_log.DebugFormat("[HGFRIENDS SERVICE]: Starting...");
}
}
#region IHGFriendsService
public int GetFriendPerms(UUID userID, UUID friendID)
{
FriendInfo[] friendsInfo = m_FriendsService.GetFriends(userID);
foreach (FriendInfo finfo in friendsInfo)
{
if (finfo.Friend.StartsWith(friendID.ToString()))
return finfo.TheirFlags;
}
return -1;
}
public bool NewFriendship(FriendInfo friend, bool verified)
{
UUID friendID;
string tmp = string.Empty, url = String.Empty, first = String.Empty, last = String.Empty;
if (!Util.ParseUniversalUserIdentifier(friend.Friend, out friendID, out url, out first, out last, out tmp))
return false;
m_log.DebugFormat("[HGFRIENDS SERVICE]: New friendship {0} {1} ({2})", friend.PrincipalID, friend.Friend, verified);
// Does the friendship already exist?
FriendInfo[] finfos = m_FriendsService.GetFriends(friend.PrincipalID);
foreach (FriendInfo finfo in finfos)
{
if (finfo.Friend.StartsWith(friendID.ToString()))
return false;
}
// Verified user session. But the user needs to confirm friendship when he gets home
if (verified)
return m_FriendsService.StoreFriend(friend.PrincipalID.ToString(), friend.Friend, 0);
// Does the reverted friendship exist? meaning that this user initiated the request
finfos = m_FriendsService.GetFriends(friendID);
bool userInitiatedOffer = false;
foreach (FriendInfo finfo in finfos)
{
if (friend.Friend.StartsWith(finfo.PrincipalID.ToString()) && finfo.Friend.StartsWith(friend.PrincipalID.ToString()) && finfo.TheirFlags == -1)
{
userInitiatedOffer = true;
// Let's delete the existing friendship relations that was stored
m_FriendsService.Delete(friendID, finfo.Friend);
break;
}
}
if (userInitiatedOffer)
{
m_FriendsService.StoreFriend(friend.PrincipalID.ToString(), friend.Friend, 1);
m_FriendsService.StoreFriend(friend.Friend, friend.PrincipalID.ToString(), 1);
// notify the user
ForwardToSim("ApproveFriendshipRequest", friendID, Util.UniversalName(first, last, url), "", friend.PrincipalID, "");
return true;
}
return false;
}
public bool DeleteFriendship(FriendInfo friend, string secret)
{
FriendInfo[] finfos = m_FriendsService.GetFriends(friend.PrincipalID);
foreach (FriendInfo finfo in finfos)
{
// We check the secret here. Or if the friendship request was initiated here, and was declined
if (finfo.Friend.StartsWith(friend.Friend) && finfo.Friend.EndsWith(secret))
{
m_log.DebugFormat("[HGFRIENDS SERVICE]: Delete friendship {0} {1}", friend.PrincipalID, friend.Friend);
m_FriendsService.Delete(friend.PrincipalID, finfo.Friend);
m_FriendsService.Delete(finfo.Friend, friend.PrincipalID.ToString());
return true;
}
}
return false;
}
public bool FriendshipOffered(UUID fromID, string fromName, UUID toID, string message)
{
UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, toID);
if (account == null)
return false;
// OK, we have that user here.
// So let's send back the call, but start a thread to continue
// with the verification and the actual action.
Util.FireAndForget(delegate { ProcessFriendshipOffered(fromID, fromName, toID, message); });
return true;
}
public bool ValidateFriendshipOffered(UUID fromID, UUID toID)
{
FriendInfo[] finfos = m_FriendsService.GetFriends(toID.ToString());
foreach (FriendInfo fi in finfos)
{
if (fi.Friend.StartsWith(fromID.ToString()) && fi.TheirFlags == -1)
return true;
}
return false;
}
public List<UUID> StatusNotification(List<string> friends, UUID foreignUserID, bool online)
{
if (m_FriendsService == null || m_PresenceService == null)
{
m_log.WarnFormat("[HGFRIENDS SERVICE]: Unable to perform status notifications because friends or presence services are missing");
return new List<UUID>();
}
// Let's unblock the caller right now, and take it from here async
List<UUID> localFriendsOnline = new List<UUID>();
m_log.DebugFormat("[HGFRIENDS SERVICE]: Status notification: foreign user {0} wants to notify {1} local friends of {2} status",
foreignUserID, friends.Count, (online ? "online" : "offline"));
// First, let's double check that the reported friends are, indeed, friends of that user
// And let's check that the secret matches
List<string> usersToBeNotified = new List<string>();
foreach (string uui in friends)
{
UUID localUserID;
string secret = string.Empty, tmp = string.Empty;
if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
{
FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
foreach (FriendInfo finfo in friendInfos)
{
if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret))
{
// great!
usersToBeNotified.Add(localUserID.ToString());
}
}
}
}
// Now, let's send the notifications
//m_log.DebugFormat("[HGFRIENDS SERVICE]: Status notification: user has {0} local friends", usersToBeNotified.Count);
// First, let's send notifications to local users who are online in the home grid
PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
if (friendSessions != null && friendSessions.Length > 0)
{
PresenceInfo friendSession = null;
foreach (PresenceInfo pinfo in friendSessions)
if (pinfo.RegionID != UUID.Zero) // let's guard against traveling agents
{
friendSession = pinfo;
break;
}
if (friendSession != null)
{
ForwardStatusNotificationToSim(friendSession.RegionID, foreignUserID, friendSession.UserID, online);
usersToBeNotified.Remove(friendSession.UserID.ToString());
UUID id;
if (UUID.TryParse(friendSession.UserID, out id))
localFriendsOnline.Add(id);
}
}
// // Lastly, let's notify the rest who may be online somewhere else
// foreach (string user in usersToBeNotified)
// {
// UUID id = new UUID(user);
// //m_UserAgentService.LocateUser(id);
// //etc...
// //if (m_TravelingAgents.ContainsKey(id) && m_TravelingAgents[id].GridExternalName != m_GridName)
// //{
// // string url = m_TravelingAgents[id].GridExternalName;
// // // forward
// //}
// //m_log.WarnFormat("[HGFRIENDS SERVICE]: User {0} is visiting another grid. HG Status notifications still not implemented.", user);
// }
// and finally, let's send the online friends
if (online)
{
return localFriendsOnline;
}
else
return new List<UUID>();
}
#endregion IHGFriendsService
#region Aux
private void ProcessFriendshipOffered(UUID fromID, String fromName, UUID toID, String message)
{
// Great, it's a genuine request. Let's proceed.
// But now we need to confirm that the requester is who he says he is
// before we act on the friendship request.
if (!fromName.Contains("@"))
return;
string[] parts = fromName.Split(new char[] {'@'});
if (parts.Length != 2)
return;
string uriStr = "http://" + parts[1];
try
{
new Uri(uriStr);
}
catch (UriFormatException)
{
return;
}
UserAgentServiceConnector uasConn = new UserAgentServiceConnector(uriStr);
Dictionary<string, object> servers = uasConn.GetServerURLs(fromID);
if (!servers.ContainsKey("FriendsServerURI"))
return;
HGFriendsServicesConnector friendsConn = new HGFriendsServicesConnector(servers["FriendsServerURI"].ToString());
if (!friendsConn.ValidateFriendshipOffered(fromID, toID))
{
m_log.WarnFormat("[HGFRIENDS SERVICE]: Friendship request from {0} to {1} is invalid. Impersonations?", fromID, toID);
return;
}
string fromUUI = Util.UniversalIdentifier(fromID, parts[0], "@" + parts[1], uriStr);
// OK, we're good!
ForwardToSim("FriendshipOffered", fromID, fromName, fromUUI, toID, message);
}
private bool ForwardToSim(string op, UUID fromID, string name, String fromUUI, UUID toID, string message)
{
PresenceInfo session = null;
GridRegion region = null;
PresenceInfo[] sessions = m_PresenceService.GetAgents(new string[] { toID.ToString() });
if (sessions != null && sessions.Length > 0)
session = sessions[0];
if (session != null)
region = m_GridService.GetRegionByUUID(UUID.Zero, session.RegionID);
switch (op)
{
case "FriendshipOffered":
// Let's store backwards
string secret = UUID.Random().ToString().Substring(0, 8);
m_FriendsService.StoreFriend(toID.ToString(), fromUUI + ";" + secret, 0);
if (m_FriendsLocalSimConnector != null) // standalone
{
GridInstantMessage im = new GridInstantMessage(null, fromID, name, toID,
(byte)InstantMessageDialog.FriendshipOffered, message, false, Vector3.Zero);
// !! HACK
im.imSessionID = im.fromAgentID;
return m_FriendsLocalSimConnector.LocalFriendshipOffered(toID, im);
}
else if (region != null) // grid
return m_FriendsSimConnector.FriendshipOffered(region, fromID, toID, message, name);
break;
case "ApproveFriendshipRequest":
if (m_FriendsLocalSimConnector != null) // standalone
return m_FriendsLocalSimConnector.LocalFriendshipApproved(fromID, name, toID);
else if (region != null) //grid
return m_FriendsSimConnector.FriendshipApproved(region, fromID, name, toID);
break;
}
return false;
}
protected void ForwardStatusNotificationToSim(UUID regionID, UUID foreignUserID, string user, bool online)
{
UUID userID;
if (UUID.TryParse(user, out userID))
{
if (m_FriendsLocalSimConnector != null)
{
m_log.DebugFormat("[HGFRIENDS SERVICE]: Local Notify, user {0} is {1}", foreignUserID, (online ? "online" : "offline"));
m_FriendsLocalSimConnector.StatusNotify(foreignUserID, userID, online);
}
else
{
GridRegion region = m_GridService.GetRegionByUUID(UUID.Zero /* !!! */, regionID);
if (region != null)
{
m_log.DebugFormat("[HGFRIENDS SERVICE]: Remote Notify to region {0}, user {1} is {2}", region.RegionName, foreignUserID, (online ? "online" : "offline"));
m_FriendsSimConnector.StatusNotify(region, foreignUserID, userID.ToString(), online);
}
}
}
}
#endregion Aux
}
}
| |
//******************************************************************************************************************************************************************************************//
// Public Domain //
// //
// Written by Peter O. in 2014. //
// //
// Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ //
// //
// If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ //
//******************************************************************************************************************************************************************************************//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor.Numbers;
namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor
{
internal static class PropertyMap {
private sealed class ReadOnlyWrapper<T> : ICollection<T> {
private readonly ICollection<T> o;
public ReadOnlyWrapper(ICollection<T> o) {
this.o = o;
}
public void Add(T v) {
throw new NotSupportedException();
}
public void Clear() {
throw new NotSupportedException();
}
public void CopyTo(T[] a, int off) {
this.o.CopyTo(a, off);
}
public bool Remove(T v) {
throw new NotSupportedException();
}
public bool Contains(T v) {
return this.o.Contains(v);
}
public int Count {
get {
return this.o.Count;
}
}
public bool IsReadOnly {
get {
return true;
}
}
public IEnumerator<T> GetEnumerator() {
return this.o.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return ((IEnumerable)this.o).GetEnumerator();
}
}
private sealed class PropertyData {
private string name;
public string Name {
get {
return this.name;
}
set {
this.name = value;
}
}
private MemberInfo prop;
public Type PropertyType {
get {
var pr = this.prop as PropertyInfo;
if (pr != null) {
return pr.PropertyType;
}
var fi = this.prop as FieldInfo;
return (fi != null) ? fi.FieldType : null;
}
}
public object GetValue(object obj) {
var pr = this.prop as PropertyInfo;
if (pr != null) {
return pr.GetValue(obj, null);
}
var fi = this.prop as FieldInfo;
return (fi != null) ? fi.GetValue(obj) : null;
}
public void SetValue(object obj, object value) {
var pr = this.prop as PropertyInfo;
if (pr != null) {
pr.SetValue(obj, value, null);
}
var fi = this.prop as FieldInfo;
if (fi != null) {
fi.SetValue(obj, value);
}
}
#if NET20 || NET40
public static bool HasUsableGetter(PropertyInfo pi) {
return pi != null && pi.CanRead && !pi.GetGetMethod().IsStatic &&
pi.GetGetMethod().IsPublic;
}
public static bool HasUsableSetter(PropertyInfo pi) {
return pi != null && pi.CanWrite && !pi.GetSetMethod().IsStatic &&
pi.GetSetMethod().IsPublic;
}
#else
public static bool HasUsableGetter(PropertyInfo pi) {
return pi != null && pi.CanRead && !pi.GetMethod.IsStatic &&
pi.GetMethod.IsPublic;
}
public static bool HasUsableSetter(PropertyInfo pi) {
return pi != null && pi.CanWrite && !pi.SetMethod.IsStatic &&
pi.SetMethod.IsPublic;
}
#endif
public bool HasUsableGetter() {
var pr = this.prop as PropertyInfo;
if (pr != null) {
return HasUsableGetter(pr);
}
var fi = this.prop as FieldInfo;
return fi != null && fi.IsPublic && !fi.IsStatic &&
!fi.IsInitOnly && !fi.IsLiteral;
}
public bool HasUsableSetter() {
var pr = this.prop as PropertyInfo;
if (pr != null) {
return HasUsableSetter(pr);
}
var fi = this.prop as FieldInfo;
return fi != null && fi.IsPublic && !fi.IsStatic &&
!fi.IsInitOnly && !fi.IsLiteral;
}
public string GetAdjustedName(bool useCamelCase) {
string thisName = this.Name;
if (useCamelCase) {
if (CBORUtilities.NameStartsWithWord(thisName, "Is")) {
thisName = thisName.Substring(2);
}
thisName = CBORUtilities.FirstCharLower(thisName);
} else {
thisName = CBORUtilities.FirstCharUpper(thisName);
}
return thisName;
}
public MemberInfo Prop {
get {
return this.prop;
}
set {
this.prop = value;
}
}
}
#if NET40 || NET20
private static bool IsGenericType(Type type) {
return type.IsGenericType;
}
private static IEnumerable<PropertyInfo> GetTypeProperties(Type t) {
return t.GetProperties(BindingFlags.Public |
BindingFlags.Instance);
}
private static IEnumerable<FieldInfo> GetTypeFields(Type t) {
return t.GetFields(BindingFlags.Public | BindingFlags.Instance);
}
private static bool IsAssignableFrom(Type superType, Type subType) {
return superType.IsAssignableFrom(subType);
}
private static MethodInfo GetTypeMethod(
Type t,
string name,
Type[] parameters) {
return t.GetMethod(name, parameters);
}
private static bool HasCustomAttribute(
Type t,
string name) {
foreach (var attr in t.GetCustomAttributes(false)) {
if (attr.GetType().FullName.Equals(name,
StringComparison.Ordinal)) {
return true;
}
}
return false;
}
#else
private static bool IsGenericType(Type type) {
return type.GetTypeInfo().IsGenericType;
}
private static bool IsAssignableFrom(Type superType, Type subType) {
return
superType.GetTypeInfo().IsAssignableFrom(subType.GetTypeInfo());
}
private static IEnumerable<PropertyInfo> GetTypeProperties(Type t) {
return t.GetRuntimeProperties();
}
private static IEnumerable<FieldInfo> GetTypeFields(Type t) {
return t.GetRuntimeFields();
}
private static MethodInfo GetTypeMethod(
Type t,
string name,
Type[] parameters) {
return t.GetRuntimeMethod(name, parameters);
}
private static bool HasCustomAttribute(
Type t,
string name) {
foreach (var attr in t.GetTypeInfo().GetCustomAttributes()) {
if (attr.GetType().FullName.Equals(name, StringComparison.Ordinal)) {
return true;
}
}
return false;
}
#endif
private static readonly IDictionary<Type, IList<PropertyData>>
ValuePropertyLists = new Dictionary<Type, IList<PropertyData>>();
private static string RemoveIsPrefix(string pn) {
return CBORUtilities.NameStartsWithWord(pn, "Is") ? pn.Substring(2) :
pn;
}
private static IList<PropertyData> GetPropertyList(Type t) {
lock (ValuePropertyLists) {
IList<PropertyData> ret = new List<PropertyData>();
if (ValuePropertyLists.ContainsKey(t)) {
return ValuePropertyLists[t];
}
bool anonymous = HasCustomAttribute(
t,
"System.Runtime.CompilerServices.CompilerGeneratedAttribute") ||
HasCustomAttribute(
t,
"Microsoft.FSharp.Core.CompilationMappingAttribute");
var names = new Dictionary<string, int>();
foreach (PropertyInfo pi in GetTypeProperties(t)) {
var pn = RemoveIsPrefix(pi.Name);
if (names.ContainsKey(pn)) {
++names[pn];
} else {
names[pn] = 1;
}
}
foreach (FieldInfo pi in GetTypeFields(t)) {
var pn = RemoveIsPrefix(pi.Name);
if (names.ContainsKey(pn)) {
++names[pn];
} else {
names[pn] = 1;
}
}
foreach (FieldInfo fi in GetTypeFields(t)) {
PropertyData pd = new PropertyMap.PropertyData() {
Name = fi.Name,
Prop = fi,
};
if (pd.HasUsableGetter() || pd.HasUsableSetter()) {
var pn = RemoveIsPrefix(pd.Name);
// Ignore ambiguous properties
if (names.ContainsKey(pn) && names[pn] > 1) {
continue;
}
ret.Add(pd);
}
}
foreach (PropertyInfo pi in GetTypeProperties(t)) {
if (pi.CanRead && (pi.CanWrite || anonymous) &&
pi.GetIndexParameters().Length == 0) {
if (PropertyData.HasUsableGetter(pi) ||
PropertyData.HasUsableSetter(pi)) {
var pn = RemoveIsPrefix(pi.Name);
// Ignore ambiguous properties
if (names.ContainsKey(pn) && names[pn] > 1) {
continue;
}
PropertyData pd = new PropertyMap.PropertyData() {
Name = pi.Name,
Prop = pi,
};
ret.Add(pd);
}
}
}
ValuePropertyLists.Add(
t,
ret);
return ret;
}
}
public static bool ExceedsKnownLength(Stream inStream, long size) {
return (inStream is MemoryStream) && (size > (inStream.Length -
inStream.Position));
}
public static void SkipStreamToEnd(Stream inStream) {
if (inStream is MemoryStream) {
inStream.Position = inStream.Length;
}
}
public static bool FirstElement(int[] dimensions) {
foreach (var d in dimensions) {
if (d == 0) {
return false;
}
}
return true;
}
public static bool NextElement(int[] index, int[] dimensions) {
for (var i = dimensions.Length - 1; i >= 0; --i) {
if (dimensions[i] > 0) {
++index[i];
if (index[i] >= dimensions[i]) {
index[i] = 0;
} else {
return true;
}
}
}
return false;
}
public static CBORObject BuildCBORArray(int[] dimensions) {
int zeroPos = dimensions.Length;
for (var i = 0; i < dimensions.Length; ++i) {
if (dimensions[i] == 0) {
{
zeroPos = i;
}
break;
}
}
int arraydims = zeroPos - 1;
if (arraydims <= 0) {
return CBORObject.NewArray();
}
var stack = new CBORObject[zeroPos];
var index = new int[zeroPos];
var stackpos = 0;
CBORObject ret = CBORObject.NewArray();
stack[0] = ret;
index[0] = 0;
for (var i = 0; i < dimensions[0]; ++i) {
ret.Add(CBORObject.NewArray());
}
++stackpos;
while (stackpos > 0) {
int curindex = index[stackpos - 1];
if (curindex < stack[stackpos - 1].Count) {
CBORObject subobj = stack[stackpos - 1][curindex];
if (stackpos < zeroPos) {
stack[stackpos] = subobj;
index[stackpos] = 0;
for (var i = 0; i < dimensions[stackpos]; ++i) {
subobj.Add(CBORObject.NewArray());
}
++index[stackpos - 1];
++stackpos;
} else {
++index[stackpos - 1];
}
} else {
--stackpos;
}
}
return ret;
}
public static CBORObject FromArray(
Object arrObj,
PODOptions options,
CBORTypeMapper mapper,
int depth) {
var arr = (Array)arrObj;
int rank = arr.Rank;
if (rank == 0) {
return CBORObject.NewArray();
}
CBORObject obj = null;
if (rank == 1) {
// Most common case: the array is one-dimensional
obj = CBORObject.NewArray();
int len = arr.GetLength(0);
for (var i = 0; i < len; ++i) {
obj.Add(
CBORObject.FromObject(
arr.GetValue(i),
options,
mapper,
depth + 1));
}
return obj;
}
var index = new int[rank];
var dimensions = new int[rank];
for (var i = 0; i < rank; ++i) {
dimensions[i] = arr.GetLength(i);
}
if (!FirstElement(dimensions)) {
return obj;
}
obj = BuildCBORArray(dimensions);
do {
CBORObject o = CBORObject.FromObject(
arr.GetValue(index),
options,
mapper,
depth + 1);
SetCBORObject(obj, index, o);
} while (NextElement(index, dimensions));
return obj;
}
private static CBORObject GetCBORObject(CBORObject cbor, int[] index) {
CBORObject ret = cbor;
foreach (var i in index) {
ret = ret[i];
}
return ret;
}
private static void SetCBORObject(
CBORObject cbor,
int[] index,
CBORObject obj) {
CBORObject ret = cbor;
for (var i = 0; i < index.Length - 1; ++i) {
ret = ret[index[i]];
}
int ilen = index[index.Length - 1];
while (ilen >= ret.Count) {
{
ret.Add(CBORObject.Null);
}
}
ret[ilen] = obj;
}
public static Array FillArray(
Array arr,
Type elementType,
CBORObject cbor,
CBORTypeMapper mapper,
PODOptions options,
int depth) {
int rank = arr.Rank;
if (rank == 0) {
return arr;
}
if (rank == 1) {
int len = arr.GetLength(0);
for (var i = 0; i < len; ++i) {
object item = cbor[i].ToObject(
elementType,
mapper,
options,
depth + 1);
arr.SetValue(
item,
i);
}
return arr;
}
var index = new int[rank];
var dimensions = new int[rank];
for (var i = 0; i < rank; ++i) {
dimensions[i] = arr.GetLength(i);
}
if (!FirstElement(dimensions)) {
return arr;
}
do {
object item = GetCBORObject(
cbor,
index).ToObject(
elementType,
mapper,
options,
depth + 1);
arr.SetValue(
item,
index);
} while (NextElement(index, dimensions));
return arr;
}
public static int[] GetDimensions(CBORObject obj) {
if (obj.Type != CBORType.Array) {
throw new CBORException();
}
// Common cases
if (obj.Count == 0) {
return new int[] { 0 };
}
if (obj[0].Type != CBORType.Array) {
return new int[] { obj.Count };
}
// Complex cases
var list = new List<int>();
list.Add(obj.Count);
while (obj.Type == CBORType.Array &&
obj.Count > 0 && obj[0].Type == CBORType.Array) {
list.Add(obj[0].Count);
obj = obj[0];
}
return list.ToArray();
}
public static object ObjectToEnum(CBORObject obj, Type enumType) {
Type utype = Enum.GetUnderlyingType(enumType);
object ret = null;
if (obj.IsNumber && obj.AsNumber().IsInteger()) {
ret = Enum.ToObject(enumType, TypeToIntegerObject(obj, utype));
if (!Enum.IsDefined(enumType, ret)) {
throw new CBORException("Unrecognized enum value: " +
obj.ToString());
}
return ret;
} else if (obj.Type == CBORType.TextString) {
var nameString = obj.AsString();
foreach (var name in Enum.GetNames(enumType)) {
if (nameString.Equals(name, StringComparison.Ordinal)) {
return Enum.Parse(enumType, name);
}
}
throw new CBORException("Not found: " + obj.ToString());
} else {
throw new CBORException("Unrecognized enum value: " +
obj.ToString());
}
}
public static object EnumToObject(Enum value) {
return value.ToString();
}
public static object EnumToObjectAsInteger(Enum value) {
Type t = Enum.GetUnderlyingType(value.GetType());
if (t.Equals(typeof(ulong))) {
ulong uvalue = Convert.ToUInt64(value,
CultureInfo.InvariantCulture);
return EInteger.FromUInt64(uvalue);
}
return t.Equals(typeof(long)) ? Convert.ToInt64(value,
CultureInfo.InvariantCulture) : (t.Equals(typeof(uint)) ?
Convert.ToInt64(value,
CultureInfo.InvariantCulture) :
Convert.ToInt32(value, CultureInfo.InvariantCulture));
}
public static ICollection<KeyValuePair<TKey, TValue>>
GetEntries<TKey, TValue>(
IDictionary<TKey, TValue> dict) {
var c = (ICollection<KeyValuePair<TKey, TValue>>)dict;
return new ReadOnlyWrapper<KeyValuePair<TKey, TValue>>(c);
}
public static object FindOneArgumentMethod(
object obj,
string name,
Type argtype) {
return GetTypeMethod(obj.GetType(), name, new[] { argtype });
}
public static object InvokeOneArgumentMethod(
object methodInfo,
object obj,
object argument) {
return ((MethodInfo)methodInfo).Invoke(obj, new[] { argument });
}
public static byte[] UUIDToBytes(Guid guid) {
var bytes2 = new byte[16];
var bytes = guid.ToByteArray();
Array.Copy(bytes, bytes2, 16);
// Swap the bytes to conform with the UUID RFC
bytes2[0] = bytes[3];
bytes2[1] = bytes[2];
bytes2[2] = bytes[1];
bytes2[3] = bytes[0];
bytes2[4] = bytes[5];
bytes2[5] = bytes[4];
bytes2[6] = bytes[7];
bytes2[7] = bytes[6];
return bytes2;
}
private static bool StartsWith(string str, string pfx) {
return str != null && str.Length >= pfx.Length &&
str.Substring(0, pfx.Length).Equals(pfx, StringComparison.Ordinal);
}
// TODO: Replace* Legacy with AsNumber methods
// in next major version
private static object TypeToIntegerObject(CBORObject objThis, Type t) {
if (t.Equals(typeof(int))) {
return objThis.AsInt32();
}
if (t.Equals(typeof(short))) {
return objThis.AsNumber().ToInt16Checked();
}
if (t.Equals(typeof(ushort))) {
return objThis.AsUInt16Legacy();
}
if (t.Equals(typeof(byte))) {
return objThis.AsByteLegacy();
}
if (t.Equals(typeof(sbyte))) {
return objThis.AsSByteLegacy();
}
if (t.Equals(typeof(long))) {
return objThis.AsNumber().ToInt64Checked();
}
if (t.Equals(typeof(uint))) {
return objThis.AsUInt32Legacy();
}
if (t.Equals(typeof(ulong))) {
return objThis.AsUInt64Legacy();
}
throw new CBORException("Type not supported");
}
public static object TypeToObject(
CBORObject objThis,
Type t,
CBORTypeMapper mapper,
PODOptions options,
int depth) {
if (t.Equals(typeof(int))) {
return objThis.AsInt32();
}
if (t.Equals(typeof(short))) {
return objThis.AsNumber().ToInt16Checked();
}
if (t.Equals(typeof(ushort))) {
return objThis.AsUInt16Legacy();
}
if (t.Equals(typeof(byte))) {
return objThis.AsByteLegacy();
}
if (t.Equals(typeof(sbyte))) {
return objThis.AsSByteLegacy();
}
if (t.Equals(typeof(long))) {
return objThis.AsNumber().ToInt64Checked();
}
if (t.Equals(typeof(uint))) {
return objThis.AsUInt32Legacy();
}
if (t.Equals(typeof(ulong))) {
return objThis.AsUInt64Legacy();
}
if (t.Equals(typeof(double))) {
return objThis.AsDouble();
}
if (t.Equals(typeof(decimal))) {
return objThis.AsDecimal();
}
if (t.Equals(typeof(float))) {
return objThis.AsSingle();
}
if (t.Equals(typeof(bool))) {
return objThis.AsBoolean();
}
if (t.Equals(typeof(char))) {
if (objThis.Type == CBORType.TextString) {
string s = objThis.AsString();
if (s.Length != 1) {
throw new CBORException("Can't convert to char");
}
return s[0];
}
if (objThis.IsNumber && objThis.AsNumber().CanFitInInt32()) {
int c = objThis.AsNumber().ToInt32IfExact();
if (c < 0 || c >= 0x10000) {
throw new CBORException("Can't convert to char");
}
return (char)c;
}
throw new CBORException("Can't convert to char");
}
if (t.Equals(typeof(DateTime))) {
return new CBORDateConverter().FromCBORObject(objThis);
}
if (t.Equals(typeof(Guid))) {
return new CBORUuidConverter().FromCBORObject(objThis);
}
if (t.Equals(typeof(Uri))) {
return new CBORUriConverter().FromCBORObject(objThis);
}
if (IsAssignableFrom(typeof(Enum), t)) {
return ObjectToEnum(objThis, t);
}
if (IsGenericType(t)) {
Type td = t.GetGenericTypeDefinition();
// Nullable types
if (td.Equals(typeof(Nullable<>))) {
Type nullableType = Nullable.GetUnderlyingType(t);
if (objThis.IsNull) {
return Activator.CreateInstance(t);
} else {
object wrappedObj = objThis.ToObject(
nullableType,
mapper,
options,
depth + 1);
return Activator.CreateInstance(
t,
wrappedObj);
}
}
}
if (objThis.Type == CBORType.ByteString) {
if (t.Equals(typeof(byte[]))) {
byte[] bytes = objThis.GetByteString();
var byteret = new byte[bytes.Length];
Array.Copy(bytes, 0, byteret, 0, byteret.Length);
return byteret;
}
}
if (objThis.Type == CBORType.Array) {
Type objectType = typeof(object);
var isList = false;
object listObject = null;
#if NET40 || NET20
if (IsAssignableFrom(typeof(Array), t)) {
Type elementType = t.GetElementType();
Array array = Array.CreateInstance(
elementType,
GetDimensions(objThis));
return FillArray(
array,
elementType,
objThis,
mapper,
options,
depth);
}
if (t.IsGenericType) {
Type td = t.GetGenericTypeDefinition();
isList = td.Equals(typeof(List<>)) || td.Equals(typeof(IList<>)) ||
td.Equals(typeof(ICollection<>)) ||
td.Equals(typeof(IEnumerable<>));
}
isList = isList && t.GetGenericArguments().Length == 1;
if (isList) {
objectType = t.GetGenericArguments()[0];
Type listType = typeof(List<>).MakeGenericType(objectType);
listObject = Activator.CreateInstance(listType);
}
#else
if (IsAssignableFrom(typeof(Array), t)) {
Type elementType = t.GetElementType();
Array array = Array.CreateInstance(
elementType,
GetDimensions(objThis));
return FillArray(
array,
elementType,
objThis,
mapper,
options,
depth);
}
if (t.GetTypeInfo().IsGenericType) {
Type td = t.GetGenericTypeDefinition();
isList = td.Equals(typeof(List<>)) || td.Equals(typeof(IList<>)) ||
td.Equals(typeof(ICollection<>)) ||
td.Equals(typeof(IEnumerable<>));
}
isList = isList && t.GenericTypeArguments.Length == 1;
if (isList) {
objectType = t.GenericTypeArguments[0];
Type listType = typeof(List<>).MakeGenericType(objectType);
listObject = Activator.CreateInstance(listType);
}
#endif
if (listObject == null) {
if (t.Equals(typeof(IList)) ||
t.Equals(typeof(ICollection)) || t.Equals(typeof(IEnumerable))) {
listObject = new List<object>();
objectType = typeof(object);
}
}
if (listObject != null) {
System.Collections.IList ie = (System.Collections.IList)listObject;
foreach (CBORObject value in objThis.Values) {
ie.Add(value.ToObject(objectType, mapper, options, depth + 1));
}
return listObject;
}
}
if (objThis.Type == CBORType.Map) {
var isDict = false;
Type keyType = null;
Type valueType = null;
object dictObject = null;
#if NET40 || NET20
isDict = t.IsGenericType;
if (t.IsGenericType) {
Type td = t.GetGenericTypeDefinition();
isDict = td.Equals(typeof(Dictionary<,>)) ||
td.Equals(typeof(IDictionary<,>));
}
// DebugUtility.Log("list=" + isDict);
isDict = isDict && t.GetGenericArguments().Length == 2;
// DebugUtility.Log("list=" + isDict);
if (isDict) {
keyType = t.GetGenericArguments()[0];
valueType = t.GetGenericArguments()[1];
Type listType = typeof(Dictionary<,>).MakeGenericType(
keyType,
valueType);
dictObject = Activator.CreateInstance(listType);
}
#else
isDict = t.GetTypeInfo().IsGenericType;
if (t.GetTypeInfo().IsGenericType) {
Type td = t.GetGenericTypeDefinition();
isDict = td.Equals(typeof(Dictionary<,>)) ||
td.Equals(typeof(IDictionary<,>));
}
// DebugUtility.Log("list=" + isDict);
isDict = isDict && t.GenericTypeArguments.Length == 2;
// DebugUtility.Log("list=" + isDict);
if (isDict) {
keyType = t.GenericTypeArguments[0];
valueType = t.GenericTypeArguments[1];
Type listType = typeof(Dictionary<,>).MakeGenericType(
keyType,
valueType);
dictObject = Activator.CreateInstance(listType);
}
#endif
if (dictObject == null) {
if (t.Equals(typeof(IDictionary))) {
dictObject = new Dictionary<object, object>();
keyType = typeof(object);
valueType = typeof(object);
}
}
if (dictObject != null) {
System.Collections.IDictionary idic =
(System.Collections.IDictionary)dictObject;
foreach (CBORObject key in objThis.Keys) {
CBORObject value = objThis[key];
idic.Add(
key.ToObject(keyType, mapper, options, depth + 1),
value.ToObject(valueType, mapper, options, depth + 1));
}
return dictObject;
}
if (mapper != null) {
if (!mapper.FilterTypeName(t.FullName)) {
throw new CBORException("Type " + t.FullName +
" not supported");
}
} else {
if (t.FullName != null && (
StartsWith(t.FullName, "Microsoft.Win32.") ||
StartsWith(t.FullName, "System.IO."))) {
throw new CBORException("Type " + t.FullName +
" not supported");
}
if (StartsWith(t.FullName, "System.") &&
!HasCustomAttribute(t, "System.SerializableAttribute")) {
throw new CBORException("Type " + t.FullName +
" not supported");
}
}
var values = new List<KeyValuePair<string, CBORObject>>();
var propNames = PropertyMap.GetPropertyNames(
t,
options != null ? options.UseCamelCase : true);
foreach (string key in propNames) {
if (objThis.ContainsKey(key)) {
CBORObject cborValue = objThis[key];
var dict = new KeyValuePair<string, CBORObject>(
key,
cborValue);
values.Add(dict);
}
}
return PropertyMap.ObjectWithProperties(
t,
values,
mapper,
options,
depth);
} else {
throw new CBORException();
}
}
public static object ObjectWithProperties(
Type t,
IEnumerable<KeyValuePair<string, CBORObject>> keysValues,
CBORTypeMapper mapper,
PODOptions options,
int depth) {
try {
object o = Activator.CreateInstance(t);
var dict = new Dictionary<string, CBORObject>();
foreach (var kv in keysValues) {
var name = kv.Key;
dict[name] = kv.Value;
}
foreach (PropertyData key in GetPropertyList(o.GetType())) {
if (!key.HasUsableSetter() || !key.HasUsableGetter()) {
// Require properties to have both a setter and
// a getter to be eligible for setting
continue;
}
var name = key.GetAdjustedName(options != null ?
options.UseCamelCase : true);
if (dict.ContainsKey(name)) {
object dobj = dict[name].ToObject(
key.PropertyType,
mapper,
options,
depth + 1);
key.SetValue(
o,
dobj);
}
}
return o;
} catch (Exception ex) {
throw new CBORException(ex.Message, ex);
}
}
public static CBORObject CallToObject(
CBORTypeMapper.ConverterInfo convinfo,
object obj) {
return (CBORObject)PropertyMap.InvokeOneArgumentMethod(
convinfo.ToObject,
convinfo.Converter,
obj);
}
public static object CallFromObject(
CBORTypeMapper.ConverterInfo convinfo,
CBORObject obj) {
return (object)PropertyMap.InvokeOneArgumentMethod(
convinfo.FromObject,
convinfo.Converter,
obj);
}
public static IEnumerable<KeyValuePair<string, object>> GetProperties(
Object o) {
return GetProperties(o, true);
}
public static IEnumerable<string> GetPropertyNames(Type t, bool
useCamelCase) {
foreach (PropertyData key in GetPropertyList(t)) {
yield return key.GetAdjustedName(useCamelCase);
}
}
public static IEnumerable<KeyValuePair<string, object>> GetProperties(
Object o,
bool useCamelCase) {
foreach (PropertyData key in GetPropertyList(o.GetType())) {
if (!key.HasUsableGetter()) {
continue;
}
yield return new KeyValuePair<string, object>(
key.GetAdjustedName(useCamelCase),
key.GetValue(o));
}
}
public static void BreakDownDateTime(
DateTime bi,
EInteger[] year,
int[] lf) {
#if NET20
DateTime dt = bi.ToUniversalTime();
#else
DateTime dt = TimeZoneInfo.ConvertTime(bi, TimeZoneInfo.Utc);
#endif
year[0] = EInteger.FromInt32(dt.Year);
lf[0] = dt.Month;
lf[1] = dt.Day;
lf[2] = dt.Hour;
lf[3] = dt.Minute;
lf[4] = dt.Second;
// lf[5] is the number of nanoseconds
lf[5] = (int)(dt.Ticks % 10000000L) * 100;
}
public static DateTime BuildUpDateTime(EInteger year, int[] dt) {
return new DateTime(
year.ToInt32Checked(),
dt[0],
dt[1],
dt[2],
dt[3],
dt[4],
DateTimeKind.Utc)
.AddMinutes(-dt[6]).AddTicks((long)(dt[5] / 100));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using Internal.Reflection.Core.NonPortable;
namespace System
{
[System.Runtime.CompilerServices.DependencyReductionRoot]
public static class InvokeUtils
{
//
// Various reflection scenarios (Array.SetValue(), reflection Invoke, delegate DynamicInvoke and FieldInfo.Set()) perform
// automatic conveniences such as automatically widening primitive types to fit the destination type.
//
// This method attempts to collect as much of that logic as possible in place. (This may not be completely possible
// as the desktop CLR is not particularly consistent across all these scenarios either.)
//
// The transforms supported are:
//
// Value-preserving widenings of primitive integrals and floats.
// Enums can be converted to the same or wider underlying primitive.
// Primitives can be converted to an enum with the same or wider underlying primitive.
//
// null converted to default(T) (this is important when T is a valuetype.)
//
// There is also another transform of T -> Nullable<T>. This method acknowleges that rule but does not actually transform the T.
// Rather, the transformation happens naturally when the caller unboxes the value to its final destination.
//
// This method is targeted by the Delegate ILTransformer.
//
//
public static Object CheckArgument(Object srcObject, RuntimeTypeHandle dstType)
{
EETypePtr dstEEType = dstType.ToEETypePtr();
return CheckArgument(srcObject, dstEEType, CheckArgumentSemantics.DynamicInvoke);
}
// This option does nothing but decide which type of exception to throw to match the legacy behavior.
internal enum CheckArgumentSemantics
{
ArraySet, // Throws InvalidCastException
DynamicInvoke, // Throws ArgumentException
}
internal static Object CheckArgument(Object srcObject, EETypePtr dstEEType, CheckArgumentSemantics semantics)
{
if (srcObject == null)
{
// null -> default(T)
if (dstEEType.IsValueType && !RuntimeImports.RhIsNullable(dstEEType))
return Runtime.RuntimeImports.RhNewObject(dstEEType);
else
return null;
}
else
{
EETypePtr srcEEType = srcObject.EETypePtr;
if (RuntimeImports.AreTypesAssignable(srcEEType, dstEEType))
return srcObject;
if (RuntimeImports.RhIsInterface(dstEEType))
{
ICastable castable = srcObject as ICastable;
Exception castError;
if (castable != null && castable.IsInstanceOfInterface(new RuntimeTypeHandle(dstEEType), out castError))
return srcObject;
}
if (!((srcEEType.IsEnum || srcEEType.IsPrimitive) && (dstEEType.IsEnum || dstEEType.IsPrimitive)))
throw CreateChangeTypeException(srcEEType, dstEEType, semantics);
RuntimeImports.RhCorElementType dstCorElementType = dstEEType.CorElementType;
if (!srcEEType.CorElementTypeInfo.CanWidenTo(dstCorElementType))
throw CreateChangeTypeArgumentException(srcEEType, dstEEType);
Object dstObject;
switch (dstCorElementType)
{
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN:
dstObject = Convert.ToBoolean(srcObject);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR:
dstObject = Convert.ToChar(srcObject);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1:
dstObject = Convert.ToSByte(srcObject);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2:
dstObject = Convert.ToInt16(srcObject);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4:
dstObject = Convert.ToInt32(srcObject);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8:
dstObject = Convert.ToInt64(srcObject);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1:
dstObject = Convert.ToByte(srcObject);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2:
dstObject = Convert.ToUInt16(srcObject);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4:
dstObject = Convert.ToUInt32(srcObject);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8:
dstObject = Convert.ToUInt64(srcObject);
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4:
if (srcEEType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR)
{
dstObject = (float)(char)srcObject;
}
else
{
dstObject = Convert.ToSingle(srcObject);
}
break;
case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8:
if (srcEEType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR)
{
dstObject = (double)(char)srcObject;
}
else
{
dstObject = Convert.ToDouble(srcObject);
}
break;
default:
Debug.Assert(false, "Unexpected CorElementType: " + dstCorElementType + ": Not a valid widening target.");
throw CreateChangeTypeException(srcEEType, dstEEType, semantics);
}
if (dstEEType.IsEnum)
{
Type dstType = ReflectionCoreNonPortable.GetRuntimeTypeForEEType(dstEEType);
dstObject = Enum.ToObject(dstType, dstObject);
}
Debug.Assert(dstObject.EETypePtr == dstEEType);
return dstObject;
}
}
private static Exception CreateChangeTypeException(EETypePtr srcEEType, EETypePtr dstEEType, CheckArgumentSemantics semantics)
{
switch (semantics)
{
case CheckArgumentSemantics.DynamicInvoke:
return CreateChangeTypeArgumentException(srcEEType, dstEEType);
case CheckArgumentSemantics.ArraySet:
return CreateChangeTypeInvalidCastException(srcEEType, dstEEType);
default:
Debug.Assert(false, "Unexpected CheckArgumentSemantics value: " + semantics);
throw new InvalidOperationException();
}
}
private static ArgumentException CreateChangeTypeArgumentException(EETypePtr srcEEType, EETypePtr dstEEType)
{
return new ArgumentException(SR.Format(SR.Arg_ObjObjEx, Type.GetTypeFromHandle(new RuntimeTypeHandle(srcEEType)), Type.GetTypeFromHandle(new RuntimeTypeHandle(dstEEType))));
}
private static InvalidCastException CreateChangeTypeInvalidCastException(EETypePtr srcEEType, EETypePtr dstEEType)
{
return new InvalidCastException(SR.InvalidCast_StoreArrayElement);
}
// -----------------------------------------------
// Infrastructure and logic for Dynamic Invocation
// -----------------------------------------------
public enum DynamicInvokeParamType
{
In = 0,
Ref = 1
}
public enum DynamicInvokeParamLookupType
{
ValuetypeObjectReturned = 0,
IndexIntoObjectArrayReturned = 1,
}
public struct ArgSetupState
{
public bool fComplete;
public object[] nullableCopyBackObjects;
}
// These thread static fields are used instead of passing parameters normally through to the helper functions
// that actually implement dynamic invocation. This allows the large number of dynamically generated
// functions to be just that little bit smaller, which, when spread across the many invocation helper thunks
// generated adds up quite a bit.
[ThreadStatic]
private static object[] s_parameters;
[ThreadStatic]
private static object[] s_nullableCopyBackObjects;
[ThreadStatic]
private static int s_curIndex;
[ThreadStatic]
private static string s_defaultValueString;
// Default parameter support
private const int DefaultParamTypeNone = 0;
private const int DefaultParamTypeBool = 1;
private const int DefaultParamTypeChar = 2;
private const int DefaultParamTypeI1 = 3;
private const int DefaultParamTypeI2 = 4;
private const int DefaultParamTypeI4 = 5;
private const int DefaultParamTypeI8 = 6;
private const int DefaultParamTypeR4 = 7;
private const int DefaultParamTypeR8 = 8;
private const int DefaultParamTypeString = 9;
private const int DefaultParamTypeDefault = 10;
private const int DefaultParamTypeDecimal = 11;
private const int DefaultParamTypeDateTime = 12;
private const int DefaultParamTypeNoneButOptional = 13;
private struct StringDataParser
{
private string _str;
private int _offset;
public StringDataParser(string str)
{
_str = str;
_offset = 0;
}
public void SetOffset(int offset)
{
_offset = offset;
}
public long GetLong()
{
long returnValue;
char curVal = _str[_offset++];
// High bit is used to indicate an extended value
// Low bit is sign bit
// The middle 14 bits are used to hold 14 bits of the actual long value.
// A sign bit approach is used so that a negative number can be represented with 1 char value.
returnValue = (long)(curVal & (char)0x7FFE);
returnValue = returnValue >> 1;
bool isNegative = ((curVal & (char)1)) == 1;
if ((returnValue == 0) && isNegative)
{
return Int64.MinValue;
}
int additionalCharCount = 0;
int bitsAcquired = 14;
// For additional characters, the first 3 additional characters hold 15 bits of data
// and the last character may hold 5 bits of data.
while ((curVal & (char)0x8000) != 0)
{
additionalCharCount++;
curVal = _str[_offset++];
long grabValue = (long)(curVal & (char)0x7FFF);
grabValue <<= bitsAcquired;
bitsAcquired += 15;
returnValue |= grabValue;
}
if (isNegative)
returnValue = -returnValue;
return returnValue;
}
public int GetInt()
{
return checked((int)GetLong());
}
public unsafe float GetFloat()
{
int inputLocation = checked((int)GetLong());
float result = 0;
byte* inputPtr = (byte*)&inputLocation;
byte* outputPtr = (byte*)&result;
for (int i = 0; i < 4; i++)
{
outputPtr[i] = inputPtr[i];
}
return result;
}
public unsafe double GetDouble()
{
long inputLocation = GetLong();
double result = 0;
byte* inputPtr = (byte*)&inputLocation;
byte* outputPtr = (byte*)&result;
for (int i = 0; i < 8; i++)
{
outputPtr[i] = inputPtr[i];
}
return result;
}
public unsafe string GetString()
{
fixed (char* strData = _str)
{
int length = (int)GetLong();
char c = _str[_offset]; // Check for index out of range concerns.
string strRet = new string(strData, _offset, length);
_offset += length;
return strRet;
}
}
public void Skip(int count)
{
_offset += count;
}
}
private static unsafe object GetDefaultValue(RuntimeTypeHandle thType, int argIndex)
{
// Group index of 0 indicates there are no default parameters
if (s_defaultValueString == null)
{
throw new ArgumentException(SR.Arg_DefaultValueMissingException);
}
StringDataParser dataParser = new StringDataParser(s_defaultValueString);
// Skip to current argument
int curArgIndex = 0;
while (curArgIndex != argIndex)
{
int skip = dataParser.GetInt();
dataParser.Skip(skip);
curArgIndex++;
}
// Discard size of current argument
int sizeOfCurrentArg = dataParser.GetInt();
int defaultValueType = dataParser.GetInt();
switch (defaultValueType)
{
case DefaultParamTypeNone:
default:
throw new ArgumentException(SR.Arg_DefaultValueMissingException);
case DefaultParamTypeString:
return dataParser.GetString();
case DefaultParamTypeDefault:
if (thType.ToEETypePtr().IsValueType)
{
if (RuntimeImports.RhIsNullable(thType.ToEETypePtr()))
{
return null;
}
else
{
return RuntimeImports.RhNewObject(thType.ToEETypePtr());
}
}
else
{
return null;
}
case DefaultParamTypeBool:
return (dataParser.GetInt() == 1);
case DefaultParamTypeChar:
return (char)dataParser.GetInt();
case DefaultParamTypeI1:
return (sbyte)dataParser.GetInt();
case DefaultParamTypeI2:
return (short)dataParser.GetInt();
case DefaultParamTypeI4:
return dataParser.GetInt();
case DefaultParamTypeI8:
return dataParser.GetLong();
case DefaultParamTypeR4:
return dataParser.GetFloat();
case DefaultParamTypeR8:
return dataParser.GetDouble();
case DefaultParamTypeDecimal:
int[] decimalBits = new int[4];
decimalBits[0] = dataParser.GetInt();
decimalBits[1] = dataParser.GetInt();
decimalBits[2] = dataParser.GetInt();
decimalBits[3] = dataParser.GetInt();
return new Decimal(decimalBits);
case DefaultParamTypeDateTime:
return new DateTime(dataParser.GetLong());
case DefaultParamTypeNoneButOptional:
return System.Reflection.Missing.Value;
}
}
[DebuggerGuidedStepThroughAttribute]
internal static object CallDynamicInvokeMethod(object thisPtr, IntPtr methodToCall, object thisPtrDynamicInvokeMethod, IntPtr dynamicInvokeHelperMethod, IntPtr dynamicInvokeHelperGenericDictionary, string defaultValueString, object[] parameters, bool invokeMethodHelperIsThisCall = true, bool methodToCallIsThisCall = true)
{
bool fDontWrapInTargetInvocationException = false;
bool parametersNeedCopyBack = false;
ArgSetupState argSetupState = default(ArgSetupState);
// Capture state of thread static invoke helper statics
object[] parametersOld = s_parameters;
object[] nullableCopyBackObjectsOld = s_nullableCopyBackObjects;
int curIndexOld = s_curIndex;
string defaultValueStringOld = s_defaultValueString;
try
{
// If the passed in array is not an actual object[] instance, we need to copy it over to an actual object[]
// instance so that the rest of the code can safely create managed object references to individual elements.
if (parameters != null && EETypePtr.EETypePtrOf<object[]>() != parameters.EETypePtr)
{
s_parameters = new object[parameters.Length];
Array.Copy(parameters, s_parameters, parameters.Length);
parametersNeedCopyBack = true;
}
else
{
s_parameters = parameters;
}
s_nullableCopyBackObjects = null;
s_curIndex = 0;
s_defaultValueString = defaultValueString;
try
{
object result = null;
if (invokeMethodHelperIsThisCall)
{
Debug.Assert(methodToCallIsThisCall == true);
result = CallIHelperThisCall(thisPtr, methodToCall, thisPtrDynamicInvokeMethod, dynamicInvokeHelperMethod, ref argSetupState);
System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
}
else
{
if (dynamicInvokeHelperGenericDictionary != IntPtr.Zero)
{
result = CallIHelperStaticCallWithInstantiation(thisPtr, methodToCall, dynamicInvokeHelperMethod, ref argSetupState, methodToCallIsThisCall, dynamicInvokeHelperGenericDictionary);
DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
}
else
{
result = CallIHelperStaticCall(thisPtr, methodToCall, dynamicInvokeHelperMethod, ref argSetupState, methodToCallIsThisCall);
DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
}
}
return result;
}
finally
{
if (parametersNeedCopyBack)
{
Array.Copy(s_parameters, parameters, parameters.Length);
}
if (!argSetupState.fComplete)
{
fDontWrapInTargetInvocationException = true;
}
else
{
// Nullable objects can't take advantage of the ability to update the boxed value on the heap directly, so perform
// an update of the parameters array now.
if (argSetupState.nullableCopyBackObjects != null)
{
for (int i = 0; i < argSetupState.nullableCopyBackObjects.Length; i++)
{
if (argSetupState.nullableCopyBackObjects[i] != null)
{
parameters[i] = DynamicInvokeBoxIntoNonNullable(argSetupState.nullableCopyBackObjects[i]);
}
}
}
}
}
}
catch (Exception e)
{
if (fDontWrapInTargetInvocationException)
{
throw;
}
else
{
throw new System.Reflection.TargetInvocationException(e);
}
}
finally
{
// Restore state of thread static helper statics
s_parameters = parametersOld;
s_nullableCopyBackObjects = nullableCopyBackObjectsOld;
s_curIndex = curIndexOld;
s_defaultValueString = defaultValueStringOld;
}
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
internal static void DynamicInvokeArgSetupComplete(ref ArgSetupState argSetupState)
{
int parametersLength = s_parameters != null ? s_parameters.Length : 0;
if (s_curIndex != parametersLength)
{
throw new System.Reflection.TargetParameterCountException();
}
argSetupState.fComplete = true;
argSetupState.nullableCopyBackObjects = s_nullableCopyBackObjects;
s_nullableCopyBackObjects = null;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public static void DynamicInvokeArgSetupPtrComplete(IntPtr argSetupStatePtr)
{
// Intrinsic filled by the ImplementLibraryDynamicInvokeHelpers transform.
// argSetupStatePtr is a pointer to a *pinned* ArgSetupState object
// ldarg.0
// call void System.InvokeUtils.DynamicInvokeArgSetupComplete(ref ArgSetupState)
// ret
throw new PlatformNotSupportedException();
}
internal static object CallIHelperThisCall(object thisPtr, IntPtr methodToCall, object thisPtrForDynamicInvokeHelperMethod, IntPtr dynamicInvokeHelperMethod, ref ArgSetupState argSetupState)
{
// Calli the dynamicInvokeHelper method with a bunch of parameters As this can't actually be defined in C# there is an IL transform that fills this in.
return null;
}
internal static object CallIHelperStaticCall(object thisPtr, IntPtr methodToCall, IntPtr dynamicInvokeHelperMethod, ref ArgSetupState argSetupState, bool isTargetThisCall)
{
// Calli the dynamicInvokeHelper method with a bunch of parameters As this can't actually be defined in C# there is an IL transform that fills this in.
return null;
}
internal static object CallIHelperStaticCallWithInstantiation(object thisPtr, IntPtr methodToCall, IntPtr dynamicInvokeHelperMethod, ref ArgSetupState argSetupState, bool isTargetThisCall, IntPtr dynamicInvokeHelperGenericDictionary)
{
// Calli the dynamicInvokeHelper method with a bunch of parameters As this can't actually be defined in C# there is an IL transform that fills this in.
return null;
}
// Template function that is used to call dynamically
internal static object DynamicInvokeThisCallTemplate(object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState)
{
// This function will look like
//
// !For each parameter to the method
// !if (parameter is In Parameter)
// localX is TypeOfParameterX&
// ldtoken TypeOfParameterX
// call DynamicInvokeParamHelperIn(RuntimeTypeHandle)
// stloc localX
// !else
// localX is TypeOfParameter
// ldtoken TypeOfParameterX
// call DynamicInvokeParamHelperRef(RuntimeTypeHandle)
// stloc localX
// ldarg.2
// call DynamicInvokeArgSetupComplete(ref ArgSetupState)
// ldarg.0 // Load this pointer
// !For each parameter
// !if (parameter is In Parameter)
// ldloc localX
// ldobj TypeOfParameterX
// !else
// ldloc localX
// ldarg.1
// calli ReturnType thiscall(TypeOfParameter1, ...)
// !if ((ReturnType != void) && !(ReturnType is a byref)
// ldnull
// !else
// box ReturnType
// ret
return null;
}
internal static object DynamicInvokeCallTemplate(object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState, bool targetIsThisCall)
{
// This function will look like
//
// !For each parameter to the method
// !if (parameter is In Parameter)
// localX is TypeOfParameterX&
// ldtoken TypeOfParameterX
// call DynamicInvokeParamHelperIn(RuntimeTypeHandle)
// stloc localX
// !else
// localX is TypeOfParameter
// ldtoken TypeOfParameterX
// call DynamicInvokeParamHelperRef(RuntimeTypeHandle)
// stloc localX
// ldarg.2
// call DynamicInvokeArgSetupComplete(ref ArgSetupState)
// !if (targetIsThisCall)
// ldarg.0 // Load this pointer
// !For each parameter
// !if (parameter is In Parameter)
// ldloc localX
// ldobj TypeOfParameterX
// !else
// ldloc localX
// ldarg.1
// calli ReturnType thiscall(TypeOfParameter1, ...)
// !if ((ReturnType != void) && !(ReturnType is a byref)
// ldnull
// !else
// box ReturnType
// ret
// !else
// !For each parameter
// !if (parameter is In Parameter)
// ldloc localX
// ldobj TypeOfParameterX
// !else
// ldloc localX
// ldarg.1
// calli ReturnType (TypeOfParameter1, ...)
// !if ((ReturnType != void) && !(ReturnType is a byref)
// ldnull
// !else
// box ReturnType
// ret
return null;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static void DynamicInvokeUnboxIntoActualNullable(object actualBoxedNullable, object boxedFillObject, EETypePtr nullableType)
{
// pin the actualBoxedNullable
// local0 is object pinned pinnedActualBoxedNullable
// ldarg.0
// stloc.0
// ldarg.1 // object to unbox
// ldarg.0
// ldflda System.Object::m_eetype
// sizeof EETypePtr
// add // byref to data data region within actualBoxedNullable
// ldarg.2
// get a byref to the data within the actual boxed nullable, and then call RhUnBox with the boxedFillObject as the boxed object, and nullableType as the unbox type, and unbox into the actualBoxedNullable
// call static void RuntimeImports.RhUnbox(object obj, void* pData, EETypePtr pUnboxToEEType);
// ret
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static object DynamicInvokeBoxIntoNonNullable(object actualBoxedNullable)
{
// pin the actualBoxedNullable
// local0 is object pinned pinnedActualBoxedNullable
// ldarg.0
// stloc.0
//
// grab the pointer to data, box using the EEType of the actualBoxedNullable, and then return the boxed object
// ldarg.0
// ldfld System.Object::m_eetype
// ldarg.0
// ldflda System.Object::m_eetype
// sizeof EETypePtr
// add
// call RuntimeImports.RhBox(EETypePtr, void*data)
// ret
return null;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
internal static /* Transform change this into byref to IntPtr*/ IntPtr DynamicInvokeParamHelperIn(RuntimeTypeHandle rth)
{
// Call DynamicInvokeParamHelperCore as an in parameter, and return a managed byref to the interesting bit. As this can't actually be defined in C# there is an IL transform that fills this in.
//
// This function exactly matches DynamicInvokeParamHelperRef except for the value of the enum passed to DynamicInvokeParamHelperCore
//
// zeroinit
// local0 is int index
// local1 is DynamicInvokeParamLookupType
// local2 is object
//
// Capture information about the parameter.
// ldarg.0
// ldloca 1 // ref DynamicInvokeParamLookupType
// ldloca 0 // ref index
// ldc.i4.0 // DynamicInvokeParamType.In
// call object DynamicInvokeParamHelperCore(RuntimeTypeHandle type, out DynamicInvokeParamLookupType paramLookupType, out int index, DynamicInvokeParamType paramType)
// stloc.2
// decode output of DynamicInvokeParamHelperCore
// if (paramLookupType == DynamicInvokeParamLookupType.ValuetypeObjectReturned)
// return &local2.m_pEEType + sizeof(EETypePtr)
// else
// return &(((object[])local2)[index])
//
// ldloc.1
// ldc.i4.0
// bne.un arrayCase
// ldloc.2
// ldflda System.Object::m_eetype
// sizeof EETypePtr
// add
// ret
// arrayCase:
// ldloc.2
// ldloc.0
// ldelema System.Object
// ret
return IntPtr.Zero;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
internal static /* Transform change this into byref to IntPtr*/ IntPtr DynamicInvokeParamHelperRef(RuntimeTypeHandle rth)
{
// Call DynamicInvokeParamHelperCore as a ref parameter, and return a managed byref to the interesting bit. As this can't actually be defined in C# there is an IL transform that fills this in.
//
// This function exactly matches DynamicInvokeParamHelperIn except for the value of the enum passed to DynamicInvokeParamHelperCore
//
// zeroinit
// local0 is int index
// local1 is DynamicInvokeParamLookupType
// local2 is object
//
// Capture information about the parameter.
// ldarg.0
// ldloca 1 // ref DynamicInvokeParamLookupType
// ldloca 0 // ref index
// ldc.i4.1 // DynamicInvokeParamType.Ref
// call object DynamicInvokeParamHelperCore(RuntimeTypeHandle type, out DynamicInvokeParamLookupType paramLookupType, out int index, DynamicInvokeParamType paramType)
// stloc.2
// decode output of DynamicInvokeParamHelperCore
// if (paramLookupType == DynamicInvokeParamLookupType.ValuetypeObjectReturned)
// return &local2.m_pEEType + sizeof(EETypePtr)
// else
// return &(((object[])local2)[index])
//
// ldloc.1
// ldc.i4.0
// bne.un arrayCase
// ldloc.2
// ldflda System.Object::m_eetype
// sizeof EETypePtr
// add
// ret
// arrayCase:
// ldloc.2
// ldloc.0
// ldelema System.Object
// ret
return IntPtr.Zero;
}
internal static object DynamicInvokeBoxedValuetypeReturn(out DynamicInvokeParamLookupType paramLookupType, object boxedValuetype, int index, RuntimeTypeHandle type, DynamicInvokeParamType paramType)
{
object finalObjectToReturn = boxedValuetype;
EETypePtr eeType = type.ToEETypePtr();
bool nullable = RuntimeImports.RhIsNullable(eeType);
if (finalObjectToReturn == null || nullable || paramType == DynamicInvokeParamType.Ref)
{
finalObjectToReturn = RuntimeImports.RhNewObject(eeType);
if (boxedValuetype != null)
{
DynamicInvokeUnboxIntoActualNullable(finalObjectToReturn, boxedValuetype, eeType);
}
}
if (nullable)
{
if (paramType == DynamicInvokeParamType.Ref)
{
if (s_nullableCopyBackObjects == null)
{
s_nullableCopyBackObjects = new object[s_parameters.Length];
}
s_nullableCopyBackObjects[index] = finalObjectToReturn;
s_parameters[index] = null;
}
}
else
{
System.Diagnostics.Debug.Assert(finalObjectToReturn != null);
if (paramType == DynamicInvokeParamType.Ref)
s_parameters[index] = finalObjectToReturn;
}
paramLookupType = DynamicInvokeParamLookupType.ValuetypeObjectReturned;
return finalObjectToReturn;
}
public static object DynamicInvokeParamHelperCore(RuntimeTypeHandle type, out DynamicInvokeParamLookupType paramLookupType, out int index, DynamicInvokeParamType paramType)
{
index = s_curIndex++;
int parametersLength = s_parameters != null ? s_parameters.Length : 0;
if (index >= parametersLength)
throw new System.Reflection.TargetParameterCountException();
object incomingParam = s_parameters[index];
// Handle default parameters
if ((incomingParam == System.Reflection.Missing.Value) && paramType == DynamicInvokeParamType.In)
{
incomingParam = GetDefaultValue(type, index);
// The default value is captured into the parameters array
s_parameters[index] = incomingParam;
}
RuntimeTypeHandle widenAndCompareType = type;
bool nullable = RuntimeImports.RhIsNullable(type.ToEETypePtr());
if (nullable)
{
widenAndCompareType = new RuntimeTypeHandle(RuntimeImports.RhGetNullableType(type.ToEETypePtr()));
}
if (widenAndCompareType.ToEETypePtr().IsPrimitive || type.ToEETypePtr().IsEnum)
{
// Nullable requires exact matching
if (incomingParam != null)
{
if ((nullable || paramType == DynamicInvokeParamType.Ref) && incomingParam != null)
{
if (widenAndCompareType.ToEETypePtr() != incomingParam.EETypePtr)
{
throw CreateChangeTypeArgumentException(incomingParam.EETypePtr, type.ToEETypePtr());
}
}
else
{
if (widenAndCompareType.ToEETypePtr().CorElementType != incomingParam.EETypePtr.CorElementType)
{
System.Diagnostics.Debug.Assert(paramType == DynamicInvokeParamType.In);
incomingParam = InvokeUtils.CheckArgument(incomingParam, widenAndCompareType.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke);
}
}
}
return DynamicInvokeBoxedValuetypeReturn(out paramLookupType, incomingParam, index, type, paramType);
}
else if (type.ToEETypePtr().IsValueType)
{
incomingParam = InvokeUtils.CheckArgument(incomingParam, type.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke);
System.Diagnostics.Debug.Assert(s_parameters[index] == null || Object.ReferenceEquals(incomingParam, s_parameters[index]));
return DynamicInvokeBoxedValuetypeReturn(out paramLookupType, incomingParam, index, type, paramType);
}
else
{
incomingParam = InvokeUtils.CheckArgument(incomingParam, widenAndCompareType.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke);
System.Diagnostics.Debug.Assert(Object.ReferenceEquals(incomingParam, s_parameters[index]));
paramLookupType = DynamicInvokeParamLookupType.IndexIntoObjectArrayReturned;
return s_parameters;
}
}
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using FarseerPhysics.Collision;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Contacts
{
/// <summary>
/// A contact edge is used to connect bodies and contacts together
/// in a contact graph where each body is a node and each contact
/// is an edge. A contact edge belongs to a doubly linked list
/// maintained in each attached body. Each contact has two contact
/// nodes, one for each attached body.
/// </summary>
public sealed class ContactEdge
{
/// <summary>
/// The contact
/// </summary>
public Contact Contact;
/// <summary>
/// The next contact edge in the body's contact list
/// </summary>
public ContactEdge Next;
/// <summary>
/// Provides quick access to the other body attached.
/// </summary>
public Body Other;
/// <summary>
/// The previous contact edge in the body's contact list
/// </summary>
public ContactEdge Prev;
}
[Flags]
public enum ContactFlags
{
None = 0,
/// <summary>
/// Used when crawling contact graph when forming islands.
/// </summary>
Island = 0x0001,
/// <summary>
/// Set when the shapes are touching.
/// </summary>
Touching = 0x0002,
/// <summary>
/// This contact can be disabled (by user)
/// </summary>
Enabled = 0x0004,
/// <summary>
/// This contact needs filtering because a fixture filter was changed.
/// </summary>
Filter = 0x0008,
/// <summary>
/// This bullet contact had a TOI event
/// </summary>
BulletHit = 0x0010,
/// <summary>
/// This contact has a valid TOI i the field TOI
/// </summary>
TOI = 0x0020
}
/// <summary>
/// The class manages contact between two shapes. A contact exists for each overlapping
/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist
/// that has no contact points.
/// </summary>
public class Contact
{
private static EdgeShape _edge = new EdgeShape();
private static ContactType[,] _registers = new[,]
{
{
ContactType.Circle,
ContactType.EdgeAndCircle,
ContactType.PolygonAndCircle,
ContactType.LoopAndCircle,
},
{
ContactType.EdgeAndCircle,
ContactType.NotSupported,
// 1,1 is invalid (no ContactType.Edge)
ContactType.EdgeAndPolygon,
ContactType.NotSupported,
// 1,3 is invalid (no ContactType.EdgeAndLoop)
},
{
ContactType.PolygonAndCircle,
ContactType.EdgeAndPolygon,
ContactType.Polygon,
ContactType.LoopAndPolygon,
},
{
ContactType.LoopAndCircle,
ContactType.NotSupported,
// 3,1 is invalid (no ContactType.EdgeAndLoop)
ContactType.LoopAndPolygon,
ContactType.NotSupported,
// 3,3 is invalid (no ContactType.Loop)
},
};
public Fixture FixtureA;
public Fixture FixtureB;
internal ContactFlags Flags;
public Manifold Manifold;
// Nodes for connecting bodies.
internal ContactEdge NodeA = new ContactEdge();
internal ContactEdge NodeB = new ContactEdge();
public float TOI;
internal int TOICount;
private ContactType _type;
private Contact(Fixture fA, int indexA, Fixture fB, int indexB)
{
Reset(fA, indexA, fB, indexB);
}
/// Enable/disable this contact. This can be used inside the pre-solve
/// contact listener. The contact is only disabled for the current
/// time step (or sub-step in continuous collisions).
public bool Enabled
{
set
{
if (value)
{
Flags |= ContactFlags.Enabled;
}
else
{
Flags &= ~ContactFlags.Enabled;
}
}
get { return (Flags & ContactFlags.Enabled) == ContactFlags.Enabled; }
}
/// <summary>
/// Get the child primitive index for fixture A.
/// </summary>
/// <value>The child index A.</value>
public int ChildIndexA { get; internal set; }
/// <summary>
/// Get the child primitive index for fixture B.
/// </summary>
/// <value>The child index B.</value>
public int ChildIndexB { get; internal set; }
/// <summary>
/// Get the contact manifold. Do not modify the manifold unless you understand the
/// internals of Box2D.
/// </summary>
/// <param name="manifold">The manifold.</param>
public void GetManifold(out Manifold manifold)
{
manifold = Manifold;
}
/// <summary>
/// Gets the world manifold.
/// </summary>
public void GetWorldManifold(out Vector2 normal, out FixedArray2<Vector2> points)
{
Body bodyA = FixtureA.Body;
Body bodyB = FixtureB.Body;
Shape shapeA = FixtureA.Shape;
Shape shapeB = FixtureB.Shape;
Collision.Collision.GetWorldManifold(ref Manifold, ref bodyA.Xf, shapeA.Radius, ref bodyB.Xf, shapeB.Radius,
out normal, out points);
}
/// <summary>
/// Determines whether this contact is touching.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is touching; otherwise, <c>false</c>.
/// </returns>
public bool IsTouching()
{
return (Flags & ContactFlags.Touching) == ContactFlags.Touching;
}
/// <summary>
/// Flag this contact for filtering. Filtering will occur the next time step.
/// </summary>
public void FlagForFiltering()
{
Flags |= ContactFlags.Filter;
}
private void Reset(Fixture fA, int indexA, Fixture fB, int indexB)
{
Flags = ContactFlags.Enabled;
FixtureA = fA;
FixtureB = fB;
ChildIndexA = indexA;
ChildIndexB = indexB;
Manifold.PointCount = 0;
NodeA.Contact = null;
NodeA.Prev = null;
NodeA.Next = null;
NodeA.Other = null;
NodeB.Contact = null;
NodeB.Prev = null;
NodeB.Next = null;
NodeB.Other = null;
TOICount = 0;
}
/// <summary>
/// Update the contact manifold and touching status.
/// Note: do not assume the fixture AABBs are overlapping or are valid.
/// </summary>
/// <param name="contactManager">The contact manager.</param>
internal void Update(ContactManager contactManager)
{
Manifold oldManifold = Manifold;
// Re-enable this contact.
Flags |= ContactFlags.Enabled;
bool touching;
bool wasTouching = (Flags & ContactFlags.Touching) == ContactFlags.Touching;
bool sensor = FixtureA.IsSensor || FixtureB.IsSensor;
Body bodyA = FixtureA.Body;
Body bodyB = FixtureB.Body;
// Is this contact a sensor?
if (sensor)
{
Shape shapeA = FixtureA.Shape;
Shape shapeB = FixtureB.Shape;
touching = AABB.TestOverlap(shapeA, ChildIndexA, shapeB, ChildIndexB, ref bodyA.Xf, ref bodyB.Xf);
// Sensors don't generate manifolds.
Manifold.PointCount = 0;
}
else
{
Evaluate(ref Manifold, ref bodyA.Xf, ref bodyB.Xf);
touching = Manifold.PointCount > 0;
// Match old contact ids to new contact ids and copy the
// stored impulses to warm start the solver.
for (int i = 0; i < Manifold.PointCount; ++i)
{
ManifoldPoint mp2 = Manifold.Points[i];
mp2.NormalImpulse = 0.0f;
mp2.TangentImpulse = 0.0f;
ContactID id2 = mp2.Id;
bool found = false;
for (int j = 0; j < oldManifold.PointCount; ++j)
{
ManifoldPoint mp1 = oldManifold.Points[j];
if (mp1.Id.Key == id2.Key)
{
mp2.NormalImpulse = mp1.NormalImpulse;
mp2.TangentImpulse = mp1.TangentImpulse;
found = true;
break;
}
}
if (found == false)
{
mp2.NormalImpulse = 0.0f;
mp2.TangentImpulse = 0.0f;
}
Manifold.Points[i] = mp2;
}
if (touching != wasTouching)
{
bodyA.Awake = true;
bodyB.Awake = true;
}
}
if (touching)
{
Flags |= ContactFlags.Touching;
}
else
{
Flags &= ~ContactFlags.Touching;
}
if (wasTouching == false && touching)
{
//Report the collision to both participants:
if (FixtureA.OnCollision != null)
Enabled = FixtureA.OnCollision(FixtureA, FixtureB, this);
//Reverse the order of the reported fixtures. The first fixture is always the one that the
//user subscribed to.
if (FixtureB.OnCollision != null)
Enabled = FixtureB.OnCollision(FixtureB, FixtureA, this);
//BeginContact can also return false and disable the contact
if (contactManager.BeginContact != null)
Enabled = contactManager.BeginContact(this);
//if the user disabled the contact (needed to exclude it in TOI solver), we also need to mark
//it as not touching.
if (Enabled == false)
Flags &= ~ContactFlags.Touching;
}
if (wasTouching && touching == false)
{
//Report the separation to both participants:
if (FixtureA != null && FixtureA.OnSeparation != null)
FixtureA.OnSeparation(FixtureA, FixtureB);
//Reverse the order of the reported fixtures. The first fixture is always the one that the
//user subscribed to.
if (FixtureB != null && FixtureB.OnSeparation != null)
FixtureB.OnSeparation(FixtureB, FixtureA);
if (contactManager.EndContact != null)
contactManager.EndContact(this);
}
if (sensor)
return;
if (contactManager.PreSolve != null)
contactManager.PreSolve(this, ref oldManifold);
}
/// <summary>
/// Evaluate this contact with your own manifold and transforms.
/// </summary>
/// <param name="manifold">The manifold.</param>
/// <param name="transformA">The first transform.</param>
/// <param name="transformB">The second transform.</param>
private void Evaluate(ref Manifold manifold, ref Transform transformA, ref Transform transformB)
{
switch (_type)
{
case ContactType.Polygon:
Collision.Collision.CollidePolygons(ref manifold,
(PolygonShape)FixtureA.Shape, ref transformA,
(PolygonShape)FixtureB.Shape, ref transformB);
break;
case ContactType.PolygonAndCircle:
Collision.Collision.CollidePolygonAndCircle(ref manifold,
(PolygonShape)FixtureA.Shape, ref transformA,
(CircleShape)FixtureB.Shape, ref transformB);
break;
case ContactType.EdgeAndCircle:
Collision.Collision.CollideEdgeAndCircle(ref manifold,
(EdgeShape)FixtureA.Shape, ref transformA,
(CircleShape)FixtureB.Shape, ref transformB);
break;
case ContactType.EdgeAndPolygon:
Collision.Collision.CollideEdgeAndPolygon(ref manifold,
(EdgeShape)FixtureA.Shape, ref transformA,
(PolygonShape)FixtureB.Shape, ref transformB);
break;
case ContactType.LoopAndCircle:
LoopShape loop = (LoopShape)FixtureA.Shape;
loop.GetChildEdge(ref _edge, ChildIndexA);
Collision.Collision.CollideEdgeAndCircle(ref manifold, _edge, ref transformA,
(CircleShape)FixtureB.Shape, ref transformB);
break;
case ContactType.LoopAndPolygon:
LoopShape loop2 = (LoopShape)FixtureA.Shape;
loop2.GetChildEdge(ref _edge, ChildIndexA);
Collision.Collision.CollideEdgeAndPolygon(ref manifold, _edge, ref transformA,
(PolygonShape)FixtureB.Shape, ref transformB);
break;
case ContactType.Circle:
Collision.Collision.CollideCircles(ref manifold,
(CircleShape)FixtureA.Shape, ref transformA,
(CircleShape)FixtureB.Shape, ref transformB);
break;
}
}
internal static Contact Create(Fixture fixtureA, int indexA, Fixture fixtureB, int indexB)
{
ShapeType type1 = fixtureA.ShapeType;
ShapeType type2 = fixtureB.ShapeType;
Debug.Assert(ShapeType.Unknown < type1 && type1 < ShapeType.TypeCount);
Debug.Assert(ShapeType.Unknown < type2 && type2 < ShapeType.TypeCount);
Contact c;
Queue<Contact> pool = fixtureA.Body.World.ContactPool;
if (pool.Count > 0)
{
c = pool.Dequeue();
if ((type1 >= type2 || (type1 == ShapeType.Edge && type2 == ShapeType.Polygon))
&&
!(type2 == ShapeType.Edge && type1 == ShapeType.Polygon))
{
c.Reset(fixtureA, indexA, fixtureB, indexB);
}
else
{
c.Reset(fixtureB, indexB, fixtureA, indexA);
}
}
else
{
// Edge+Polygon is non-symetrical due to the way Erin handles collision type registration.
if ((type1 >= type2 || (type1 == ShapeType.Edge && type2 == ShapeType.Polygon))
&&
!(type2 == ShapeType.Edge && type1 == ShapeType.Polygon))
{
c = new Contact(fixtureA, indexA, fixtureB, indexB);
}
else
{
c = new Contact(fixtureB, indexB, fixtureA, indexA);
}
}
c._type = _registers[(int)type1, (int)type2];
return c;
}
internal void Destroy()
{
FixtureA.Body.World.ContactPool.Enqueue(this);
Reset(null, 0, null, 0);
}
#region Nested type: ContactType
private enum ContactType
{
NotSupported,
Polygon,
PolygonAndCircle,
Circle,
EdgeAndPolygon,
EdgeAndCircle,
LoopAndPolygon,
LoopAndCircle,
}
#endregion
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type GraphServiceDrivesCollectionRequest.
/// </summary>
public partial class GraphServiceDrivesCollectionRequest : BaseRequest, IGraphServiceDrivesCollectionRequest
{
/// <summary>
/// Constructs a new GraphServiceDrivesCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public GraphServiceDrivesCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Drive to the collection via POST.
/// </summary>
/// <param name="drive">The Drive to add.</param>
/// <returns>The created Drive.</returns>
public System.Threading.Tasks.Task<Drive> AddAsync(Drive drive)
{
return this.AddAsync(drive, CancellationToken.None);
}
/// <summary>
/// Adds the specified Drive to the collection via POST.
/// </summary>
/// <param name="drive">The Drive to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Drive.</returns>
public System.Threading.Tasks.Task<Drive> AddAsync(Drive drive, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<Drive>(drive, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IGraphServiceDrivesCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IGraphServiceDrivesCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<GraphServiceDrivesCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceDrivesCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceDrivesCollectionRequest Expand(Expression<Func<Drive, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceDrivesCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceDrivesCollectionRequest Select(Expression<Func<Drive, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceDrivesCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceDrivesCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceDrivesCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IGraphServiceDrivesCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Cards.Extensions.Tfs.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using 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;
namespace HostMe.Sdk.Model
{
/// <summary>
/// PaymentCharge
/// </summary>
[DataContract]
public partial class PaymentCharge : IEquatable<PaymentCharge>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="PaymentCharge" /> class.
/// </summary>
/// <param name="Id">Id.</param>
/// <param name="Amount">Amount.</param>
/// <param name="Created">Created.</param>
/// <param name="Currency">Currency.</param>
/// <param name="Paid">Paid.</param>
/// <param name="Refunded">Refunded.</param>
/// <param name="Status">Status.</param>
/// <param name="AmountRefunded">AmountRefunded.</param>
/// <param name="CustomerId">CustomerId.</param>
public PaymentCharge(int? Id = null, int? Amount = null, DateTimeOffset? Created = null, string Currency = null, bool? Paid = null, bool? Refunded = null, string Status = null, int? AmountRefunded = null, string CustomerId = null)
{
this.Id = Id;
this.Amount = Amount;
this.Created = Created;
this.Currency = Currency;
this.Paid = Paid;
this.Refunded = Refunded;
this.Status = Status;
this.AmountRefunded = AmountRefunded;
this.CustomerId = CustomerId;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=true)]
public int? Id { get; set; }
/// <summary>
/// Gets or Sets Amount
/// </summary>
[DataMember(Name="amount", EmitDefaultValue=true)]
public int? Amount { get; set; }
/// <summary>
/// Gets or Sets Created
/// </summary>
[DataMember(Name="created", EmitDefaultValue=true)]
public DateTimeOffset? Created { get; set; }
/// <summary>
/// Gets or Sets Currency
/// </summary>
[DataMember(Name="currency", EmitDefaultValue=true)]
public string Currency { get; set; }
/// <summary>
/// Gets or Sets Paid
/// </summary>
[DataMember(Name="paid", EmitDefaultValue=true)]
public bool? Paid { get; set; }
/// <summary>
/// Gets or Sets Refunded
/// </summary>
[DataMember(Name="refunded", EmitDefaultValue=true)]
public bool? Refunded { get; set; }
/// <summary>
/// Gets or Sets Status
/// </summary>
[DataMember(Name="status", EmitDefaultValue=true)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets AmountRefunded
/// </summary>
[DataMember(Name="amountRefunded", EmitDefaultValue=true)]
public int? AmountRefunded { get; set; }
/// <summary>
/// Gets or Sets CustomerId
/// </summary>
[DataMember(Name="customerId", EmitDefaultValue=true)]
public string CustomerId { 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 PaymentCharge {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Amount: ").Append(Amount).Append("\n");
sb.Append(" Created: ").Append(Created).Append("\n");
sb.Append(" Currency: ").Append(Currency).Append("\n");
sb.Append(" Paid: ").Append(Paid).Append("\n");
sb.Append(" Refunded: ").Append(Refunded).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" AmountRefunded: ").Append(AmountRefunded).Append("\n");
sb.Append(" CustomerId: ").Append(CustomerId).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 PaymentCharge);
}
/// <summary>
/// Returns true if PaymentCharge instances are equal
/// </summary>
/// <param name="other">Instance of PaymentCharge to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PaymentCharge other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Amount == other.Amount ||
this.Amount != null &&
this.Amount.Equals(other.Amount)
) &&
(
this.Created == other.Created ||
this.Created != null &&
this.Created.Equals(other.Created)
) &&
(
this.Currency == other.Currency ||
this.Currency != null &&
this.Currency.Equals(other.Currency)
) &&
(
this.Paid == other.Paid ||
this.Paid != null &&
this.Paid.Equals(other.Paid)
) &&
(
this.Refunded == other.Refunded ||
this.Refunded != null &&
this.Refunded.Equals(other.Refunded)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.AmountRefunded == other.AmountRefunded ||
this.AmountRefunded != null &&
this.AmountRefunded.Equals(other.AmountRefunded)
) &&
(
this.CustomerId == other.CustomerId ||
this.CustomerId != null &&
this.CustomerId.Equals(other.CustomerId)
);
}
/// <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.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Amount != null)
hash = hash * 59 + this.Amount.GetHashCode();
if (this.Created != null)
hash = hash * 59 + this.Created.GetHashCode();
if (this.Currency != null)
hash = hash * 59 + this.Currency.GetHashCode();
if (this.Paid != null)
hash = hash * 59 + this.Paid.GetHashCode();
if (this.Refunded != null)
hash = hash * 59 + this.Refunded.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.AmountRefunded != null)
hash = hash * 59 + this.AmountRefunded.GetHashCode();
if (this.CustomerId != null)
hash = hash * 59 + this.CustomerId.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// Alias ID's are indices into BitSets.
// 0 is reserved for the global namespace alias.
// 1 is reserved for this assembly.
// Start assigning at kaidStartAssigning.
internal enum KAID
{
kaidNil = -1,
kaidGlobal = 0,
kaidThisAssembly,
kaidUnresolved,
kaidStartAssigning,
// Module id's are in their own range.
kaidMinModule = 0x10000000,
}
/*
* Define the different access levels that symbols can have.
*/
internal enum ACCESS
{
ACC_UNKNOWN, // Not yet determined.
ACC_PRIVATE,
ACC_INTERNAL,
ACC_PROTECTED,
ACC_INTERNALPROTECTED, // internal OR protected
ACC_PUBLIC
}
// The kinds of aggregates.
internal enum AggKindEnum
{
Unknown,
Class,
Delegate,
Interface,
Struct,
Enum,
Lim
}
/////////////////////////////////////////////////////////////////////////////////
// Special constraints.
internal enum SpecCons
{
None = 0x00,
New = 0x01,
Ref = 0x02,
Val = 0x04
}
// ----------------------------------------------------------------------------
//
// Symbol - the base symbol.
//
// ----------------------------------------------------------------------------
internal abstract class Symbol
{
private SYMKIND _kind; // the symbol kind
private bool _isBogus; // can't be used in our language -- unsupported type(s)
private bool _checkedBogus; // Have we checked a method args/return for bogus types
private ACCESS _access; // access level
// If this is true, then we had an error the first time so do not give an error the second time.
public Name name; // name of the symbol
public ParentSymbol parent; // parent of the symbol
public Symbol nextChild; // next child of this parent
public Symbol nextSameName; // next child of this parent with same name.
public ACCESS GetAccess()
{
Debug.Assert(_access != ACCESS.ACC_UNKNOWN);
return _access;
}
public void SetAccess(ACCESS access)
{
_access = access;
}
public SYMKIND getKind()
{
return _kind;
}
public void setKind(SYMKIND kind)
{
_kind = kind;
}
public symbmask_t mask()
{
return (symbmask_t)(1 << (int)_kind);
}
public bool checkBogus()
{
Debug.Assert(_checkedBogus);
return _isBogus;
} // if this Debug.Assert fires then call COMPILER_BASE::CheckBogus() instead
public bool getBogus()
{
return _isBogus;
}
public bool hasBogus()
{
return _checkedBogus;
}
public void setBogus(bool isBogus)
{
_isBogus = isBogus;
_checkedBogus = true;
}
public void initBogus()
{
_isBogus = false;
_checkedBogus = false;
}
public bool computeCurrentBogusState()
{
if (hasBogus())
{
return checkBogus();
}
bool fBogus = false;
switch (getKind())
{
case SYMKIND.SK_PropertySymbol:
case SYMKIND.SK_MethodSymbol:
{
MethodOrPropertySymbol meth = this.AsMethodOrPropertySymbol();
if (meth.RetType != null)
{
fBogus = meth.RetType.computeCurrentBogusState();
}
if (meth.Params != null)
{
for (int i = 0; !fBogus && i < meth.Params.Count; i++)
{
fBogus |= meth.Params[i].computeCurrentBogusState();
}
}
}
break;
/*
case SYMKIND.SK_ParameterModifierType:
case SYMKIND.SK_OptionalModifierType:
case SYMKIND.SK_PointerType:
case SYMKIND.SK_ArrayType:
case SYMKIND.SK_NullableType:
case SYMKIND.SK_PinnedType:
if (this.AsType().GetBaseOrParameterOrElementType() != null)
{
fBogus = this.AsType().GetBaseOrParameterOrElementType().computeCurrentBogusState();
}
break;
*/
case SYMKIND.SK_EventSymbol:
if (this.AsEventSymbol().type != null)
{
fBogus = this.AsEventSymbol().type.computeCurrentBogusState();
}
break;
case SYMKIND.SK_FieldSymbol:
if (this.AsFieldSymbol().GetType() != null)
{
fBogus = this.AsFieldSymbol().GetType().computeCurrentBogusState();
}
break;
/*
case SYMKIND.SK_ErrorType:
this.setBogus(false);
break;
case SYMKIND.SK_AggregateType:
fBogus = this.AsAggregateType().getAggregate().computeCurrentBogusState();
for (int i = 0; !fBogus && i < this.AsAggregateType().GetTypeArgsAll().size; i++)
{
fBogus |= this.AsAggregateType().GetTypeArgsAll()[i].computeCurrentBogusState();
}
break;
*/
case SYMKIND.SK_TypeParameterSymbol:
/*
case SYMKIND.SK_TypeParameterType:
case SYMKIND.SK_VoidType:
case SYMKIND.SK_NullType:
case SYMKIND.SK_OpenTypePlaceholderType:
case SYMKIND.SK_ArgumentListType:
case SYMKIND.SK_NaturalIntegerType:
*/
case SYMKIND.SK_LocalVariableSymbol:
setBogus(false);
break;
case SYMKIND.SK_AggregateSymbol:
fBogus = hasBogus() && checkBogus();
break;
case SYMKIND.SK_Scope:
case SYMKIND.SK_LambdaScope:
case SYMKIND.SK_NamespaceSymbol:
case SYMKIND.SK_NamespaceDeclaration:
default:
Debug.Assert(false, "CheckBogus with invalid Symbol kind");
setBogus(false);
break;
}
if (fBogus)
{
// Only set this if at least 1 declared thing is bogus
setBogus(fBogus);
}
return hasBogus() && checkBogus();
}
public bool IsNamespaceSymbol() { return _kind == SYMKIND.SK_NamespaceSymbol; }
public bool IsNamespaceDeclaration() { return _kind == SYMKIND.SK_NamespaceDeclaration; }
public bool IsAggregateSymbol() { return _kind == SYMKIND.SK_AggregateSymbol; }
public bool IsAggregateDeclaration() { return _kind == SYMKIND.SK_AggregateDeclaration; }
public bool IsFieldSymbol() { return _kind == SYMKIND.SK_FieldSymbol; }
public bool IsLocalVariableSymbol() { return _kind == SYMKIND.SK_LocalVariableSymbol; }
public bool IsMethodSymbol() { return _kind == SYMKIND.SK_MethodSymbol; }
public bool IsPropertySymbol() { return _kind == SYMKIND.SK_PropertySymbol; }
public bool IsTypeParameterSymbol() { return _kind == SYMKIND.SK_TypeParameterSymbol; }
public bool IsEventSymbol() { return _kind == SYMKIND.SK_EventSymbol; }
public bool IsMethodOrPropertySymbol()
{
return IsMethodSymbol() || IsPropertySymbol();
}
public bool IsFMETHSYM()
{
return IsMethodSymbol();
}
public CType getType()
{
CType type = null;
if (IsMethodOrPropertySymbol())
{
type = this.AsMethodOrPropertySymbol().RetType;
}
else if (IsFieldSymbol())
{
type = this.AsFieldSymbol().GetType();
}
else if (IsEventSymbol())
{
type = this.AsEventSymbol().type;
}
return type;
}
public bool isStatic
{
get
{
bool fStatic = false;
if (IsFieldSymbol())
{
fStatic = this.AsFieldSymbol().isStatic;
}
else if (IsEventSymbol())
{
fStatic = this.AsEventSymbol().isStatic;
}
else if (IsMethodOrPropertySymbol())
{
fStatic = this.AsMethodOrPropertySymbol().isStatic;
}
else if (IsAggregateSymbol())
{
fStatic = true;
}
return fStatic;
}
}
private Assembly GetAssembly()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
case SYMKIND.SK_FieldSymbol:
case SYMKIND.SK_EventSymbol:
case SYMKIND.SK_TypeParameterSymbol:
return parent.AsAggregateSymbol().AssociatedAssembly;
case SYMKIND.SK_AggregateDeclaration:
return this.AsAggregateDeclaration().GetAssembly();
case SYMKIND.SK_AggregateSymbol:
return this.AsAggregateSymbol().AssociatedAssembly;
case SYMKIND.SK_NamespaceDeclaration:
case SYMKIND.SK_NamespaceSymbol:
case SYMKIND.SK_AssemblyQualifiedNamespaceSymbol:
default:
// Should never call this with any other kind.
Debug.Assert(false, "GetAssemblyID called on bad sym kind");
return null;
}
}
/*
* returns the assembly id for the declaration of this symbol
*/
private bool InternalsVisibleTo(Assembly assembly)
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
case SYMKIND.SK_FieldSymbol:
case SYMKIND.SK_EventSymbol:
case SYMKIND.SK_TypeParameterSymbol:
return parent.AsAggregateSymbol().InternalsVisibleTo(assembly);
case SYMKIND.SK_AggregateDeclaration:
return this.AsAggregateDeclaration().Agg().InternalsVisibleTo(assembly);
case SYMKIND.SK_AggregateSymbol:
return this.AsAggregateSymbol().InternalsVisibleTo(assembly);
case SYMKIND.SK_NamespaceDeclaration:
case SYMKIND.SK_ExternalAliasDefinitionSymbol:
case SYMKIND.SK_NamespaceSymbol:
case SYMKIND.SK_AssemblyQualifiedNamespaceSymbol:
default:
// Should never call this with any other kind.
Debug.Assert(false, "InternalsVisibleTo called on bad sym kind");
return false;
}
}
public bool SameAssemOrFriend(Symbol sym)
{
Assembly assem = GetAssembly();
return assem == sym.GetAssembly() || sym.InternalsVisibleTo(assem);
}
/*
* returns the inputfile where a symbol was declared.
*
* returns null for namespaces because they can be declared
* in multiple files.
*/
public InputFile getInputFile()
{
switch (_kind)
{
case SYMKIND.SK_NamespaceSymbol:
case SYMKIND.SK_AssemblyQualifiedNamespaceSymbol:
// namespaces don't have input files
// call with a NamespaceDeclaration instead
Debug.Assert(false);
return null;
case SYMKIND.SK_NamespaceDeclaration:
return null;
case SYMKIND.SK_AggregateSymbol:
{
AggregateSymbol AggregateSymbol = this.AsAggregateSymbol();
if (!AggregateSymbol.IsSource())
return AggregateSymbol.DeclOnly().getInputFile();
// Because an AggregateSymbol that isn't metadata can be defined across multiple
// files, getInputFile isn't a reasonable operation.
Debug.Assert(false);
return null;
}
/*
case SK_AggregateType:
return ((Symbol)this.AsAggregateType().getAggregate()).getInputFile();
*/
case SYMKIND.SK_AggregateDeclaration:
return this.AsAggregateDeclaration().getInputFile();
/*
case SK_TypeParameterType:
if (this.AsTypeParameterType().GetOwningSymbol().IsAggregateSymbol())
{
ASSERT(0);
return null;
}
else
{
ASSERT(this.AsTypeParameterType().GetOwningSymbol().IsMethodSymbol());
return AsTypeParameterType().GetOwningSymbol().AsMethodSymbol().getInputFile();
}
*/
case SYMKIND.SK_TypeParameterSymbol:
if (parent.IsAggregateSymbol())
{
// Because an AggregateSymbol that isn't metadata can be defined across multiple
// files, getInputFile isn't a reasonable operation.
Debug.Assert(false);
return null;
}
else if (parent.IsMethodSymbol())
return parent.AsMethodSymbol().getInputFile();
Debug.Assert(false);
break;
case SYMKIND.SK_FieldSymbol:
return this.AsFieldSymbol().containingDeclaration().getInputFile();
case SYMKIND.SK_MethodSymbol:
return this.AsMethodSymbol().containingDeclaration().getInputFile();
case SYMKIND.SK_PropertySymbol:
return this.AsPropertySymbol().containingDeclaration().getInputFile();
case SYMKIND.SK_EventSymbol:
return this.AsEventSymbol().containingDeclaration().getInputFile();
/*
case SK_PointerType:
case SK_NullableType:
case SK_ArrayType:
case SK_PinnedType:
case SK_ParameterModifierType:
case SK_OptionalModifierType:
return AsType().GetBaseOrParameterOrElementType().getInputFile();
*/
case SYMKIND.SK_GlobalAttributeDeclaration:
return parent.getInputFile();
/*
case SK_NullType:
case SK_VoidType:
return null;
*/
default:
Debug.Assert(false);
break;
}
return null;
}
/* Returns if the symbol is virtual. */
public bool IsVirtual()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
return this.AsMethodSymbol().isVirtual;
case SYMKIND.SK_EventSymbol:
return this.AsEventSymbol().methAdd != null && this.AsEventSymbol().methAdd.isVirtual;
case SYMKIND.SK_PropertySymbol:
return (this.AsPropertySymbol().methGet != null && this.AsPropertySymbol().methGet.isVirtual) ||
(this.AsPropertySymbol().methSet != null && this.AsPropertySymbol().methSet.isVirtual);
default:
return false;
}
}
public bool IsOverride()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
return this.AsMethodOrPropertySymbol().isOverride;
case SYMKIND.SK_EventSymbol:
return this.AsEventSymbol().isOverride;
default:
return false;
}
}
public bool IsHideByName()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
return this.AsMethodOrPropertySymbol().isHideByName;
case SYMKIND.SK_EventSymbol:
return this.AsEventSymbol().methAdd != null && this.AsEventSymbol().methAdd.isHideByName;
default:
return true;
}
}
// Returns the virtual that this sym overrides (if IsOverride() is true), null otherwise.
public Symbol SymBaseVirtual()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
return this.AsMethodOrPropertySymbol().swtSlot.Sym;
case SYMKIND.SK_EventSymbol:
default:
return null;
}
}
/*
* returns true if this symbol is a normal symbol visible to the user
*/
public bool isUserCallable()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
return this.AsMethodSymbol().isUserCallable();
default:
break;
}
return true;
}
}
/*
* We have member functions here to do casts that, in DEBUG, check the
* symbol kind to make sure it is right. For example, the casting method
* for METHODSYM is called "asMETHODSYM". In retail builds, these
* methods optimize away to nothing.
*/
internal static class SymbolExtensions
{
public static IEnumerable<Symbol> Children(this ParentSymbol symbol)
{
if (symbol == null)
yield break;
Symbol current = symbol.firstChild;
while (current != null)
{
yield return current;
current = current.nextChild;
}
}
internal static MethodSymbol AsFMETHSYM(this Symbol symbol) { return symbol as MethodSymbol; }
internal static NamespaceOrAggregateSymbol AsNamespaceOrAggregateSymbol(this Symbol symbol) { return symbol as NamespaceOrAggregateSymbol; }
internal static NamespaceSymbol AsNamespaceSymbol(this Symbol symbol) { return symbol as NamespaceSymbol; }
internal static AssemblyQualifiedNamespaceSymbol AsAssemblyQualifiedNamespaceSymbol(this Symbol symbol) { return symbol as AssemblyQualifiedNamespaceSymbol; }
internal static NamespaceDeclaration AsNamespaceDeclaration(this Symbol symbol) { return symbol as NamespaceDeclaration; }
internal static AggregateSymbol AsAggregateSymbol(this Symbol symbol) { return symbol as AggregateSymbol; }
internal static AggregateDeclaration AsAggregateDeclaration(this Symbol symbol) { return symbol as AggregateDeclaration; }
internal static FieldSymbol AsFieldSymbol(this Symbol symbol) { return symbol as FieldSymbol; }
internal static LocalVariableSymbol AsLocalVariableSymbol(this Symbol symbol) { return symbol as LocalVariableSymbol; }
internal static MethodSymbol AsMethodSymbol(this Symbol symbol) { return symbol as MethodSymbol; }
internal static PropertySymbol AsPropertySymbol(this Symbol symbol) { return symbol as PropertySymbol; }
internal static MethodOrPropertySymbol AsMethodOrPropertySymbol(this Symbol symbol) { return symbol as MethodOrPropertySymbol; }
internal static Scope AsScope(this Symbol symbol) { return symbol as Scope; }
internal static TypeParameterSymbol AsTypeParameterSymbol(this Symbol symbol) { return symbol as TypeParameterSymbol; }
internal static EventSymbol AsEventSymbol(this Symbol symbol) { return symbol as EventSymbol; }
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Dumps commands in QueryStatus and Exec.
// #define DUMP_COMMANDS
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.InteractiveWindow.Shell
{
internal sealed class VsInteractiveWindowCommandFilter : IOleCommandTarget
{
//
// Command filter chain:
// *window* -> VsTextView -> ... -> *pre-language + the current language service's filter* -> editor services -> *preEditor* -> editor
//
private IOleCommandTarget _preLanguageCommandFilter;
private IOleCommandTarget _editorServicesCommandFilter;
private IOleCommandTarget _preEditorCommandFilter;
private IOleCommandTarget _editorCommandFilter;
// we route undo/redo commands to this target:
internal IOleCommandTarget currentBufferCommandHandler;
internal IOleCommandTarget firstLanguageServiceCommandFilter;
private readonly IInteractiveWindow _window;
internal readonly IVsTextView textViewAdapter;
private readonly IWpfTextViewHost _textViewHost;
internal readonly IEnumerable<Lazy<IVsInteractiveWindowOleCommandTargetProvider, ContentTypeMetadata>> _oleCommandTargetProviders;
internal readonly IContentTypeRegistryService _contentTypeRegistry;
public VsInteractiveWindowCommandFilter(IVsEditorAdaptersFactoryService adapterFactory, IInteractiveWindow window, IVsTextView textViewAdapter, IVsTextBuffer bufferAdapter, IEnumerable<Lazy<IVsInteractiveWindowOleCommandTargetProvider, ContentTypeMetadata>> oleCommandTargetProviders, IContentTypeRegistryService contentTypeRegistry)
{
_window = window;
_oleCommandTargetProviders = oleCommandTargetProviders;
_contentTypeRegistry = contentTypeRegistry;
this.textViewAdapter = textViewAdapter;
// make us a code window so we'll have the same colors as a normal code window.
IVsTextEditorPropertyContainer propContainer;
ErrorHandler.ThrowOnFailure(((IVsTextEditorPropertyCategoryContainer)textViewAdapter).GetPropertyCategory(Microsoft.VisualStudio.Editor.DefGuidList.guidEditPropCategoryViewMasterSettings, out propContainer));
propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewComposite_AllCodeWindowDefaults, true);
propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGlobalOpt_AutoScrollCaretOnTextEntry, true);
// editor services are initialized in textViewAdapter.Initialize - hook underneath them:
_preEditorCommandFilter = new CommandFilter(this, CommandFilterLayer.PreEditor);
ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(_preEditorCommandFilter, out _editorCommandFilter));
textViewAdapter.Initialize(
(IVsTextLines)bufferAdapter,
IntPtr.Zero,
(uint)TextViewInitFlags.VIF_HSCROLL | (uint)TextViewInitFlags.VIF_VSCROLL | (uint)TextViewInitFlags3.VIF_NO_HWND_SUPPORT,
new[] { new INITVIEW { fSelectionMargin = 0, fWidgetMargin = 0, fVirtualSpace = 0, fDragDropMove = 1 } });
// disable change tracking because everything will be changed
var textViewHost = adapterFactory.GetWpfTextViewHost(textViewAdapter);
_preLanguageCommandFilter = new CommandFilter(this, CommandFilterLayer.PreLanguage);
ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(_preLanguageCommandFilter, out _editorServicesCommandFilter));
_textViewHost = textViewHost;
}
private IOleCommandTarget TextViewCommandFilterChain
{
get
{
// Non-character command processing starts with WindowFrame which calls ReplWindow.Exec.
// We need to invoke the view's Exec method in order to invoke its full command chain
// (features add their filters to the view).
return (IOleCommandTarget)textViewAdapter;
}
}
#region IOleCommandTarget
public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
var nextTarget = TextViewCommandFilterChain;
return nextTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
var nextTarget = TextViewCommandFilterChain;
return nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
#endregion
public IWpfTextViewHost TextViewHost
{
get
{
return _textViewHost;
}
}
private enum CommandFilterLayer
{
PreLanguage,
PreEditor
}
private sealed class CommandFilter : IOleCommandTarget
{
private readonly VsInteractiveWindowCommandFilter _window;
private readonly CommandFilterLayer _layer;
public CommandFilter(VsInteractiveWindowCommandFilter window, CommandFilterLayer layer)
{
_window = window;
_layer = layer;
}
public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
try
{
switch (_layer)
{
case CommandFilterLayer.PreLanguage:
return _window.PreLanguageCommandFilterQueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
case CommandFilterLayer.PreEditor:
return _window.PreEditorCommandFilterQueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
default:
throw Roslyn.Utilities.ExceptionUtilities.UnexpectedValue(_layer);
}
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
{
// Exceptions should not escape from command filters.
return _window._editorCommandFilter.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
}
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
try
{
switch (_layer)
{
case CommandFilterLayer.PreLanguage:
return _window.PreLanguageCommandFilterExec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
case CommandFilterLayer.PreEditor:
return _window.PreEditorCommandFilterExec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
default:
throw Roslyn.Utilities.ExceptionUtilities.UnexpectedValue(_layer);
}
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
{
// Exceptions should not escape from command filters.
return _window._editorCommandFilter.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
}
}
private int PreEditorCommandFilterQueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
if (pguidCmdGroup == Guids.InteractiveCommandSetId)
{
switch ((CommandIds)prgCmds[0].cmdID)
{
case CommandIds.BreakLine:
prgCmds[0].cmdf = _window.CurrentLanguageBuffer != null ? CommandEnabled : CommandDisabled;
prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU;
return VSConstants.S_OK;
}
}
else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
{
switch ((VSConstants.VSStd97CmdID)prgCmds[0].cmdID)
{
// TODO: Add support of rotating clipboard ring
// https://github.com/dotnet/roslyn/issues/5651
case VSConstants.VSStd97CmdID.PasteNextTBXCBItem:
prgCmds[0].cmdf = CommandDisabled;
return VSConstants.S_OK;
}
}
return _editorCommandFilter.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
private int PreEditorCommandFilterExec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
var nextTarget = _editorCommandFilter;
if (pguidCmdGroup == Guids.InteractiveCommandSetId)
{
switch ((CommandIds)nCmdID)
{
case CommandIds.BreakLine:
if (_window.Operations.BreakLine())
{
return VSConstants.S_OK;
}
break;
}
}
else if (pguidCmdGroup == VSConstants.VSStd2K)
{
switch ((VSConstants.VSStd2KCmdID)nCmdID)
{
case VSConstants.VSStd2KCmdID.TYPECHAR:
{
var operations = _window.Operations as IInteractiveWindowOperations2;
if (operations != null)
{
char typedChar = (char)(ushort)System.Runtime.InteropServices.Marshal.GetObjectForNativeVariant(pvaIn);
operations.TypeChar(typedChar);
return VSConstants.S_OK;
}
else
{
_window.Operations.Delete();
}
break;
}
case VSConstants.VSStd2KCmdID.RETURN:
if (_window.Operations.Return())
{
return VSConstants.S_OK;
}
break;
// TODO:
//case VSConstants.VSStd2KCmdID.DELETEWORDLEFT:
//case VSConstants.VSStd2KCmdID.DELETEWORDRIGHT:
// break;
case VSConstants.VSStd2KCmdID.BACKSPACE:
_window.Operations.Backspace();
return VSConstants.S_OK;
case VSConstants.VSStd2KCmdID.UP:
if (_window.CurrentLanguageBuffer != null && !_window.IsRunning && CaretAtEnd && UseSmartUpDown)
{
_window.Operations.HistoryPrevious();
return VSConstants.S_OK;
}
break;
case VSConstants.VSStd2KCmdID.DOWN:
if (_window.CurrentLanguageBuffer != null && !_window.IsRunning && CaretAtEnd && UseSmartUpDown)
{
_window.Operations.HistoryNext();
return VSConstants.S_OK;
}
break;
case VSConstants.VSStd2KCmdID.CANCEL:
if (_window.TextView.Selection.IsEmpty)
{
_window.Operations.Cancel();
}
break;
case VSConstants.VSStd2KCmdID.BOL:
_window.Operations.Home(false);
return VSConstants.S_OK;
case VSConstants.VSStd2KCmdID.BOL_EXT:
_window.Operations.Home(true);
return VSConstants.S_OK;
case VSConstants.VSStd2KCmdID.EOL:
_window.Operations.End(false);
return VSConstants.S_OK;
case VSConstants.VSStd2KCmdID.EOL_EXT:
_window.Operations.End(true);
return VSConstants.S_OK;
case VSConstants.VSStd2KCmdID.CUTLINE:
{
var operations = _window.Operations as IInteractiveWindowOperations2;
if (operations != null)
{
operations.CutLine();
return VSConstants.S_OK;
}
}
break;
case VSConstants.VSStd2KCmdID.DELETELINE:
{
var operations = _window.Operations as IInteractiveWindowOperations2;
if (operations != null)
{
operations.DeleteLine();
return VSConstants.S_OK;
}
}
break;
}
}
else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
{
switch ((VSConstants.VSStd97CmdID)nCmdID)
{
// TODO: Add support of rotating clipboard ring
// https://github.com/dotnet/roslyn/issues/5651
case VSConstants.VSStd97CmdID.PasteNextTBXCBItem:
return (int)OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED;
case VSConstants.VSStd97CmdID.Paste:
_window.Operations.Paste();
return VSConstants.S_OK;
case VSConstants.VSStd97CmdID.Cut:
_window.Operations.Cut();
return VSConstants.S_OK;
case VSConstants.VSStd97CmdID.Copy:
{
var operations = _window.Operations as IInteractiveWindowOperations2;
if (operations != null)
{
operations.Copy();
return VSConstants.S_OK;
}
}
break;
case VSConstants.VSStd97CmdID.Delete:
_window.Operations.Delete();
return VSConstants.S_OK;
case VSConstants.VSStd97CmdID.SelectAll:
_window.Operations.SelectAll();
return VSConstants.S_OK;
}
}
return nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
private int PreLanguageCommandFilterQueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
var nextTarget = firstLanguageServiceCommandFilter ?? _editorServicesCommandFilter;
if (pguidCmdGroup == Guids.InteractiveCommandSetId)
{
switch ((CommandIds)prgCmds[0].cmdID)
{
case CommandIds.HistoryNext:
case CommandIds.HistoryPrevious:
case CommandIds.SearchHistoryNext:
case CommandIds.SearchHistoryPrevious:
case CommandIds.SmartExecute:
// TODO: Submit?
prgCmds[0].cmdf = _window.CurrentLanguageBuffer != null ? CommandEnabled : CommandDisabled;
prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU;
return VSConstants.S_OK;
case CommandIds.AbortExecution:
prgCmds[0].cmdf = _window.IsRunning ? CommandEnabled : CommandDisabled;
prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU;
return VSConstants.S_OK;
case CommandIds.Reset:
prgCmds[0].cmdf = !_window.IsResetting ? CommandEnabled : CommandDisabled;
prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU;
return VSConstants.S_OK;
default:
prgCmds[0].cmdf = CommandEnabled;
break;
}
prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU;
}
else if (currentBufferCommandHandler != null && pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
{
// undo/redo support:
switch ((VSConstants.VSStd97CmdID)prgCmds[0].cmdID)
{
case VSConstants.VSStd97CmdID.Undo:
case VSConstants.VSStd97CmdID.MultiLevelUndo:
case VSConstants.VSStd97CmdID.MultiLevelUndoList:
case VSConstants.VSStd97CmdID.Redo:
case VSConstants.VSStd97CmdID.MultiLevelRedo:
case VSConstants.VSStd97CmdID.MultiLevelRedoList:
return currentBufferCommandHandler.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
}
if (nextTarget != null)
{
var result = nextTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
#if DUMP_COMMANDS
//DumpCmd("QS", result, ref pguidCmdGroup, prgCmds[0].cmdID, prgCmds[0].cmdf);
#endif
return result;
}
return VSConstants.E_FAIL;
}
private int PreLanguageCommandFilterExec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
var nextTarget = firstLanguageServiceCommandFilter ?? _editorServicesCommandFilter;
if (pguidCmdGroup == Guids.InteractiveCommandSetId)
{
switch ((CommandIds)nCmdID)
{
case CommandIds.AbortExecution: _window.Evaluator.AbortExecution(); return VSConstants.S_OK;
case CommandIds.Reset: _window.Operations.ResetAsync(); return VSConstants.S_OK;
case CommandIds.SmartExecute: _window.Operations.ExecuteInput(); return VSConstants.S_OK;
case CommandIds.HistoryNext: _window.Operations.HistoryNext(); return VSConstants.S_OK;
case CommandIds.HistoryPrevious: _window.Operations.HistoryPrevious(); return VSConstants.S_OK;
case CommandIds.ClearScreen: _window.Operations.ClearView(); return VSConstants.S_OK;
case CommandIds.SearchHistoryNext:
_window.Operations.HistorySearchNext();
return VSConstants.S_OK;
case CommandIds.SearchHistoryPrevious:
_window.Operations.HistorySearchPrevious();
return VSConstants.S_OK;
}
}
else if (pguidCmdGroup == VSConstants.VSStd2K)
{
switch ((VSConstants.VSStd2KCmdID)nCmdID)
{
case VSConstants.VSStd2KCmdID.RETURN:
if (_window.Operations.TrySubmitStandardInput())
{
return VSConstants.S_OK;
}
break;
case VSConstants.VSStd2KCmdID.SHOWCONTEXTMENU:
ShowContextMenu();
return VSConstants.S_OK;
}
}
else if (currentBufferCommandHandler != null && pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97)
{
// undo/redo support:
switch ((VSConstants.VSStd97CmdID)nCmdID)
{
// TODO: remove (https://github.com/dotnet/roslyn/issues/5642)
case VSConstants.VSStd97CmdID.FindReferences:
return VSConstants.S_OK;
case VSConstants.VSStd97CmdID.Undo:
case VSConstants.VSStd97CmdID.MultiLevelUndo:
case VSConstants.VSStd97CmdID.MultiLevelUndoList:
case VSConstants.VSStd97CmdID.Redo:
case VSConstants.VSStd97CmdID.MultiLevelRedo:
case VSConstants.VSStd97CmdID.MultiLevelRedoList:
return currentBufferCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
}
int res = nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
#if DUMP_COMMANDS
DumpCmd("Exec", result, ref pguidCmdGroup, nCmdID, 0);
#endif
return res;
}
private void ShowContextMenu()
{
var uishell = (IVsUIShell)InteractiveWindowPackage.GetGlobalService(typeof(SVsUIShell));
if (uishell != null)
{
var pt = System.Windows.Forms.Cursor.Position;
var position = new[] { new POINTS { x = (short)pt.X, y = (short)pt.Y } };
var guid = Guids.InteractiveCommandSetId;
ErrorHandler.ThrowOnFailure(uishell.ShowContextMenu(0, ref guid, (int)MenuIds.InteractiveWindowContextMenu, position, this));
}
}
private const uint CommandEnabled = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED);
private const uint CommandDisabled = (uint)(OLECMDF.OLECMDF_SUPPORTED);
private const uint CommandDisabledAndHidden = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED);
private bool CaretAtEnd
{
get
{
var caret = _window.TextView.Caret;
return caret.Position.BufferPosition.Position == caret.Position.BufferPosition.Snapshot.Length;
}
}
private bool UseSmartUpDown
{
get
{
return _window.TextView.Options.GetOptionValue(InteractiveWindowOptions.SmartUpDown);
}
}
public IOleCommandTarget EditorServicesCommandFilter
{
get
{
return _editorServicesCommandFilter;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Grace.Data.Immutable;
using Grace.DependencyInjection.Exceptions;
using Grace.DependencyInjection.Impl.KnownTypeStrategies;
using Grace.DependencyInjection.Impl.Wrappers;
using Grace.Diagnostics;
namespace Grace.DependencyInjection.Impl
{
/// <summary>
/// Root injection scope that is inherited by the Dependency injection container
/// </summary>
[DebuggerDisplay("{" + nameof(DebugDisplayString) + ",nq}")]
[DebuggerTypeProxy(typeof(InjectionScopeDebuggerView))]
public class InjectionScope : BaseExportLocatorScope, IInjectionScope
{
#region Fields
/// <summary>
/// Internal field storage
/// </summary>
protected InternalFieldStorageClass InternalFieldStorage = new InternalFieldStorageClass();
/// <summary>
/// string constant that is used to locate a lock for adding strategies to the container
/// Note: Do not use this unless you are working on container internals
/// </summary>
public const string ActivationStrategyAddLockName = "ActivationStrategyAddLock";
#endregion
#region Constructors
/// <summary>
/// Constructor that takes configuration action
/// </summary>
/// <param name="configuration">configuration action</param>
public InjectionScope(Action<InjectionScopeConfiguration> configuration) : this(CreateConfiguration(configuration), null, "RootScope")
{
}
/// <summary>
/// Constructor takes a configuration object
/// </summary>
/// <param name="configuration"></param>
public InjectionScope(IInjectionScopeConfiguration configuration) : this(configuration, null, "RootScope")
{
}
/// <summary>
/// Configuration object constructor
/// </summary>
/// <param name="configuration"></param>
/// <param name="parent"></param>
/// <param name="name"></param>
public InjectionScope(IInjectionScopeConfiguration configuration, IInjectionScope parent, string name) :
base(parent, name, new ActivationStrategyDelegateCache())
{
configuration.SetInjectionScope(this);
InternalFieldStorage.ScopeConfiguration = configuration;
InternalFieldStorage.InjectionContextCreator = configuration.Implementation.Locate<IInjectionContextCreator>();
InternalFieldStorage.CanLocateTypeService = configuration.Implementation.Locate<ICanLocateTypeService>();
InternalFieldStorage.ActivationStrategyCompiler = configuration.Implementation.Locate<IActivationStrategyCompiler>();
InternalFieldStorage.StrategyCollectionContainer =
AddDisposable(configuration.Implementation.Locate<IActivationStrategyCollectionContainer<ICompiledExportStrategy>>());
InternalFieldStorage.DecoratorCollectionContainer =
AddDisposable(configuration.Implementation.Locate<IActivationStrategyCollectionContainer<ICompiledDecoratorStrategy>>());
if (configuration.AutoRegisterUnknown && Parent == null)
{
InternalFieldStorage.MissingExportStrategyProviders =
InternalFieldStorage.MissingExportStrategyProviders.Add(
configuration.Implementation.Locate<IMissingExportStrategyProvider>());
}
if (configuration.SupportFuncType)
{
StrategyCollectionContainer.AddStrategy(new FuncTypeStrategy(this));
}
}
#endregion
#region Public members
/// <summary>
/// Scope configuration
/// </summary>
public IInjectionScopeConfiguration ScopeConfiguration => InternalFieldStorage.ScopeConfiguration;
/// <summary>
/// Compiler that produces Activation Strategy Delegates
/// </summary>
IActivationStrategyCompiler IInjectionScope.StrategyCompiler => InternalFieldStorage.ActivationStrategyCompiler;
/// <summary>
/// Can Locator type
/// </summary>
/// <param name="type">type to locate</param>
/// <param name="consider"></param>
/// <param name="key">key to use while locating</param>
/// <returns></returns>
public override bool CanLocate(Type type, ActivationStrategyFilter consider = null, object key = null)
{
return InternalFieldStorage.CanLocateTypeService.CanLocate(this, type, consider, key);
}
/// <summary>
/// Locate specific type using extra data or key
/// </summary>
/// <param name="type">type to locate</param>
/// <param name="extraData">extra data to be used during construction</param>
/// <param name="consider">filter out exports you don't want to consider</param>
/// <param name="withKey">key to use for locating type</param>
/// <param name="isDynamic">skip cache and look through exports</param>
/// <returns>located instance</returns>
// ReSharper disable once MethodOverloadWithOptionalParameter
public override object Locate(Type type, object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false)
{
IInjectionContext context = extraData == null ?
null : CreateInjectionContextFromExtraData(type, extraData);
if (withKey == null && consider == null && !isDynamic)
{
return DelegateCache.ExecuteActivationStrategyDelegateWithContext(type, this, false, context);
}
return InternalLocate(this, this, type, consider, withKey, context, false, isDynamic);
}
/// <summary>
/// Locate specific type using extra data or key
/// </summary>
/// <typeparam name="T">type to locate</typeparam>
/// <param name="extraData">extra data</param>
/// <param name="consider">filter out exports you don't want to consider</param>
/// <param name="withKey">key to use during construction</param>
/// <param name="isDynamic">skip cache and look at all strategies</param>
/// <returns>located instance</returns>
// ReSharper disable once MethodOverloadWithOptionalParameter
public override T Locate<T>(object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false)
{
return (T)Locate(typeof(T), extraData, consider, withKey, isDynamic);
}
/// <summary>
/// Locate all instances of a type
/// </summary>
/// <param name="type">type to locate</param>
/// <param name="extraData">extra data </param>
/// <param name="consider">provide method to filter out exports</param>
/// <param name="comparer">comparer to use for sorting</param>
/// <returns>list of all type</returns>
public override List<object> LocateAll(Type type, object extraData = null, ActivationStrategyFilter consider = null, IComparer<object> comparer = null)
{
return ((IInjectionScope)this).InternalLocateAll(this, this, type, extraData, consider, comparer);
}
/// <summary>
/// Locate all of a specific type
/// </summary>
/// <typeparam name="T">type to locate</typeparam>
/// <param name="type">type to locate</param>
/// <param name="extraData">extra data to use during construction</param>
/// <param name="consider">provide method to filter out exports</param>
/// <param name="comparer">comparer to use for sorting</param>
/// <returns>list of all located</returns>
public override List<T> LocateAll<T>(Type type = null, object extraData = null, ActivationStrategyFilter consider = null, IComparer<T> comparer = null)
{
return ((IInjectionScope)this).InternalLocateAll(this, this, type ?? typeof(T), extraData, consider, comparer);
}
/// <summary>
/// Try to locate a specific type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">located value</param>
/// <param name="extraData">extra data to be used during construction</param>
/// <param name="consider">filter out exports you don't want</param>
/// <param name="withKey">key to use while locating</param>
/// <param name="isDynamic">skip cache and look at all exports</param>
/// <returns></returns>
public override bool TryLocate<T>(out T value, object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false)
{
var context = CreateInjectionContextFromExtraData(typeof(T), extraData);
var newValue = InternalLocate(this, this, typeof(T), consider, withKey, context, true, isDynamic);
var returnValue = false;
if (newValue != null)
{
returnValue = true;
value = (T)newValue;
}
else
{
value = default(T);
}
return returnValue;
}
/// <summary>
/// Try to locate an export by type
/// </summary>
/// <param name="type">locate type</param>
/// <param name="value">out value</param>
/// <param name="extraData">extra data to use during locate</param>
/// <param name="consider">filter out exports you don't want</param>
/// <param name="withKey">key to use during locate</param>
/// <param name="isDynamic">skip cache and look at all exports</param>
/// <returns>returns tue if export found</returns>
public override bool TryLocate(Type type, out object value, object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false)
{
var context = CreateInjectionContextFromExtraData(type, extraData);
value = InternalLocate(this, this, type, consider, withKey, context, true, isDynamic);
return value != null;
}
/// <summary>
/// Locate by name
/// </summary>
/// <param name="name"></param>
/// <param name="extraData"></param>
/// <param name="consider"></param>
/// <returns></returns>
public override object LocateByName(string name, object extraData = null, ActivationStrategyFilter consider = null)
{
return ((IInjectionScope)this).LocateByNameFromChildScope(this,
this, name, extraData, consider, false);
}
/// <summary>
/// Locate all by specific name
/// </summary>
/// <param name="name"></param>
/// <param name="extraData"></param>
/// <param name="consider"></param>
/// <returns></returns>
public override List<object> LocateAllByName(string name, object extraData = null, ActivationStrategyFilter consider = null)
{
return ((IInjectionScope)this).InternalLocateAllByName(this,
this,
name,
extraData,
consider);
}
/// <summary>
/// Try to locate by name
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="extraData"></param>
/// <param name="consider"></param>
/// <returns></returns>
public override bool TryLocateByName(string name, out object value, object extraData = null, ActivationStrategyFilter consider = null)
{
value = ((IInjectionScope)this).LocateByNameFromChildScope(this,
this, name, extraData, consider, true);
return value != null;
}
/// <summary>
/// Being lifetime scope
/// </summary>
/// <param name="scopeName"></param>
/// <returns></returns>
public override IExportLocatorScope BeginLifetimeScope(string scopeName = "")
{
return new LifetimeScope(this, this, scopeName, DelegateCache);
}
/// <summary>
/// Create injection context
/// </summary>
/// <param name="extraData">extra data</param>
/// <returns></returns>
public override IInjectionContext CreateContext(object extraData = null)
{
return InternalFieldStorage.InjectionContextCreator.CreateContext(extraData);
}
/// <summary>
/// Configure the injection scope
/// </summary>
/// <param name="registrationBlock"></param>
public void Configure(Action<IExportRegistrationBlock> registrationBlock)
{
lock (GetLockObject(ActivationStrategyAddLockName))
{
var provider = ScopeConfiguration.Implementation.Locate<IExportRegistrationBlockValueProvider>();
registrationBlock(provider);
foreach (var inspector in provider.GetInspectors())
{
StrategyCollectionContainer.AddInspector(inspector);
WrapperCollectionContainer.AddInspector(inspector);
DecoratorCollectionContainer.AddInspector(inspector);
}
foreach (var missingExportStrategyProvider in provider.GetMissingExportStrategyProviders())
{
InternalFieldStorage.MissingExportStrategyProviders = InternalFieldStorage.MissingExportStrategyProviders.Add(missingExportStrategyProvider);
}
foreach (var expressionProvider in provider.GetMissingDependencyExpressionProviders())
{
InternalFieldStorage.MissingDependencyExpressionProviders =
InternalFieldStorage.MissingDependencyExpressionProviders.Add(expressionProvider);
}
foreach (var injectionValueProvider in provider.GetValueProviders())
{
InternalFieldStorage.ValueProviders = InternalFieldStorage.ValueProviders.Add(injectionValueProvider);
}
foreach (var compiledWrapperStrategy in provider.GetWrapperStrategies())
{
WrapperCollectionContainer.AddStrategy(compiledWrapperStrategy);
}
foreach (var decorator in provider.GetDecoratorStrategies())
{
DecoratorCollectionContainer.AddStrategy(decorator);
}
foreach (var strategy in provider.GetExportStrategies())
{
StrategyCollectionContainer.AddStrategy(strategy);
foreach (var secondaryStrategy in strategy.SecondaryStrategies())
{
StrategyCollectionContainer.AddStrategy(secondaryStrategy);
}
}
foreach (var selector in provider.GetMemberInjectionSelectors())
{
InternalFieldStorage.MemberInjectionSelectors = InternalFieldStorage.MemberInjectionSelectors.Add(selector);
}
}
}
/// <summary>
/// Configure with module
/// </summary>
/// <param name="module">configuration module</param>
public void Configure(IConfigurationModule module)
{
if (module == null) throw new ArgumentNullException(nameof(module));
Configure(module.Configure);
}
/// <summary>
/// Strategies associated with this scope
/// </summary>
public IActivationStrategyCollectionContainer<ICompiledExportStrategy> StrategyCollectionContainer
=> InternalFieldStorage.StrategyCollectionContainer;
/// <summary>
/// Wrappers associated with this scope
/// </summary>
public IActivationStrategyCollectionContainer<ICompiledWrapperStrategy> WrapperCollectionContainer =>
InternalFieldStorage.Wrappers ?? GetWrappers();
/// <summary>
/// Decorators associated with this scope
/// </summary>
public IActivationStrategyCollectionContainer<ICompiledDecoratorStrategy> DecoratorCollectionContainer
=> InternalFieldStorage.DecoratorCollectionContainer;
/// <summary>
/// Member
/// </summary>
public IEnumerable<IMemberInjectionSelector> MemberInjectionSelectors => InternalFieldStorage.MemberInjectionSelectors;
/// <summary>
/// List of missing export strategy providers
/// </summary>
public IEnumerable<IMissingExportStrategyProvider> MissingExportStrategyProviders => InternalFieldStorage.MissingExportStrategyProviders;
/// <summary>
/// List of missing dependency expression providers
/// </summary>
public IEnumerable<IMissingDependencyExpressionProvider> MissingDependencyExpressionProviders =>
InternalFieldStorage.MissingDependencyExpressionProviders;
/// <summary>
/// List of value providers that can be used during construction of linq expression
/// </summary>
public IEnumerable<IInjectionValueProvider> InjectionValueProviders => InternalFieldStorage.ValueProviders;
/// <summary>
/// Locate an export from a child scope
/// </summary>
/// <param name="childScope">scope where the locate originated</param>
/// <param name="disposalScope"></param>
/// <param name="type">type to locate</param>
/// <param name="extraData"></param>
/// <param name="consider"></param>
/// <param name="key"></param>
/// <param name="allowNull"></param>
/// <param name="isDynamic"></param>
/// <returns>configuration object</returns>
object IInjectionScope.LocateFromChildScope(IExportLocatorScope childScope, IDisposalScope disposalScope, Type type, object extraData, ActivationStrategyFilter consider, object key, bool allowNull, bool isDynamic)
{
return InternalLocate(childScope, disposalScope, type, consider, key, CreateInjectionContextFromExtraData(type, extraData), allowNull, isDynamic);
}
/// <summary>
///
/// </summary>
/// <param name="childScope"></param>
/// <param name="disposalScope"></param>
/// <param name="name"></param>
/// <param name="extraData"></param>
/// <param name="consider"></param>
/// <param name="allowNull"></param>
/// <returns></returns>
object IInjectionScope.LocateByNameFromChildScope(IExportLocatorScope childScope, IDisposalScope disposalScope,
string name,
object extraData, ActivationStrategyFilter consider, bool allowNull)
{
var collection = StrategyCollectionContainer.GetActivationStrategyCollectionByName(name);
ICompiledExportStrategy strategy = null;
if (collection != null)
{
if (consider != null)
{
var context = new StaticInjectionContext(typeof(object));
strategy =
collection.GetStrategies()
.FirstOrDefault(
s => (!s.HasConditions || s.Conditions.All(con => con.MeetsCondition(s, context))) && consider(s));
}
else
{
strategy = collection.GetPrimary();
if (strategy == null)
{
var context = new StaticInjectionContext(typeof(object));
strategy = collection.GetStrategies()
.FirstOrDefault(
s => !s.HasConditions || s.Conditions.All(con => con.MeetsCondition(s, context)));
}
}
}
if (strategy != null)
{
var strategyDelegate =
strategy.GetActivationStrategyDelegate(this, InternalFieldStorage.ActivationStrategyCompiler, typeof(object));
return strategyDelegate(childScope, disposalScope, CreateContext(extraData));
}
if (Parent != null)
{
return ((IInjectionScope)Parent).LocateByNameFromChildScope(childScope, disposalScope, name, extraData,
consider, allowNull);
}
if (!allowNull)
{
throw new LocateException(new StaticInjectionContext(typeof(object)));
}
return null;
}
/// <summary>
/// Internal locate all method
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="scope"></param>
/// <param name="disposalScope"></param>
/// <param name="type"></param>
/// <param name="extraData"></param>
/// <param name="consider"></param>
/// <param name="comparer"></param>
/// <returns></returns>
List<T> IInjectionScope.InternalLocateAll<T>(IExportLocatorScope scope, IDisposalScope disposalScope, Type type, object extraData, ActivationStrategyFilter consider, IComparer<T> comparer)
{
var returnList = new List<T>();
var context = CreateInjectionContextFromExtraData(typeof(T), extraData);
var collection = StrategyCollectionContainer.GetActivationStrategyCollection(type);
if (collection != null)
{
LocateEnumerablesFromStrategyCollection(collection, scope, disposalScope, type, context, consider, returnList);
}
if (type.IsConstructedGenericType)
{
var genericType = type.GetGenericTypeDefinition();
collection = StrategyCollectionContainer.GetActivationStrategyCollection(genericType);
if (collection != null)
{
LocateEnumerablesFromStrategyCollection(collection, scope, disposalScope, type, context, consider, returnList);
}
}
var injectionParent = Parent as IInjectionScope;
if (injectionParent != null)
{
returnList.AddRange(injectionParent.InternalLocateAll<T>(scope, disposalScope, type, context, consider, null));
}
if (comparer != null)
{
returnList.Sort(comparer);
}
return returnList;
}
/// <summary>
///
/// </summary>
/// <param name="scope"></param>
/// <param name="disposalScope"></param>
/// <param name="exportName"></param>
/// <param name="extraData"></param>
/// <param name="consider"></param>
/// <returns></returns>
List<object> IInjectionScope.InternalLocateAllByName(IExportLocatorScope scope, IDisposalScope disposalScope, string exportName, object extraData, ActivationStrategyFilter consider)
{
var context = CreateContext(extraData);
var returnList = new List<object>();
var collection = StrategyCollectionContainer.GetActivationStrategyCollectionByName(exportName);
foreach (var strategy in collection.GetStrategies())
{
if (consider == null || consider(strategy))
{
var activation = strategy.GetActivationStrategyDelegate(this,
InternalFieldStorage.ActivationStrategyCompiler, typeof(object));
returnList.Add(activation(scope, disposalScope, context.Clone()));
}
}
var injectionScopeParent = Parent as IInjectionScope;
if (injectionScopeParent != null)
{
returnList.AddRange(injectionScopeParent.InternalLocateAllByName(scope, disposalScope, exportName, context, consider));
}
return returnList;
}
/// <summary>
/// Creates a new child scope
/// This is best used for long term usage, not per request scenario
/// </summary>
/// <param name="configure">configure scope</param>
/// <param name="scopeName">scope name </param>
/// <returns></returns>
public IInjectionScope CreateChildScope(Action<IExportRegistrationBlock> configure = null, string scopeName = "")
{
var newScope = new InjectionScope(ScopeConfiguration.Clone(), this, scopeName);
if (configure != null)
{
newScope.Configure(configure);
}
return newScope;
}
#endregion
#region Non public members
/// <summary>
/// Creates a new configuration object
/// </summary>
/// <param name="configuration"></param>
/// <returns></returns>
protected static IInjectionScopeConfiguration CreateConfiguration(Action<InjectionScopeConfiguration> configuration)
{
var configurationObject = new InjectionScopeConfiguration();
configuration?.Invoke(configurationObject);
return configurationObject;
}
/// <summary>
/// Create an injection context from extra data
/// </summary>
/// <param name="type"></param>
/// <param name="extraData"></param>
/// <returns></returns>
protected virtual IInjectionContext CreateInjectionContextFromExtraData(Type type, object extraData)
{
return CreateContext(extraData);
}
private object InternalLocate(IExportLocatorScope scope, IDisposalScope disposalScope, Type type, ActivationStrategyFilter consider, object key, IInjectionContext injectionContext, bool allowNull, bool isDynamic)
{
if (type == typeof(ILocatorService) || type == typeof(IExportLocatorScope))
{
return scope;
}
if (isDynamic)
{
if (type.IsArray)
{
return DynamicArray(scope, disposalScope, type, consider, injectionContext);
}
if (type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
return DynamicIEnumerable(scope, disposalScope, type, consider, injectionContext);
}
}
var compiledDelegate = InternalFieldStorage.ActivationStrategyCompiler.FindDelegate(this, type, consider, key, injectionContext, InternalFieldStorage.MissingExportStrategyProviders != ImmutableLinkedList<IMissingExportStrategyProvider>.Empty);
if (compiledDelegate != null)
{
if (key == null && consider == null)
{
compiledDelegate = AddObjectFactory(type, compiledDelegate);
}
return compiledDelegate(scope, disposalScope ?? scope, injectionContext);
}
if (Parent != null)
{
var injectionScopeParent = (IInjectionScope)Parent;
return injectionScopeParent.LocateFromChildScope(scope, disposalScope, type, injectionContext, consider, key, allowNull, isDynamic);
}
if (type == typeof(IInjectionScope) &&
ScopeConfiguration.Behaviors.AllowInjectionScopeLocation)
{
return scope;
}
var value = ScopeConfiguration.Implementation.Locate<IInjectionContextValueProvider>()
.GetValueFromInjectionContext(scope, type, null, injectionContext, !allowNull);
if (value != null)
{
return value;
}
if (!allowNull)
{
throw new LocateException(new StaticInjectionContext(type));
}
return null;
}
private object DynamicIEnumerable(IExportLocatorScope scope, IDisposalScope disposalScope, Type type, ActivationStrategyFilter consider, IInjectionContext injectionContext)
{
if (InternalFieldStorage.DynamicIEnumerableLocator == null)
{
Interlocked.CompareExchange(ref InternalFieldStorage.DynamicIEnumerableLocator,
ScopeConfiguration.Implementation.Locate<IDynamicIEnumerableLocator>(), null);
}
return InternalFieldStorage.DynamicIEnumerableLocator.Locate(this, scope, disposalScope, type, consider, injectionContext);
}
private object DynamicArray(IExportLocatorScope scope, IDisposalScope disposalScope, Type type, ActivationStrategyFilter consider, IInjectionContext injectionContext)
{
if (InternalFieldStorage.DynamicArrayLocator == null)
{
Interlocked.CompareExchange(ref InternalFieldStorage.DynamicArrayLocator,
ScopeConfiguration.Implementation.Locate<IDynamicArrayLocator>(), null);
}
return InternalFieldStorage.DynamicArrayLocator.Locate(this, scope, disposalScope, type, consider, injectionContext);
}
private ActivationStrategyDelegate AddObjectFactory(Type type, ActivationStrategyDelegate activationStrategyDelegate)
{
DelegateCache.AddDelegate(type, activationStrategyDelegate);
return activationStrategyDelegate;
}
private IActivationStrategyCollectionContainer<ICompiledWrapperStrategy> GetWrappers()
{
if (InternalFieldStorage.Wrappers != null)
{
return InternalFieldStorage.Wrappers;
}
var wrapperCollectionProvider = ScopeConfiguration.Implementation.Locate<IDefaultWrapperCollectionProvider>();
if (Interlocked.CompareExchange(ref InternalFieldStorage.Wrappers, wrapperCollectionProvider.ProvideCollection(this), null) == null)
{
AddDisposable(InternalFieldStorage.Wrappers);
}
return InternalFieldStorage.Wrappers;
}
private void LocateEnumerablesFromStrategyCollection<TStrategy, TValue>(IActivationStrategyCollection<TStrategy> collection, IExportLocatorScope scope, IDisposalScope disposalScope, Type type, IInjectionContext context, ActivationStrategyFilter filter, List<TValue> returnList) where TStrategy : IWrapperOrExportActivationStrategy
{
foreach (var strategy in collection.GetStrategies())
{
ProcessStrategyForCollection(scope, disposalScope, type, context, filter, returnList, strategy);
}
if (InternalFieldStorage.ScopeConfiguration.ReturnKeyedInEnumerable)
{
foreach (var keyValuePair in collection.GetKeyedStrategies())
{
ProcessStrategyForCollection(scope, disposalScope, type, context, filter, returnList, keyValuePair.Value);
}
}
}
private void ProcessStrategyForCollection<TStrategy, TValue>(IExportLocatorScope scope, IDisposalScope disposalScope,
Type type, IInjectionContext context, ActivationStrategyFilter filter, List<TValue> returnList, TStrategy strategy)
where TStrategy : IWrapperOrExportActivationStrategy
{
if (strategy.HasConditions)
{
var pass = true;
foreach (var condition in strategy.Conditions)
{
if (!condition.MeetsCondition(strategy, new StaticInjectionContext(type)))
{
pass = false;
break;
}
}
if (!pass)
{
return;
}
}
if (filter != null && !filter(strategy))
{
return;
}
var activationDelegate =
strategy.GetActivationStrategyDelegate(this, InternalFieldStorage.ActivationStrategyCompiler, type);
if (activationDelegate != null)
{
returnList.Add(
(TValue)activationDelegate(scope, disposalScope, context?.Clone()));
}
}
private string DebugDisplayString => "Exports: " + StrategyCollectionContainer.GetAllStrategies().Count();
#endregion
#region Internal storage class
/// <summary>
/// Class for storing fields for injection scope,
/// Fields that are not on the fast path are put in this class to keep the injection scope as light as possible
/// </summary>
protected class InternalFieldStorageClass
{
/// <summary>
/// List of member injection selectors
/// </summary>
public ImmutableLinkedList<IMemberInjectionSelector> MemberInjectionSelectors = ImmutableLinkedList<IMemberInjectionSelector>.Empty;
/// <summary>
/// List of missing dependency expression providers
/// </summary>
public ImmutableLinkedList<IMissingDependencyExpressionProvider> MissingDependencyExpressionProviders = ImmutableLinkedList<IMissingDependencyExpressionProvider>.Empty;
/// <summary>
/// Dynamic array locator
/// </summary>
public IDynamicArrayLocator DynamicArrayLocator;
/// <summary>
/// dynamic ienumerable locator
/// </summary>
public IDynamicIEnumerableLocator DynamicIEnumerableLocator;
/// <summary>
/// Wrappers for scope
/// </summary>
public IActivationStrategyCollectionContainer<ICompiledWrapperStrategy> Wrappers;
/// <summary>
/// Value providers
/// </summary>
public ImmutableLinkedList<IInjectionValueProvider> ValueProviders = ImmutableLinkedList<IInjectionValueProvider>.Empty;
/// <summary>
/// Missing export strategy providers
/// </summary>
public ImmutableLinkedList<IMissingExportStrategyProvider> MissingExportStrategyProviders =
ImmutableLinkedList<IMissingExportStrategyProvider>.Empty;
/// <summary>
/// activation strategy compiler
/// </summary>
public IActivationStrategyCompiler ActivationStrategyCompiler;
/// <summary>
/// Strategy collection
/// </summary>
public IActivationStrategyCollectionContainer<ICompiledExportStrategy> StrategyCollectionContainer;
/// <summary>
/// Decorators
/// </summary>
public IActivationStrategyCollectionContainer<ICompiledDecoratorStrategy> DecoratorCollectionContainer;
/// <summary>
/// Scope configuration
/// </summary>
public IInjectionScopeConfiguration ScopeConfiguration;
/// <summary>
/// Creates injection context when needed
/// </summary>
public IInjectionContextCreator InjectionContextCreator;
/// <summary>
/// Implementation to tell if a type can be located
/// </summary>
public ICanLocateTypeService CanLocateTypeService;
}
#endregion
}
}
| |
//
// KyuBatch.cs
//
// Author:
// Jarl Erik Schmidt <[email protected]>
//
// Copyright (c) 2013 Jarl Erik Schmidt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace Winterday.MonoGame.Graphics
{
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
/// <summary>
/// An alternative to <see cref="Microsoft.Xna.Framework.Graphics.SpriteBatch"/> that allows quads to be
/// positioned and rotated along three axises.
/// </summary>
public class KyuBatch : IDisposable
{
const int DefaultCapacity = 256;
const int VerticesPerQuad = 6;
// 0 3--4
// |\ \ |
// | \ \|
// 1--2 5
const int TriOne_TopLeft = 0;
const int TriOne_BottomLeft = 1;
const int TriOne_BottomRight = 2;
const int TriTwo_TopLeft = 3;
const int TriTwo_TopRight = 4;
const int TriTwo_BottomRight = 5;
readonly GraphicsDevice _device;
readonly BasicEffect _effect;
readonly int _capacity;
readonly VertexPositionColorTexture[] _vertexData;
int _count = 0;
bool _started;
public Vector3 CameraPosition { get; set; }
public bool IsOrthographic { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Winterday.MonoGame.Graphics.KyuBatch"/> class.
/// </summary>
/// <param name="device">The current graphicsdevice.</param>
/// <param name="capacity">The maximum number of quads per draw call for the instance.</param>
public KyuBatch (GraphicsDevice device, int capacity = DefaultCapacity)
{
if (device == null)
throw new ArgumentNullException ("device");
if (capacity < 1)
throw new ArgumentException ("Batch must have a capacity of at least one item", "capacity");
_device = device;
_capacity = capacity;
IsOrthographic = true;
_vertexData = new VertexPositionColorTexture[capacity * VerticesPerQuad];
_effect = new BasicEffect (device);
}
/// <summary>
/// Unload this instance.
/// </summary>
public void Unload ()
{
_effect.Dispose ();
}
/// <summary>
/// Reset this instance, discarding any batched draw calls
/// </summary>
public void Reset ()
{
_effect.Texture = null;
_started = false;
_count = 0;
}
/// <summary>
/// Sets necessary graphics modes and prepares the batch to draw.
/// </summary>
/// <remarks>Must be called before <see cref="Draw"/>.</remarks>
/// <remarks>
/// Throws <see cref="System.InvalidOperationException"/> if <see cref="Begin()"/>
/// has already been called.
/// </remarks>
public void Begin ()
{
Begin (null, null);
}
/// <summary>
/// Sets necessary graphics modes and prepares the batch to draw.
/// </summary>
/// <param name="matrixProvider">Provider for world, view and projection matrices</param>
/// <remarks>Must be called before <see cref="Draw()"/>.</remarks>
/// <remarks>
/// Throws <see cref="System.InvalidOperationException"/> if <see cref="Begin()"/>
/// has already been called.
/// </remarks>
public void Begin (IMatrixProvider matrixProvider)
{
Begin (null, matrixProvider);
}
/// <summary>
/// Sets necessary graphics modes and prepares the batch to draw.
/// </summary>
/// <param name="texture">The texture for drawn quads</param>
/// <remarks>Must be called before <see cref="Draw"/>.</remarks>
/// <remarks>
/// Throws <see cref="System.InvalidOperationException"/> if <see cref="Begin()"/>
/// has already been called.
/// </remarks>
public void Begin (Texture2D texture)
{
Begin (texture, null);
}
/// <summary>
/// Sets necessary graphics modes and prepares the batch to draw.
/// </summary>
/// <param name="texture">The texture for drawn quads</param>
/// <param name="matrixProvider">Provider for world, view and projection matrices</param>
/// <remarks>Must be called before <see cref="Draw"/>.</remarks>
/// <remarks>
/// Throws <see cref="System.InvalidOperationException"/> if <see cref="Begin()"/>
/// has already been called.
/// </remarks>
public void Begin (Texture2D texture, IMatrixProvider matrixProvider)
{
if (_started) {
throw new InvalidOperationException ("Begin() has already been called");
}
_started = true;
if (matrixProvider != null) {
_effect.World = matrixProvider.WorldMatrix;
_effect.View = matrixProvider.ViewMatrix;
_effect.Projection = matrixProvider.ProjectionMatrix;
} else {
var viewport = _device.Viewport;
_effect.World = Matrix.Identity;
_effect.View = Matrix.CreateLookAt (new Vector3(0, 0, 1), Vector3.Zero, Vector3.Up);
_effect.Projection = Matrix.CreateOrthographicOffCenter (0, viewport.Width, viewport.Height, 0, 1, 1000);
}
_effect.Alpha = 0.5f;
_effect.DiffuseColor = Color.White.ToVector3 ();
_effect.SpecularColor = _effect.DiffuseColor;
_effect.AmbientLightColor = _effect.DiffuseColor;
_effect.Texture = texture;
_effect.TextureEnabled = texture != null;
_effect.VertexColorEnabled = true;
_effect.LightingEnabled = false;
}
/// <summary>
/// Batches a draw call for a quad with the given parameters.
/// </summary>
/// <param name="position">Position of the quad in 3D space</param>
/// <param name="rotation">Rotation of quad allong 3 axies</param>
/// <param name="size">The size of the quad</param>
/// <param name="scale">Scaling to apply to the quad</param>
/// <param name="sourceRect">Source rectangle (ignored if no texture is specified)</param>
/// <param name="color">The vertex color for the quad</param>
/// <remarks>
/// Throws <see cref="System.InvalidOperationException"/> if <see cref="Begin()"/>
/// has not been called.
/// </remarks>
public void Draw (Vector3 position, Vector3 rotation, Vector2 size, Vector2 scale, Vector4 sourceRect, Color color)
{
Draw (ref position, ref rotation, ref size, ref scale, ref sourceRect, ref color);
}
/// <summary>
/// Batches a draw call for a quad with the given parameters.
/// </summary>
/// <param name="position">Position of the quad in 3D space</param>
/// <param name="rotation">Rotation of quad allong 3 axies</param>
/// <param name="size">The size of the quad</param>
/// <param name="scale">Scaling to apply to the quad</param>
/// <param name="sourceRect">Source rectangle (ignored if no texture is specified)</param>
/// <param name="color">The vertex color for the quad</param>
/// <remarks>
/// Throws <see cref="System.InvalidOperationException"/> if <see cref="Begin()"/>
/// has not been called.
/// </remarks>
public void Draw (
ref Vector3 position, ref Vector3 rotation, ref Vector2 size, ref Vector2 scale,ref Vector4 sourceRect, ref Color color
)
{
if (!_started) {
throw new InvalidOperationException ("Call Begin() first");
}
if (_count == _capacity)
Flush ();
int offset = _count;
var transform = Matrix.Identity *
Matrix.CreateFromYawPitchRoll (rotation.X, rotation.Y, rotation.Z) *
Matrix.CreateScale (scale.X, scale.Y, 1) *
Matrix.CreateTranslation (position.X, position.Y, position.Z);
var x2 = size.X / 2;
var x1 = -x2;
var y2 = size.Y / 2;
var y1 = -y2;
var tx1 = sourceRect.X;
var tx2 = sourceRect.X + sourceRect.Z;
var ty1 = sourceRect.Y;
var ty2 = sourceRect.Y + sourceRect.W;
setVertex (x1, y1, tx1, ty1, ref transform, ref color, ref _vertexData [offset + TriOne_TopLeft]);
setVertex (x2, y1, tx2, ty1, ref transform, ref color, ref _vertexData [offset + TriTwo_TopRight]);
setVertex (x1, y2, tx1, ty2, ref transform, ref color, ref _vertexData [offset + TriOne_BottomLeft]);
setVertex (x2, y2, tx2, ty2, ref transform, ref color, ref _vertexData [offset + TriOne_BottomRight]);
_vertexData [offset + TriTwo_TopLeft] = _vertexData [offset + TriOne_TopLeft];
_vertexData [offset + TriTwo_BottomRight] = _vertexData [offset + TriOne_BottomRight];
_count += VerticesPerQuad;
}
void setVertex (
float x, float y, float tx, float ty, ref Matrix transform, ref Color color,
ref VertexPositionColorTexture vertex
)
{
vertex.Color = color;
vertex.Position = Vector3.Transform (new Vector3 (x, y, 0), transform);
vertex.TextureCoordinate = new Vector2 (tx, ty);
}
/// <summary>
/// Draws all the batched quads to the graphics device.
/// </summary>
/// <remarks>
/// Throws <see cref="System.InvalidOperationException"/> if <see cref="Begin()"/>
/// has not been called.
/// </remarks>
public void End ()
{
if (!_started) {
throw new InvalidOperationException ("Call Begin() first");
}
Flush ();
_started = false;
_effect.Texture = null;
}
void Flush ()
{
_device.RasterizerState = new RasterizerState () { CullMode = CullMode.None };
foreach (var technique in _effect.Techniques) {
foreach (var pass in technique.Passes) {
pass.Apply ();
_device.DrawUserPrimitives<VertexPositionColorTexture>(PrimitiveType.TriangleList,
_vertexData, 0, _count);
}
}
_effect.End ();
_count = 0;
}
/// <summary>
/// Releases all resource used by the <see cref="Winterday.MonoGame.Graphics.KyuBatch"/> object.
/// </summary>
/// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="Winterday.MonoGame.Graphics.KyuBatch"/>. The
/// <see cref="Dispose"/> method leaves the <see cref="Winterday.MonoGame.Graphics.KyuBatch"/> in an unusable state.
/// After calling <see cref="Dispose"/>, you must release all references to the
/// <see cref="Winterday.MonoGame.Graphics.KyuBatch"/> so the garbage collector can reclaim the memory that the
/// <see cref="Winterday.MonoGame.Graphics.KyuBatch"/> was occupying.</remarks>
public void Dispose ()
{
_effect.Dispose ();
}
}
}
| |
using System;
using TrueCraft.API;
using TrueCraft.Core.Logic.Items;
using TrueCraft.API.Logic;
using TrueCraft.API.World;
using TrueCraft.API.Networking;
using fNbt;
using TrueCraft.Core.Windows;
using System.Collections.Generic;
using TrueCraft.Core.Entities;
namespace TrueCraft.Core.Logic.Blocks
{
public class ChestBlock : BlockProvider, ICraftingRecipe
{
public static readonly byte BlockID = 0x36;
public override byte ID { get { return 0x36; } }
public override double BlastResistance { get { return 12.5; } }
public override double Hardness { get { return 2.5; } }
public override byte Luminance { get { return 0; } }
public override bool Opaque { get { return false; } }
public override string DisplayName { get { return "Chest"; } }
public override Tuple<int, int> GetTextureMap(byte metadata)
{
return new Tuple<int, int>(10, 1);
}
public ItemStack[,] Pattern
{
get
{
return new[,]
{
{
new ItemStack(WoodenPlanksBlock.BlockID),
new ItemStack(WoodenPlanksBlock.BlockID),
new ItemStack(WoodenPlanksBlock.BlockID)
},
{
new ItemStack(WoodenPlanksBlock.BlockID),
ItemStack.EmptyStack,
new ItemStack(WoodenPlanksBlock.BlockID)
},
{
new ItemStack(WoodenPlanksBlock.BlockID),
new ItemStack(WoodenPlanksBlock.BlockID),
new ItemStack(WoodenPlanksBlock.BlockID)
}
};
}
}
public ItemStack Output
{
get { return new ItemStack(BlockID); }
}
public bool SignificantMetadata
{
get { return false; }
}
private static readonly Coordinates3D[] AdjacentBlocks =
{
Coordinates3D.North,
Coordinates3D.South,
Coordinates3D.West,
Coordinates3D.East
};
public override void ItemUsedOnBlock(Coordinates3D coordinates, ItemStack item, BlockFace face, IWorld world, IRemoteClient user)
{
int adjacent = 0;
var coords = coordinates + MathHelper.BlockFaceToCoordinates(face);
Coordinates3D _ = Coordinates3D.Down;
// Check for adjacent chests. We can only allow one adjacent check block.
for (int i = 0; i < AdjacentBlocks.Length; i++)
{
if (world.GetBlockID(coords + AdjacentBlocks[i]) == ChestBlock.BlockID)
{
_ = coords + AdjacentBlocks[i];
adjacent++;
}
}
if (adjacent <= 1)
{
if (_ != Coordinates3D.Down)
{
// Confirm that adjacent chest is not a double chest
for (int i = 0; i < AdjacentBlocks.Length; i++)
{
if (world.GetBlockID(_ + AdjacentBlocks[i]) == ChestBlock.BlockID)
adjacent++;
}
}
if (adjacent <= 1)
base.ItemUsedOnBlock(coordinates, item, face, world, user);
}
}
public override void BlockPlaced(BlockDescriptor descriptor, BlockFace face, IWorld world, IRemoteClient user)
{
world.SetMetadata(descriptor.Coordinates, (byte)MathHelper.DirectionByRotationFlat(user.Entity.Yaw, true));
}
public override bool BlockRightClicked(BlockDescriptor descriptor, BlockFace face, IWorld world, IRemoteClient user)
{
var adjacent = -Coordinates3D.One; // -1, no adjacent chest
var self = descriptor.Coordinates;
for (int i = 0; i < AdjacentBlocks.Length; i++)
{
var test = self + AdjacentBlocks[i];
if (world.GetBlockID(test) == ChestBlock.BlockID)
{
adjacent = test;
var up = world.BlockRepository.GetBlockProvider(world.GetBlockID(test + Coordinates3D.Up));
if (up.Opaque && !(up is WallSignBlock)) // Wall sign blocks are an exception
return false; // Obstructed
break;
}
}
var upSelf = world.BlockRepository.GetBlockProvider(world.GetBlockID(self + Coordinates3D.Up));
if (upSelf.Opaque && !(upSelf is WallSignBlock))
return false; // Obstructed
if (adjacent != -Coordinates3D.One)
{
// Ensure that chests are always opened in the same arrangement
if (adjacent.X < self.X ||
adjacent.Z < self.Z)
{
var _ = adjacent;
adjacent = self;
self = _; // Swap
}
}
var window = new ChestWindow((InventoryWindow)user.Inventory, adjacent != -Coordinates3D.One);
// Add items
var entity = world.GetTileEntity(self);
if (entity != null)
{
foreach (var item in (NbtList)entity["Items"])
{
var slot = ItemStack.FromNbt((NbtCompound)item);
window.ChestInventory[slot.Index] = slot;
}
}
// Add adjacent items
if (adjacent != -Coordinates3D.One)
{
entity = world.GetTileEntity(adjacent);
if (entity != null)
{
foreach (var item in (NbtList)entity["Items"])
{
var slot = ItemStack.FromNbt((NbtCompound)item);
window.ChestInventory[slot.Index + ChestWindow.DoubleChestSecondaryIndex] = slot;
}
}
}
window.WindowChange += (sender, e) =>
{
var entitySelf = new NbtList("Items", NbtTagType.Compound);
var entityAdjacent = new NbtList("Items", NbtTagType.Compound);
for (int i = 0; i < window.ChestInventory.Items.Length; i++)
{
var item = window.ChestInventory.Items[i];
if (!item.Empty)
{
if (i < ChestWindow.DoubleChestSecondaryIndex)
{
item.Index = i;
entitySelf.Add(item.ToNbt());
}
else
{
item.Index = i - ChestWindow.DoubleChestSecondaryIndex;
entityAdjacent.Add(item.ToNbt());
}
}
}
var newEntity = world.GetTileEntity(self);
if (newEntity == null)
newEntity = new NbtCompound(new[] { entitySelf });
else
newEntity["Items"] = entitySelf;
world.SetTileEntity(self, newEntity);
if (adjacent != -Coordinates3D.One)
{
newEntity = world.GetTileEntity(adjacent);
if (newEntity == null)
newEntity = new NbtCompound(new[] { entityAdjacent });
else
newEntity["Items"] = entityAdjacent;
world.SetTileEntity(adjacent, newEntity);
}
};
user.OpenWindow(window);
return false;
}
public override void BlockMined(BlockDescriptor descriptor, BlockFace face, IWorld world, IRemoteClient user)
{
var self = descriptor.Coordinates;
var entity = world.GetTileEntity(self);
var manager = user.Server.GetEntityManagerForWorld(world);
if (entity != null)
{
foreach (var item in (NbtList)entity["Items"])
{
var slot = ItemStack.FromNbt((NbtCompound)item);
manager.SpawnEntity(new ItemEntity(descriptor.Coordinates + new Vector3(0.5), slot));
}
}
world.SetTileEntity(self, null);
base.BlockMined(descriptor, face, world, user);
}
}
}
| |
using IntuiLab.Kinect.DataUserTracking;
using IntuiLab.Kinect.Enums;
using Microsoft.Kinect;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Media.Media3D;
namespace IntuiLab.Kinect.GestureRecognizer.Gestures
{
internal class PushCondition : Condition
{
#region Fields
/// <summary>
/// Instance of Checker
/// </summary>
private readonly Checker m_refChecker;
/// <summary>
/// Hand treated
/// </summary>
private readonly JointType m_refHand;
/// <summary>
/// Movement direction to hand
/// </summary>
private EnumKinectDirectionGesture m_refDirection;
/// <summary>
/// Consecutive numbers of frame where the condition is satisfied
/// </summary>
private int m_nIndex;
/// <summary>
/// Informe if the gesture is begin
/// </summary>
private bool m_GestureBegin;
/// <summary>
/// Hand velocity in each frame
/// </summary>
private List<double> m_handVelocity;
/// <summary>
/// Hand position when the gesture begin
/// </summary>
private Point3D m_refStartPoint;
#endregion
/// <summary>
/// Constructor
/// </summary>
/// <param name="refUser">User data</param>
/// <param name="leftOrRightHand">Hand treated</param>
public PushCondition(UserData refUser, JointType leftOrRightHand)
: base(refUser)
{
m_nIndex = 0;
m_refHand = leftOrRightHand;
m_refChecker = new Checker(refUser, PropertiesPluginKinect.Instance.PushCheckerTolerance);
m_handVelocity = new List<double>();
m_GestureBegin = false;
}
/// <summary>
/// See description in Condition class
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected override void Check(object sender, NewSkeletonEventArgs e)
{
// Relative position between HipCenter and Hand
List<EnumKinectDirectionGesture> handToHipOrientation = m_refChecker.GetRelativePosition(JointType.HipCenter, m_refHand).ToList();
// Movement directions to hand
List<EnumKinectDirectionGesture> handMovement = m_refChecker.GetAbsoluteMovement(m_refHand).ToList();
// Relative velocity of hand
m_handVelocity.Add(m_refChecker.GetRelativeVelocity(JointType.HipCenter, m_refHand));
double handVelocity = m_refChecker.GetRelativeVelocity(JointType.HipCenter, m_refHand);
if (m_refHand == JointType.HandRight)
{
IntuiLab.Kinect.Utils.DebugLog.DebugTraceLog("Push speed = " + handVelocity, false);
}
// Speed condition
if (handVelocity < PropertiesPluginKinect.Instance.PushLowerBoundForVelocity)
{
Reset();
}
// Condition : Hand is in front of the body
else if (handToHipOrientation.Contains(EnumKinectDirectionGesture.KINECT_DIRECTION_FORWARD)
&& handToHipOrientation.Contains(EnumKinectDirectionGesture.KINECT_DIRECTION_UPWARD))
{
// Movement did not start yet, initializing
if (m_refDirection == EnumKinectDirectionGesture.KINECT_DIRECTION_NONE)
{
// Condition : Movement direction hand => forward
if (handMovement.Contains(EnumKinectDirectionGesture.KINECT_DIRECTION_FORWARD))
{
m_GestureBegin = true;
m_refDirection = EnumKinectDirectionGesture.KINECT_DIRECTION_FORWARD;
// Save the start hand position
m_refStartPoint = new Point3D(
e.m_refSkeletonData.GetJointPosition(m_refHand).X,
e.m_refSkeletonData.GetJointPosition(m_refHand).Y,
e.m_refSkeletonData.GetJointPosition(m_refHand).Z);
// Notify the gesture Push is begin
RaiseGestureBegining(this, new BeginGestureEventArgs
{
Gesture = EnumGesture.GESTURE_PUSH,
Posture = EnumPosture.POSTURE_NONE
});
}
else
{
// Take other direction
Reset();
}
}
// Movement direction hand changed
else if (!handMovement.Contains(m_refDirection))
{
Reset();
}
else
{
// Gesture Push is complete
if (m_nIndex >= PropertiesPluginKinect.Instance.PushLowerBoundForSuccess)
{
// Get the end hand position
Point3D endPoint = new Point3D(
e.m_refSkeletonData.GetJointPosition(m_refHand).X,
e.m_refSkeletonData.GetJointPosition(m_refHand).Y,
e.m_refSkeletonData.GetJointPosition(m_refHand).Z);
// difference between the start and end point
double dx = endPoint.X - m_refStartPoint.X;
double dy = endPoint.Y - m_refStartPoint.Y;
double dz = endPoint.Z - m_refStartPoint.Z;
// Condition : Square 15cm aroud the start position in X-Axis and Y-Axis && the hand forward at least 10cm in Z-Axis
if (Math.Abs(dx) < 0.15 && Math.Abs(dy) < 0.15 && Math.Abs(dz) > 0.1)
{
// Calculate mean velocity
double meanVelocity = 0;
foreach (double velocity in m_handVelocity)
{
meanVelocity += velocity;
}
meanVelocity = meanVelocity / (double)m_handVelocity.Count;
IntuiLab.Kinect.Utils.DebugLog.DebugTraceLog("Mean Velocity = " + meanVelocity, false);
// Notify Gesture Push is detected
FireSucceeded(this, new SuccessGestureEventArgs
{
Gesture = EnumGesture.GESTURE_PUSH,
Posture = EnumPosture.POSTURE_NONE
});
IntuiLab.Kinect.Utils.DebugLog.DebugTraceLog("Condition Push complete", false);
m_nIndex = 0;
m_refDirection = EnumKinectDirectionGesture.KINECT_DIRECTION_NONE;
}
else
{
Reset();
}
}
// Step successful, waiting for next
else
{
m_nIndex++;
}
}
}
}
/// <summary>
/// Restart detecting
/// </summary>
private void Reset()
{
// If gesture begin, notify gesture is end
if (m_GestureBegin)
{
m_GestureBegin = false;
RaiseGestureEnded(this, new EndGestureEventArgs
{
Gesture = EnumGesture.GESTURE_PUSH,
Posture = EnumPosture.POSTURE_NONE
});
}
m_nIndex = 0;
m_refDirection = EnumKinectDirectionGesture.KINECT_DIRECTION_NONE;
m_refStartPoint = new Point3D();
m_handVelocity.Clear();
FireFailed(this, new FailedGestureEventArgs
{
refCondition = this
});
}
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net.Sockets
{
internal static class SocketPal
{
public const bool SupportsMultipleConnectAttempts = true;
private static void MicrosecondsToTimeValue(long microseconds, ref Interop.Winsock.TimeValue socketTime)
{
const int microcnv = 1000000;
socketTime.Seconds = (int)(microseconds / microcnv);
socketTime.Microseconds = (int)(microseconds % microcnv);
}
public static void Initialize()
{
// Ensure that WSAStartup has been called once per process.
// The System.Net.NameResolution contract is responsible for the initialization.
Dns.GetHostName();
}
public static SocketError GetLastSocketError()
{
int win32Error = Marshal.GetLastWin32Error();
Debug.Assert(win32Error != 0, "Expected non-0 error");
return (SocketError)win32Error;
}
public static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeCloseSocket socket)
{
socket = SafeCloseSocket.CreateWSASocket(addressFamily, socketType, protocolType);
return socket.IsInvalid ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetBlocking(SafeCloseSocket handle, bool shouldBlock, out bool willBlock)
{
int intBlocking = shouldBlock ? 0 : -1;
SocketError errorCode;
errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONBIO,
ref intBlocking);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
willBlock = intBlocking == 0;
return errorCode;
}
public static SocketError GetSockName(SafeCloseSocket handle, byte[] buffer, ref int nameLen)
{
SocketError errorCode = Interop.Winsock.getsockname(handle, buffer, ref nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetAvailable(SafeCloseSocket handle, out int available)
{
int value = 0;
SocketError errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONREAD,
ref value);
available = value;
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetPeerName(SafeCloseSocket handle, byte[] buffer, ref int nameLen)
{
SocketError errorCode = Interop.Winsock.getpeername(handle, buffer, ref nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Bind(SafeCloseSocket handle, ProtocolType socketProtocolType, byte[] buffer, int nameLen)
{
SocketError errorCode = Interop.Winsock.bind(handle, buffer, nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Listen(SafeCloseSocket handle, int backlog)
{
SocketError errorCode = Interop.Winsock.listen(handle, backlog);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Accept(SafeCloseSocket handle, byte[] buffer, ref int nameLen, out SafeCloseSocket socket)
{
socket = SafeCloseSocket.Accept(handle, buffer, ref nameLen);
return socket.IsInvalid ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Connect(SafeCloseSocket handle, byte[] peerAddress, int peerAddressLen)
{
SocketError errorCode = Interop.Winsock.WSAConnect(
handle.DangerousGetHandle(),
peerAddress,
peerAddressLen,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Send(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out int bytesTransferred)
{
int count = buffers.Count;
WSABuffer[] WSABuffers = new WSABuffer[count];
GCHandle[] objectsToPin = null;
try
{
objectsToPin = new GCHandle[count];
for (int i = 0; i < count; ++i)
{
ArraySegment<byte> buffer = buffers[i];
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
}
unsafe
{
SocketError errorCode = Interop.Winsock.WSASend(
handle.DangerousGetHandle(),
WSABuffers,
count,
out bytesTransferred,
socketFlags,
null,
IntPtr.Zero);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
finally
{
if (objectsToPin != null)
{
for (int i = 0; i < objectsToPin.Length; ++i)
{
if (objectsToPin[i].IsAllocated)
{
objectsToPin[i].Free();
}
}
}
}
}
public static unsafe SocketError Send(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) =>
Send(handle, new ReadOnlySpan<byte>(buffer, offset, size), socketFlags, out bytesTransferred);
public static unsafe SocketError Send(SafeCloseSocket handle, ReadOnlySpan<byte> buffer, SocketFlags socketFlags, out int bytesTransferred)
{
int bytesSent;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
bytesSent = Interop.Winsock.send(handle.DangerousGetHandle(), bufferPtr, buffer.Length, socketFlags);
}
if (bytesSent == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesSent;
return SocketError.Success;
}
public static unsafe SocketError SendFile(SafeCloseSocket handle, SafeFileHandle fileHandle, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
{
fixed (byte* prePinnedBuffer = preBuffer)
fixed (byte* postPinnedBuffer = postBuffer)
{
bool success = TransmitFileHelper(handle, fileHandle, null, preBuffer, postBuffer, flags);
return (success ? SocketError.Success : SocketPal.GetLastSocketError());
}
}
public static unsafe SocketError SendTo(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] peerAddress, int peerAddressSize, out int bytesTransferred)
{
int bytesSent;
if (buffer.Length == 0)
{
bytesSent = Interop.Winsock.sendto(
handle.DangerousGetHandle(),
null,
0,
socketFlags,
peerAddress,
peerAddressSize);
}
else
{
fixed (byte* pinnedBuffer = &buffer[0])
{
bytesSent = Interop.Winsock.sendto(
handle.DangerousGetHandle(),
pinnedBuffer + offset,
size,
socketFlags,
peerAddress,
peerAddressSize);
}
}
if (bytesSent == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesSent;
return SocketError.Success;
}
public static SocketError Receive(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, ref SocketFlags socketFlags, out int bytesTransferred)
{
int count = buffers.Count;
WSABuffer[] WSABuffers = new WSABuffer[count];
GCHandle[] objectsToPin = null;
try
{
objectsToPin = new GCHandle[count];
for (int i = 0; i < count; ++i)
{
ArraySegment<byte> buffer = buffers[i];
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
}
unsafe
{
SocketError errorCode = Interop.Winsock.WSARecv(
handle.DangerousGetHandle(),
WSABuffers,
count,
out bytesTransferred,
ref socketFlags,
null,
IntPtr.Zero);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
finally
{
if (objectsToPin != null)
{
for (int i = 0; i < objectsToPin.Length; ++i)
{
if (objectsToPin[i].IsAllocated)
{
objectsToPin[i].Free();
}
}
}
}
}
public static unsafe SocketError Receive(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) =>
Receive(handle, new Span<byte>(buffer, offset, size), socketFlags, out bytesTransferred);
public static unsafe SocketError Receive(SafeCloseSocket handle, Span<byte> buffer, SocketFlags socketFlags, out int bytesTransferred)
{
int bytesReceived;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
bytesReceived = Interop.Winsock.recv(handle.DangerousGetHandle(), bufferPtr, buffer.Length, socketFlags);
}
if (bytesReceived == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesReceived;
return SocketError.Success;
}
public static unsafe IPPacketInformation GetIPPacketInformation(Interop.Winsock.ControlData* controlBuffer)
{
IPAddress address = controlBuffer->length == UIntPtr.Zero ? IPAddress.None : new IPAddress((long)controlBuffer->address);
return new IPPacketInformation(address, (int)controlBuffer->index);
}
public static unsafe IPPacketInformation GetIPPacketInformation(Interop.Winsock.ControlDataIPv6* controlBuffer)
{
IPAddress address = controlBuffer->length != UIntPtr.Zero ?
new IPAddress(new Span<byte>(controlBuffer->address, Interop.Winsock.IPv6AddressLength)) :
IPAddress.IPv6None;
return new IPPacketInformation(address, (int)controlBuffer->index);
}
public static unsafe SocketError ReceiveMessageFrom(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int size, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
{
bool ipv4, ipv6;
Socket.GetIPProtocolInformation(socket.AddressFamily, socketAddress, out ipv4, out ipv6);
bytesTransferred = 0;
receiveAddress = socketAddress;
ipPacketInformation = default(IPPacketInformation);
fixed (byte* ptrBuffer = buffer)
fixed (byte* ptrSocketAddress = socketAddress.Buffer)
{
Interop.Winsock.WSAMsg wsaMsg;
wsaMsg.socketAddress = (IntPtr)ptrSocketAddress;
wsaMsg.addressLength = (uint)socketAddress.Size;
wsaMsg.flags = socketFlags;
WSABuffer wsaBuffer;
wsaBuffer.Length = size;
wsaBuffer.Pointer = (IntPtr)(ptrBuffer + offset);
wsaMsg.buffers = (IntPtr)(&wsaBuffer);
wsaMsg.count = 1;
if (ipv4)
{
Interop.Winsock.ControlData controlBuffer;
wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer);
wsaMsg.controlBuffer.Length = sizeof(Interop.Winsock.ControlData);
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
(IntPtr)(&wsaMsg),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
return GetLastSocketError();
}
ipPacketInformation = GetIPPacketInformation(&controlBuffer);
}
else if (ipv6)
{
Interop.Winsock.ControlDataIPv6 controlBuffer;
wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer);
wsaMsg.controlBuffer.Length = sizeof(Interop.Winsock.ControlDataIPv6);
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
(IntPtr)(&wsaMsg),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
return GetLastSocketError();
}
ipPacketInformation = GetIPPacketInformation(&controlBuffer);
}
else
{
wsaMsg.controlBuffer.Pointer = IntPtr.Zero;
wsaMsg.controlBuffer.Length = 0;
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
(IntPtr)(&wsaMsg),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
return GetLastSocketError();
}
}
socketFlags = wsaMsg.flags;
}
return SocketError.Success;
}
public static unsafe SocketError ReceiveFrom(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] socketAddress, ref int addressLength, out int bytesTransferred)
{
int bytesReceived;
if (buffer.Length == 0)
{
bytesReceived = Interop.Winsock.recvfrom(handle.DangerousGetHandle(), null, 0, socketFlags, socketAddress, ref addressLength);
}
else
{
fixed (byte* pinnedBuffer = &buffer[0])
{
bytesReceived = Interop.Winsock.recvfrom(handle.DangerousGetHandle(), pinnedBuffer + offset, size, socketFlags, socketAddress, ref addressLength);
}
}
if (bytesReceived == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesReceived;
return SocketError.Success;
}
public static SocketError WindowsIoctl(SafeCloseSocket handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength)
{
if (ioControlCode == Interop.Winsock.IoctlSocketConstants.FIONBIO)
{
throw new InvalidOperationException(SR.net_sockets_useblocking);
}
SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking(
handle.DangerousGetHandle(),
ioControlCode,
optionInValue,
optionInValue != null ? optionInValue.Length : 0,
optionOutValue,
optionOutValue != null ? optionOutValue.Length : 0,
out optionLength,
IntPtr.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static unsafe SocketError SetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
ref optionValue,
sizeof(int));
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
optionValue,
optionValue != null ? optionValue.Length : 0);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static void SetReceivingDualModeIPv4PacketInformation(Socket socket)
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
}
public static SocketError SetMulticastOption(SafeCloseSocket handle, SocketOptionName optionName, MulticastOption optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest();
#pragma warning disable CS0618 // Address is marked obsolete
ipmr.MulticastAddress = unchecked((int)optionValue.Group.Address);
#pragma warning restore CS0618
if (optionValue.LocalAddress != null)
{
#pragma warning disable CS0618 // Address is marked obsolete
ipmr.InterfaceAddress = unchecked((int)optionValue.LocalAddress.Address);
#pragma warning restore CS0618
}
else
{ //this structure works w/ interfaces as well
int ifIndex = IPAddress.HostToNetworkOrder(optionValue.InterfaceIndex);
ipmr.InterfaceAddress = unchecked((int)ifIndex);
}
#if BIGENDIAN
ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) |
(((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) |
(((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) |
((uint) ipmr.MulticastAddress >> 24));
if (optionValue.LocalAddress != null)
{
ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) |
(((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) |
(((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) |
((uint) ipmr.InterfaceAddress >> 24));
}
#endif
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.IP,
optionName,
ref ipmr,
Interop.Winsock.IPMulticastRequest.Size);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetIPv6MulticastOption(SafeCloseSocket handle, SocketOptionName optionName, IPv6MulticastOption optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest();
ipmr.MulticastAddress = optionValue.Group.GetAddressBytes();
ipmr.InterfaceIndex = unchecked((int)optionValue.InterfaceIndex);
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.IPv6,
optionName,
ref ipmr,
Interop.Winsock.IPv6MulticastRequest.Size);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetLingerOption(SafeCloseSocket handle, LingerOption optionValue)
{
Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger();
lngopt.OnOff = optionValue.Enabled ? (ushort)1 : (ushort)0;
lngopt.Time = (ushort)optionValue.LingerTime;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
ref lngopt,
4);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static void SetIPProtectionLevel(Socket socket, SocketOptionLevel optionLevel, int protectionLevel)
{
socket.SetSocketOption(optionLevel, SocketOptionName.IPProtectionLevel, protectionLevel);
}
public static SocketError GetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue)
{
int optionLength = 4; // sizeof(int)
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
optionName,
out optionValue,
ref optionLength);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue, ref int optionLength)
{
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
optionName,
optionValue,
ref optionLength);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetMulticastOption(SafeCloseSocket handle, SocketOptionName optionName, out MulticastOption optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest();
int optlen = Interop.Winsock.IPMulticastRequest.Size;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.IP,
optionName,
out ipmr,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(MulticastOption);
return GetLastSocketError();
}
#if BIGENDIAN
ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) |
(((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) |
(((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) |
((uint) ipmr.MulticastAddress >> 24));
ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) |
(((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) |
(((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) |
((uint) ipmr.InterfaceAddress >> 24));
#endif // BIGENDIAN
IPAddress multicastAddr = new IPAddress(ipmr.MulticastAddress);
IPAddress multicastIntr = new IPAddress(ipmr.InterfaceAddress);
optionValue = new MulticastOption(multicastAddr, multicastIntr);
return SocketError.Success;
}
public static SocketError GetIPv6MulticastOption(SafeCloseSocket handle, SocketOptionName optionName, out IPv6MulticastOption optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest();
int optlen = Interop.Winsock.IPv6MulticastRequest.Size;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.IP,
optionName,
out ipmr,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(IPv6MulticastOption);
return GetLastSocketError();
}
optionValue = new IPv6MulticastOption(new IPAddress(ipmr.MulticastAddress), ipmr.InterfaceIndex);
return SocketError.Success;
}
public static SocketError GetLingerOption(SafeCloseSocket handle, out LingerOption optionValue)
{
Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger();
int optlen = 4;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
out lngopt,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(LingerOption);
return GetLastSocketError();
}
optionValue = new LingerOption(lngopt.OnOff != 0, (int)lngopt.Time);
return SocketError.Success;
}
public static SocketError Poll(SafeCloseSocket handle, int microseconds, SelectMode mode, out bool status)
{
IntPtr rawHandle = handle.DangerousGetHandle();
IntPtr[] fileDescriptorSet = new IntPtr[2] { (IntPtr)1, rawHandle };
Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue();
// A negative timeout value implies an indefinite wait.
int socketCount;
if (microseconds != -1)
{
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
Interop.Winsock.select(
0,
mode == SelectMode.SelectRead ? fileDescriptorSet : null,
mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
mode == SelectMode.SelectError ? fileDescriptorSet : null,
ref IOwait);
}
else
{
socketCount =
Interop.Winsock.select(
0,
mode == SelectMode.SelectRead ? fileDescriptorSet : null,
mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
mode == SelectMode.SelectError ? fileDescriptorSet : null,
IntPtr.Zero);
}
if ((SocketError)socketCount == SocketError.SocketError)
{
status = false;
return GetLastSocketError();
}
status = (int)fileDescriptorSet[0] != 0 && fileDescriptorSet[1] == rawHandle;
return SocketError.Success;
}
public static SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds)
{
IntPtr[] readfileDescriptorSet = Socket.SocketListToFileDescriptorSet(checkRead);
IntPtr[] writefileDescriptorSet = Socket.SocketListToFileDescriptorSet(checkWrite);
IntPtr[] errfileDescriptorSet = Socket.SocketListToFileDescriptorSet(checkError);
// This code used to erroneously pass a non-null timeval structure containing zeroes
// to select() when the caller specified (-1) for the microseconds parameter. That
// caused select to actually have a *zero* timeout instead of an infinite timeout
// turning the operation into a non-blocking poll.
//
// Now we pass a null timeval struct when microseconds is (-1).
//
// Negative microsecond values that weren't exactly (-1) were originally successfully
// converted to a timeval struct containing unsigned non-zero integers. This code
// retains that behavior so that any app working around the original bug with,
// for example, (-2) specified for microseconds, will continue to get the same behavior.
int socketCount;
if (microseconds != -1)
{
Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue();
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
Interop.Winsock.select(
0, // ignored value
readfileDescriptorSet,
writefileDescriptorSet,
errfileDescriptorSet,
ref IOwait);
}
else
{
socketCount =
Interop.Winsock.select(
0, // ignored value
readfileDescriptorSet,
writefileDescriptorSet,
errfileDescriptorSet,
IntPtr.Zero);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Interop.Winsock.select returns socketCount:{socketCount}");
if ((SocketError)socketCount == SocketError.SocketError)
{
return GetLastSocketError();
}
Socket.SelectFileDescriptor(checkRead, readfileDescriptorSet);
Socket.SelectFileDescriptor(checkWrite, writefileDescriptorSet);
Socket.SelectFileDescriptor(checkError, errfileDescriptorSet);
return SocketError.Success;
}
public static SocketError Shutdown(SafeCloseSocket handle, bool isConnected, bool isDisconnected, SocketShutdown how)
{
SocketError err = Interop.Winsock.shutdown(handle, (int)how);
if (err != SocketError.SocketError)
{
return SocketError.Success;
}
err = GetLastSocketError();
Debug.Assert(err != SocketError.NotConnected || (!isConnected && !isDisconnected));
return err;
}
public static unsafe SocketError ConnectAsync(Socket socket, SafeCloseSocket handle, byte[] socketAddress, int socketAddressLen, ConnectOverlappedAsyncResult asyncResult)
{
// This will pin the socketAddress buffer.
asyncResult.SetUnmanagedStructures(socketAddress);
try
{
int ignoreBytesSent;
bool success = socket.ConnectEx(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(socketAddress, 0),
socketAddressLen,
IntPtr.Zero,
0,
out ignoreBytesSent,
asyncResult.DangerousOverlappedPointer); // SafeHandle was just created in SetUnmanagedStructures
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError SendAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up unmanaged structures for overlapped WSASend.
asyncResult.SetUnmanagedStructures(buffer, offset, count, null);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASend(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
ref asyncResult._singleBuffer,
1, // There is only ever 1 buffer being sent.
out bytesTransferred,
socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError SendAsync(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASend.
asyncResult.SetUnmanagedStructures(buffers);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASend(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
asyncResult._wsaBuffers,
asyncResult._wsaBuffers.Length,
out bytesTransferred,
socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
// This assumes preBuffer/postBuffer are pinned already
private static unsafe bool TransmitFileHelper(
SafeHandle socket,
SafeHandle fileHandle,
NativeOverlapped* overlapped,
byte[] preBuffer,
byte[] postBuffer,
TransmitFileOptions flags)
{
bool needTransmitFileBuffers = false;
Interop.Mswsock.TransmitFileBuffers transmitFileBuffers = default(Interop.Mswsock.TransmitFileBuffers);
if (preBuffer != null && preBuffer.Length > 0)
{
needTransmitFileBuffers = true;
transmitFileBuffers.Head = Marshal.UnsafeAddrOfPinnedArrayElement(preBuffer, 0);
transmitFileBuffers.HeadLength = preBuffer.Length;
}
if (postBuffer != null && postBuffer.Length > 0)
{
needTransmitFileBuffers = true;
transmitFileBuffers.Tail = Marshal.UnsafeAddrOfPinnedArrayElement(postBuffer, 0);
transmitFileBuffers.TailLength = postBuffer.Length;
}
bool success = Interop.Mswsock.TransmitFile(socket, fileHandle, 0, 0, overlapped,
needTransmitFileBuffers ? &transmitFileBuffers : null, flags);
return success;
}
public static unsafe SocketError SendFileAsync(SafeCloseSocket handle, FileStream fileStream, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, TransmitFileAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(fileStream, preBuffer, postBuffer, (flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0);
try
{
bool success = TransmitFileHelper(
handle,
fileStream?.SafeFileHandle,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
preBuffer,
postBuffer,
flags);
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError SendToAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASendTo.
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASendTo(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
ref asyncResult._singleBuffer,
1, // There is only ever 1 buffer being sent.
out bytesTransferred,
socketFlags,
asyncResult.GetSocketAddressPtr(),
asyncResult.SocketAddress.Size,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSARecv.
asyncResult.SetUnmanagedStructures(buffer, offset, count, null);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecv(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
ref asyncResult._singleBuffer,
1,
out bytesTransferred,
ref socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveAsync(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASend.
asyncResult.SetUnmanagedStructures(buffers);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecv(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
asyncResult._wsaBuffers,
asyncResult._wsaBuffers.Length,
out bytesTransferred,
ref socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveFromAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSARecvFrom.
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecvFrom(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
ref asyncResult._singleBuffer,
1,
out bytesTransferred,
ref socketFlags,
asyncResult.GetSocketAddressPtr(),
asyncResult.GetSocketAddressSizePtr(),
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveMessageFromAsync(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, socketFlags);
try
{
int bytesTransfered;
SocketError errorCode = (SocketError)socket.WSARecvMsg(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
out bytesTransfered,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransfered);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError AcceptAsync(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult)
{
// The buffer needs to contain the requested data plus room for two sockaddrs and 16 bytes
// of associated data for each.
int addressBufferSize = socketAddressSize + 16;
byte[] buffer = new byte[receiveSize + ((addressBufferSize) * 2)];
// Set up asyncResult for overlapped AcceptEx.
// This call will use completion ports on WinNT.
asyncResult.SetUnmanagedStructures(buffer, addressBufferSize);
try
{
// This can throw ObjectDisposedException.
int bytesTransferred;
bool success = socket.AcceptEx(
handle,
acceptHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.Buffer, 0),
receiveSize,
addressBufferSize,
addressBufferSize,
out bytesTransferred,
asyncResult.DangerousOverlappedPointer); // SafeHandle was just created in SetUnmanagedStructures
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static void CheckDualModeReceiveSupport(Socket socket)
{
// Dual-mode sockets support received packet info on Windows.
}
internal static unsafe SocketError DisconnectAsync(Socket socket, SafeCloseSocket handle, bool reuseSocket, DisconnectOverlappedAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(null);
try
{
// This can throw ObjectDisposedException
bool success = socket.DisconnectEx(
handle,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
(int)(reuseSocket ? TransmitFileOptions.ReuseSocket : 0),
0);
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
internal static SocketError Disconnect(Socket socket, SafeCloseSocket handle, bool reuseSocket)
{
SocketError errorCode = SocketError.Success;
// This can throw ObjectDisposedException (handle, and retrieving the delegate).
if (!socket.DisconnectExBlocking(handle, IntPtr.Zero, (int)(reuseSocket ? TransmitFileOptions.ReuseSocket : 0), 0))
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
}
| |
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
namespace DockSample
{
public partial class MainForm : Form
{
private bool m_bSaveLayout = true;
private DeserializeDockContent m_deserializeDockContent;
private DummySolutionExplorer m_solutionExplorer;
private DummyPropertyWindow m_propertyWindow;
private DummyToolbox m_toolbox;
private DummyOutputWindow m_outputWindow;
private DummyTaskList m_taskList;
private bool _showSplash;
private SplashScreen _splashScreen;
public MainForm()
{
InitializeComponent();
AutoScaleMode = AutoScaleMode.Dpi;
SetSplashScreen();
CreateStandardControls();
showRightToLeft.Checked = (RightToLeft == RightToLeft.Yes);
RightToLeftLayout = showRightToLeft.Checked;
m_solutionExplorer.RightToLeftLayout = RightToLeftLayout;
m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);
vsToolStripExtender1.DefaultRenderer = _toolStripProfessionalRenderer;
SetSchema(this.menuItemSchemaVS2013Blue, null);
}
#region Methods
private IDockContent FindDocument(string text)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
foreach (Form form in MdiChildren)
if (form.Text == text)
return form as IDockContent;
return null;
}
else
{
foreach (IDockContent content in dockPanel.Documents)
if (content.DockHandler.TabText == text)
return content;
return null;
}
}
private DummyDoc CreateNewDocument()
{
DummyDoc dummyDoc = new DummyDoc();
int count = 1;
string text = $"Document{count}";
while (FindDocument(text) != null)
{
count++;
text = $"Document{count}";
}
dummyDoc.Text = text;
return dummyDoc;
}
private DummyDoc CreateNewDocument(string text)
{
DummyDoc dummyDoc = new DummyDoc();
dummyDoc.Text = text;
return dummyDoc;
}
private void CloseAllDocuments()
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
foreach (Form form in MdiChildren)
form.Close();
}
else
{
foreach (IDockContent document in dockPanel.DocumentsToArray())
{
// IMPORANT: dispose all panes.
document.DockHandler.DockPanel = null;
document.DockHandler.Close();
}
}
}
private IDockContent GetContentFromPersistString(string persistString)
{
if (persistString == typeof(DummySolutionExplorer).ToString())
return m_solutionExplorer;
else if (persistString == typeof(DummyPropertyWindow).ToString())
return m_propertyWindow;
else if (persistString == typeof(DummyToolbox).ToString())
return m_toolbox;
else if (persistString == typeof(DummyOutputWindow).ToString())
return m_outputWindow;
else if (persistString == typeof(DummyTaskList).ToString())
return m_taskList;
else
{
// DummyDoc overrides GetPersistString to add extra information into persistString.
// Any DockContent may override this value to add any needed information for deserialization.
string[] parsedStrings = persistString.Split(new char[] { ',' });
if (parsedStrings.Length != 3)
return null;
if (parsedStrings[0] != typeof(DummyDoc).ToString())
return null;
DummyDoc dummyDoc = new DummyDoc();
if (parsedStrings[1] != string.Empty)
dummyDoc.FileName = parsedStrings[1];
if (parsedStrings[2] != string.Empty)
dummyDoc.Text = parsedStrings[2];
return dummyDoc;
}
}
private void CloseAllContents()
{
// we don't want to create another instance of tool window, set DockPanel to null
m_solutionExplorer.DockPanel = null;
m_propertyWindow.DockPanel = null;
m_toolbox.DockPanel = null;
m_outputWindow.DockPanel = null;
m_taskList.DockPanel = null;
// Close all other document windows
CloseAllDocuments();
// IMPORTANT: dispose all float windows.
foreach (var window in dockPanel.FloatWindows.ToList())
window.Dispose();
System.Diagnostics.Debug.Assert(dockPanel.Panes.Count == 0);
System.Diagnostics.Debug.Assert(dockPanel.Contents.Count == 0);
System.Diagnostics.Debug.Assert(dockPanel.FloatWindows.Count == 0);
}
private readonly ToolStripRenderer _toolStripProfessionalRenderer = new ToolStripProfessionalRenderer();
private void SetSchema(object sender, System.EventArgs e)
{
// Persist settings when rebuilding UI
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.temp.config");
dockPanel.SaveAsXml(configFile);
CloseAllContents();
if (sender == this.menuItemSchemaVS2005)
{
this.dockPanel.Theme = this.vS2005Theme1;
this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2005, vS2005Theme1);
}
else if (sender == this.menuItemSchemaVS2003)
{
this.dockPanel.Theme = this.vS2003Theme1;
this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2003, vS2003Theme1);
}
else if (sender == this.menuItemSchemaVS2012Light)
{
this.dockPanel.Theme = this.vS2012LightTheme1;
this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2012, vS2012LightTheme1);
}
else if (sender == this.menuItemSchemaVS2012Blue)
{
this.dockPanel.Theme = this.vS2012BlueTheme1;
this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2012, vS2012BlueTheme1);
}
else if (sender == this.menuItemSchemaVS2012Dark)
{
this.dockPanel.Theme = this.vS2012DarkTheme1;
this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2012, vS2012DarkTheme1);
}
else if (sender == this.menuItemSchemaVS2013Blue)
{
this.dockPanel.Theme = this.vS2013BlueTheme1;
this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2013, vS2013BlueTheme1);
}
else if (sender == this.menuItemSchemaVS2013Light)
{
this.dockPanel.Theme = this.vS2013LightTheme1;
this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2013, vS2013LightTheme1);
}
else if (sender == this.menuItemSchemaVS2013Dark)
{
this.dockPanel.Theme = this.vS2013DarkTheme1;
this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2013, vS2013DarkTheme1);
}
else if (sender == this.menuItemSchemaVS2015Blue)
{
this.dockPanel.Theme = this.vS2015BlueTheme1;
this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015BlueTheme1);
}
else if (sender == this.menuItemSchemaVS2015Light)
{
this.dockPanel.Theme = this.vS2015LightTheme1;
this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015LightTheme1);
}
else if (sender == this.menuItemSchemaVS2015Dark)
{
this.dockPanel.Theme = this.vS2015DarkTheme1;
this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015DarkTheme1);
}
menuItemSchemaVS2005.Checked = (sender == menuItemSchemaVS2005);
menuItemSchemaVS2003.Checked = (sender == menuItemSchemaVS2003);
menuItemSchemaVS2012Light.Checked = (sender == menuItemSchemaVS2012Light);
menuItemSchemaVS2012Blue.Checked = (sender == menuItemSchemaVS2012Blue);
menuItemSchemaVS2012Dark.Checked = (sender == menuItemSchemaVS2012Dark);
menuItemSchemaVS2013Light.Checked = (sender == menuItemSchemaVS2013Light);
menuItemSchemaVS2013Blue.Checked = (sender == menuItemSchemaVS2013Blue);
menuItemSchemaVS2013Dark.Checked = (sender == menuItemSchemaVS2013Dark);
menuItemSchemaVS2015Light.Checked = (sender == menuItemSchemaVS2015Light);
menuItemSchemaVS2015Blue.Checked = (sender == menuItemSchemaVS2015Blue);
menuItemSchemaVS2015Dark.Checked = (sender == menuItemSchemaVS2015Dark);
if (dockPanel.Theme.ColorPalette != null)
{
statusBar.BackColor = dockPanel.Theme.ColorPalette.MainWindowStatusBarDefault.Background;
}
if (File.Exists(configFile))
dockPanel.LoadFromXml(configFile, m_deserializeDockContent);
}
private void EnableVSRenderer(VisualStudioToolStripExtender.VsVersion version, ThemeBase theme)
{
vsToolStripExtender1.SetStyle(mainMenu, version, theme);
vsToolStripExtender1.SetStyle(toolBar, version, theme);
vsToolStripExtender1.SetStyle(statusBar, version, theme);
}
private void SetDocumentStyle(object sender, System.EventArgs e)
{
DocumentStyle oldStyle = dockPanel.DocumentStyle;
DocumentStyle newStyle;
if (sender == menuItemDockingMdi)
newStyle = DocumentStyle.DockingMdi;
else if (sender == menuItemDockingWindow)
newStyle = DocumentStyle.DockingWindow;
else if (sender == menuItemDockingSdi)
newStyle = DocumentStyle.DockingSdi;
else
newStyle = DocumentStyle.SystemMdi;
if (oldStyle == newStyle)
return;
if (oldStyle == DocumentStyle.SystemMdi || newStyle == DocumentStyle.SystemMdi)
CloseAllDocuments();
dockPanel.DocumentStyle = newStyle;
menuItemDockingMdi.Checked = (newStyle == DocumentStyle.DockingMdi);
menuItemDockingWindow.Checked = (newStyle == DocumentStyle.DockingWindow);
menuItemDockingSdi.Checked = (newStyle == DocumentStyle.DockingSdi);
menuItemSystemMdi.Checked = (newStyle == DocumentStyle.SystemMdi);
menuItemLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi);
menuItemLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi);
toolBarButtonLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi);
toolBarButtonLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi);
}
#endregion
#region Event Handlers
private void menuItemExit_Click(object sender, System.EventArgs e)
{
Close();
}
private void menuItemSolutionExplorer_Click(object sender, System.EventArgs e)
{
m_solutionExplorer.Show(dockPanel);
}
private void menuItemPropertyWindow_Click(object sender, System.EventArgs e)
{
m_propertyWindow.Show(dockPanel);
}
private void menuItemToolbox_Click(object sender, System.EventArgs e)
{
m_toolbox.Show(dockPanel);
}
private void menuItemOutputWindow_Click(object sender, System.EventArgs e)
{
m_outputWindow.Show(dockPanel);
}
private void menuItemTaskList_Click(object sender, System.EventArgs e)
{
m_taskList.Show(dockPanel);
}
private void menuItemAbout_Click(object sender, System.EventArgs e)
{
AboutDialog aboutDialog = new AboutDialog();
aboutDialog.ShowDialog(this);
}
private void menuItemNew_Click(object sender, System.EventArgs e)
{
DummyDoc dummyDoc = CreateNewDocument();
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
dummyDoc.MdiParent = this;
dummyDoc.Show();
}
else
dummyDoc.Show(dockPanel);
}
private void menuItemOpen_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.InitialDirectory = Application.ExecutablePath;
openFile.Filter = "rtf files (*.rtf)|*.rtf|txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFile.FilterIndex = 1;
openFile.RestoreDirectory = true;
if (openFile.ShowDialog() == DialogResult.OK)
{
string fullName = openFile.FileName;
string fileName = Path.GetFileName(fullName);
if (FindDocument(fileName) != null)
{
MessageBox.Show("The document: " + fileName + " has already opened!");
return;
}
DummyDoc dummyDoc = new DummyDoc();
dummyDoc.Text = fileName;
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
dummyDoc.MdiParent = this;
dummyDoc.Show();
}
else
dummyDoc.Show(dockPanel);
try
{
dummyDoc.FileName = fullName;
}
catch (Exception exception)
{
dummyDoc.Close();
MessageBox.Show(exception.Message);
}
}
}
private void menuItemFile_Popup(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
menuItemClose.Enabled =
menuItemCloseAll.Enabled =
menuItemCloseAllButThisOne.Enabled = (ActiveMdiChild != null);
}
else
{
menuItemClose.Enabled = (dockPanel.ActiveDocument != null);
menuItemCloseAll.Enabled =
menuItemCloseAllButThisOne.Enabled = (dockPanel.DocumentsCount > 0);
}
}
private void menuItemClose_Click(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
ActiveMdiChild.Close();
else if (dockPanel.ActiveDocument != null)
dockPanel.ActiveDocument.DockHandler.Close();
}
private void menuItemCloseAll_Click(object sender, System.EventArgs e)
{
CloseAllDocuments();
}
private void MainForm_Load(object sender, System.EventArgs e)
{
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
if (File.Exists(configFile))
dockPanel.LoadFromXml(configFile, m_deserializeDockContent);
}
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
if (m_bSaveLayout)
dockPanel.SaveAsXml(configFile);
else if (File.Exists(configFile))
File.Delete(configFile);
}
private void menuItemToolBar_Click(object sender, System.EventArgs e)
{
toolBar.Visible = menuItemToolBar.Checked = !menuItemToolBar.Checked;
}
private void menuItemStatusBar_Click(object sender, System.EventArgs e)
{
statusBar.Visible = menuItemStatusBar.Checked = !menuItemStatusBar.Checked;
}
private void toolBar_ButtonClick(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem == toolBarButtonNew)
menuItemNew_Click(null, null);
else if (e.ClickedItem == toolBarButtonOpen)
menuItemOpen_Click(null, null);
else if (e.ClickedItem == toolBarButtonSolutionExplorer)
menuItemSolutionExplorer_Click(null, null);
else if (e.ClickedItem == toolBarButtonPropertyWindow)
menuItemPropertyWindow_Click(null, null);
else if (e.ClickedItem == toolBarButtonToolbox)
menuItemToolbox_Click(null, null);
else if (e.ClickedItem == toolBarButtonOutputWindow)
menuItemOutputWindow_Click(null, null);
else if (e.ClickedItem == toolBarButtonTaskList)
menuItemTaskList_Click(null, null);
else if (e.ClickedItem == toolBarButtonLayoutByCode)
menuItemLayoutByCode_Click(null, null);
else if (e.ClickedItem == toolBarButtonLayoutByXml)
menuItemLayoutByXml_Click(null, null);
}
private void menuItemNewWindow_Click(object sender, System.EventArgs e)
{
MainForm newWindow = new MainForm();
newWindow.Text = newWindow.Text + " - New";
newWindow.Show();
}
private void menuItemTools_Popup(object sender, System.EventArgs e)
{
menuItemLockLayout.Checked = !this.dockPanel.AllowEndUserDocking;
}
private void menuItemLockLayout_Click(object sender, System.EventArgs e)
{
dockPanel.AllowEndUserDocking = !dockPanel.AllowEndUserDocking;
}
private void menuItemLayoutByCode_Click(object sender, System.EventArgs e)
{
dockPanel.SuspendLayout(true);
CloseAllContents();
CreateStandardControls();
m_solutionExplorer.Show(dockPanel, DockState.DockRight);
m_propertyWindow.Show(m_solutionExplorer.Pane, m_solutionExplorer);
m_toolbox.Show(dockPanel, new Rectangle(98, 133, 200, 383));
m_outputWindow.Show(m_solutionExplorer.Pane, DockAlignment.Bottom, 0.35);
m_taskList.Show(m_toolbox.Pane, DockAlignment.Left, 0.4);
DummyDoc doc1 = CreateNewDocument("Document1");
DummyDoc doc2 = CreateNewDocument("Document2");
DummyDoc doc3 = CreateNewDocument("Document3");
DummyDoc doc4 = CreateNewDocument("Document4");
doc1.Show(dockPanel, DockState.Document);
doc2.Show(doc1.Pane, null);
doc3.Show(doc1.Pane, DockAlignment.Bottom, 0.5);
doc4.Show(doc3.Pane, DockAlignment.Right, 0.5);
dockPanel.ResumeLayout(true, true);
}
private void SetSplashScreen()
{
_showSplash = true;
_splashScreen = new SplashScreen();
ResizeSplash();
_splashScreen.Visible = true;
_splashScreen.TopMost = true;
Timer _timer = new Timer();
_timer.Tick += (sender, e) =>
{
_splashScreen.Visible = false;
_timer.Enabled = false;
_showSplash = false;
};
_timer.Interval = 4000;
_timer.Enabled = true;
}
private void ResizeSplash()
{
if (_showSplash) {
var centerXMain = (this.Location.X + this.Width) / 2.0;
var LocationXSplash = Math.Max(0, centerXMain - (_splashScreen.Width / 2.0));
var centerYMain = (this.Location.Y + this.Height) / 2.0;
var LocationYSplash = Math.Max(0, centerYMain - (_splashScreen.Height / 2.0));
_splashScreen.Location = new Point((int)Math.Round(LocationXSplash), (int)Math.Round(LocationYSplash));
}
}
private void CreateStandardControls()
{
m_solutionExplorer = new DummySolutionExplorer();
m_propertyWindow = new DummyPropertyWindow();
m_toolbox = new DummyToolbox();
m_outputWindow = new DummyOutputWindow();
m_taskList = new DummyTaskList();
}
private void menuItemLayoutByXml_Click(object sender, System.EventArgs e)
{
dockPanel.SuspendLayout(true);
// In order to load layout from XML, we need to close all the DockContents
CloseAllContents();
CreateStandardControls();
Assembly assembly = Assembly.GetAssembly(typeof(MainForm));
Stream xmlStream = assembly.GetManifestResourceStream("DockSample.Resources.DockPanel.xml");
dockPanel.LoadFromXml(xmlStream, m_deserializeDockContent);
xmlStream.Close();
dockPanel.ResumeLayout(true, true);
}
private void menuItemCloseAllButThisOne_Click(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
Form activeMdi = ActiveMdiChild;
foreach (Form form in MdiChildren)
{
if (form != activeMdi)
form.Close();
}
}
else
{
foreach (IDockContent document in dockPanel.DocumentsToArray())
{
if (!document.DockHandler.IsActivated)
document.DockHandler.Close();
}
}
}
private void menuItemShowDocumentIcon_Click(object sender, System.EventArgs e)
{
dockPanel.ShowDocumentIcon = menuItemShowDocumentIcon.Checked = !menuItemShowDocumentIcon.Checked;
}
private void showRightToLeft_Click(object sender, EventArgs e)
{
CloseAllContents();
if (showRightToLeft.Checked)
{
this.RightToLeft = RightToLeft.No;
this.RightToLeftLayout = false;
}
else
{
this.RightToLeft = RightToLeft.Yes;
this.RightToLeftLayout = true;
}
m_solutionExplorer.RightToLeftLayout = this.RightToLeftLayout;
showRightToLeft.Checked = !showRightToLeft.Checked;
}
private void exitWithoutSavingLayout_Click(object sender, EventArgs e)
{
m_bSaveLayout = false;
Close();
m_bSaveLayout = true;
}
#endregion
private void MainForm_SizeChanged(object sender, EventArgs e)
{
ResizeSplash();
}
}
}
| |
// 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.Globalization;
using System.Runtime.CompilerServices;
namespace System.Numerics
{
/// <summary>
/// A structure encapsulating a 3D Plane
/// </summary>
public struct Plane : IEquatable<Plane>
{
private const float NormalizeEpsilon = 1.192092896e-07f; // smallest such that 1.0+NormalizeEpsilon != 1.0
/// <summary>
/// The normal vector of the Plane.
/// </summary>
public Vector3 Normal;
/// <summary>
/// The distance of the Plane along its normal from the origin.
/// </summary>
public float D;
/// <summary>
/// Constructs a Plane from the X, Y, and Z components of its normal, and its distance from the origin on that normal.
/// </summary>
/// <param name="x">The X-component of the normal.</param>
/// <param name="y">The Y-component of the normal.</param>
/// <param name="z">The Z-component of the normal.</param>
/// <param name="d">The distance of the Plane along its normal from the origin.</param>
public Plane(float x, float y, float z, float d)
{
Normal = new Vector3(x, y, z);
this.D = d;
}
/// <summary>
/// Constructs a Plane from the given normal and distance along the normal from the origin.
/// </summary>
/// <param name="normal">The Plane's normal vector.</param>
/// <param name="d">The Plane's distance from the origin along its normal vector.</param>
public Plane(Vector3 normal, float d)
{
this.Normal = normal;
this.D = d;
}
/// <summary>
/// Constructs a Plane from the given Vector4.
/// </summary>
/// <param name="value">A vector whose first 3 elements describe the normal vector,
/// and whose W component defines the distance along that normal from the origin.</param>
public Plane(Vector4 value)
{
Normal = new Vector3(value.X, value.Y, value.Z);
D = value.W;
}
/// <summary>
/// Creates a Plane that contains the three given points.
/// </summary>
/// <param name="point1">The first point defining the Plane.</param>
/// <param name="point2">The second point defining the Plane.</param>
/// <param name="point3">The third point defining the Plane.</param>
/// <returns>The Plane containing the three points.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Plane CreateFromVertices(Vector3 point1, Vector3 point2, Vector3 point3)
{
if (Vector.IsHardwareAccelerated)
{
Vector3 a = point2 - point1;
Vector3 b = point3 - point1;
// N = Cross(a, b)
Vector3 n = Vector3.Cross(a, b);
Vector3 normal = Vector3.Normalize(n);
// D = - Dot(N, point1)
float d = -Vector3.Dot(normal, point1);
return new Plane(normal, d);
}
else
{
float ax = point2.X - point1.X;
float ay = point2.Y - point1.Y;
float az = point2.Z - point1.Z;
float bx = point3.X - point1.X;
float by = point3.Y - point1.Y;
float bz = point3.Z - point1.Z;
// N=Cross(a,b)
float nx = ay * bz - az * by;
float ny = az * bx - ax * bz;
float nz = ax * by - ay * bx;
// Normalize(N)
float ls = nx * nx + ny * ny + nz * nz;
float invNorm = 1.0f / MathF.Sqrt(ls);
Vector3 normal = new Vector3(
nx * invNorm,
ny * invNorm,
nz * invNorm);
return new Plane(
normal,
-(normal.X * point1.X + normal.Y * point1.Y + normal.Z * point1.Z));
}
}
/// <summary>
/// Creates a new Plane whose normal vector is the source Plane's normal vector normalized.
/// </summary>
/// <param name="value">The source Plane.</param>
/// <returns>The normalized Plane.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Plane Normalize(Plane value)
{
if (Vector.IsHardwareAccelerated)
{
float normalLengthSquared = value.Normal.LengthSquared();
if (MathF.Abs(normalLengthSquared - 1.0f) < NormalizeEpsilon)
{
// It already normalized, so we don't need to farther process.
return value;
}
float normalLength = MathF.Sqrt(normalLengthSquared);
return new Plane(
value.Normal / normalLength,
value.D / normalLength);
}
else
{
float f = value.Normal.X * value.Normal.X + value.Normal.Y * value.Normal.Y + value.Normal.Z * value.Normal.Z;
if (MathF.Abs(f - 1.0f) < NormalizeEpsilon)
{
return value; // It already normalized, so we don't need to further process.
}
float fInv = 1.0f / MathF.Sqrt(f);
return new Plane(
value.Normal.X * fInv,
value.Normal.Y * fInv,
value.Normal.Z * fInv,
value.D * fInv);
}
}
/// <summary>
/// Transforms a normalized Plane by a Matrix.
/// </summary>
/// <param name="plane"> The normalized Plane to transform.
/// This Plane must already be normalized, so that its Normal vector is of unit length, before this method is called.</param>
/// <param name="matrix">The transformation matrix to apply to the Plane.</param>
/// <returns>The transformed Plane.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Plane Transform(Plane plane, Matrix4x4 matrix)
{
Matrix4x4 m;
Matrix4x4.Invert(matrix, out m);
float x = plane.Normal.X, y = plane.Normal.Y, z = plane.Normal.Z, w = plane.D;
return new Plane(
x * m.M11 + y * m.M12 + z * m.M13 + w * m.M14,
x * m.M21 + y * m.M22 + z * m.M23 + w * m.M24,
x * m.M31 + y * m.M32 + z * m.M33 + w * m.M34,
x * m.M41 + y * m.M42 + z * m.M43 + w * m.M44);
}
/// <summary>
/// Transforms a normalized Plane by a Quaternion rotation.
/// </summary>
/// <param name="plane"> The normalized Plane to transform.
/// This Plane must already be normalized, so that its Normal vector is of unit length, before this method is called.</param>
/// <param name="rotation">The Quaternion rotation to apply to the Plane.</param>
/// <returns>A new Plane that results from applying the rotation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Plane Transform(Plane plane, Quaternion rotation)
{
// Compute rotation matrix.
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wx2 = rotation.W * x2;
float wy2 = rotation.W * y2;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float xz2 = rotation.X * z2;
float yy2 = rotation.Y * y2;
float yz2 = rotation.Y * z2;
float zz2 = rotation.Z * z2;
float m11 = 1.0f - yy2 - zz2;
float m21 = xy2 - wz2;
float m31 = xz2 + wy2;
float m12 = xy2 + wz2;
float m22 = 1.0f - xx2 - zz2;
float m32 = yz2 - wx2;
float m13 = xz2 - wy2;
float m23 = yz2 + wx2;
float m33 = 1.0f - xx2 - yy2;
float x = plane.Normal.X, y = plane.Normal.Y, z = plane.Normal.Z;
return new Plane(
x * m11 + y * m21 + z * m31,
x * m12 + y * m22 + z * m32,
x * m13 + y * m23 + z * m33,
plane.D);
}
/// <summary>
/// Calculates the dot product of a Plane and Vector4.
/// </summary>
/// <param name="plane">The Plane.</param>
/// <param name="value">The Vector4.</param>
/// <returns>The dot product.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Plane plane, Vector4 value)
{
return plane.Normal.X * value.X +
plane.Normal.Y * value.Y +
plane.Normal.Z * value.Z +
plane.D * value.W;
}
/// <summary>
/// Returns the dot product of a specified Vector3 and the normal vector of this Plane plus the distance (D) value of the Plane.
/// </summary>
/// <param name="plane">The plane.</param>
/// <param name="value">The Vector3.</param>
/// <returns>The resulting value.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DotCoordinate(Plane plane, Vector3 value)
{
if (Vector.IsHardwareAccelerated)
{
return Vector3.Dot(plane.Normal, value) + plane.D;
}
else
{
return plane.Normal.X * value.X +
plane.Normal.Y * value.Y +
plane.Normal.Z * value.Z +
plane.D;
}
}
/// <summary>
/// Returns the dot product of a specified Vector3 and the Normal vector of this Plane.
/// </summary>
/// <param name="plane">The plane.</param>
/// <param name="value">The Vector3.</param>
/// <returns>The resulting dot product.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DotNormal(Plane plane, Vector3 value)
{
if (Vector.IsHardwareAccelerated)
{
return Vector3.Dot(plane.Normal, value);
}
else
{
return plane.Normal.X * value.X +
plane.Normal.Y * value.Y +
plane.Normal.Z * value.Z;
}
}
/// <summary>
/// Returns a boolean indicating whether the two given Planes are equal.
/// </summary>
/// <param name="value1">The first Plane to compare.</param>
/// <param name="value2">The second Plane to compare.</param>
/// <returns>True if the Planes are equal; False otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Plane value1, Plane value2)
{
return (value1.Normal.X == value2.Normal.X &&
value1.Normal.Y == value2.Normal.Y &&
value1.Normal.Z == value2.Normal.Z &&
value1.D == value2.D);
}
/// <summary>
/// Returns a boolean indicating whether the two given Planes are not equal.
/// </summary>
/// <param name="value1">The first Plane to compare.</param>
/// <param name="value2">The second Plane to compare.</param>
/// <returns>True if the Planes are not equal; False if they are equal.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Plane value1, Plane value2)
{
return (value1.Normal.X != value2.Normal.X ||
value1.Normal.Y != value2.Normal.Y ||
value1.Normal.Z != value2.Normal.Z ||
value1.D != value2.D);
}
/// <summary>
/// Returns a boolean indicating whether the given Plane is equal to this Plane instance.
/// </summary>
/// <param name="other">The Plane to compare this instance to.</param>
/// <returns>True if the other Plane is equal to this instance; False otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(Plane other)
{
if (Vector.IsHardwareAccelerated)
{
return this.Normal.Equals(other.Normal) && this.D == other.D;
}
else
{
return (Normal.X == other.Normal.X &&
Normal.Y == other.Normal.Y &&
Normal.Z == other.Normal.Z &&
D == other.D);
}
}
/// <summary>
/// Returns a boolean indicating whether the given Object is equal to this Plane instance.
/// </summary>
/// <param name="obj">The Object to compare against.</param>
/// <returns>True if the Object is equal to this Plane; False otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Equals(object obj)
{
if (obj is Plane)
{
return Equals((Plane)obj);
}
return false;
}
/// <summary>
/// Returns a String representing this Plane instance.
/// </summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
CultureInfo ci = CultureInfo.CurrentCulture;
return string.Format(ci, "{{Normal:{0} D:{1}}}", Normal.ToString(), D.ToString(ci));
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
return Normal.GetHashCode() + D.GetHashCode();
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Reflection;
namespace System.Management.Automation.Interpreter {
internal partial class LightLambda {
#region Generated LightLambda Run Methods
// *** BEGIN GENERATED CODE ***
// generated by function: gen_run_methods from: generate_dynamic_instructions.py
internal const int MaxParameters = 16;
internal TRet Run0<TRet>() {
if (_compiled != null || TryGetCompiled()) {
return ((Func<TRet>)_compiled)();
}
var frame = MakeFrame();
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid0() {
if (_compiled != null || TryGetCompiled()) {
((Action)_compiled)();
return;
}
var frame = MakeFrame();
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun0<TRet>(LightLambda lambda) {
return new Func<TRet>(lambda.Run0<TRet>);
}
internal static Delegate MakeRunVoid0(LightLambda lambda) {
return new Action(lambda.RunVoid0);
}
internal TRet Run1<T0,TRet>(T0 arg0) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,TRet>)_compiled)(arg0);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid1<T0>(T0 arg0) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0>)_compiled)(arg0);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun1<T0,TRet>(LightLambda lambda) {
return new Func<T0,TRet>(lambda.Run1<T0,TRet>);
}
internal static Delegate MakeRunVoid1<T0>(LightLambda lambda) {
return new Action<T0>(lambda.RunVoid1<T0>);
}
internal TRet Run2<T0,T1,TRet>(T0 arg0,T1 arg1) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,TRet>)_compiled)(arg0, arg1);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid2<T0,T1>(T0 arg0,T1 arg1) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1>)_compiled)(arg0, arg1);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun2<T0,T1,TRet>(LightLambda lambda) {
return new Func<T0,T1,TRet>(lambda.Run2<T0,T1,TRet>);
}
internal static Delegate MakeRunVoid2<T0,T1>(LightLambda lambda) {
return new Action<T0,T1>(lambda.RunVoid2<T0,T1>);
}
internal TRet Run3<T0,T1,T2,TRet>(T0 arg0,T1 arg1,T2 arg2) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,TRet>)_compiled)(arg0, arg1, arg2);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid3<T0,T1,T2>(T0 arg0,T1 arg1,T2 arg2) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2>)_compiled)(arg0, arg1, arg2);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun3<T0,T1,T2,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,TRet>(lambda.Run3<T0,T1,T2,TRet>);
}
internal static Delegate MakeRunVoid3<T0,T1,T2>(LightLambda lambda) {
return new Action<T0,T1,T2>(lambda.RunVoid3<T0,T1,T2>);
}
internal TRet Run4<T0,T1,T2,T3,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,TRet>)_compiled)(arg0, arg1, arg2, arg3);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid4<T0,T1,T2,T3>(T0 arg0,T1 arg1,T2 arg2,T3 arg3) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3>)_compiled)(arg0, arg1, arg2, arg3);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun4<T0,T1,T2,T3,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,TRet>(lambda.Run4<T0,T1,T2,T3,TRet>);
}
internal static Delegate MakeRunVoid4<T0,T1,T2,T3>(LightLambda lambda) {
return new Action<T0,T1,T2,T3>(lambda.RunVoid4<T0,T1,T2,T3>);
}
internal TRet Run5<T0,T1,T2,T3,T4,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid5<T0,T1,T2,T3,T4>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4>)_compiled)(arg0, arg1, arg2, arg3, arg4);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun5<T0,T1,T2,T3,T4,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,TRet>(lambda.Run5<T0,T1,T2,T3,T4,TRet>);
}
internal static Delegate MakeRunVoid5<T0,T1,T2,T3,T4>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4>(lambda.RunVoid5<T0,T1,T2,T3,T4>);
}
internal TRet Run6<T0,T1,T2,T3,T4,T5,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid6<T0,T1,T2,T3,T4,T5>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun6<T0,T1,T2,T3,T4,T5,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,TRet>(lambda.Run6<T0,T1,T2,T3,T4,T5,TRet>);
}
internal static Delegate MakeRunVoid6<T0,T1,T2,T3,T4,T5>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5>(lambda.RunVoid6<T0,T1,T2,T3,T4,T5>);
}
internal TRet Run7<T0,T1,T2,T3,T4,T5,T6,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid7<T0,T1,T2,T3,T4,T5,T6>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun7<T0,T1,T2,T3,T4,T5,T6,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,TRet>(lambda.Run7<T0,T1,T2,T3,T4,T5,T6,TRet>);
}
internal static Delegate MakeRunVoid7<T0,T1,T2,T3,T4,T5,T6>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6>(lambda.RunVoid7<T0,T1,T2,T3,T4,T5,T6>);
}
internal TRet Run8<T0,T1,T2,T3,T4,T5,T6,T7,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid8<T0,T1,T2,T3,T4,T5,T6,T7>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun8<T0,T1,T2,T3,T4,T5,T6,T7,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,TRet>(lambda.Run8<T0,T1,T2,T3,T4,T5,T6,T7,TRet>);
}
internal static Delegate MakeRunVoid8<T0,T1,T2,T3,T4,T5,T6,T7>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7>(lambda.RunVoid8<T0,T1,T2,T3,T4,T5,T6,T7>);
}
internal TRet Run9<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid9<T0,T1,T2,T3,T4,T5,T6,T7,T8>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun9<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>(lambda.Run9<T0,T1,T2,T3,T4,T5,T6,T7,T8,TRet>);
}
internal static Delegate MakeRunVoid9<T0,T1,T2,T3,T4,T5,T6,T7,T8>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8>(lambda.RunVoid9<T0,T1,T2,T3,T4,T5,T6,T7,T8>);
}
internal TRet Run10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>(lambda.Run10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,TRet>);
}
internal static Delegate MakeRunVoid10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>(lambda.RunVoid10<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9>);
}
internal TRet Run11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>(lambda.Run11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,TRet>);
}
internal static Delegate MakeRunVoid11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(lambda.RunVoid11<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>);
}
internal TRet Run12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>(lambda.Run12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,TRet>);
}
internal static Delegate MakeRunVoid12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>(lambda.RunVoid12<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11>);
}
internal TRet Run13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>(lambda.Run13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,TRet>);
}
internal static Delegate MakeRunVoid13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>(lambda.RunVoid13<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12>);
}
internal TRet Run14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
frame.Data[13] = arg13;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
frame.Data[13] = arg13;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>(lambda.Run14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,TRet>);
}
internal static Delegate MakeRunVoid14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>(lambda.RunVoid14<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13>);
}
internal TRet Run15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13,T14 arg14) {
if (_compiled != null || TryGetCompiled()) {
return ((Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14);
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
frame.Data[13] = arg13;
frame.Data[14] = arg14;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
return (TRet)frame.Pop();
}
internal void RunVoid15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13,T14 arg14) {
if (_compiled != null || TryGetCompiled()) {
((Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14);
return;
}
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
frame.Data[2] = arg2;
frame.Data[3] = arg3;
frame.Data[4] = arg4;
frame.Data[5] = arg5;
frame.Data[6] = arg6;
frame.Data[7] = arg7;
frame.Data[8] = arg8;
frame.Data[9] = arg9;
frame.Data[10] = arg10;
frame.Data[11] = arg11;
frame.Data[12] = arg12;
frame.Data[13] = arg13;
frame.Data[14] = arg14;
var current = frame.Enter();
try { _interpreter.Run(frame); } finally { frame.Leave(current); }
}
internal static Delegate MakeRun15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>(LightLambda lambda) {
return new Func<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>(lambda.Run15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,TRet>);
}
internal static Delegate MakeRunVoid15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>(LightLambda lambda) {
return new Action<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>(lambda.RunVoid15<T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14>);
}
// *** END GENERATED CODE ***
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Linq;
using UnityEngine;
public class SexHeightmapGenerator
{
protected Texture2D heightMap;
double hmapWidth, hmapHeight;
protected double minX, minZ, maxX, maxZ;
protected double lowerBound, upperBound;
protected double maxRadius;
protected String filename;
ColorSpectrumObj spectrum;
// Variables Holder
Variables Vars;
/// <summary>
/// Initializes a new instance of the <see cref="SexHeightmapGenerator"/> class.
/// </summary>
/// <param name="Vars">Variables instane.</param>
/// <param name="filename">Filename.</param>
/// <param name="maxRadius">Max radius.</param>
/// <param name="minX">Minimum X coord.</param>
/// <param name="minZ">Minimum Z coord.</param>
/// <param name="maxX">Max X coord.</param>
/// <param name="maxZ">Max Z coord.</param>
public SexHeightmapGenerator (Variables Vars, String filename, double maxRadius,
double minX, double minZ, double maxX, double maxZ)
{
this.Vars = Vars;
this.filename = filename;
this.maxRadius = maxRadius;
this.minX = minX;
this.minZ = minZ;
this.maxX = maxX;
this.maxZ = maxZ;
// this.minX = minZ;
// this.minZ = maxX;
// this.maxX = maxZ;
// this.maxZ = minX;
}
/// <summary>
/// Gets the mesh heightmap.
/// </summary>
/// <returns>The mesh heightmap texture.</returns>
/// <param name="heightMapWidth">Height map texture width.</param>
/// <param name="heightMapHeight">Height map texture height.</param>
public Texture2D GetMeshHeightmap(double heightMapWidth,
double heightMapHeight){
DataHandler dataHandler = new DataHandler(filename, Vars.COLUMN_X, Vars.COLUMN_Y, Vars.COLUMN_Z, minX, minZ, maxX, maxZ);
hmapWidth = heightMapWidth;
hmapHeight = heightMapHeight;
double[] bnds= dataHandler.GetBounds();
lowerBound = 0f;
upperBound = bnds[1];
heightMap = new Texture2D((int)heightMapWidth, (int)heightMapHeight);
heightMap = CreateHeightMap(dataHandler.GetData());
SaveToDisk(heightMap, "GA_" + Vars.TERRAIN_NAME);
return heightMap;
}
/// <summary>
/// Gets the mesh colormap texture.
/// </summary>
/// <returns>The mesh colormap texture.</returns>
/// <param name="heightMapWidth">Height map texture width.</param>
/// <param name="heightMapHeight">Height map texture height.</param>
/// <param name="spectrum">ColorSpectrumObj.</param>
public Texture2D GetMeshColormap(double heightMapWidth,
double heightMapHeight,
ColorSpectrumObj spectrum){
DataHandler dataHandler = new DataHandler(filename, Vars.COLUMN_X, Vars.COLUMN_Y, Vars.COLUMN_Z, minX, minZ, maxX, maxZ);
hmapWidth = heightMapWidth;
hmapHeight = heightMapHeight;
double[] bnds= dataHandler.GetBounds();
lowerBound = bnds[0];
upperBound = bnds[1];
UnityEngine.Color[] colors = new UnityEngine.Color[]{UnityEngine.Color.red,
UnityEngine.Color.red,
UnityEngine.Color.magenta,
UnityEngine.Color.black,
UnityEngine.Color.cyan,
UnityEngine.Color.blue,
UnityEngine.Color.blue};
float[] proportions = new float[]{0.0f,
(float)((-lowerBound)/(upperBound-lowerBound))/2f,
(float)((-lowerBound)/(upperBound-lowerBound))-0.005f,
(float)((-lowerBound)/(upperBound-lowerBound)),
(float)((-lowerBound)/(upperBound-lowerBound))+0.005f,
(float)((-lowerBound)/(upperBound-lowerBound))+(1-(float)((-lowerBound)/(upperBound-lowerBound)))/2f,
1.0f};
this.spectrum = new ColorSpectrumObj(colors, proportions);
heightMap = new Texture2D((int)heightMapWidth, (int)heightMapHeight);
heightMap = CreateColorMap(dataHandler.GetData());
SaveToDisk(heightMap, "GA_Color_" + Vars.TERRAIN_NAME);
return heightMap;
}
/// <summary>
/// Gets the hills heightmap texture.
/// </summary>
/// <returns>The hills heightmap texture.</returns>
/// <param name="heightMapWidth">Height map texture width.</param>
/// <param name="heightMapHeight">Height map texture height.</param>
public Texture2D GetHillsHeightmap(double heightMapWidth,
double heightMapHeight){
DataHandler dataHandler = new DataHandler(filename, Vars.COLUMN_X, Vars.COLUMN_Y, Vars.COLUMN_Z, minX, minZ, maxX, maxZ);
double[] bnds= dataHandler.GetBounds();
lowerBound = 0f;
upperBound = bnds[1];
HeightmapGenerator heightGen = new HeightmapGenerator(Vars, filename, Vars.MAX_RADIUS, Vars.MIN_X,Vars.MIN_Z,Vars.MAX_X,Vars.MAX_Z);
heightMap = heightGen.GetHeightmap(heightMapWidth, heightMapHeight, true);
SaveToDisk(heightMap, "heightmap_" + Vars.TERRAIN_NAME);
return heightMap;
}
/// <summary>
/// Gets the heightmap with terrain type Cylindrical.
/// </summary>
/// <returns>The heightmap texture.</returns>
/// <param name="bWidth">Texture width.</param>
/// <param name="bHeight">Texture height.</param>
public virtual Texture2D GetHillsSexHeightmapCylinder(double bWidth, double bHeight){
DataHandler dataHandler = new DataHandler(filename, Vars.COLUMN_X, Vars.COLUMN_Y, Vars.COLUMN_Z, minX, minZ, maxX, maxZ);
List<double[]> data = dataHandler.GetData();
heightMap = new Texture2D((int)bWidth, (int)bHeight);
FillInColor(UnityEngine.Color.black);
double[] bnds= dataHandler.GetBounds();
lowerBound = 0;
upperBound = bnds[1];
double it = (upperBound-lowerBound)/Vars.ITERATION_NUMBER;
if(it == 0)
it = 1f;
System.Drawing.Bitmap bit = new System.Drawing.Bitmap(heightMap.width, heightMap.height);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bit);
double h = lowerBound;
while(data.Count != 0){
h += it;
List<int> toRemove = new List<int>();
for(int i=0; i<data.Count; i++){
if(Math.Abs(data[i][1]) < h){ //If middle of the values is less than the lower bounds, then add it "toRemove" List
toRemove.Add(i);
double height = Math.Abs(data[i][1]);
System.Drawing.Color col = ColourConvert(height);
Brush brush = new SolidBrush(col);
Rectangle rect = new Rectangle((int)(data[i][0] * bWidth) - 5, (int)(data[i][2] * bHeight) - 5, 10 , 10);
g.FillEllipse(brush, rect);
}
}
for(int i=0; i<toRemove.Count; i++){
data.RemoveAt(toRemove[i]-i);
}
}
bit.RotateFlip(RotateFlipType.Rotate180FlipX);
ImageConverter imgconv = new ImageConverter();
byte[] hmapbytes = (byte[])imgconv.ConvertTo(bit, typeof(byte[]));
heightMap.LoadImage(hmapbytes);
heightMap.Apply();
SaveToDisk(heightMap, "heightmap_" + Vars.TERRAIN_NAME);
return heightMap;
}
/// <summary>
/// Saves texture to disk memory.
/// </summary>
/// <param name="img">Image.</param>
/// <param name="filename">Filename.</param>
public void SaveToDisk(Texture2D img, string filename) {
byte[] bytes = img.EncodeToPNG();
File.WriteAllBytes(Application.dataPath + "/Heightmaps/Images/" + filename + ".png", bytes);
}
public Texture2D GetHillsColormap(double heightMapWidth,
double heightMapHeight,
ColorSpectrumObj spectrum){
DataHandler dataHandler = new DataHandler(filename, Vars.COLUMN_X, Vars.COLUMN_Y, Vars.COLUMN_Z, minX, minZ, maxX, maxZ);
hmapWidth = heightMapWidth;
hmapHeight = heightMapHeight;
double[] bnds= dataHandler.GetBounds();
lowerBound = bnds[0];
upperBound = bnds[1];
UnityEngine.Color[] colors = new UnityEngine.Color[]{UnityEngine.Color.red,
UnityEngine.Color.red,
UnityEngine.Color.magenta,
UnityEngine.Color.black,
UnityEngine.Color.cyan,
UnityEngine.Color.blue,
UnityEngine.Color.blue};
float[] proportions = new float[]{0.0f,
(float)((-lowerBound)/(upperBound-lowerBound))/2f,
(float)((-lowerBound)/(upperBound-lowerBound))-0.005f,
(float)((-lowerBound)/(upperBound-lowerBound)),
(float)((-lowerBound)/(upperBound-lowerBound))+0.005f,
(float)((-lowerBound)/(upperBound-lowerBound))+(1-(float)((-lowerBound)/(upperBound-lowerBound)))/2f,
1.0f};
this.spectrum = new ColorSpectrumObj(colors, proportions);
Texture2D colorMap = new Texture2D((int)heightMapWidth, (int)heightMapHeight);
ColormapGenerator colorGen = new ColormapGenerator(Vars, filename, Vars.MAX_RADIUS, Vars.MIN_X,Vars.MIN_Z,Vars.MAX_X,Vars.MAX_Z, this.spectrum);
colorMap = colorGen.GetHeightmap(heightMapWidth, heightMapHeight, dataHandler.GetData(), lowerBound, upperBound);
SaveToDisk(colorMap, "colormap_" + Vars.TERRAIN_NAME);
return colorMap;
}
public Texture2D GetHillsColormapCylinder(double heightMapWidth,
double heightMapHeight,
ColorSpectrumObj spectrum){
DataHandler dataHandler = new DataHandler(filename, Vars.COLUMN_X, Vars.COLUMN_Y, Vars.COLUMN_Z, minX, minZ, maxX, maxZ);
hmapWidth = heightMapWidth;
hmapHeight = heightMapHeight;
double[] bnds= dataHandler.GetBounds();
lowerBound = bnds[0];
upperBound = bnds[1];
UnityEngine.Color[] colors = new UnityEngine.Color[]{UnityEngine.Color.red,
UnityEngine.Color.red,
UnityEngine.Color.magenta,
UnityEngine.Color.black,
UnityEngine.Color.cyan,
UnityEngine.Color.blue,
UnityEngine.Color.blue};
float[] proportions = new float[]{0.0f,
(float)((-lowerBound)/(upperBound-lowerBound))/2f,
(float)((-lowerBound)/(upperBound-lowerBound))-0.005f,
(float)((-lowerBound)/(upperBound-lowerBound)),
(float)((-lowerBound)/(upperBound-lowerBound))+0.005f,
(float)((-lowerBound)/(upperBound-lowerBound))+(1-(float)((-lowerBound)/(upperBound-lowerBound)))/2f,
1.0f};
this.spectrum = new ColorSpectrumObj(colors, proportions);
Texture2D colorMap = new Texture2D((int)heightMapWidth, (int)heightMapHeight);
ColormapGenerator colorGen = new ColormapGenerator(Vars, filename, Vars.MAX_RADIUS, Vars.MIN_X,Vars.MIN_Z,Vars.MAX_X,Vars.MAX_Z, this.spectrum);
colorMap = colorGen.GetHeightmapCylinder(heightMapWidth, heightMapHeight, dataHandler.GetData(), lowerBound, upperBound);
SaveToDisk(colorMap, "colormap_" + Vars.TERRAIN_NAME);
return colorMap;
}
protected void FillInColor(UnityEngine.Color c){
for(int i = 0; i < heightMap.width; i++) {
for(int j = 0; j < heightMap.height; j++) {
heightMap.SetPixel(i,j, c);
}
}
}
/// <summary>
/// Performs the same function as <see cref="ColorFromHeight"/>
/// however returns a System.Drawing.Color instead of a Unity
/// Color object.
/// </summary>
/// <returns>The color associated with the height from
/// the designated ColorSpectrumObj.</returns>
/// <param name="val">Height value.</param>
public System.Drawing.Color ColourConvert(double val)
{
UnityEngine.Color unityC = GrayscaleFromHeight(val, upperBound, lowerBound);
UnityEngine.Color32 unicolour = new UnityEngine.Color(unityC.r, unityC.g, unityC.b, unityC.a);
System.Drawing.Color wincolour = new System.Drawing.Color();
wincolour = System.Drawing.Color.FromArgb(unicolour.a, unicolour.r, unicolour.g, unicolour.b);
return wincolour;
}
double[,] map;
bool[,] map_pump;
bool[,] map_nonzero;
bool[,] map_nonzero_temp;
double[,] map_temp;
protected Texture2D CreateHeightMap(List<double[]> data){
/// Parallel Processing
int numCores = SystemInfo.processorCount;
// convert list of double[] to list of Vector3's and sort it.
List<Vector3> points = new List<Vector3>();
for(int i=0; i<data.Count; i++){
double[] t = data[i];
points.Add(new Vector3((float)t[0], (float)Math.Abs(t[1]), (float)t[2]));
}
//Genetic Algorithm for mesh construction
map = new double[(int)hmapWidth, (int)hmapHeight];
map_pump = new bool[(int)hmapWidth, (int)hmapHeight];
map_nonzero = new bool[(int)hmapWidth, (int)hmapHeight];
map_nonzero_temp = new bool[(int)hmapWidth, (int)hmapHeight];
map_temp = new double[(int)hmapWidth, (int)hmapHeight];
for(int i=0; i<points.Count; i++){
Vector3 p = points[i];
int x = (int)(p.x*(hmapWidth-1));
int z = (int)(p.z*(hmapHeight-1));
map[x, z] = p.y;
map_pump[x, z] = true;
heightMap.SetPixel(x,z,GrayscaleFromHeight(p.y, upperBound, lowerBound));
}
for(int a=0; a<hmapWidth; a++){
for (int b=0; b<hmapHeight; b++){
if(!map_pump[a,b])
map[a,b] = 0f;//(-lowerBound)/(upperBound-lowerBound);
map_nonzero[a,b] = true;
}
}
heightMap.Apply();
Array.Copy (map, map_temp,map.Length);
Array.Copy (map_nonzero, map_nonzero_temp, map_nonzero.Length);
int iterationMax = Vars.GENETIC_MAX_ITERATION; //Variable in CSV
//BEGIN GENETIC ALGORITHM
for(int i=0; i<iterationMax; i++){
for(int n=0; n<numCores; n++){
System.Threading.ParameterizedThreadStart pts = new System.Threading.ParameterizedThreadStart(GenerateMesh);
System.Threading.Thread worker = new System.Threading.Thread(pts);
worker.Start(new int[]{(int)(hmapHeight/numCores)*n, (int)((hmapHeight/numCores)*(n+1))});
}
Array.Copy (map_temp, map, map_temp.Length);
Array.Copy (map_nonzero_temp, map_nonzero, map_nonzero_temp.Length);
}
heightMap.Apply();
// adjust pumps
for(int i=0; i<Vars.GENETIC_SMOOTH_ITERATION; i++){
for(int n=0; n<numCores; n++){
System.Threading.ParameterizedThreadStart pts = new System.Threading.ParameterizedThreadStart(SmoothMesh);
System.Threading.Thread worker = new System.Threading.Thread(pts);
worker.Start(new int[]{(int)(hmapHeight/numCores)*n, (int)((hmapHeight/numCores)*(n+1))});
}
Array.Copy (map_temp, map, map_temp.Length);
Array.Copy (map_nonzero_temp, map_nonzero, map_nonzero_temp.Length);
}
heightMap.Apply();
// Scale values back to original bounds:
double minC = map.Cast<double>().Min(), maxC = map.Cast<double>().Max ();
for(int x=0; x<hmapWidth; x++){
for (int z=0; z<hmapHeight; z++){
heightMap.SetPixel(x,z,GrayscaleFromHeight(map[x, z], maxC, minC));
}
}
heightMap.Apply();
return heightMap;
}
protected Texture2D CreateColorMap(List<double[]> data){
/// Parallel Processing
int numCores = SystemInfo.processorCount;
// convert list of double[] to list of Vector3's and sort it.
List<Vector3> points = new List<Vector3>();
for(int i=0; i<data.Count; i++){
double[] t = data[i];
points.Add(new Vector3((float)t[0], (float)t[1], (float)t[2]));
}
//Genetic Algorithm for mesh construction
map = new double[(int)hmapWidth, (int)hmapHeight];
map_pump = new bool[(int)hmapWidth, (int)hmapHeight];
map_nonzero = new bool[(int)hmapWidth, (int)hmapHeight];
map_nonzero_temp = new bool[(int)hmapWidth, (int)hmapHeight];
map_temp = new double[(int)hmapWidth, (int)hmapHeight];
for(int i=0; i<points.Count; i++){
Vector3 p = points[i];
int x = (int)(p.x*(hmapWidth-1));
int z = (int)(p.z*(hmapHeight-1));
map[x, z] = p.y;
map_pump[x, z] = true;
heightMap.SetPixel(x,z,ColorFromHeight(p.y, upperBound, lowerBound));
}
for(int a=0; a<hmapWidth; a++){
for (int b=0; b<hmapHeight; b++){
if(!map_pump[a,b])
map[a,b] = 0f;
map_nonzero[a,b] = true;
}
}
heightMap.Apply();
Array.Copy (map, map_temp,map.Length);
Array.Copy (map_nonzero, map_nonzero_temp, map_nonzero.Length);
int iterationMax = Vars.GENETIC_MAX_ITERATION; //Variable in CSV
//BEGIN GENETIC ALGORITHM
for(int i=0; i<iterationMax; i++){
for(int n=0; n<numCores; n++){
System.Threading.ParameterizedThreadStart pts = new System.Threading.ParameterizedThreadStart(GenerateMesh);
System.Threading.Thread worker = new System.Threading.Thread(pts);
worker.Start(new int[]{(int)(hmapHeight/numCores)*n, (int)((hmapHeight/numCores)*(n+1))});
}
Array.Copy (map_temp, map, map_temp.Length);
Array.Copy (map_nonzero_temp, map_nonzero, map_nonzero_temp.Length);
}
heightMap.Apply();
// adjust pumps
for(int i=0; i<Vars.GENETIC_SMOOTH_ITERATION; i++){
for(int n=0; n<numCores; n++){
System.Threading.ParameterizedThreadStart pts = new System.Threading.ParameterizedThreadStart(SmoothMesh);
System.Threading.Thread worker = new System.Threading.Thread(pts);
worker.Start(new int[]{(int)(hmapHeight/numCores)*n, (int)((hmapHeight/numCores)*(n+1))});
}
Array.Copy (map_temp, map, map_temp.Length);
Array.Copy (map_nonzero_temp, map_nonzero, map_nonzero_temp.Length);
}
heightMap.Apply();
// Scale values back to original bounds:
double minC = map.Cast<double>().Min(), maxC = map.Cast<double>().Max ();
for(int x=0; x<hmapWidth; x++){
for (int z=0; z<hmapHeight; z++){
heightMap.SetPixel(x,z,ColorFromHeight(map[x, z], maxC, minC));
}
}
heightMap.Apply();
return heightMap;
}
protected UnityEngine.Color ColorFromHeight(double height, double maxHeight, double minHeight)
{
double scalar = (height-minHeight) / (maxHeight-minHeight);
UnityEngine.Color val = spectrum.GetColorFromVal((float)scalar);
return val;
}
protected virtual UnityEngine.Color GrayscaleFromHeight(double height, double maxHeight, double minHeight)
{
UnityEngine.Color color = new UnityEngine.Color(0,0,0,1);
double scalar = (height-minHeight) / (maxHeight-minHeight);
Int32 mColor = (Int32)Math.Floor(scalar * Math.Pow(2, 24));
Int32 b = mColor%256;
Int32 g = mColor%(256*256);
g /= 256;
Int32 r = mColor;
r /= 256*256;
color.r = (float)((float)r/256f);
color.g = (float)((float)g/256f);
color.b = (float)((float)b/256f);
return color;
}
/// <summary>
/// Smooths the array representing the mesh texture.
/// </summary>
/// <param name="rangeArray">Array containing the data
/// in the form.</param>
private void SmoothMesh(object rangeArray){
for(int x=0; x<hmapWidth; x++){
for (int z=0; z<hmapHeight; z++){
double avg = 0f;
double div = 0f;
if(x > 0){
avg += map[x-1, z];
div += map_nonzero[x-1, z]? 1 : 0;
}if(z > 0){
avg += map[x, z-1];
div += map_nonzero[x, z-1]? 1 : 0;
}if(x < hmapWidth-1){
avg += map[x+1, z];
div += map_nonzero[x+1, z]? 1 : 0;
}if( z < hmapHeight-1){
avg += map[x, z+1];
div += map_nonzero[x, z+1]? 1 : 0;
}if(x > 0 && z > 0){
avg += map[x-1, z-1];
div += map_nonzero[x-1, z-1]? 1 : 0;
}if(x < hmapWidth-1 && z > 0){
avg += map[x+1, z-1];
div += map_nonzero[x+1, z-1]? 1 : 0;
}if(x > 0 && z < hmapHeight-1){
avg += map[x-1, z+1];
div += map_nonzero[x-1, z+1]? 1 : 0;
}if(x < hmapWidth-1 && z < hmapHeight-1){
avg += map[x+1, z+1];
div += map_nonzero[x+1, z+1]? 1 : 0;
}
avg = (div != 0) ? avg/div : 0f;
map_temp[x,z] = avg;
map_nonzero_temp[x, z] = (avg != 0f) ? true : false;
}
}
}
/// <summary>
/// Generates the initial terrain data.
/// </summary>
/// <param name="rangeArray">Array containing the data
/// in the form.</param>
private void GenerateMesh(object rangeArray){
int start = ((int[])rangeArray)[0];
int stop = ((int[])rangeArray)[1];
for(int x=0; x<hmapWidth; x++){
for(int z=start; z<stop; z++){
if(!map_pump[x,z]){
double avg = 0f;
double div = 0f;
if(x > 0){
avg += map[x-1, z];
div += map_nonzero[x-1, z]? 1 : 0;
}if(z > 0){
avg += map[x, z-1];
div += map_nonzero[x, z-1]? 1 : 0;
}if(x < hmapWidth-1){
avg += map[x+1, z];
div += map_nonzero[x+1, z]? 1 : 0;
}if( z < hmapHeight-1){
avg += map[x, z+1];
div += map_nonzero[x, z+1]? 1 : 0;
}if(x > 0 && z > 0){
avg += map[x-1, z-1];
div += map_nonzero[x-1, z-1]? 1 : 0;
}if(x < hmapWidth-1 && z > 0){
avg += map[x+1, z-1];
div += map_nonzero[x+1, z-1]? 1 : 0;
}if(x > 0 && z < hmapHeight-1){
avg += map[x-1, z+1];
div += map_nonzero[x-1, z+1]? 1 : 0;
}if(x < hmapWidth-1 && z < hmapHeight-1){
avg += map[x+1, z+1];
div += map_nonzero[x+1, z+1]? 1 : 0;
}
avg = (div != 0) ? avg/div : 0f;
map_temp[x,z] = avg;
map_nonzero_temp[x, z] = (avg != 0f) ? true : false;
}
}
}
}
}
| |
using Godot;
#if REAL_T_IS_DOUBLE
using real_t = System.Double;
#else
using real_t = System.Single;
#endif
[Tool]
public class PlayerSprite : Sprite
{
private static Texture _stand = ResourceLoader.Load<Texture>("res://assets/player/textures/stand.png");
private static Texture _jump = ResourceLoader.Load<Texture>("res://assets/player/textures/jump.png");
private static Texture _run = ResourceLoader.Load<Texture>("res://assets/player/textures/run.png");
private const int FRAMERATE = 15;
private int _direction;
private float _progress;
private Node25D _parent;
private PlayerMath25D _parentMath;
public override void _Ready()
{
_parent = GetParent<Node25D>();
_parentMath = _parent.GetChild<PlayerMath25D>(0);
}
public override void _Process(real_t delta)
{
if (Engine.EditorHint)
{
return; // Don't run this in the editor.
}
SpriteBasis();
bool movement = CheckMovement(); // Always run to get direction, but don't always use return bool.
// Test-only move and collide, check if the player is on the ground.
var k = _parentMath.MoveAndCollide(Vector3.Down * 10 * delta, true, true, true);
if (k != null)
{
if (movement)
{
// TODO: https://github.com/godotengine/godot/issues/28748
Hframes = 6;
Texture = _run;
if (Input.IsActionPressed("movement_modifier"))
{
delta /= 2;
}
_progress = (_progress + FRAMERATE * delta) % 6;
Frame = _direction * 6 + (int)_progress;
}
else
{
Hframes = 1;
Texture = _stand;
_progress = 0;
Frame = _direction;
}
}
else
{
Hframes = 2;
Texture = _jump;
_progress = 0;
int jumping = _parentMath.verticalSpeed < 0 ? 1 : 0;
Frame = _direction * 2 + jumping;
}
}
public void SetViewMode(int viewModeIndex)
{
Transform2D t = Transform;
switch (viewModeIndex)
{
case 0:
t.x = new Vector2(1, 0);
t.y = new Vector2(0, 0.75f);
break;
case 1:
t.x = new Vector2(1, 0);
t.y = new Vector2(0, 1);
break;
case 2:
t.x = new Vector2(1, 0);
t.y = new Vector2(0, 0.5f);
break;
case 3:
t.x = new Vector2(1, 0);
t.y = new Vector2(0, 1);
break;
case 4:
t.x = new Vector2(1, 0);
t.y = new Vector2(0.75f, 0.75f);
break;
case 5:
t.x = new Vector2(1, 0.25f);
t.y = new Vector2(0, 1);
break;
}
Transform = t;
}
/// <summary>
/// Change the basis of the sprite to try and make it fit multiple view modes.
/// </summary>
private void SpriteBasis()
{
if (!Engine.EditorHint)
{
if (Input.IsActionPressed("forty_five_mode"))
{
SetViewMode(0);
}
else if (Input.IsActionPressed("isometric_mode"))
{
SetViewMode(1);
}
else if (Input.IsActionPressed("top_down_mode"))
{
SetViewMode(2);
}
else if (Input.IsActionPressed("front_side_mode"))
{
SetViewMode(3);
}
else if (Input.IsActionPressed("oblique_y_mode"))
{
SetViewMode(4);
}
else if (Input.IsActionPressed("oblique_z_mode"))
{
SetViewMode(5);
}
}
}
// There might be a more efficient way to do this, but I can't think of it.
private bool CheckMovement()
{
// Gather player input and store movement to these int variables. Note: These indeed have to be integers.
int x = 0;
int z = 0;
if (Input.IsActionPressed("move_right"))
{
x++;
}
if (Input.IsActionPressed("move_left"))
{
x--;
}
if (Input.IsActionPressed("move_forward"))
{
z--;
}
if (Input.IsActionPressed("move_back"))
{
z++;
}
// Check for isometric controls and add more to movement accordingly.
// For efficiency, only check the X axis since this X axis value isn't used anywhere else.
if (!_parentMath.isometricControls && _parent.Basis25D.x.IsEqualApprox(Basis25D.Isometric.x * Node25D.SCALE))
{
if (Input.IsActionPressed("move_right"))
{
z++;
}
if (Input.IsActionPressed("move_left"))
{
z--;
}
if (Input.IsActionPressed("move_forward"))
{
x++;
}
if (Input.IsActionPressed("move_back"))
{
x--;
}
}
// Set the direction based on which inputs were pressed.
if (x == 0)
{
if (z == 0)
{
return false; // No movement
}
else if (z > 0)
{
_direction = 0;
}
else
{
_direction = 4;
}
}
else if (x > 0)
{
if (z == 0)
{
_direction = 2;
FlipH = true;
}
else if (z > 0)
{
_direction = 1;
FlipH = true;
}
else
{
_direction = 3;
FlipH = true;
}
}
else
{
if (z == 0)
{
_direction = 2;
FlipH = false;
}
else if (z > 0)
{
_direction = 1;
FlipH = false;
}
else
{
_direction = 3;
FlipH = false;
}
}
return true; // There is movement
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using SteamKit2;
using SteamTrade.Exceptions;
namespace SteamTrade
{
public class TradeManager
{
const int MaxGapTimeDefault = 15;
const int MaxTradeTimeDefault = 180;
const int TradePollingIntervalDefault = 800;
string apiKey;
string sessionId;
string token;
DateTime tradeStartTime;
DateTime lastOtherActionTime;
Trade trade;
/// <summary>
/// Initializes a new instance of the <see cref="SteamTrade.TradeManager"/> class.
/// </summary>
/// <param name='apiKey'>
/// The Steam Web API key. Cannot be null.
/// </param>
/// <param name='sessionId'>
/// Session identifier. Cannot be null.
/// </param>
/// <param name='token'>
/// Session token. Cannot be null.
/// </param>
public TradeManager (string apiKey, string sessionId, string token)
{
if (apiKey == null)
throw new ArgumentNullException ("apiKey");
if (sessionId == null)
throw new ArgumentNullException ("sessionId");
if (token == null)
throw new ArgumentNullException ("token");
SetTradeTimeLimits (MaxTradeTimeDefault, MaxGapTimeDefault, TradePollingIntervalDefault);
this.apiKey = apiKey;
this.sessionId = sessionId;
this.token = token;
}
#region Public Properties
/// <summary>
/// Gets or the maximum trading time the bot will take in seconds.
/// </summary>
/// <value>
/// The maximum trade time.
/// </value>
public int MaxTradeTimeSec
{
get;
private set;
}
/// <summary>
/// Gets or the maxmium amount of time the bot will wait between actions.
/// </summary>
/// <value>
/// The maximum action gap.
/// </value>
public int MaxActionGapSec
{
get;
private set;
}
/// <summary>
/// Gets the Trade polling interval in milliseconds.
/// </summary>
public int TradePollingInterval
{
get;
private set;
}
/// <summary>
/// Gets the inventory of the bot.
/// </summary>
/// <value>
/// The bot's inventory fetched via Steam Web API.
/// </value>
public Inventory MyInventory
{
get;
private set;
}
/// <summary>
/// Gets the inventory of the other trade partner.
/// </summary>
/// <value>
/// The other trade partner's inventory fetched via Steam Web API.
/// </value>
public Inventory OtherInventory
{
get;
private set;
}
/// <summary>
/// Gets or sets a value indicating whether the trade thread running.
/// </summary>
/// <value>
/// <c>true</c> if the trade thread running; otherwise, <c>false</c>.
/// </value>
public bool IsTradeThreadRunning
{
get;
internal set;
}
#endregion Public Properties
#region Public Events
/// <summary>
/// Occurs when the trade times out because either the user didn't complete an
/// action in a set amount of time, or they took too long with the whole trade.
/// </summary>
public EventHandler OnTimeout;
/// <summary>
/// Occurs When the trade ends either by timeout, error, cancellation, or acceptance.
/// </summary>
public EventHandler OnTradeEnded;
#endregion Public Events
#region Public Methods
/// <summary>
/// Sets the trade time limits.
/// </summary>
/// <param name='maxTradeTime'>
/// Max trade time in seconds.
/// </param>
/// <param name='maxActionGap'>
/// Max gap between user action in seconds.
/// </param>
/// <param name='pollingInterval'>The trade polling interval in milliseconds.</param>
public void SetTradeTimeLimits (int maxTradeTime, int maxActionGap, int pollingInterval)
{
MaxTradeTimeSec = maxTradeTime;
MaxActionGapSec = maxActionGap;
TradePollingInterval = pollingInterval;
}
/// <summary>
/// Creates a trade object, starts the trade, and returns it for use.
/// Call <see cref="FetchInventories"/> before using this method.
/// </summary>
/// <returns>
/// The trade object to use to interact with the Steam trade.
/// </returns>
/// <param name='me'>
/// The <see cref="SteamID"/> of the bot.
/// </param>
/// <param name='other'>
/// The <see cref="SteamID"/> of the other trade partner.
/// </param>
/// <remarks>
/// If the needed inventories are <c>null</c> then they will be fetched.
/// </remarks>
public Trade StartTrade (SteamID me, SteamID other)
{
if (OtherInventory == null || MyInventory == null)
InitializeTrade (me, other);
var t = new Trade (me, other, sessionId, token, apiKey, MyInventory, OtherInventory);
t.OnClose += delegate
{
IsTradeThreadRunning = false;
if (OnTradeEnded != null)
OnTradeEnded (this, null);
};
trade = t;
StartTradeThread ();
return t;
}
/// <summary>
/// Stops the trade thread.
/// </summary>
/// <remarks>
/// Also, nulls out the inventory objects so they have to be fetched
/// again if a new trade is started.
/// </remarks>
public void StopTrade ()
{
// TODO: something to check that trade was the Trade returned from StartTrade
OtherInventory = null;
MyInventory = null;
IsTradeThreadRunning = false;
}
/// <summary>
/// Fetchs the inventories of both the bot and the other user as well as the TF2 item schema.
/// </summary>
/// <param name='me'>
/// The <see cref="SteamID"/> of the bot.
/// </param>
/// <param name='other'>
/// The <see cref="SteamID"/> of the other trade partner.
/// </param>
/// <remarks>
/// This should be done anytime a new user is traded with or the inventories are out of date. It should
/// be done sometime before calling <see cref="StartTrade"/>.
/// </remarks>
public void InitializeTrade (SteamID me, SteamID other)
{
// fetch other player's inventory from the Steam API.
OtherInventory = Inventory.FetchInventory (other.ConvertToUInt64 (), apiKey);
if (OtherInventory == null)
{
throw new InventoryFetchException (other);
}
// fetch our inventory from the Steam API.
MyInventory = Inventory.FetchInventory (me.ConvertToUInt64 (), apiKey);
if (MyInventory == null)
{
throw new InventoryFetchException (me);
}
// check that the schema was already successfully fetched
if (Trade.CurrentSchema == null)
Trade.CurrentSchema = Schema.FetchSchema (apiKey);
if (Trade.CurrentSchema == null)
throw new TradeException ("Could not download the latest item schema.");
}
#endregion Public Methods
private void StartTradeThread ()
{
// initialize data to use in thread
tradeStartTime = DateTime.Now;
lastOtherActionTime = DateTime.Now;
var pollThread = new Thread (() =>
{
IsTradeThreadRunning = true;
DebugPrint ("Trade thread starting.");
// main thread loop for polling
while (IsTradeThreadRunning)
{
Thread.Sleep (TradePollingInterval);
try
{
bool action = trade.Poll ();
if (action)
lastOtherActionTime = DateTime.Now;
if (trade.OtherUserCancelled)
{
IsTradeThreadRunning = false;
try
{
trade.CancelTrade ();
}
catch (Exception)
{
// ignore. possibly log. We don't care if the Cancel web command fails here we just want
// to fire the OnClose event.
DebugPrint ("[TRADEMANAGER] error trying to cancel from poll thread");
}
}
CheckTradeTimeout (trade);
}
catch (Exception ex)
{
// TODO: find a new way to do this w/o the trade events
// if (OnError != null)
// OnError ("Error Polling Trade: " + e);
// ok then we should stop polling...
IsTradeThreadRunning = false;
DebugPrint ("[TRADEMANAGER] general error caught: " + ex);
}
}
DebugPrint ("Trade thread shutting down.");
if (OnTradeEnded != null)
OnTradeEnded (this, null);
});
pollThread.Start();
}
void CheckTradeTimeout (Trade trade)
{
var now = DateTime.Now;
DateTime actionTimeout = lastOtherActionTime.AddSeconds (MaxActionGapSec);
int untilActionTimeout = (int)Math.Round ((actionTimeout - now).TotalSeconds);
DebugPrint (String.Format ("{0} {1}", actionTimeout, untilActionTimeout));
DateTime tradeTimeout = tradeStartTime.AddSeconds (MaxTradeTimeSec);
int untilTradeTimeout = (int)Math.Round ((tradeTimeout - now).TotalSeconds);
if (untilActionTimeout <= 0 || untilTradeTimeout <= 0)
{
// stop thread
IsTradeThreadRunning = false;
DebugPrint ("timed out...");
if (OnTimeout != null)
{
OnTimeout (this, null);
}
trade.CancelTrade ();
}
else if (untilActionTimeout <= 20 && untilActionTimeout % 10 == 0)
{
trade.SendMessage ("Are You AFK? The trade will be canceled in " + untilActionTimeout + " seconds if you don't do something.");
}
}
[Conditional ("DEBUG_TRADE_MANAGER")]
void DebugPrint (string output)
{
// I don't really want to add the Logger as a dependecy to TradeManager so I
// print using the console directly. To enable this for debugging put this:
// #define DEBUG_TRADE_MANAGER
// at the first line of this file.
System.Console.WriteLine (output);
}
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
using Plugin.Geolocator;
using Plugin.Geolocator.Abstractions;
using Plugin.Permissions.Abstractions;
namespace Sensus.Probes.Location
{
/// <summary>
/// A GPS receiver. Implemented as a singleton.
/// </summary>
public class GpsReceiver
{
#region static members
public static readonly GpsReceiver SINGLETON = new GpsReceiver();
public static GpsReceiver Get()
{
return SINGLETON;
}
#endregion
private event EventHandler<PositionEventArgs> PositionChanged;
private IGeolocator _locator;
private bool _readingIsComing;
private ManualResetEvent _readingWait;
private Position _reading;
private int _readingTimeoutMS;
private List<Tuple<EventHandler<PositionEventArgs>, bool>> _listenerHeadings;
private readonly object _locker = new object();
public IGeolocator Locator
{
get { return _locator; }
}
private bool ListeningForChanges
{
get { return PositionChanged != null; }
}
public int MinimumDistanceThreshold
{
// because GPS is only so accurate, successive readings can fire the trigger even if one is not moving -- if the threshold is too small. theoretically
// the minimum value of the threshold should be equal to the desired accuracy; however, the desired accuracy is just a request. use 2x the desired
// accuracy just to be sure.
get { return (int)(2 * _locator.DesiredAccuracy); }
}
private GpsReceiver()
{
_readingIsComing = false;
_readingWait = new ManualResetEvent(false);
_reading = null;
_readingTimeoutMS = 120000;
_listenerHeadings = new List<Tuple<EventHandler<PositionEventArgs>, bool>>();
_locator = CrossGeolocator.Current;
_locator.DesiredAccuracy = SensusServiceHelper.Get().GpsDesiredAccuracyMeters;
_locator.PositionChanged += (o, e) =>
{
SensusServiceHelper.Get().Logger.Log("GPS position has changed.", LoggingLevel.Verbose, GetType());
if (PositionChanged != null)
PositionChanged(o, e);
};
}
public async void AddListener(EventHandler<PositionEventArgs> listener, bool includeHeading)
{
if (SensusServiceHelper.Get().ObtainPermission(Permission.Location) != PermissionStatus.Granted)
throw new Exception("Could not access GPS.");
// if we're already listening, stop listening first so that the locator can be configured with
// the most recent listening settings below.
if (ListeningForChanges)
await _locator.StopListeningAsync();
// add new listener
PositionChanged += listener;
_listenerHeadings.Add(new Tuple<EventHandler<PositionEventArgs>, bool>(listener, includeHeading));
_locator.DesiredAccuracy = SensusServiceHelper.Get().GpsDesiredAccuracyMeters;
TimeSpan andreaNew = TimeSpan.FromMilliseconds(SensusServiceHelper.Get().GpsMinTimeDelayMS);
await _locator.StartListeningAsync(SensusServiceHelper.Get().GpsMinTimeDelayMS, SensusServiceHelper.Get().GpsMinDistanceDelayMeters, _listenerHeadings.Any(t => t.Item2), GetListenerSettings());
SensusServiceHelper.Get().Logger.Log("GPS receiver is now listening for changes.", LoggingLevel.Normal, GetType());
}
public async void RemoveListener(EventHandler<PositionEventArgs> listener)
{
if (ListeningForChanges)
await _locator.StopListeningAsync();
PositionChanged -= listener;
_listenerHeadings.RemoveAll(t => t.Item1 == listener);
TimeSpan andreaNew = TimeSpan.FromMilliseconds(SensusServiceHelper.Get().GpsMinTimeDelayMS);
if (ListeningForChanges)
await _locator.StartListeningAsync(SensusServiceHelper.Get().GpsMinTimeDelayMS, SensusServiceHelper.Get().GpsMinDistanceDelayMeters, _listenerHeadings.Any(t => t.Item2), GetListenerSettings());
else
SensusServiceHelper.Get().Logger.Log("All listeners removed from GPS receiver. Stopped listening.", LoggingLevel.Normal, GetType());
}
private ListenerSettings GetListenerSettings()
{
ListenerSettings settings = null;
#if __IOS__
float gpsDeferralDistanceMeters = SensusServiceHelper.Get().GpsDeferralDistanceMeters;
float gpsDeferralTimeMinutes = SensusServiceHelper.Get().GpsDeferralTimeMinutes;
settings = new ListenerSettings
{
AllowBackgroundUpdates = true,
PauseLocationUpdatesAutomatically = SensusServiceHelper.Get().GpsPauseLocationUpdatesAutomatically,
ActivityType = SensusServiceHelper.Get().GpsActivityType,
ListenForSignificantChanges = SensusServiceHelper.Get().GpsListenForSignificantChanges,
DeferLocationUpdates = SensusServiceHelper.Get().GpsDeferLocationUpdates,
DeferralDistanceMeters = gpsDeferralDistanceMeters < 0 ? default(double?) : gpsDeferralDistanceMeters,
DeferralTime = gpsDeferralTimeMinutes < 0 ? default(TimeSpan?) : TimeSpan.FromMinutes(gpsDeferralTimeMinutes)
};
#endif
return settings;
}
/// <summary>
/// Gets a GPS reading. Will block the current thread while waiting for a GPS reading. Should not
/// be called from the main / UI thread, since GPS runs on main thread (will deadlock).
/// </summary>
/// <returns>The reading.</returns>
/// <param name="cancellationToken">Cancellation token.</param>
public Position GetReading(CancellationToken cancellationToken)
{
return GetReading(0, cancellationToken);
}
/// <summary>
/// Gets a GPS reading, reusing an old one if it isn't too old. Will block the current thread while waiting for a GPS reading. Should not
/// be called from the main / UI thread, since GPS runs on main thread (will deadlock).
/// </summary>
/// <returns>The reading.</returns>
/// <param name="maxReadingAgeForReuseMS">Maximum age of old reading to reuse (milliseconds).</param>
/// <param name="cancellationToken">Cancellation token.</param>
public Position GetReading(int maxReadingAgeForReuseMS, CancellationToken cancellationToken)
{
lock (_locker)
{
try
{
SensusServiceHelper.Get().AssertNotOnMainThread(GetType() + " GetReading");
}
catch (Exception)
{
return null;
}
if (SensusServiceHelper.Get().ObtainPermission(Permission.Location) != PermissionStatus.Granted)
return null;
// reuse existing reading if it isn't too old
if (_reading != null && maxReadingAgeForReuseMS > 0)
{
double readingAgeMS = (DateTimeOffset.UtcNow - _reading.Timestamp).TotalMilliseconds;
if (readingAgeMS <= maxReadingAgeForReuseMS)
{
SensusServiceHelper.Get().Logger.Log("Reusing previous GPS reading, which is " + readingAgeMS + "ms old (maximum = " + maxReadingAgeForReuseMS + "ms).", LoggingLevel.Verbose, GetType());
return _reading;
}
}
if (_readingIsComing)
SensusServiceHelper.Get().Logger.Log("A GPS reading is coming. Will wait for it.", LoggingLevel.Debug, GetType());
else
{
_readingIsComing = true; // tell any subsequent, concurrent callers that we're taking a reading
_readingWait.Reset(); // make them wait
new Thread(async () =>
{
try
{
SensusServiceHelper.Get().Logger.Log("Taking GPS reading.", LoggingLevel.Debug, GetType());
DateTimeOffset readingStart = DateTimeOffset.UtcNow;
_locator.DesiredAccuracy = SensusServiceHelper.Get().GpsDesiredAccuracyMeters;
TimeSpan dariusnew = TimeSpan.FromMilliseconds(_readingTimeoutMS);
Position newReading = await _locator.GetPositionAsync(_readingTimeoutMS, cancellationToken);
DateTimeOffset readingEnd = DateTimeOffset.UtcNow;
if (newReading != null)
{
// create copy of new position to keep return references separate, since the same Position object is returned multiple times when a change listener is attached.
_reading = new Position(newReading);
SensusServiceHelper.Get().Logger.Log("GPS reading obtained in " + (readingEnd - readingStart).TotalSeconds + " seconds.", LoggingLevel.Verbose, GetType());
}
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("GPS reading failed: " + ex.Message, LoggingLevel.Normal, GetType());
_reading = null;
}
_readingWait.Set(); // tell anyone waiting on the shared reading that it is ready
_readingIsComing = false; // direct any future calls to this method to get their own reading
}).Start();
}
}
_readingWait.WaitOne(_readingTimeoutMS);
if (_reading == null)
SensusServiceHelper.Get().Logger.Log("GPS reading is null.", LoggingLevel.Normal, GetType());
return _reading;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
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.Cursor;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.Multi.Components;
using osu.Game.Users;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Multi.Lounge.Components
{
public class RoomInspector : MultiplayerComposite
{
private const float transition_duration = 100;
private readonly MarginPadding contentPadding = new MarginPadding { Horizontal = 20, Vertical = 10 };
private ParticipantCountDisplay participantCount;
private OsuSpriteText name;
private BeatmapTypeInfo beatmapTypeInfo;
private ParticipantInfo participantInfo;
[Resolved]
private BeatmapManager beatmaps { get; set; }
private readonly Bindable<RoomStatus> status = new Bindable<RoomStatus>(new RoomStatusNoneSelected());
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.FromHex(@"343138"),
},
new GridContainer
{
RelativeSizeAxes = Axes.Both,
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.Distributed),
},
Content = new[]
{
new Drawable[]
{
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.X,
Height = 200,
Masking = true,
Children = new Drawable[]
{
new MultiplayerBackgroundSprite { RelativeSizeAxes = Axes.Both },
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = ColourInfo.GradientVertical(Color4.Black.Opacity(0.5f), Color4.Black.Opacity(0)),
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding(20),
Children = new Drawable[]
{
participantCount = new ParticipantCountDisplay
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
name = new OsuSpriteText
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Font = OsuFont.GetFont(size: 30),
Current = Name
},
},
},
},
},
new StatusColouredContainer(transition_duration)
{
RelativeSizeAxes = Axes.X,
Height = 5,
Child = new Box { RelativeSizeAxes = Axes.Both }
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.FromHex(@"28242d"),
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
LayoutDuration = transition_duration,
Padding = contentPadding,
Spacing = new Vector2(0f, 5f),
Children = new Drawable[]
{
new StatusColouredContainer(transition_duration)
{
AutoSizeAxes = Axes.Both,
Child = new StatusText
{
Font = OsuFont.GetFont(weight: FontWeight.Bold, size: 14),
}
},
beatmapTypeInfo = new BeatmapTypeInfo(),
},
},
},
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = contentPadding,
Children = new Drawable[]
{
participantInfo = new ParticipantInfo(),
},
},
},
},
},
new Drawable[]
{
new MatchParticipants
{
RelativeSizeAxes = Axes.Both,
}
}
}
}
};
Status.BindValueChanged(_ => updateStatus(), true);
RoomID.BindValueChanged(_ => updateStatus(), true);
}
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
var dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
dependencies.CacheAs(status, new CacheInfo(nameof(Room.Status), typeof(Room)));
return dependencies;
}
private void updateStatus()
{
if (RoomID.Value == null)
{
status.Value = new RoomStatusNoneSelected();
participantCount.FadeOut(transition_duration);
beatmapTypeInfo.FadeOut(transition_duration);
name.FadeOut(transition_duration);
participantInfo.FadeOut(transition_duration);
}
else
{
status.Value = Status.Value;
participantCount.FadeIn(transition_duration);
beatmapTypeInfo.FadeIn(transition_duration);
name.FadeIn(transition_duration);
participantInfo.FadeIn(transition_duration);
}
}
private class RoomStatusNoneSelected : RoomStatus
{
public override string Message => @"No Room Selected";
public override Color4 GetAppropriateColour(OsuColour colours) => colours.Gray8;
}
private class StatusText : OsuSpriteText
{
[Resolved(typeof(Room), nameof(Room.Status))]
private Bindable<RoomStatus> status { get; set; }
[BackgroundDependencyLoader]
private void load()
{
status.BindValueChanged(s => Text = s.NewValue.Message, true);
}
}
private class MatchParticipants : MultiplayerComposite
{
private readonly FillFlowContainer fill;
public MatchParticipants()
{
Padding = new MarginPadding { Horizontal = 10 };
InternalChild = new ScrollContainer
{
RelativeSizeAxes = Axes.Both,
Child = fill = new FillFlowContainer
{
Spacing = new Vector2(10),
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Full,
}
};
}
[BackgroundDependencyLoader]
private void load()
{
RoomID.BindValueChanged(_ => updateParticipants(), true);
}
[Resolved]
private APIAccess api { get; set; }
private GetRoomScoresRequest request;
private void updateParticipants()
{
var roomId = RoomID.Value ?? 0;
request?.Cancel();
// nice little progressive fade
int time = 500;
foreach (var c in fill.Children)
{
c.Delay(500 - time).FadeOut(time, Easing.Out);
time = Math.Max(20, time - 20);
c.Expire();
}
if (roomId == 0) return;
request = new GetRoomScoresRequest(roomId);
request.Success += scores =>
{
if (roomId != RoomID.Value)
return;
fill.Clear();
foreach (var s in scores)
fill.Add(new UserTile(s.User));
fill.FadeInFromZero(1000, Easing.OutQuint);
};
api.Queue(request);
}
protected override void Dispose(bool isDisposing)
{
request?.Cancel();
base.Dispose(isDisposing);
}
private class UserTile : CompositeDrawable, IHasTooltip
{
private readonly User user;
public string TooltipText => user.Username;
public UserTile(User user)
{
this.user = user;
Size = new Vector2(70f);
CornerRadius = 5f;
Masking = true;
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.FromHex(@"27252d"),
},
new UpdateableAvatar
{
RelativeSizeAxes = Axes.Both,
User = user,
},
};
}
}
}
}
}
| |
#region "Copyright"
/*
FOR FURTHER DETAILS ABOUT LICENSING, PLEASE VISIT "LICENSE.txt" INSIDE THE SAGEFRAME FOLDER
*/
#endregion
#region "References"
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using SageFrame.Web;
using SageFrame.SageMenu;
using System.IO;
using SageFrame.Common.Shared;
using System.Collections.Generic;
using SageFrame.MenuManager;
using System.Text;
using System.Text.RegularExpressions;
#endregion
public partial class Modules_SageMenu_SageMenu : BaseAdministrationUserControl
{
public int UserModuleID, PortalID;
public string ContainerClientID = string.Empty, appPath = string.Empty, DefaultPage = string.Empty;
public string UserName = string.Empty, PageName = string.Empty, CultureCode = string.Empty;
public string Extension = string.Empty;
public string menuType = string.Empty;
string pagePath = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
Initialize();
Extension = SageFrameSettingKeys.PageExtension;
CreateDynamicNav();
UserModuleID = int.Parse(SageUserModuleID);
PortalID = GetPortalID;
UserName = GetUsername;
CultureCode = GetCurrentCulture();
PageName = Path.GetFileNameWithoutExtension(PagePath);
string modulePath = ResolveUrl(this.AppRelativeTemplateSourceDirectory);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "SageMenuGlobal", " var Path='" + ResolveUrl(modulePath) + "';", true);
pagePath = IsParent ? ResolveUrl(GetParentURL) : ResolveUrl(GetParentURL) + "portal/" + GetPortalSEOName;
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "SageMenuGlobal1", " var PagePath='" + pagePath + "';", true);
SageFrameConfig sfConfig = new SageFrameConfig();
DefaultPage = sfConfig.GetSettingsByKey(SageFrameSettingKeys.PortalDefaultPage).ToLower();
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "SageMenuGlobal2", " var SageFrameDefaultPage='" + DefaultPage + "';", true);
GetCurrentMenuID();
GetAllMenuSettings();
}
public void CreateDynamicNav()
{
ContainerClientID = "divNav_" + SageUserModuleID;
ltrNav.Text = "<div id='" + ContainerClientID + "'></div>";
}
public void GetCurrentMenuID()
{
SageMenuSettingInfo objinf = new SageMenuSettingInfo();
objinf = MenuController.GetMenuSetting(GetPortalID, UserModuleID);
Session["MenuID"] = objinf.MenuID;
}
public void Initialize()
{
appPath = GetApplicationName;
IncludeJs("SageMenu", "/Modules/SageMenu/js/SageMenu.js");
// IncludeJs("SageMenu", "/Modules/SageMenu/js/hoverIntent.js");
IncludeJs("SageMenu", "/Modules/SageMenu/js/superfish.js");
IncludeCss("SageMenu", "/Modules/SageMenu/css/module.css");
}
public void GetAllMenuSettings()
{
SageMenuSettingInfo objMenuSetting = new SageMenuSettingInfo();
objMenuSetting = MenuController.GetMenuSetting(PortalID, UserModuleID);
BuildMenu(objMenuSetting);
}
public void BuildMenu(SageMenuSettingInfo objMenuSetting)
{
menuType = objMenuSetting.MenuType;
switch (int.Parse(objMenuSetting.MenuType))
{
case 0:
//LoadTopAdminMenu();
break;
case 1:
GetPages(objMenuSetting);
break;
case 2:
LoadSideMenu(objMenuSetting);
break;
case 3:
LoadFooterMenu(objMenuSetting);
break;
}
}
#region "GetPages"
public void GetPages(SageMenuSettingInfo objMenuSetting)
{
List<MenuManagerInfo> objMenuInfoList = GetMenuFront(PortalID, UserName, CultureCode, UserModuleID);
BindPages(objMenuInfoList, objMenuSetting);
}
public void BindPages(List<MenuManagerInfo> objMenuInfoList, SageMenuSettingInfo objMenuSetting)
{
int pageID = 0;
int parentID = 0;
string itemPath = string.Empty; ;
StringBuilder html = new StringBuilder();
int rootItemCount = 0;
foreach (MenuManagerInfo objMenuInfo in objMenuInfoList)
{
if (int.Parse(objMenuInfo.MenuLevel) == 0)
{
rootItemCount = objMenuInfoList.IndexOf(objMenuInfo);
}
}
html.Append(BuildMenuClassContainer(int.Parse(objMenuSetting.TopMenuSubType)));
int countMenuInfo = 0;
foreach (MenuManagerInfo objMenuInfo in objMenuInfoList)
{
pageID = objMenuInfo.MenuItemID;
parentID = objMenuInfo.ParentID;
if (objMenuInfo.MenuLevel == "0")
{
string PageURL = objMenuInfo.URL.Split('/').Last();
string pageLink = objMenuInfo.LinkType == "0" ? pagePath + PageURL + Extension : objMenuInfo.LinkURL;
if (objMenuInfo.LinkURL == string.Empty)
{
pageLink = pageLink.IndexOf(Extension) > 0 ? pageLink : pageLink + Extension;
}
string firstclass = string.Empty;
string activeClass = PageURL == PageName ? "sfActive" : "";
if (objMenuInfo.ChildCount > 0)
{
firstclass = countMenuInfo == 0 ? "class='sfFirst sfParent " + activeClass + "'" : countMenuInfo == rootItemCount ? "class='sfParent sfLast " + activeClass + "'" : "class='sfParent " + activeClass + "'";
}
else
{
firstclass = countMenuInfo == 0 ? "class='sfFirst " + activeClass + "'" : countMenuInfo == rootItemCount ? "class='sfLast " + activeClass + "'" : "class='" + activeClass + "'";
}
html.Append("<li ");
html.Append(firstclass);
html.Append(">");
string menuItem = BuildMenuItem(int.Parse(objMenuSetting.DisplayMode), objMenuInfo, pageLink, objMenuSetting.Caption);
html.Append(menuItem);
if (objMenuInfo.LinkType == "1")
{
html.Append("<ul class='megamenu'><li style=''><div class='megawrapper'>");
html.Append(objMenuInfo.HtmlContent);
html.Append("</div></li></ul>");
}
else
{
if (objMenuInfo.ChildCount > 0)
{
html.Append("<ul style='display: none; visibility: hidden;'>");
itemPath = objMenuInfo.Title;
string childCategory = BindChildCategory(objMenuInfoList, pageID, int.Parse(objMenuSetting.DisplayMode), objMenuSetting.Caption);
html.Append(childCategory);
html.Append("</ul>");
}
}
html.Append("</li>");
}
itemPath = string.Empty;
countMenuInfo++;
}
html.Append("</ul></div>");
ltrNav.Text = html.ToString();
}
#endregion
#region "LoadSideMenu"
public void LoadSideMenu(SageMenuSettingInfo objMenuSetting)
{
List<MenuInfo> objMenuInfoList = GetSideMenu(PortalID, UserName, objMenuSetting.MenuID, CultureCode);
BuildSideMenu(objMenuInfoList, objMenuSetting);
}
public void BuildSideMenu(List<MenuInfo> objMenuInfoList, SageMenuSettingInfo objMenuSetting)
{
int pageID = 0;
int parentID = 0;
int categoryLevel = 0;
string itemPath = string.Empty;
StringBuilder html = new StringBuilder();
html.Append("<div class='");
html.Append(ContainerClientID);
html.Append("'>");
if (objMenuInfoList.Count > 0)
{
html.Append("<ul class='sfSidemenu'>");
foreach (MenuInfo objMenu in objMenuInfoList)
{
pageID = objMenu.PageID;
parentID = objMenu.ParentID;
categoryLevel = objMenu.Level;
string PageURL = objMenu.TabPath.Split('/').Last();
string pageLink = GetApplicationName + "/" + PageURL + Extension;
if (objMenu.Level == 0)
{
html.Append("<li class='sfLevel1'>");
if (objMenu.ChildCount > 0)
{
string sideMenuItem = BuildSideMenuItem(int.Parse(objMenuSetting.DisplayMode), objMenu, pageLink, "");
html.Append(sideMenuItem);
}
else
{
string sideMenuItem = BuildSideMenuItem(int.Parse(objMenuSetting.DisplayMode), objMenu, pageLink, "");
html.Append(sideMenuItem);
}
if (objMenu.ChildCount > 0)
{
html.Append("<ul>");
string sideMenuChildren = BindSideMenuChildren(objMenuInfoList, pageID, int.Parse(objMenuSetting.DisplayMode));
html.Append(sideMenuChildren);
html.Append("</ul>");
}
html.Append("</li>");
}
itemPath = string.Empty;
}
html.Append("</ul>");
}
html.Append("</div>");
ltrNav.Text = html.ToString();
}
public string BindSideMenuChildren(List<MenuInfo> objMenuList, int pageID, int menuDisplayMode)
{
StringBuilder html = new StringBuilder();
string childNodes = string.Empty;
string path = string.Empty;
string itemPath = string.Empty;
foreach (MenuInfo objMenu in objMenuList)
{
if (objMenu.Level > 0)
{
if (objMenu.ParentID == pageID)
{
itemPath = objMenu.PageName;
string PageURL = objMenu.TabPath.Split('/').Last();
string pageLink = pagePath + PageURL + Extension;
string styleClass = objMenu.ChildCount > 0 ? " class='sfParent'" : "";
html.Append("<li ");
html.Append(styleClass);
html.Append(">");
string sideMenuItem = BuildSideMenuItem(menuDisplayMode, objMenu, pageLink, "0");
html.Append(sideMenuItem);
childNodes = BindSideMenuChildren(objMenuList, objMenu.PageID, menuDisplayMode);
if (childNodes != string.Empty)
{
html.Append("<ul>");
html.Append(childNodes);
html.Append("</ul>");
}
html.Append("</li>");
}
}
}
return html.ToString();
}
#endregion
#region
public void LoadFooterMenu(SageMenuSettingInfo objMenuSetting)
{
List<MenuManagerInfo> objMenuMangerList = GetFooterMenu_Localized(PortalID, UserName, CultureCode, UserModuleID);
BuildFooterMenu(objMenuMangerList, objMenuSetting);
}
public List<MenuManagerInfo> GetFooterMenu_Localized(int PortalID, string UserName, string CultureCode, int UserModuleID)
{
List<MenuManagerInfo> lstMenuItems = new List<MenuManagerInfo>();
lstMenuItems = MenuManagerDataController.GetSageMenu_Localized(UserModuleID, PortalID, UserName, CultureCode);
IEnumerable<MenuManagerInfo> lstParent = new List<MenuManagerInfo>();
List<MenuManagerInfo> lstHierarchy = new List<MenuManagerInfo>();
lstParent = from pg in lstMenuItems
where pg.MenuLevel == "0"
select pg;
foreach (MenuManagerInfo parent in lstParent)
{
lstHierarchy.Add(parent);
GetChildPages(ref lstHierarchy, parent, lstMenuItems);
}
return (lstHierarchy);
}
public void BuildFooterMenu(List<MenuManagerInfo> objMenuManagerInfoList, SageMenuSettingInfo objMenuSetting)
{
int pageID = 0;
int parentID = 0;
string itemPath = string.Empty;
StringBuilder html = new StringBuilder();
html.Append("<div class='" + ContainerClientID + "'> <ul class='sfFootermenu'>");
foreach (MenuManagerInfo objMenuManagerInfo in objMenuManagerInfoList)
{
pageID = objMenuManagerInfo.MenuItemID;
parentID = objMenuManagerInfo.ParentID;
if (objMenuManagerInfo.MenuLevel == "0")
{
string PageURL = objMenuManagerInfo.URL.Split('/').Last();
string pageLink = objMenuManagerInfo.LinkType == "0" ? pagePath + PageURL + Extension : "/" + PageURL;
if (PageURL == string.Empty && objMenuManagerInfo.LinkType == "2")
{
pageLink = objMenuManagerInfo.LinkURL;
}
else
{
pageLink = objMenuManagerInfo.LinkType == "0" ? pagePath + PageURL + Extension : "/" + PageURL;
}
if (objMenuManagerInfo.LinkURL == string.Empty)
{
pageLink = pageLink.IndexOf(Extension) > 0 ? pageLink : pageLink + Extension;
}
if (objMenuManagerInfo.ChildCount > 0)
{
html.Append("<li class='sfParent'>");
}
else
{
html.Append("<li>");
}
string menuItem = BuildMenuItem(int.Parse(objMenuSetting.DisplayMode), objMenuManagerInfo, pageLink, objMenuSetting.Caption);
html.Append(menuItem);
if (objMenuManagerInfo.LinkType == "1")
{
html.Append("<ul class='megamenu'><li><div class='megawrapper'>");
html.Append(objMenuManagerInfo.HtmlContent);
html.Append("</div></li><ul>");
}
else
{
if (objMenuManagerInfo.ChildCount > 0)
{
html.Append("<ul>");
itemPath = objMenuManagerInfo.Title;
string footerChild = BuildFooterChildren(objMenuManagerInfoList, pageID, int.Parse(objMenuSetting.DisplayMode), objMenuSetting.Caption);
html.Append(footerChild);
html.Append("</ul>");
}
}
html.Append("</li>");
}
itemPath = string.Empty;
}
html.Append("</div>");
ltrNav.Text = html.ToString();
}
public string BuildFooterChildren(List<MenuManagerInfo> objMenuManagerInfoList, int pageID, int menuDisplayMode, string showCaption)
{
StringBuilder html = new StringBuilder();
string childNodes = string.Empty;
string path = string.Empty;
string itemPath = string.Empty;
foreach (MenuManagerInfo objMenuManagerInfo in objMenuManagerInfoList)
{
if (int.Parse(objMenuManagerInfo.MenuLevel) > 0)
{
if (objMenuManagerInfo.ParentID == pageID)
{
itemPath = objMenuManagerInfo.Title;
string PageURL = objMenuManagerInfo.URL.Split('/').Last();
string pageLink = objMenuManagerInfo.LinkType == "0" ? pagePath + PageURL + Extension : "/" + PageURL;
if (PageURL == string.Empty && objMenuManagerInfo.LinkType == "2")
{
pageLink = objMenuManagerInfo.LinkURL;
}
else
{
pageLink = objMenuManagerInfo.LinkType == "0" ? pagePath + PageURL + Extension : "/" + PageURL;
}
//if (objMenuManagerInfo.LinkURL == string.Empty)
//{
// pageLink = pageLink.IndexOf(Extension) > 0 ? pageLink : pageLink + Extension;
//}
html.Append("<li>");
string menuItem = BuildMenuItem(menuDisplayMode, objMenuManagerInfo, pageLink, showCaption);
html.Append(menuItem);
childNodes = BuildFooterChildren(objMenuManagerInfoList, objMenuManagerInfo.PageID, menuDisplayMode, showCaption);
if (childNodes != string.Empty)
{
html.Append("<ul>");
html.Append(childNodes);
html.Append("</ul>");
}
html.Append("</li>");
}
}
}
return html.ToString();
}
#endregion
private List<MenuManagerInfo> GetMenuFront(int PortalID, string UserName, string CultureCode, int UserModuleID)
{
try
{
List<MenuManagerInfo> lstMenuItems = new List<MenuManagerInfo>();
if (SageFrameSettingKeys.FrontMenu && UserName == "anonymoususer")
{
if (!SageFrame.Common.CacheHelper.Get(CultureCode + ".FrontMenu" + PortalID.ToString(), out lstMenuItems))
{
lstMenuItems = MenuManagerDataController.GetSageMenu_Localized(UserModuleID, PortalID, UserName, CultureCode);
SageFrame.Common.CacheHelper.Add(lstMenuItems, CultureCode + ".FrontMenu" + PortalID.ToString());
}
}
else
{
lstMenuItems = MenuManagerDataController.GetSageMenu_Localized(UserModuleID, PortalID, UserName, CultureCode);
}
IEnumerable<MenuManagerInfo> lstParent = new List<MenuManagerInfo>();
List<MenuManagerInfo> lstHierarchy = new List<MenuManagerInfo>();
lstParent = from pg in lstMenuItems
where pg.MenuLevel == "0"
select pg;
foreach (MenuManagerInfo parent in lstParent)
{
lstHierarchy.Add(parent);
GetChildPages(ref lstHierarchy, parent, lstMenuItems);
}
return (lstHierarchy);
}
catch (Exception)
{
throw;
}
}
private void GetChildPages(ref List<MenuManagerInfo> lstHierarchy, MenuManagerInfo parent, List<MenuManagerInfo> lstPages)
{
foreach (MenuManagerInfo obj in lstPages)
{
if (obj.ParentID == parent.MenuItemID)
{
lstHierarchy.Add(obj);
GetChildPages(ref lstHierarchy, obj, lstPages);
}
}
}
private string BuildMenuClassContainer(int MenuMode)
{
string html = "<div id='" + ContainerClientID + "'>";
switch (MenuMode)
{
case 1:
html += "<ul class='sf-menu sf-vertical'>";
break;
case 2:
html += "<ul class='sf-menu sf-navbar'>";
break;
case 3:
html += "<span id='sfResponsiveNavBtn' class='inactive'></span><ul class='sf-menu sfDropdown clearfix'>";
break;
case 4:
html += "<ul class='sf-menu sfCssmenu'>";
break;
}
return html;
}
private string BuildMenuItem(int displayMode, MenuManagerInfo objMenuInfo, string pageLink, string caption)
{
StringBuilder html = new StringBuilder();
if (objMenuInfo.IsActive != null)
{
if (!objMenuInfo.IsActive)
{
pageLink = "#";
}
}
string title = objMenuInfo.PageName;
pageLink = pageLink.Replace("&", "-and-");
if (objMenuInfo.LinkType != null)
{
title = objMenuInfo.LinkType == "0" ? objMenuInfo.PageName : objMenuInfo.Title;
}
string image = appPath + "/PageImages/" + objMenuInfo.ImageIcon;
string imageTag = objMenuInfo.ImageIcon != string.Empty ? "<img src=" + image + ">" : "";
string arrowStyle = objMenuInfo.ChildCount > 0 ? "<span class='sf-sub-indicator'></span>" : "";
switch (displayMode)
{
case 0://image only
if (caption == "1")
{
html.Append("<a href='");
html.Append(pageLink);
html.Append("'><span class='sfPageicon'>");
html.Append(imageTag);
html.Append("<em>");
html.Append(objMenuInfo.Caption);
html.Append("</em>");
html.Append("</span>");
html.Append(arrowStyle);
html.Append("</a>");
}
else
{
html.Append("<a href='");
html.Append(pageLink);
html.Append("'><span class='sfPageicon'>");
html.Append(imageTag);
html.Append("</span>");
html.Append(arrowStyle);
html.Append("</a>");
}
break;
case 1://text only
if (caption == "1")
{
html.Append("<a href='");
html.Append(pageLink);
html.Append("'><span class='sfPagename'>");
html.Append(title);
html.Append("<em>");
html.Append(objMenuInfo.Caption);
html.Append("</em>");
html.Append("</span>");
html.Append(arrowStyle);
html.Append("</a>");
}
else
{
html.Append("<a href='");
html.Append(pageLink);
html.Append("'><span class='sfPagename'>");
html.Append(title);
html.Append("</span>");
html.Append(arrowStyle);
html.Append("</a>");
}
break;
case 2: //text and image both
if (caption == "1")
{
html.Append("<a href='");
html.Append(pageLink);
html.Append("'><span class='sfPageicon'>");
html.Append(imageTag);
html.Append("</span><span class='sfPagename'>");
html.Append(title);
html.Append("<em>");
html.Append(objMenuInfo.Caption);
html.Append("</em>");
html.Append("</span>");
html.Append(arrowStyle);
html.Append("</a>");
}
else
{
html.Append("<a href='");
html.Append(pageLink);
html.Append("'><span class='sfPageicon'>");
html.Append(imageTag);
html.Append("</span><span class='sfPagename'>");
html.Append(title);
html.Append("</span>");
html.Append(arrowStyle);
html.Append("</a>");
}
break;
}
return html.ToString();
}
private List<MenuInfo> GetSideMenu(int PortalID, string UserName, int MenuID, string CultureCode)
{
List<MenuInfo> lstMenu = MenuController.GetSideMenu(PortalID, UserName, MenuID, CultureCode);
List<MenuInfo> lstNewMenu = new List<MenuInfo>();
foreach (MenuInfo obj in lstMenu)
{
obj.ChildCount = lstMenu.Count(
delegate(MenuInfo objMenu)
{
return (objMenu.ParentID == obj.PageID);
}
);
obj.Title = obj.PageName;
// if (obj.Level > 0)
//{
lstNewMenu.Add(obj);
//}
}
return lstNewMenu;
}
private List<MenuManagerInfo> GetCustomSideMenu(int PortalID, string UserName, string CultureCode, int UserModuleID)
{
List<MenuManagerInfo> lstMenuItems = new List<MenuManagerInfo>();
if (SageFrameSettingKeys.SideMenu && UserName == "anonymoususer")
{
if (!SageFrame.Common.CacheHelper.Get(CultureCode + ".SideMenu" + PortalID.ToString(), out lstMenuItems))
{
lstMenuItems = MenuManagerDataController.GetSageMenu(UserModuleID, PortalID, UserName);
SageFrame.Common.CacheHelper.Add(lstMenuItems, CultureCode + ".SideMenu" + PortalID.ToString());
}
}
else
{
lstMenuItems = MenuManagerDataController.GetSageMenu(UserModuleID, PortalID, UserName);
}
IEnumerable<MenuManagerInfo> lstParent = new List<MenuManagerInfo>();
List<MenuManagerInfo> lstHierarchy = new List<MenuManagerInfo>();
lstParent = from pg in lstMenuItems
where pg.MenuLevel == "0"
select pg;
foreach (MenuManagerInfo parent in lstParent)
{
lstHierarchy.Add(parent);
GetChildPages(ref lstHierarchy, parent, lstMenuItems);
}
return (lstHierarchy);
}
private string BindChildCategory(List<MenuManagerInfo> objMenuInfoList, int pageID, int menuDisplayMode, string ShowCaption)
{
string strListmaker = string.Empty;
string childNodes = string.Empty;
string path = string.Empty;
string itemPath = string.Empty;
StringBuilder html = new StringBuilder();
foreach (MenuManagerInfo objMenuInfo in objMenuInfoList)
{
if (int.Parse(objMenuInfo.MenuLevel) > 0)
{
if (objMenuInfo.ParentID == pageID)
{
itemPath = objMenuInfo.Title;
string PageURL = objMenuInfo.URL.Split('/').Last();
string pageLink = string.Empty;
if (PageURL == string.Empty && objMenuInfo.LinkType == "2")
{
pageLink = objMenuInfo.LinkURL;
}
else
{
pageLink = objMenuInfo.LinkType == "0" ? pagePath + PageURL + Extension : "/" + PageURL;
}
if (objMenuInfo.LinkURL == "0")
{
pageLink = pageLink.IndexOf(Extension) > 0 ? pageLink : pageLink + Extension;
}
string styleClass = objMenuInfo.ChildCount > 0 ? "class='sfParent'" : "";
html.Append("<li ");
html.Append(styleClass);
html.Append(">");
string buildMenu = BuildMenuItem(menuDisplayMode, objMenuInfo, pageLink, ShowCaption);
html.Append(buildMenu);
childNodes = BindChildCategory(objMenuInfoList, objMenuInfo.MenuItemID, menuDisplayMode, ShowCaption);
if (childNodes != string.Empty)
{
html.Append("<ul>");
html.Append(childNodes);
html.Append("</ul>");
}
if (objMenuInfo.HtmlContent != string.Empty)
{
html.Append("<ul class='megamenu'><li><div class='megawrapper'>");
html.Append(objMenuInfo.HtmlContent);
html.Append("</div></li></ul>");
}
html.Append("</li>");
}
}
}
return html.ToString();
}
private string BuildSideMenuItem(int displayMode, MenuInfo objMenuInfo, string pageLink, string caption)
{
StringBuilder html = new StringBuilder();
string title = objMenuInfo.PageName;
pageLink = pageLink.Replace("&", "-and-");
string image = appPath + "/PageImages/" + objMenuInfo.IconFile;
string imageTag = objMenuInfo.IconFile != string.Empty ? "<img src=" + image + ">" : "";
string arrowStyle = objMenuInfo.ChildCount > 0 ? "<span class='sf-sub-indicator'></span>" : "";
string firstclass = string.Empty;
string activeClass = objMenuInfo.PageName == PageName ? " sfActive" : "";
string isParent = objMenuInfo.ChildCount > 0 ? (objMenuInfo.Level == 1 ? "class='sfParent level1 " + activeClass + "'" : "class='sfParent " + activeClass + "'") : (objMenuInfo.Level == 1 ? "class='level1 " + activeClass + "'" : "class='" + activeClass + "'");
switch (displayMode)
{
case 0://image only
if (caption == "1")
{
html.Append("<a ");
html.Append(isParent);
html.Append(" href='");
html.Append(pageLink);
html.Append("'><span class='sfPageicon'>");
html.Append(imageTag);
html.Append("</span>");
html.Append(arrowStyle);
html.Append("</a>");
}
else
{
html.Append("<a ");
html.Append(isParent);
html.Append(" href='");
html.Append(pageLink);
html.Append("'><span class='sfPageicon'>");
html.Append(imageTag);
html.Append("</span>");
html.Append(arrowStyle);
html.Append("</a>");
}
break;
case 1://text only
if (caption == "1")
{
html.Append("<a ");
html.Append(isParent);
html.Append(" href='");
html.Append(pageLink);
html.Append("'>");
html.Append(arrowStyle);
html.Append("<span class='sfPagename'>");
html.Append(title);
html.Append("</span></a>");
}
else
{
html.Append("<a ");
html.Append(isParent);
html.Append(" href='");
html.Append(pageLink);
html.Append("'>");
html.Append(arrowStyle);
html.Append("<span class='sfPagename'>");
html.Append(title.Replace("-", " "));
html.Append("</span></a>");
}
break;
case 2://text and image both
if (caption == "1")
{
html.Append("<a ");
html.Append(isParent);
html.Append(" href='");
html.Append(pageLink);
html.Append("'>");
html.Append(arrowStyle);
html.Append("<span class='sfPagename'>");
html.Append(title);
html.Append("</span></a>");
}
else
{
html.Append("<a ");
html.Append(isParent);
html.Append(" href='");
html.Append(pageLink);
html.Append("'>");
html.Append(arrowStyle);
html.Append("<span class='sfPagename'>");
html.Append(GetSideMenuPadding(objMenuInfo.Level));
html.Append(title.Replace("-", " "));
html.Append("</span></a>");
}
break;
}
return html.ToString();
}
public string GetSideMenuPadding(int level)
{
string padding = string.Empty;
for (var i = 0; i < level; i++)
{
padding += " ";
}
return padding;
}
}
| |
using UnityEngine;
using System.Collections;
[AddComponentMenu("2D Toolkit/Sprite/tk2dTiledSprite")]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
[ExecuteInEditMode]
/// <summary>
/// Sprite implementation that tiles a sprite to fill given dimensions.
/// </summary>
public class tk2dTiledSprite : tk2dBaseSprite
{
Mesh mesh;
Vector2[] meshUvs;
Vector3[] meshVertices;
Color32[] meshColors;
int[] meshIndices;
[SerializeField]
Vector2 _dimensions = new Vector2(50.0f, 50.0f);
[SerializeField]
Anchor _anchor = Anchor.LowerLeft;
/// <summary>
/// Gets or sets the dimensions.
/// </summary>
/// <value>
/// Use this to change the dimensions of the sliced sprite in pixel units
/// </value>
public Vector2 dimensions
{
get { return _dimensions; }
set
{
if (value != _dimensions)
{
_dimensions = value;
UpdateVertices();
#if UNITY_EDITOR
EditMode__CreateCollider();
#endif
UpdateCollider();
}
}
}
/// <summary>
/// The anchor position for this tiled sprite
/// </summary>
public Anchor anchor
{
get { return _anchor; }
set
{
if (value != _anchor)
{
_anchor = value;
UpdateVertices();
#if UNITY_EDITOR
EditMode__CreateCollider();
#endif
UpdateCollider();
}
}
}
[SerializeField]
protected bool _createBoxCollider = false;
/// <summary>
/// Create a trimmed box collider for this sprite
/// </summary>
public bool CreateBoxCollider {
get { return _createBoxCollider; }
set {
if (_createBoxCollider != value) {
_createBoxCollider = value;
UpdateCollider();
}
}
}
new void Awake()
{
base.Awake();
// Create mesh, independently to everything else
mesh = new Mesh();
mesh.hideFlags = HideFlags.DontSave;
GetComponent<MeshFilter>().mesh = mesh;
// This will not be set when instantiating in code
// In that case, Build will need to be called
if (Collection)
{
// reset spriteId if outside bounds
// this is when the sprite collection data is corrupt
if (_spriteId < 0 || _spriteId >= Collection.Count)
_spriteId = 0;
Build();
if (boxCollider == null)
boxCollider = GetComponent<BoxCollider>();
}
}
protected void OnDestroy()
{
if (mesh)
{
#if UNITY_EDITOR
DestroyImmediate(mesh);
#else
Destroy(mesh);
#endif
}
}
new protected void SetColors(Color32[] dest)
{
int numVertices;
int numIndices;
tk2dSpriteGeomGen.GetTiledSpriteGeomDesc(out numVertices, out numIndices, CurrentSprite, dimensions);
tk2dSpriteGeomGen.SetSpriteColors (dest, 0, numVertices, _color, collectionInst.premultipliedAlpha);
}
// Calculated center and extents
Vector3 boundsCenter = Vector3.zero, boundsExtents = Vector3.zero;
public override void Build()
{
var spriteDef = CurrentSprite;
int numVertices;
int numIndices;
tk2dSpriteGeomGen.GetTiledSpriteGeomDesc(out numVertices, out numIndices, spriteDef, dimensions);
if (meshUvs == null || meshUvs.Length != numVertices) {
meshUvs = new Vector2[numVertices];
meshVertices = new Vector3[numVertices];
meshColors = new Color32[numVertices];
}
if (meshIndices == null || meshIndices.Length != numIndices) {
meshIndices = new int[numIndices];
}
float colliderOffsetZ = ( boxCollider != null ) ? ( boxCollider.center.z ) : 0.0f;
float colliderExtentZ = ( boxCollider != null ) ? ( boxCollider.size.z * 0.5f ) : 0.5f;
tk2dSpriteGeomGen.SetTiledSpriteGeom(meshVertices, meshUvs, 0, out boundsCenter, out boundsExtents, spriteDef, _scale, dimensions, anchor, colliderOffsetZ, colliderExtentZ);
tk2dSpriteGeomGen.SetTiledSpriteIndices(meshIndices, 0, 0, spriteDef, dimensions);
SetColors(meshColors);
if (mesh == null)
{
mesh = new Mesh();
mesh.hideFlags = HideFlags.DontSave;
}
else
{
mesh.Clear();
}
mesh.vertices = meshVertices;
mesh.colors32 = meshColors;
mesh.uv = meshUvs;
mesh.triangles = meshIndices;
mesh.RecalculateBounds();
GetComponent<MeshFilter>().mesh = mesh;
UpdateCollider();
UpdateMaterial();
}
protected override void UpdateGeometry() { UpdateGeometryImpl(); }
protected override void UpdateColors() { UpdateColorsImpl(); }
protected override void UpdateVertices() { UpdateGeometryImpl(); }
protected void UpdateColorsImpl()
{
#if UNITY_EDITOR
// This can happen with prefabs in the inspector
if (meshColors == null || meshColors.Length == 0)
return;
#endif
if (meshColors == null || meshColors.Length == 0) {
Build();
}
else {
SetColors(meshColors);
mesh.colors32 = meshColors;
}
}
protected void UpdateGeometryImpl()
{
#if UNITY_EDITOR
// This can happen with prefabs in the inspector
if (mesh == null)
return;
#endif
Build();
}
#region Collider
protected override void UpdateCollider()
{
if (CreateBoxCollider) {
if (boxCollider == null) {
boxCollider = GetComponent<BoxCollider>();
if (boxCollider == null) {
boxCollider = gameObject.AddComponent<BoxCollider>();
}
}
boxCollider.extents = boundsExtents;
boxCollider.center = boundsCenter;
} else {
#if UNITY_EDITOR
boxCollider = GetComponent<BoxCollider>();
if (boxCollider != null) {
DestroyImmediate(boxCollider);
}
#else
if (boxCollider != null) {
Destroy(boxCollider);
}
#endif
}
}
#if UNITY_EDITOR
void OnDrawGizmos() {
if (mesh != null) {
Bounds b = mesh.bounds;
Gizmos.color = Color.clear;
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawCube(b.center, b.extents * 2);
Gizmos.matrix = Matrix4x4.identity;
Gizmos.color = Color.white;
}
}
#endif
protected override void CreateCollider() {
UpdateCollider();
}
#if UNITY_EDITOR
public override void EditMode__CreateCollider() {
UpdateCollider();
}
#endif
#endregion
protected override void UpdateMaterial()
{
if (GetComponent<Renderer>().sharedMaterial != collectionInst.spriteDefinitions[spriteId].materialInst)
GetComponent<Renderer>().material = collectionInst.spriteDefinitions[spriteId].materialInst;
}
protected override int GetCurrentVertexCount()
{
#if UNITY_EDITOR
if (meshVertices == null)
return 0;
#endif
return 16;
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Rotorz.ReorderableList;
using System.Linq;
using System.Reflection;
using System.IO;
namespace Fungus
{
[CustomEditor (typeof(Flowchart))]
public class FlowchartEditor : Editor
{
protected class AddVariableInfo
{
public Flowchart flowchart;
public System.Type variableType;
}
protected SerializedProperty descriptionProp;
protected SerializedProperty colorCommandsProp;
protected SerializedProperty hideComponentsProp;
protected SerializedProperty stepPauseProp;
protected SerializedProperty saveSelectionProp;
protected SerializedProperty localizationIdProp;
protected SerializedProperty variablesProp;
protected SerializedProperty hideCommandsProp;
protected Texture2D addTexture;
protected virtual void OnEnable()
{
if (NullTargetCheck()) // Check for an orphaned editor instance
return;
descriptionProp = serializedObject.FindProperty("description");
colorCommandsProp = serializedObject.FindProperty("colorCommands");
hideComponentsProp = serializedObject.FindProperty("hideComponents");
stepPauseProp = serializedObject.FindProperty("stepPause");
saveSelectionProp = serializedObject.FindProperty("saveSelection");
localizationIdProp = serializedObject.FindProperty("localizationId");
variablesProp = serializedObject.FindProperty("variables");
hideCommandsProp = serializedObject.FindProperty("hideCommands");
addTexture = Resources.Load("Icons/add_small") as Texture2D;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
Flowchart flowchart = target as Flowchart;
flowchart.UpdateHideFlags();
EditorGUILayout.PropertyField(descriptionProp);
EditorGUILayout.PropertyField(colorCommandsProp);
EditorGUILayout.PropertyField(hideComponentsProp);
EditorGUILayout.PropertyField(stepPauseProp);
EditorGUILayout.PropertyField(saveSelectionProp);
EditorGUILayout.PropertyField(localizationIdProp);
// Show list of commands to hide in Add Command menu
ReorderableListGUI.Title(new GUIContent(hideCommandsProp.displayName, hideCommandsProp.tooltip));
ReorderableListGUI.ListField(hideCommandsProp);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Flowchart Window"))
{
EditorWindow.GetWindow(typeof(FlowchartWindow), false, "Flowchart");
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
serializedObject.ApplyModifiedProperties();
}
public virtual void DrawVariablesGUI()
{
serializedObject.Update();
Flowchart t = target as Flowchart;
if (t.variables.Count == 0)
{
t.variablesExpanded = true;
}
if (!t.variablesExpanded)
{
if (GUILayout.Button ("Variables (" + t.variables.Count + ")", GUILayout.Height(24)))
{
t.variablesExpanded = true;
}
// Draw disclosure triangle
Rect lastRect = GUILayoutUtility.GetLastRect();
lastRect.x += 5;
lastRect.y += 5;
EditorGUI.Foldout(lastRect, false, "");
}
else
{
Rect listRect = new Rect();
if (t.variables.Count > 0)
{
// Remove any null variables from the list
// Can sometimes happen when upgrading to a new version of Fungus (if .meta GUID changes for a variable class)
for (int i = t.variables.Count - 1; i >= 0; i--)
{
if (t.variables[i] == null)
{
t.variables.RemoveAt(i);
}
}
ReorderableListGUI.Title("Variables");
VariableListAdaptor adaptor = new VariableListAdaptor(variablesProp, 0);
ReorderableListFlags flags = ReorderableListFlags.DisableContextMenu | ReorderableListFlags.HideAddButton;
ReorderableListControl.DrawControlFromState(adaptor, null, flags);
listRect = GUILayoutUtility.GetLastRect();
}
else
{
GUILayoutUtility.GetRect(300, 24);
listRect = GUILayoutUtility.GetLastRect();
listRect.y += 20;
}
float plusWidth = 32;
float plusHeight = 24;
Rect buttonRect = listRect;
float buttonHeight = 24;
buttonRect.x = 4;
buttonRect.y -= buttonHeight - 1;
buttonRect.height = buttonHeight;
if (!Application.isPlaying)
{
buttonRect.width -= 30;
}
if (GUI.Button (buttonRect, "Variables"))
{
t.variablesExpanded = false;
}
// Draw disclosure triangle
Rect lastRect = buttonRect;
lastRect.x += 5;
lastRect.y += 5;
EditorGUI.Foldout(lastRect, true, "");
Rect plusRect = listRect;
plusRect.x += plusRect.width - plusWidth;
plusRect.y -= plusHeight - 1;
plusRect.width = plusWidth;
plusRect.height = plusHeight;
if (!Application.isPlaying &&
GUI.Button(plusRect, addTexture))
{
GenericMenu menu = new GenericMenu ();
List<System.Type> types = FindAllDerivedTypes<Variable>();
// Add variable types without a category
foreach (System.Type type in types)
{
VariableInfoAttribute variableInfo = VariableEditor.GetVariableInfo(type);
if (variableInfo == null ||
variableInfo.Category != "")
{
continue;
}
AddVariableInfo addVariableInfo = new AddVariableInfo();
addVariableInfo.flowchart = t;
addVariableInfo.variableType = type;
GUIContent typeName = new GUIContent(variableInfo.VariableType);
menu.AddItem(typeName, false, AddVariable, addVariableInfo);
}
// Add types with a category
foreach (System.Type type in types)
{
VariableInfoAttribute variableInfo = VariableEditor.GetVariableInfo(type);
if (variableInfo == null ||
variableInfo.Category == "")
{
continue;
}
AddVariableInfo info = new AddVariableInfo();
info.flowchart = t;
info.variableType = type;
GUIContent typeName = new GUIContent(variableInfo.Category + "/" + variableInfo.VariableType);
menu.AddItem(typeName, false, AddVariable, info);
}
menu.ShowAsContext ();
}
}
serializedObject.ApplyModifiedProperties();
}
protected virtual void AddVariable(object obj)
{
AddVariableInfo addVariableInfo = obj as AddVariableInfo;
if (addVariableInfo == null)
{
return;
}
Flowchart flowchart = addVariableInfo.flowchart;
System.Type variableType = addVariableInfo.variableType;
Undo.RecordObject(flowchart, "Add Variable");
Variable newVariable = flowchart.gameObject.AddComponent(variableType) as Variable;
newVariable.key = flowchart.GetUniqueVariableKey("");
flowchart.variables.Add(newVariable);
}
public static List<System.Type> FindAllDerivedTypes<T>()
{
return FindAllDerivedTypes<T>(Assembly.GetAssembly(typeof(T)));
}
public static List<System.Type> FindAllDerivedTypes<T>(Assembly assembly)
{
var derivedType = typeof(T);
return assembly
.GetTypes()
.Where(t =>
t != derivedType &&
derivedType.IsAssignableFrom(t)
).ToList();
}
/**
* When modifying custom editor code you can occasionally end up with orphaned editor instances.
* When this happens, you'll get a null exception error every time the scene serializes / deserialized.
* Once this situation occurs, the only way to fix it is to restart the Unity editor.
* As a workaround, this function detects if this editor is an orphan and deletes it.
*/
protected virtual bool NullTargetCheck()
{
try
{
// The serializedObject accessor creates a new SerializedObject if needed.
// However, this will fail with a null exception if the target object no longer exists.
#pragma warning disable 0219
SerializedObject so = serializedObject;
}
catch (System.NullReferenceException)
{
DestroyImmediate(this);
return true;
}
return false;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata
{
partial class MetadataReader
{
internal const string ClrPrefix = "<CLR>";
internal static readonly byte[] WinRTPrefix = new[] {
(byte)'<',
(byte)'W',
(byte)'i',
(byte)'n',
(byte)'R',
(byte)'T',
(byte)'>'
};
#region Projection Tables
// Maps names of projected types to projection information for each type.
// Both arrays are of the same length and sorted by the type name.
private static string[] s_projectedTypeNames;
private static ProjectionInfo[] s_projectionInfos;
private struct ProjectionInfo
{
public readonly string WinRTNamespace;
public readonly StringHandle.VirtualIndex ClrNamespace;
public readonly StringHandle.VirtualIndex ClrName;
public readonly AssemblyReferenceHandle.VirtualIndex AssemblyRef;
public readonly TypeDefTreatment Treatment;
public readonly bool IsIDisposable;
public ProjectionInfo(
string winRtNamespace,
StringHandle.VirtualIndex clrNamespace,
StringHandle.VirtualIndex clrName,
AssemblyReferenceHandle.VirtualIndex clrAssembly,
TypeDefTreatment treatment = TypeDefTreatment.RedirectedToClrType,
bool isIDisposable = false)
{
this.WinRTNamespace = winRtNamespace;
this.ClrNamespace = clrNamespace;
this.ClrName = clrName;
this.AssemblyRef = clrAssembly;
this.Treatment = treatment;
this.IsIDisposable = isIDisposable;
}
}
private TypeDefTreatment GetWellKnownTypeDefinitionTreatment(TypeDefinitionHandle typeDef)
{
InitializeProjectedTypes();
StringHandle name = TypeDefTable.GetName(typeDef);
int index = StringStream.BinarySearchRaw(s_projectedTypeNames, name);
if (index < 0)
{
return TypeDefTreatment.None;
}
StringHandle namespaceName = TypeDefTable.GetNamespace(typeDef);
if (StringStream.EqualsRaw(namespaceName, StringStream.GetVirtualValue(s_projectionInfos[index].ClrNamespace)))
{
return s_projectionInfos[index].Treatment;
}
// TODO: we can avoid this comparison if info.DotNetNamespace == info.WinRtNamespace
if (StringStream.EqualsRaw(namespaceName, s_projectionInfos[index].WinRTNamespace))
{
return s_projectionInfos[index].Treatment | TypeDefTreatment.MarkInternalFlag;
}
return TypeDefTreatment.None;
}
private int GetProjectionIndexForTypeReference(TypeReferenceHandle typeRef, out bool isIDisposable)
{
InitializeProjectedTypes();
int index = StringStream.BinarySearchRaw(s_projectedTypeNames, TypeRefTable.GetName(typeRef));
if (index >= 0 && StringStream.EqualsRaw(TypeRefTable.GetNamespace(typeRef), s_projectionInfos[index].WinRTNamespace))
{
isIDisposable = s_projectionInfos[index].IsIDisposable;
return index;
}
isIDisposable = false;
return -1;
}
internal static AssemblyReferenceHandle GetProjectedAssemblyRef(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return AssemblyReferenceHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].AssemblyRef);
}
internal static StringHandle GetProjectedName(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrName);
}
internal static StringHandle GetProjectedNamespace(int projectionIndex)
{
Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length);
return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrNamespace);
}
private static void InitializeProjectedTypes()
{
if (s_projectedTypeNames == null || s_projectionInfos == null)
{
var systemRuntimeWindowsRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime;
var systemRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime;
var systemObjectModel = AssemblyReferenceHandle.VirtualIndex.System_ObjectModel;
var systemRuntimeWindowsUiXaml = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml;
var systemRuntimeInterop = AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime;
var systemNumericsVectors = AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors;
// sorted by name
var keys = new string[50];
var values = new ProjectionInfo[50];
int k = 0, v = 0;
// WARNING: Keys must be sorted by name and must only contain ASCII characters. WinRTNamespace must also be ASCII only.
keys[k++] = "AttributeTargets"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeTargets, systemRuntime);
keys[k++] = "AttributeUsageAttribute"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeUsageAttribute, systemRuntime, treatment: TypeDefTreatment.RedirectedToClrAttribute);
keys[k++] = "Color"; values[v++] = new ProjectionInfo("Windows.UI", StringHandle.VirtualIndex.Windows_UI, StringHandle.VirtualIndex.Color, systemRuntimeWindowsRuntime);
keys[k++] = "CornerRadius"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.CornerRadius, systemRuntimeWindowsUiXaml);
keys[k++] = "DateTime"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.DateTimeOffset, systemRuntime);
keys[k++] = "Duration"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Duration, systemRuntimeWindowsUiXaml);
keys[k++] = "DurationType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.DurationType, systemRuntimeWindowsUiXaml);
keys[k++] = "EventHandler`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.EventHandler1, systemRuntime);
keys[k++] = "EventRegistrationToken"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime, StringHandle.VirtualIndex.EventRegistrationToken, systemRuntimeInterop);
keys[k++] = "GeneratorPosition"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Controls.Primitives", StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives, StringHandle.VirtualIndex.GeneratorPosition, systemRuntimeWindowsUiXaml);
keys[k++] = "GridLength"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridLength, systemRuntimeWindowsUiXaml);
keys[k++] = "GridUnitType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridUnitType, systemRuntimeWindowsUiXaml);
keys[k++] = "HResult"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Exception, systemRuntime);
keys[k++] = "IBindableIterable"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IEnumerable, systemRuntime);
keys[k++] = "IBindableVector"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IList, systemRuntime);
keys[k++] = "IClosable"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.IDisposable, systemRuntime, isIDisposable: true);
keys[k++] = "ICommand"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Input", StringHandle.VirtualIndex.System_Windows_Input, StringHandle.VirtualIndex.ICommand, systemObjectModel);
keys[k++] = "IIterable`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IEnumerable1, systemRuntime);
keys[k++] = "IKeyValuePair`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.KeyValuePair2, systemRuntime);
keys[k++] = "IMapView`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyDictionary2, systemRuntime);
keys[k++] = "IMap`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IDictionary2, systemRuntime);
keys[k++] = "INotifyCollectionChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.INotifyCollectionChanged, systemObjectModel);
keys[k++] = "INotifyPropertyChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.INotifyPropertyChanged, systemObjectModel);
keys[k++] = "IReference`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Nullable1, systemRuntime);
keys[k++] = "IVectorView`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyList1, systemRuntime);
keys[k++] = "IVector`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IList1, systemRuntime);
keys[k++] = "KeyTime"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.KeyTime, systemRuntimeWindowsUiXaml);
keys[k++] = "Matrix"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media", StringHandle.VirtualIndex.Windows_UI_Xaml_Media, StringHandle.VirtualIndex.Matrix, systemRuntimeWindowsUiXaml);
keys[k++] = "Matrix3D"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Media3D", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D, StringHandle.VirtualIndex.Matrix3D, systemRuntimeWindowsUiXaml);
keys[k++] = "Matrix3x2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix3x2, systemNumericsVectors);
keys[k++] = "Matrix4x4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix4x4, systemNumericsVectors);
keys[k++] = "NotifyCollectionChangedAction"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedAction, systemObjectModel);
keys[k++] = "NotifyCollectionChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs, systemObjectModel);
keys[k++] = "NotifyCollectionChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler, systemObjectModel);
keys[k++] = "Plane"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Plane, systemNumericsVectors);
keys[k++] = "Point"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Point, systemRuntimeWindowsRuntime);
keys[k++] = "PropertyChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventArgs, systemObjectModel);
keys[k++] = "PropertyChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventHandler, systemObjectModel);
keys[k++] = "Quaternion"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Quaternion, systemNumericsVectors);
keys[k++] = "Rect"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Rect, systemRuntimeWindowsRuntime);
keys[k++] = "RepeatBehavior"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehavior, systemRuntimeWindowsUiXaml);
keys[k++] = "RepeatBehaviorType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehaviorType, systemRuntimeWindowsUiXaml);
keys[k++] = "Size"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Size, systemRuntimeWindowsRuntime);
keys[k++] = "Thickness"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Thickness, systemRuntimeWindowsUiXaml);
keys[k++] = "TimeSpan"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.TimeSpan, systemRuntime);
keys[k++] = "TypeName"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Type, systemRuntime);
keys[k++] = "Uri"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Uri, systemRuntime);
keys[k++] = "Vector2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector2, systemNumericsVectors);
keys[k++] = "Vector3"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector3, systemNumericsVectors);
keys[k++] = "Vector4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector4, systemNumericsVectors);
Debug.Assert(k == keys.Length && v == keys.Length && k == v);
AssertSorted(keys);
s_projectedTypeNames = keys;
s_projectionInfos = values;
}
}
[Conditional("DEBUG")]
private static void AssertSorted(string[] keys)
{
for (int i = 0; i < keys.Length - 1; i++)
{
Debug.Assert(String.CompareOrdinal(keys[i], keys[i + 1]) < 0);
}
}
// test only
internal static string[] GetProjectedTypeNames()
{
InitializeProjectedTypes();
return s_projectedTypeNames;
}
#endregion
private static uint TreatmentAndRowId(byte treatment, int rowId)
{
return ((uint)treatment << TokenTypeIds.RowIdBitCount) | (uint)rowId;
}
#region TypeDef
[MethodImpl(MethodImplOptions.NoInlining)]
internal uint CalculateTypeDefTreatmentAndRowId(TypeDefinitionHandle handle)
{
Debug.Assert(_metadataKind != MetadataKind.Ecma335);
TypeDefTreatment treatment;
TypeAttributes flags = TypeDefTable.GetFlags(handle);
EntityHandle extends = TypeDefTable.GetExtends(handle);
if ((flags & TypeAttributes.WindowsRuntime) != 0)
{
if (_metadataKind == MetadataKind.WindowsMetadata)
{
treatment = GetWellKnownTypeDefinitionTreatment(handle);
if (treatment != TypeDefTreatment.None)
{
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
// Is this an attribute?
if (extends.Kind == HandleKind.TypeReference && IsSystemAttribute((TypeReferenceHandle)extends))
{
treatment = TypeDefTreatment.NormalAttribute;
}
else
{
treatment = TypeDefTreatment.NormalNonAttribute;
}
}
else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && NeedsWinRTPrefix(flags, extends))
{
// WinMDExp emits two versions of RuntimeClasses and Enums:
//
// public class Foo {} // the WinRT reference class
// internal class <CLR>Foo {} // the implementation class that we want WinRT consumers to ignore
//
// The adapter's job is to undo WinMDExp's transformations. I.e. turn the above into:
//
// internal class <WinRT>Foo {} // the WinRT reference class that we want CLR consumers to ignore
// public class Foo {} // the implementation class
//
// We only add the <WinRT> prefix here since the WinRT view is the only view that is marked WindowsRuntime
// De-mangling the CLR name is done below.
// tomat: The CLR adapter implements a back-compat quirk: Enums exported with an older WinMDExp have only one version
// not marked with tdSpecialName. These enums should *not* be mangled and flipped to private.
// We don't implement this flag since the WinMDs producted by the older WinMDExp are not used in the wild.
treatment = TypeDefTreatment.PrefixWinRTName;
}
else
{
treatment = TypeDefTreatment.None;
}
// Scan through Custom Attributes on type, looking for interesting bits. We only
// need to do this for RuntimeClasses
if ((treatment == TypeDefTreatment.PrefixWinRTName || treatment == TypeDefTreatment.NormalNonAttribute))
{
if ((flags & TypeAttributes.Interface) == 0
&& HasAttribute(handle, "Windows.UI.Xaml", "TreatAsAbstractComposableClassAttribute"))
{
treatment |= TypeDefTreatment.MarkAbstractFlag;
}
}
}
else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && IsClrImplementationType(handle))
{
// <CLR> implementation classes are not marked WindowsRuntime, but still need to be modified
// by the adapter.
treatment = TypeDefTreatment.UnmangleWinRTName;
}
else
{
treatment = TypeDefTreatment.None;
}
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
private bool IsClrImplementationType(TypeDefinitionHandle typeDef)
{
var attrs = TypeDefTable.GetFlags(typeDef);
if ((attrs & (TypeAttributes.VisibilityMask | TypeAttributes.SpecialName)) != TypeAttributes.SpecialName)
{
return false;
}
return StringStream.StartsWithRaw(TypeDefTable.GetName(typeDef), ClrPrefix);
}
#endregion
#region TypeRef
internal uint CalculateTypeRefTreatmentAndRowId(TypeReferenceHandle handle)
{
Debug.Assert(_metadataKind != MetadataKind.Ecma335);
bool isIDisposable;
int projectionIndex = GetProjectionIndexForTypeReference(handle, out isIDisposable);
if (projectionIndex >= 0)
{
return TreatmentAndRowId((byte)TypeRefTreatment.UseProjectionInfo, projectionIndex);
}
else
{
return TreatmentAndRowId((byte)GetSpecialTypeRefTreatment(handle), handle.RowId);
}
}
private TypeRefTreatment GetSpecialTypeRefTreatment(TypeReferenceHandle handle)
{
if (StringStream.EqualsRaw(TypeRefTable.GetNamespace(handle), "System"))
{
StringHandle name = TypeRefTable.GetName(handle);
if (StringStream.EqualsRaw(name, "MulticastDelegate"))
{
return TypeRefTreatment.SystemDelegate;
}
if (StringStream.EqualsRaw(name, "Attribute"))
{
return TypeRefTreatment.SystemAttribute;
}
}
return TypeRefTreatment.None;
}
private bool IsSystemAttribute(TypeReferenceHandle handle)
{
return StringStream.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") &&
StringStream.EqualsRaw(TypeRefTable.GetName(handle), "Attribute");
}
private bool IsSystemEnum(TypeReferenceHandle handle)
{
return StringStream.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") &&
StringStream.EqualsRaw(TypeRefTable.GetName(handle), "Enum");
}
private bool NeedsWinRTPrefix(TypeAttributes flags, EntityHandle extends)
{
if ((flags & (TypeAttributes.VisibilityMask | TypeAttributes.Interface)) != TypeAttributes.Public)
{
return false;
}
if (extends.Kind != HandleKind.TypeReference)
{
return false;
}
// Check if the type is a delegate, struct, or attribute
TypeReferenceHandle extendsRefHandle = (TypeReferenceHandle)extends;
if (StringStream.EqualsRaw(TypeRefTable.GetNamespace(extendsRefHandle), "System"))
{
StringHandle nameHandle = TypeRefTable.GetName(extendsRefHandle);
if (StringStream.EqualsRaw(nameHandle, "MulticastDelegate")
|| StringStream.EqualsRaw(nameHandle, "ValueType")
|| StringStream.EqualsRaw(nameHandle, "Attribute"))
{
return false;
}
}
return true;
}
#endregion
#region MethodDef
private uint CalculateMethodDefTreatmentAndRowId(MethodDefinitionHandle methodDef)
{
MethodDefTreatment treatment = MethodDefTreatment.Implementation;
TypeDefinitionHandle parentTypeDef = GetDeclaringType(methodDef);
TypeAttributes parentFlags = TypeDefTable.GetFlags(parentTypeDef);
if ((parentFlags & TypeAttributes.WindowsRuntime) != 0)
{
if (IsClrImplementationType(parentTypeDef))
{
treatment = MethodDefTreatment.Implementation;
}
else if (parentFlags.IsNested())
{
treatment = MethodDefTreatment.Implementation;
}
else if ((parentFlags & TypeAttributes.Interface) != 0)
{
treatment = MethodDefTreatment.InterfaceMethod;
}
else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && (parentFlags & TypeAttributes.Public) == 0)
{
treatment = MethodDefTreatment.Implementation;
}
else
{
treatment = MethodDefTreatment.Other;
var parentBaseType = TypeDefTable.GetExtends(parentTypeDef);
if (parentBaseType.Kind == HandleKind.TypeReference)
{
switch (GetSpecialTypeRefTreatment((TypeReferenceHandle)parentBaseType))
{
case TypeRefTreatment.SystemAttribute:
treatment = MethodDefTreatment.AttributeMethod;
break;
case TypeRefTreatment.SystemDelegate:
treatment = MethodDefTreatment.DelegateMethod | MethodDefTreatment.MarkPublicFlag;
break;
}
}
}
}
if (treatment == MethodDefTreatment.Other)
{
// we want to hide the method if it implements
// only redirected interfaces
// We also want to check if the methodImpl is IClosable.Close,
// so we can change the name
bool seenRedirectedInterfaces = false;
bool seenNonRedirectedInterfaces = false;
bool isIClosableClose = false;
foreach (var methodImplHandle in new MethodImplementationHandleCollection(this, parentTypeDef))
{
MethodImplementation methodImpl = GetMethodImplementation(methodImplHandle);
if (methodImpl.MethodBody == methodDef)
{
EntityHandle declaration = methodImpl.MethodDeclaration;
// See if this MethodImpl implements a redirected interface
// In WinMD, MethodImpl will always use MemberRef and TypeRefs to refer to redirected interfaces,
// even if they are in the same module.
if (declaration.Kind == HandleKind.MemberReference &&
ImplementsRedirectedInterface((MemberReferenceHandle)declaration, out isIClosableClose))
{
seenRedirectedInterfaces = true;
if (isIClosableClose)
{
// This method implements IClosable.Close
// Let's rename to IDisposable later
// Once we know this implements IClosable.Close, we are done
// looking
break;
}
}
else
{
// Now we know this implements a non-redirected interface
// But we need to keep looking, just in case we got a methodimpl that
// implements the IClosable.Close method and needs to be renamed
seenNonRedirectedInterfaces = true;
}
}
}
if (isIClosableClose)
{
treatment = MethodDefTreatment.DisposeMethod;
}
else if (seenRedirectedInterfaces && !seenNonRedirectedInterfaces)
{
// Only hide if all the interfaces implemented are redirected
treatment = MethodDefTreatment.HiddenInterfaceImplementation;
}
}
// If treatment is other, then this is a non-managed WinRT runtime class definition
// Find out about various bits that we apply via attributes and name parsing
if (treatment == MethodDefTreatment.Other)
{
treatment |= GetMethodTreatmentFromCustomAttributes(methodDef);
}
return TreatmentAndRowId((byte)treatment, methodDef.RowId);
}
private MethodDefTreatment GetMethodTreatmentFromCustomAttributes(MethodDefinitionHandle methodDef)
{
MethodDefTreatment treatment = 0;
foreach (var caHandle in GetCustomAttributes(methodDef))
{
StringHandle namespaceHandle, nameHandle;
if (!GetAttributeTypeNameRaw(caHandle, out namespaceHandle, out nameHandle))
{
continue;
}
Debug.Assert(!namespaceHandle.IsVirtual && !nameHandle.IsVirtual);
if (StringStream.EqualsRaw(namespaceHandle, "Windows.UI.Xaml"))
{
if (StringStream.EqualsRaw(nameHandle, "TreatAsPublicMethodAttribute"))
{
treatment |= MethodDefTreatment.MarkPublicFlag;
}
if (StringStream.EqualsRaw(nameHandle, "TreatAsAbstractMethodAttribute"))
{
treatment |= MethodDefTreatment.MarkAbstractFlag;
}
}
}
return treatment;
}
#endregion
#region FieldDef
/// <summary>
/// The backing field of a WinRT enumeration type is not public although the backing fields
/// of managed enumerations are. To allow managed languages to directly access this field,
/// it is made public by the metadata adapter.
/// </summary>
private uint CalculateFieldDefTreatmentAndRowId(FieldDefinitionHandle handle)
{
var flags = FieldTable.GetFlags(handle);
FieldDefTreatment treatment = FieldDefTreatment.None;
if ((flags & FieldAttributes.RTSpecialName) != 0 && StringStream.EqualsRaw(FieldTable.GetName(handle), "value__"))
{
TypeDefinitionHandle typeDef = GetDeclaringType(handle);
EntityHandle baseTypeHandle = TypeDefTable.GetExtends(typeDef);
if (baseTypeHandle.Kind == HandleKind.TypeReference)
{
var typeRef = (TypeReferenceHandle)baseTypeHandle;
if (StringStream.EqualsRaw(TypeRefTable.GetName(typeRef), "Enum") &&
StringStream.EqualsRaw(TypeRefTable.GetNamespace(typeRef), "System"))
{
treatment = FieldDefTreatment.EnumValue;
}
}
}
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
#endregion
#region MemberRef
private uint CalculateMemberRefTreatmentAndRowId(MemberReferenceHandle handle)
{
MemberRefTreatment treatment;
// We need to rename the MemberRef for IClosable.Close as well
// so that the MethodImpl for the Dispose method can be correctly shown
// as IDisposable.Dispose instead of IDisposable.Close
bool isIDisposable;
if (ImplementsRedirectedInterface(handle, out isIDisposable) && isIDisposable)
{
treatment = MemberRefTreatment.Dispose;
}
else
{
treatment = MemberRefTreatment.None;
}
return TreatmentAndRowId((byte)treatment, handle.RowId);
}
/// <summary>
/// We want to know if a given method implements a redirected interface.
/// For example, if we are given the method RemoveAt on a class "A"
/// which implements the IVector interface (which is redirected
/// to IList in .NET) then this method would return true. The most
/// likely reason why we would want to know this is that we wish to hide
/// (mark private) all methods which implement methods on a redirected
/// interface.
/// </summary>
/// <param name="memberRef">The declaration token for the method</param>
/// <param name="isIDisposable">
/// Returns true if the redirected interface is <see cref="IDisposable"/>.
/// </param>
/// <returns>True if the method implements a method on a redirected interface.
/// False otherwise.</returns>
private bool ImplementsRedirectedInterface(MemberReferenceHandle memberRef, out bool isIDisposable)
{
isIDisposable = false;
EntityHandle parent = MemberRefTable.GetClass(memberRef);
TypeReferenceHandle typeRef;
if (parent.Kind == HandleKind.TypeReference)
{
typeRef = (TypeReferenceHandle)parent;
}
else if (parent.Kind == HandleKind.TypeSpecification)
{
BlobHandle blob = TypeSpecTable.GetSignature((TypeSpecificationHandle)parent);
BlobReader sig = new BlobReader(BlobStream.GetMemoryBlock(blob));
if (sig.Length < 2 ||
sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_GENERICINST ||
sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_CLASS)
{
return false;
}
EntityHandle token = sig.ReadTypeHandle();
if (token.Kind != HandleKind.TypeReference)
{
return false;
}
typeRef = (TypeReferenceHandle)token;
}
else
{
return false;
}
return GetProjectionIndexForTypeReference(typeRef, out isIDisposable) >= 0;
}
#endregion
#region AssemblyRef
private int FindMscorlibAssemblyRefNoProjection()
{
for (int i = 1; i <= AssemblyRefTable.NumberOfNonVirtualRows; i++)
{
if (StringStream.EqualsRaw(AssemblyRefTable.GetName(i), "mscorlib"))
{
return i;
}
}
throw new BadImageFormatException(SR.WinMDMissingMscorlibRef);
}
#endregion
#region CustomAttribute
internal CustomAttributeValueTreatment CalculateCustomAttributeValueTreatment(CustomAttributeHandle handle)
{
Debug.Assert(_metadataKind != MetadataKind.Ecma335);
var parent = CustomAttributeTable.GetParent(handle);
// Check for Windows.Foundation.Metadata.AttributeUsageAttribute.
// WinMD rules:
// - The attribute is only applicable on TypeDefs.
// - Constructor must be a MemberRef with TypeRef.
if (!IsWindowsAttributeUsageAttribute(parent, handle))
{
return CustomAttributeValueTreatment.None;
}
var targetTypeDef = (TypeDefinitionHandle)parent;
if (StringStream.EqualsRaw(TypeDefTable.GetNamespace(targetTypeDef), "Windows.Foundation.Metadata"))
{
if (StringStream.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "VersionAttribute"))
{
return CustomAttributeValueTreatment.AttributeUsageVersionAttribute;
}
if (StringStream.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "DeprecatedAttribute"))
{
return CustomAttributeValueTreatment.AttributeUsageDeprecatedAttribute;
}
}
bool allowMultiple = HasAttribute(targetTypeDef, "Windows.Foundation.Metadata", "AllowMultipleAttribute");
return allowMultiple ? CustomAttributeValueTreatment.AttributeUsageAllowMultiple : CustomAttributeValueTreatment.AttributeUsageAllowSingle;
}
private bool IsWindowsAttributeUsageAttribute(EntityHandle targetType, CustomAttributeHandle attributeHandle)
{
// Check for Windows.Foundation.Metadata.AttributeUsageAttribute.
// WinMD rules:
// - The attribute is only applicable on TypeDefs.
// - Constructor must be a MemberRef with TypeRef.
if (targetType.Kind != HandleKind.TypeDefinition)
{
return false;
}
var attributeCtor = CustomAttributeTable.GetConstructor(attributeHandle);
if (attributeCtor.Kind != HandleKind.MemberReference)
{
return false;
}
var attributeType = MemberRefTable.GetClass((MemberReferenceHandle)attributeCtor);
if (attributeType.Kind != HandleKind.TypeReference)
{
return false;
}
var attributeTypeRef = (TypeReferenceHandle)attributeType;
return StringStream.EqualsRaw(TypeRefTable.GetName(attributeTypeRef), "AttributeUsageAttribute") &&
StringStream.EqualsRaw(TypeRefTable.GetNamespace(attributeTypeRef), "Windows.Foundation.Metadata");
}
private bool HasAttribute(EntityHandle token, string asciiNamespaceName, string asciiTypeName)
{
foreach (var caHandle in GetCustomAttributes(token))
{
StringHandle namespaceName, typeName;
if (GetAttributeTypeNameRaw(caHandle, out namespaceName, out typeName) &&
StringStream.EqualsRaw(typeName, asciiTypeName) &&
StringStream.EqualsRaw(namespaceName, asciiNamespaceName))
{
return true;
}
}
return false;
}
private bool GetAttributeTypeNameRaw(CustomAttributeHandle caHandle, out StringHandle namespaceName, out StringHandle typeName)
{
namespaceName = typeName = default(StringHandle);
EntityHandle typeDefOrRef = GetAttributeTypeRaw(caHandle);
if (typeDefOrRef.IsNil)
{
return false;
}
if (typeDefOrRef.Kind == HandleKind.TypeReference)
{
TypeReferenceHandle typeRef = (TypeReferenceHandle)typeDefOrRef;
var resolutionScope = TypeRefTable.GetResolutionScope(typeRef);
if (!resolutionScope.IsNil && resolutionScope.Kind == HandleKind.TypeReference)
{
// we don't need to handle nested types
return false;
}
// other resolution scopes don't affect full name
typeName = TypeRefTable.GetName(typeRef);
namespaceName = TypeRefTable.GetNamespace(typeRef);
}
else if (typeDefOrRef.Kind == HandleKind.TypeDefinition)
{
TypeDefinitionHandle typeDef = (TypeDefinitionHandle)typeDefOrRef;
if (TypeDefTable.GetFlags(typeDef).IsNested())
{
// we don't need to handle nested types
return false;
}
typeName = TypeDefTable.GetName(typeDef);
namespaceName = TypeDefTable.GetNamespace(typeDef);
}
else
{
// invalid metadata
return false;
}
return true;
}
/// <summary>
/// Returns the type definition or reference handle of the attribute type.
/// </summary>
/// <returns><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/> or nil token if the metadata is invalid and the type can't be determined.</returns>
private EntityHandle GetAttributeTypeRaw(CustomAttributeHandle handle)
{
var ctor = CustomAttributeTable.GetConstructor(handle);
if (ctor.Kind == HandleKind.MethodDefinition)
{
return GetDeclaringType((MethodDefinitionHandle)ctor);
}
if (ctor.Kind == HandleKind.MemberReference)
{
// In general the parent can be MethodDef, ModuleRef, TypeDef, TypeRef, or TypeSpec.
// For attributes only TypeDef and TypeRef are applicable.
EntityHandle typeDefOrRef = MemberRefTable.GetClass((MemberReferenceHandle)ctor);
HandleKind handleType = typeDefOrRef.Kind;
if (handleType == HandleKind.TypeReference || handleType == HandleKind.TypeDefinition)
{
return typeDefOrRef;
}
}
return default(EntityHandle);
}
#endregion
}
}
| |
/*
Copyright 2014 David Bordoley
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace SQLitePCL.pretty
{
internal class WriteLockedRef<T>
{
private readonly object gate = new object();
private T value;
public WriteLockedRef(T defaultValue)
{
this.value = defaultValue;
}
public T Value
{
get { return value; }
set
{
lock (gate)
{
this.value = value;
}
}
}
}
/// <summary>
/// Extensions methods for <see cref="IAsyncDatabaseConnection"/>.
/// </summary>
public static class AsyncDatabaseConnection
{
/// <summary>
/// Builds an IAsyncDatabaseConnection using the specified scheduler.
/// </summary>
/// <returns>An IAsyncDatabaseConnection using the specified scheduler.</returns>
/// <param name="This">A SQLiteDatabaseConnectionBuilder instance.</param>
/// <param name="scheduler">An RX scheduler</param>
public static IAsyncDatabaseConnection BuildAsyncDatabaseConnection(
this SQLiteDatabaseConnectionBuilder This,
IScheduler scheduler)
{
Contract.Requires(This != null);
Contract.Requires(scheduler != null);
var progressHandlerResult = new WriteLockedRef<bool>(false);
var db = This.With(progressHandler: () => progressHandlerResult.Value).Build();
return new AsyncDatabaseConnectionImpl(db, scheduler, progressHandlerResult);
}
/// <summary>
/// Builds an IAsyncDatabaseConnection using the default TaskPool scheduler.
/// </summary>
/// <returns>An IAsyncDatabaseConnection using the default TaskPool scheduler.</returns>
/// <param name="This">A SQLiteDatabaseConnectionBuilder instance.</param>
public static IAsyncDatabaseConnection BuildAsyncDatabaseConnection(this SQLiteDatabaseConnectionBuilder This) =>
This.BuildAsyncDatabaseConnection(TaskPoolScheduler.Default);
/// <summary>
/// Compiles and executes multiple SQL statements.
/// </summary>
/// <param name="This">An asynchronous database connection.</param>
/// <param name="sql">One or more semicolon delimited SQL statements.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <returns>A task that completes when all statements have been executed.</returns>
public static Task ExecuteAllAsync(
this IAsyncDatabaseConnection This,
string sql,
CancellationToken cancellationToken)
{
Contract.Requires(sql != null);
return This.Use((conn, ct) => conn.ExecuteAll(sql), cancellationToken);
}
/// <summary>
/// Compiles and executes multiple SQL statements.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="sql">One or more semicolon delimited SQL statements.</param>
/// <returns>A task that completes when all statements have been executed.</returns>
public static Task ExecuteAllAsync(this IAsyncDatabaseConnection This, string sql) =>
This.ExecuteAllAsync(sql, CancellationToken.None);
/// <summary>
/// Compiles and executes a SQL statement with the provided bind parameter values.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="sql">The SQL statement to compile and execute.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <param name="values">The bind parameter values.</param>
/// <returns>A task that completes when the statement has been executed.</returns>
public static Task ExecuteAsync(
this IAsyncDatabaseConnection This,
string sql,
CancellationToken cancellationToken,
params object[] values)
{
Contract.Requires(sql != null);
Contract.Requires(values != null);
return This.Use((conn, ct) => conn.Execute(sql, values), cancellationToken);
}
/// <summary>
/// Compiles and executes a SQL statement with the provided bind parameter values.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="sql">The SQL statement to compile and execute.</param>
/// <param name="values">The bind parameter values.</param>
/// <returns>A task that completes when the statement has been executed.</returns>
public static Task ExecuteAsync(this IAsyncDatabaseConnection This, string sql, params object[] values) =>
This.ExecuteAsync(sql, CancellationToken.None, values);
/// <summary>
/// Compiles and executes a SQL statement.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="sql">The SQL statement to compile and execute.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <returns>A task that completes when the statement has been executed.</returns>
public static Task ExecuteAsync(
this IAsyncDatabaseConnection This,
string sql,
CancellationToken cancellationToken)
{
Contract.Requires(sql != null);
return This.Use((conn, ct) => conn.Execute(sql), cancellationToken);
}
/// <summary>
/// Compiles and executes a SQL statement.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="sql">The SQL statement to compile and execute.</param>
/// <returns>A task that completes when the statement has been executed.</returns>
public static Task ExecuteAsync(this IAsyncDatabaseConnection This, string sql) =>
This.ExecuteAsync(sql, CancellationToken.None);
/// <summary>
/// Opens the blob located by the a database, table, column, and rowid for incremental asynchronous I/O as a <see cref="System.IO.Stream"/>.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="database">The database containing the blob.</param>
/// <param name="tableName">The table containing the blob.</param>
/// <param name="columnName">The column containing the blob.</param>
/// <param name="rowId">The row containing the blob.</param>
/// <param name="canWrite">
/// <see langwords="true"/> if the Stream should be open for both read and write operations.
/// <see langwords="false"/> if the Stream should be open oly for read operations.
/// </param>
/// <returns>A <see cref="Task"/> that completes with a <see cref="System.IO.Stream"/> that can be used to asynchronously write and read to and from blob.</returns>
public static Task<Stream> OpenBlobAsync(
this IAsyncDatabaseConnection This,
string database,
string tableName,
string columnName,
long rowId,
bool canWrite = false) =>
This.OpenBlobAsync(database, tableName, columnName, rowId, canWrite, CancellationToken.None);
/// <summary>
/// Opens the blob located by the a database, table, column, and rowid for incremental asynchronous I/O as a <see cref="System.IO.Stream"/>.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="database">The database containing the blob.</param>
/// <param name="tableName">The table containing the blob.</param>
/// <param name="columnName">The column containing the blob.</param>
/// <param name="rowId">The row containing the blob.</param>
/// <param name="canWrite">
/// <see langwords="true"/> if the Stream should be open for both read and write operations.
/// <see langwords="false"/> if the Stream should be open oly for read operations.
/// </param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <returns>A <see cref="Task"/> that completes with a <see cref="System.IO.Stream"/> that can be used to asynchronously write and read to and from blob.</returns>
public static Task<Stream> OpenBlobAsync(
this IAsyncDatabaseConnection This,
string database,
string tableName,
string columnName,
long rowId,
bool canWrite,
CancellationToken cancellationToken)
{
Contract.Requires(database != null);
Contract.Requires(tableName != null);
Contract.Requires(columnName != null);
return This.Use<Stream>((db, ct) =>
{
var blob = db.OpenBlob(database, tableName, columnName, rowId, canWrite);
return new AsyncBlobStream(blob, This);
}, cancellationToken);
}
/// <summary>
/// Opens the blob located by the a database, table, column, and rowid for incremental asynchronous I/O as a <see cref="System.IO.Stream"/>.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="columnInfo">The ColumnInfo of the blob value.</param>
/// <param name="rowId">The row containing the blob.</param>
/// <param name="canWrite">
/// <see langwords="true"/> if the Stream should be open for both read and write operations.
/// <see langwords="false"/> if the Stream should be open oly for read operations.
/// </param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <returns>A <see cref="Task"/> that completes with a <see cref="System.IO.Stream"/> that can be used to asynchronously write and read to and from blob.</returns>
public static Task<Stream> OpenBlobAsync(
this IAsyncDatabaseConnection This,
ColumnInfo columnInfo,
long rowId,
bool canWrite,
CancellationToken cancellationToken)
{
Contract.Requires(columnInfo != null);
return This.OpenBlobAsync(columnInfo.DatabaseName, columnInfo.TableName, columnInfo.OriginName, rowId, canWrite, cancellationToken);
}
/// <summary>
/// Opens the blob located by the a database, table, column, and rowid for incremental asynchronous I/O as a <see cref="System.IO.Stream"/>.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="columnInfo">The ColumnInfo of the blob value.</param>
/// <param name="rowId">The row containing the blob.</param>
/// <param name="canWrite">
/// <see langwords="true"/> if the Stream should be open for both read and write operations.
/// <see langwords="false"/> if the Stream should be open oly for read operations.
/// </param>
/// <returns>A <see cref="Task"/> that completes with a <see cref="System.IO.Stream"/> that can be used to asynchronously write and read to and from blob.</returns>
public static Task<Stream> OpenBlobAsync(
this IAsyncDatabaseConnection This,
ColumnInfo columnInfo,
long rowId,
bool canWrite = false) =>
This.OpenBlobAsync(columnInfo, rowId, canWrite, CancellationToken.None);
/// <summary>
/// Compiles one or more SQL statements.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="sql">One or more semicolon delimited SQL statements.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <returns>A <see cref="Task"/> that completes with a <see cref="IReadOnlyList<T>"/>
/// of the compiled <see cref="IAsyncStatement"/>instances.</returns>
public static Task<IReadOnlyList<IAsyncStatement>> PrepareAllAsync(
this IAsyncDatabaseConnection This,
string sql,
CancellationToken cancellationToken)
{
Contract.Requires(sql != null);
return This.Use<IReadOnlyList<IAsyncStatement>>((conn, ct) =>
{
// Eagerly prepare all the statements. The synchronous version of PrepareAll()
// is lazy, preparing each statement when MoveNext() is called on the Enumerator.
// Hence an implementation like:
//
// return conn.PrepareAll(sql).Select(stmt => new AsyncStatementImpl(stmt, This));
//
// would result in unintentional database access not on the operations queue.
// Added bonus of being eager: Callers can retrieve individual statements via
// the index in the list.
return conn.PrepareAll(sql).Select(stmt => new AsyncStatementImpl(stmt, This)).ToList();
}, cancellationToken);
}
/// <summary>
/// Compiles one or more SQL statements.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="sql">One or more semicolon delimited SQL statements.</param>
/// <returns>A <see cref="Task"/> that completes with a <see cref="IReadOnlyList<T>"/>
/// of the compiled <see cref="IAsyncStatement"/>instances.</returns>
public static Task<IReadOnlyList<IAsyncStatement>> PrepareAllAsync(this IAsyncDatabaseConnection This, string sql) =>
This.PrepareAllAsync(sql, CancellationToken.None);
/// <summary>
/// Compiles a SQL statement.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="sql">The SQL statement to compile.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <returns>Task that completes with a <see cref="IAsyncStatement"/> that
/// can be used to query the result set asynchronously.</returns>
public static Task<IAsyncStatement> PrepareStatementAsync(
this IAsyncDatabaseConnection This,
string sql,
CancellationToken cancellationToken)
{
Contract.Requires(sql != null);
return This.Use<IAsyncStatement>((conn, ct) =>
{
var stmt = conn.PrepareStatement(sql);
return new AsyncStatementImpl(stmt, This);
}, cancellationToken);
}
/// <summary>
/// Compiles a SQL statement.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="sql">The SQL statement to compile.</param>
/// <returns>Task that completes with a <see cref="IAsyncStatement"/> that
/// can be used to query the result set asynchronously.</returns>
public static Task<IAsyncStatement> PrepareStatementAsync(this IAsyncDatabaseConnection This, string sql) =>
This.PrepareStatementAsync(sql, CancellationToken.None);
/// <summary>
/// Returns a cold observable that compiles a SQL statement with
/// provided bind parameter values, that publishes the rows in the result
/// set for each subscription.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="sql">The SQL statement to compile and Query.</param>
/// <param name="values">The bind parameter values.</param>
/// <returns>A cold observable of rows in the result set.</returns>
public static IObservable<IReadOnlyList<IResultSetValue>> Query(
this IAsyncDatabaseConnection This,
string sql,
params object[] values)
{
Contract.Requires(This != null);
Contract.Requires(sql != null);
Contract.Requires(values != null);
return This.Use((conn, ct) => conn.Query(sql, values));
}
/// <summary>
/// Returns a cold observable that compiles a SQL statement
/// that publishes the rows in the result set for each subscription.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="sql">The SQL statement to compile and Query.</param>
/// <returns>A cold observable of rows in the result set.</returns>
public static IObservable<IReadOnlyList<IResultSetValue>> Query(
this IAsyncDatabaseConnection This,
string sql)
{
Contract.Requires(sql != null);
return This.Use(conn => conn.Query(sql));
}
/// <summary>
/// Schedules the <see cref="Action"/> <paramref name="f"/> on the database operations queue.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="f">The action.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <returns>A task that completes when <paramref name="f"/> returns.</returns>
public static Task Use(
this IAsyncDatabaseConnection This,
Action<IDatabaseConnection, CancellationToken> f,
CancellationToken cancellationToken)
{
Contract.Requires(f != null);
return This.Use((conn, ct) =>
{
f(conn, ct);
return Enumerable.Empty<Unit>();
}, cancellationToken);
}
/// <summary>
/// Schedules the <see cref="Action"/> <paramref name="f"/> on the database operations queue.
/// </summary>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="f">The action.</param>
/// <returns>A task that completes when <paramref name="f"/> returns.</returns>
public static Task Use(this IAsyncDatabaseConnection This, Action<IDatabaseConnection> f)
{
Contract.Requires(f != null);
return This.Use((db, ct) => f(db), CancellationToken.None);
}
/// <summary>
/// Schedules the <see cref="Func<T,TResult>"/> <paramref name="f"/> on the database operations queue.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="f">A function from <see cref="IDatabaseConnection"/> to <typeparamref name="T"/>.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <returns>A task that completes with the result of <paramref name="f"/>.</returns>
public static Task<T> Use<T>(
this IAsyncDatabaseConnection This,
Func<IDatabaseConnection, CancellationToken, T> f,
CancellationToken cancellationToken)
{
Contract.Requires(This != null);
Contract.Requires(f != null);
return This.Use((conn, ct) => new[] { f(conn, ct) }).ToTask(cancellationToken);
}
/// <summary>
/// Schedules the <see cref="Func<T,TResult>"/> <paramref name="f"/> on the database operations queue.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="f">A function from <see cref="IDatabaseConnection"/> to <typeparamref name="T"/>.</param>
/// <returns>A task that completes with the result of <paramref name="f"/>.</returns>
public static Task<T> Use<T>(this IAsyncDatabaseConnection This, Func<IDatabaseConnection,T> f)
{
Contract.Requires(f != null);
return This.Use((db, ct) => f(db), CancellationToken.None);
}
/// <summary>
/// Returns a cold IObservable which schedules the function f on the database operation queue each
/// time it is is subscribed to. The published values are generated by enumerating the IEnumerable returned by f.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="This">The asynchronous database connection.</param>
/// <param name="f">
/// A function that may synchronously use the provided IDatabaseConnection and returns
/// an IEnumerable of produced values that are published to the subscribed IObserver.
/// The returned IEnumerable may block. This allows the IEnumerable to provide the results of
/// enumerating a SQLite prepared statement for instance.
/// </param>
/// <returns>A cold observable of the values produced by the function f.</returns>
public static IObservable<T> Use<T>(this IAsyncDatabaseConnection This, Func<IDatabaseConnection, IEnumerable<T>> f)
{
Contract.Requires(f != null);
return This.Use((conn, ct) => f(conn));
}
}
internal sealed class AsyncDatabaseConnectionImpl : IAsyncDatabaseConnection
{
private readonly OperationsQueue queue = new OperationsQueue();
private readonly IScheduler scheduler;
private readonly SQLiteDatabaseConnection conn;
private readonly WriteLockedRef<bool> progressHandlerResult;
private bool disposed = false;
internal AsyncDatabaseConnectionImpl(SQLiteDatabaseConnection conn, IScheduler scheduler, WriteLockedRef<bool> progressHandlerResult)
{
this.conn = conn;
this.scheduler = scheduler;
this.progressHandlerResult = progressHandlerResult;
this.Trace = Observable.FromEventPattern<DatabaseTraceEventArgs>(conn, "Trace").Select(e => e.EventArgs);
this.Profile = Observable.FromEventPattern<DatabaseProfileEventArgs>(conn, "Profile").Select(e => e.EventArgs);
this.Update = Observable.FromEventPattern<DatabaseUpdateEventArgs>(conn, "Update").Select(e => e.EventArgs);
}
public IObservable<DatabaseTraceEventArgs> Trace { get; }
public IObservable<DatabaseProfileEventArgs> Profile { get; }
public IObservable<DatabaseUpdateEventArgs> Update { get; }
public async Task DisposeAsync()
{
if (disposed)
{
return;
}
this.disposed = true;
await this.queue.DisposeAsync();
// FIXME: This is a little broken. We really should track open Async
// AsyncStatementImpl's and AsyncBlobStream's and dispose them here first.
// Othewise those objects won't have their state correctly set to disposed,
// leading to some user errors.
// Two possible solutions:
// * Track the open AsyncStatementImpl's and AsyncBlobStream's
// * Add a disposing event, and listen to it from AsyncStatementImpl's and AsyncBlobStream's.
this.conn.Dispose();
}
// Yes async void is evil and ugly. This is essentially a compromise decision to avoid
// common deadlock pitfalls. For instance, if Dispose was implemented as
//
// public void Dispose()
// {
// this.DisposeAsync().Wait();
// }
//
// then this trivial example would deadlock when run on the task pool:
//
// using (var db = SQLite3.OpenInMemoryDb().AsAsyncDatabaseConnection())
// {
// await db.Use(_ => { });
// }
//
// In this case, the task pool immediately schedules the call to Dispose() after the
// Action completes on the same thread. This results in deadlock as the call to Dispose()
// is waiting for the queue to indicate its empty, but the current running item on the
// queue never completes since its blocked by the Dispose() call.
//
// A fix for this is available in .NET 4.5.3, which provides TaskCreationOptions.RunContinuationsAsynchronously
// Unfortunately this is not, and will not for the forseable future be available in the PCL profile.
// Also the RX implementation of ToTask() does not accept TaskCreationOptions but that could
// be worked around with a custom implementation.
//
// Another fix considered but abandoned was to provide variant of Use() accepting an
// IScheduler that can be used to ObserveOn(). However this would essentially double the
// number of static methods in this class, and would only in practice be
// useful in unit tests, as most client code will typically call these async
// methods from an event loop, which doesn't suffer from this bug.
public async void Dispose()
{
await this.DisposeAsync();
}
public IObservable<T> Use<T>(Func<IDatabaseConnection, CancellationToken, IEnumerable<T>> f)
{
Contract.Requires(f != null);
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return Observable.Create((IObserver<T> observer, CancellationToken cancellationToken) =>
{
// Prevent calls to subscribe after the connection is disposed
if (this.disposed)
{
observer.OnError(new ObjectDisposedException(this.GetType().FullName));
return Task.FromResult(Unit.Default);
}
return queue.EnqueueOperation(ct =>
{
this.progressHandlerResult.Value = false;
var ctSubscription = ct.Register(() => this.progressHandlerResult.Value = true);
try
{
ct.ThrowIfCancellationRequested();
// Note: Diposing the connection wrapper doesn't dispose the underlying connection
// The intent here is to prevent access to the underlying connection outside of the
// function call.
using (var db = new DelegatingDatabaseConnection(this.conn))
{
foreach (var e in f(db, ct))
{
observer.OnNext(e);
ct.ThrowIfCancellationRequested();
}
observer.OnCompleted();
}
}
finally
{
ctSubscription.Dispose();
this.progressHandlerResult.Value = false;
}
}, scheduler, cancellationToken);
});
}
}
}
| |
// 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.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
namespace System.Data.Common
{
internal static partial class ADP
{
// NOTE: Initializing a Task in SQL CLR requires the "UNSAFE" permission set (https://docs.microsoft.com/en-us/dotnet/framework/performance/sql-server-programming-and-host-protection-attributes)
// Therefore we are lazily initializing these Tasks to avoid forcing customers to use the "UNSAFE" set when they are actually using no Async features
private static Task<bool> _trueTask;
internal static Task<bool> TrueTask => _trueTask ?? (_trueTask = Task.FromResult(true));
private static Task<bool> _falseTask;
internal static Task<bool> FalseTask => _falseTask ?? (_falseTask = Task.FromResult(false));
internal const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout;
static partial void TraceException(string trace, Exception e);
internal static void TraceExceptionAsReturnValue(Exception e)
{
TraceException("<comm.ADP.TraceException|ERR|THROW> '{0}'", e);
}
internal static void TraceExceptionWithoutRethrow(Exception e)
{
Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e);
}
internal static ArgumentException Argument(string error)
{
ArgumentException e = new ArgumentException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException Argument(string error, Exception inner)
{
ArgumentException e = new ArgumentException(error, inner);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException Argument(string error, string parameter)
{
ArgumentException e = new ArgumentException(error, parameter);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentNullException ArgumentNull(string parameter)
{
ArgumentNullException e = new ArgumentNullException(parameter);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentNullException ArgumentNull(string parameter, string error)
{
ArgumentNullException e = new ArgumentNullException(parameter, error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName)
{
ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName)
{
ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message);
TraceExceptionAsReturnValue(e);
return e;
}
internal static IndexOutOfRangeException IndexOutOfRange(string error)
{
IndexOutOfRangeException e = new IndexOutOfRangeException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static InvalidCastException InvalidCast(string error)
{
return InvalidCast(error, null);
}
internal static InvalidCastException InvalidCast(string error, Exception inner)
{
InvalidCastException e = new InvalidCastException(error, inner);
TraceExceptionAsReturnValue(e);
return e;
}
internal static InvalidOperationException InvalidOperation(string error)
{
InvalidOperationException e = new InvalidOperationException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static NotSupportedException NotSupported()
{
NotSupportedException e = new NotSupportedException();
TraceExceptionAsReturnValue(e);
return e;
}
internal static NotSupportedException NotSupported(string error)
{
NotSupportedException e = new NotSupportedException(error);
TraceExceptionAsReturnValue(e);
return e;
}
// the return value is true if the string was quoted and false if it was not
// this allows the caller to determine if it is an error or not for the quotedString to not be quoted
internal static bool RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString)
{
int prefixLength = quotePrefix != null ? quotePrefix.Length : 0;
int suffixLength = quoteSuffix != null ? quoteSuffix.Length : 0;
if ((suffixLength + prefixLength) == 0)
{
unquotedString = quotedString;
return true;
}
if (quotedString == null)
{
unquotedString = quotedString;
return false;
}
int quotedStringLength = quotedString.Length;
// is the source string too short to be quoted
if (quotedStringLength < prefixLength + suffixLength)
{
unquotedString = quotedString;
return false;
}
// is the prefix present?
if (prefixLength > 0)
{
if (!quotedString.StartsWith(quotePrefix, StringComparison.Ordinal))
{
unquotedString = quotedString;
return false;
}
}
// is the suffix present?
if (suffixLength > 0)
{
if (!quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal))
{
unquotedString = quotedString;
return false;
}
unquotedString = quotedString.Substring(prefixLength, quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix + quoteSuffix, quoteSuffix);
}
else
{
unquotedString = quotedString.Substring(prefixLength, quotedStringLength - prefixLength);
}
return true;
}
internal static ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, string value, string method)
{
return ArgumentOutOfRange(SR.Format(SR.ADP_NotSupportedEnumerationValue, type.Name, value, method), type.Name);
}
internal static InvalidOperationException DataAdapter(string error)
{
return InvalidOperation(error);
}
private static InvalidOperationException Provider(string error)
{
return InvalidOperation(error);
}
internal static ArgumentException InvalidMultipartName(string property, string value)
{
ArgumentException e = new ArgumentException(SR.Format(SR.ADP_InvalidMultipartName, property, value));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value)
{
ArgumentException e = new ArgumentException(SR.Format(SR.ADP_InvalidMultipartNameQuoteUsage, property, value));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit)
{
ArgumentException e = new ArgumentException(SR.Format(SR.ADP_InvalidMultipartNameToManyParts, property, value, limit));
TraceExceptionAsReturnValue(e);
return e;
}
internal static void CheckArgumentNull(object value, string parameterName)
{
if (null == value)
{
throw ArgumentNull(parameterName);
}
}
// only StackOverflowException & ThreadAbortException are sealed classes
private static readonly Type s_stackOverflowType = typeof(StackOverflowException);
private static readonly Type s_outOfMemoryType = typeof(OutOfMemoryException);
private static readonly Type s_threadAbortType = typeof(ThreadAbortException);
private static readonly Type s_nullReferenceType = typeof(NullReferenceException);
private static readonly Type s_accessViolationType = typeof(AccessViolationException);
private static readonly Type s_securityType = typeof(SecurityException);
internal static bool IsCatchableExceptionType(Exception e)
{
// a 'catchable' exception is defined by what it is not.
Debug.Assert(e != null, "Unexpected null exception!");
Type type = e.GetType();
return ((type != s_stackOverflowType) &&
(type != s_outOfMemoryType) &&
(type != s_threadAbortType) &&
(type != s_nullReferenceType) &&
(type != s_accessViolationType) &&
!s_securityType.IsAssignableFrom(type));
}
internal static bool IsCatchableOrSecurityExceptionType(Exception e)
{
// a 'catchable' exception is defined by what it is not.
// since IsCatchableExceptionType defined SecurityException as not 'catchable'
// this method will return true for SecurityException has being catchable.
// the other way to write this method is, but then SecurityException is checked twice
// return ((e is SecurityException) || IsCatchableExceptionType(e));
Debug.Assert(e != null, "Unexpected null exception!");
Type type = e.GetType();
return ((type != s_stackOverflowType) &&
(type != s_outOfMemoryType) &&
(type != s_threadAbortType) &&
(type != s_nullReferenceType) &&
(type != s_accessViolationType));
}
// Invalid Enumeration
internal static ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value)
{
return ArgumentOutOfRange(SR.Format(SR.ADP_InvalidEnumerationValue, type.Name, value.ToString(CultureInfo.InvariantCulture)), type.Name);
}
//
// DbConnectionOptions, DataAccess
//
internal static ArgumentException ConnectionStringSyntax(int index)
{
return Argument(SR.Format(SR.ADP_ConnectionStringSyntax, index));
}
internal static ArgumentException KeywordNotSupported(string keyword)
{
return Argument(SR.Format(SR.ADP_KeywordNotSupported, keyword));
}
internal static ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException)
{
return ADP.Argument(SR.Format(SR.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException);
}
//
// DbConnectionOptions, DataAccess, SqlClient
//
internal static Exception InvalidConnectionOptionValue(string key)
{
return InvalidConnectionOptionValue(key, null);
}
internal static Exception InvalidConnectionOptionValue(string key, Exception inner)
{
return Argument(SR.Format(SR.ADP_InvalidConnectionOptionValue, key), inner);
}
//
// Generic Data Provider Collection
//
internal static ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection)
{
return Argument(SR.Format(SR.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name));
}
internal static ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType)
{
return ArgumentNull(parameter, SR.Format(SR.ADP_CollectionNullValue, collection.Name, itemType.Name));
}
internal static IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count)
{
return IndexOutOfRange(SR.Format(SR.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture)));
}
internal static IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection)
{
return IndexOutOfRange(SR.Format(SR.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name));
}
internal static InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue)
{
return InvalidCast(SR.Format(SR.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name));
}
//
// DbConnection
//
private static string ConnectionStateMsg(ConnectionState state)
{
switch (state)
{
case (ConnectionState.Closed):
case (ConnectionState.Connecting | ConnectionState.Broken): // treated the same as closed
return SR.ADP_ConnectionStateMsg_Closed;
case (ConnectionState.Connecting):
return SR.ADP_ConnectionStateMsg_Connecting;
case (ConnectionState.Open):
return SR.ADP_ConnectionStateMsg_Open;
case (ConnectionState.Open | ConnectionState.Executing):
return SR.ADP_ConnectionStateMsg_OpenExecuting;
case (ConnectionState.Open | ConnectionState.Fetching):
return SR.ADP_ConnectionStateMsg_OpenFetching;
default:
return SR.Format(SR.ADP_ConnectionStateMsg, state.ToString());
}
}
//
// : Stream
//
internal static Exception StreamClosed([CallerMemberName] string method = "")
{
return InvalidOperation(SR.Format(SR.ADP_StreamClosed, method));
}
internal static string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString)
{
var resultString = new StringBuilder(unQuotedString.Length + quoteSuffix.Length + quoteSuffix.Length);
AppendQuotedString(resultString, quotePrefix, quoteSuffix, unQuotedString);
return resultString.ToString();
}
internal static string AppendQuotedString(StringBuilder buffer, string quotePrefix, string quoteSuffix, string unQuotedString)
{
if (!string.IsNullOrEmpty(quotePrefix))
{
buffer.Append(quotePrefix);
}
// Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar".
if (!string.IsNullOrEmpty(quoteSuffix))
{
int start = buffer.Length;
buffer.Append(unQuotedString);
buffer.Replace(quoteSuffix, quoteSuffix + quoteSuffix, start, unQuotedString.Length);
buffer.Append(quoteSuffix);
}
else
{
buffer.Append(unQuotedString);
}
return buffer.ToString();
}
//
// Generic Data Provider Collection
//
internal static ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection)
{
return Argument(SR.Format(SR.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
}
internal static ArgumentException ParametersIsParent(Type parameterType, ICollection collection)
{
return Argument(SR.Format(SR.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
}
internal enum InternalErrorCode
{
UnpooledObjectHasOwner = 0,
UnpooledObjectHasWrongOwner = 1,
PushingObjectSecondTime = 2,
PooledObjectHasOwner = 3,
PooledObjectInPoolMoreThanOnce = 4,
CreateObjectReturnedNull = 5,
NewObjectCannotBePooled = 6,
NonPooledObjectUsedMoreThanOnce = 7,
AttemptingToPoolOnRestrictedToken = 8,
// ConnectionOptionsInUse = 9,
ConvertSidToStringSidWReturnedNull = 10,
// UnexpectedTransactedObject = 11,
AttemptingToConstructReferenceCollectionOnStaticObject = 12,
AttemptingToEnlistTwice = 13,
CreateReferenceCollectionReturnedNull = 14,
PooledObjectWithoutPool = 15,
UnexpectedWaitAnyResult = 16,
SynchronousConnectReturnedPending = 17,
CompletedConnectReturnedPending = 18,
NameValuePairNext = 20,
InvalidParserState1 = 21,
InvalidParserState2 = 22,
InvalidParserState3 = 23,
InvalidBuffer = 30,
UnimplementedSMIMethod = 40,
InvalidSmiCall = 41,
SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50,
SqlDependencyProcessDispatcherFailureCreateInstance = 51,
SqlDependencyProcessDispatcherFailureAppDomain = 52,
SqlDependencyCommandHashIsNotAssociatedWithNotification = 53,
UnknownTransactionFailure = 60,
}
internal static Exception InternalError(InternalErrorCode internalError)
{
return InvalidOperation(SR.Format(SR.ADP_InternalProviderError, (int)internalError));
}
//
// : DbDataReader
//
internal static Exception DataReaderClosed([CallerMemberName] string method = "")
{
return InvalidOperation(SR.Format(SR.ADP_DataReaderClosed, method));
}
internal static ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName)
{
return ArgumentOutOfRange(SR.Format(SR.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
}
internal static ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName)
{
return ArgumentOutOfRange(SR.Format(SR.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
}
internal static IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex)
{
return IndexOutOfRange(SR.Format(SR.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture)));
}
internal static Exception InvalidDataLength(long length)
{
return IndexOutOfRange(SR.Format(SR.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture)));
}
internal static bool CompareInsensitiveInvariant(string strvalue, string strconst) =>
0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase);
internal static int DstCompare(string strA, string strB) => CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.DefaultCompareOptions);
internal static bool IsEmptyArray(string[] array) => (null == array) || (0 == array.Length);
internal static bool IsNull(object value)
{
if ((null == value) || (DBNull.Value == value))
{
return true;
}
INullable nullable = (value as INullable);
return ((null != nullable) && nullable.IsNull);
}
internal static Exception InvalidSeekOrigin(string parameterName)
{
return ArgumentOutOfRange(SR.ADP_InvalidSeekOrigin, parameterName);
}
internal static void SetCurrentTransaction(Transaction transaction)
{
Transaction.Current = transaction;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using Aimp.DotNet.Build;
using Nuke.Common;
using Nuke.Common.Execution;
using Nuke.Common.Git;
using Nuke.Common.IO;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.GitVersion;
using Nuke.Common.Tools.MSBuild;
using Nuke.Common.Tools.NuGet;
using Nuke.Common.Tools.SonarScanner;
using Nuke.Common.Utilities.Collections;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.IO.PathConstruction;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
[CheckBuildProjectConfigurations]
[UnsetVisualStudioEnvironmentVariables]
partial class Build : NukeBuild
{
public static int Main() => Execute<Build>(x => x.Compile);
[Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")]
readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release;
[Solution] readonly Solution Solution;
[GitRepository] readonly GitRepository GitRepository;
[GitVersion(NoFetch = true, UpdateAssemblyInfo = false)] readonly GitVersion GitVersion;
[Parameter] readonly string SonarUrl;
[Parameter] readonly string SonarUser;
[Parameter] readonly string SonarPassword;
[Parameter] readonly string SonarProjectKey;
[Parameter] readonly string SonarProjectName;
[Parameter] readonly string Source;
[Parameter] readonly string NugetApiKey;
[Parameter] readonly string RequestSourceBranch;
[Parameter] readonly string RequestTargetBranch;
[Parameter] readonly string RequestId;
AbsolutePath SourceDirectory => RootDirectory / "src";
AbsolutePath TestsDirectory => RootDirectory / "tests";
AbsolutePath OutputDirectory => RootDirectory / "output";
readonly string MasterBranch = "master";
readonly string DevelopBranch = "develop";
readonly string ReleaseBranchPrefix = "release";
readonly string HotfixBranchPrefix = "hotfix";
string _version = "1.0.0.0";
Target Clean => _ => _
.Before(Restore)
.Executes(() =>
{
SourceDirectory.GlobDirectories("**/bin", "**/obj").ForEach(DeleteDirectory);
EnsureCleanDirectory(OutputDirectory);
});
Target Restore => _ => _
.Executes(() =>
{
NuGetTasks.NuGetRestore(c => c.SetTargetPath(Solution));
MSBuild(_ => _
.SetTargetPath(Solution)
.SetTargets("Restore"));
});
Target Version => _ => _
.Executes(() =>
{
_version = GitRepository.Branch.StartsWith(ReleaseBranchPrefix)
? GitRepository.Branch.Split("/")[1]
: GitVersion.AssemblySemVer;
Logger.Info($"Assembly version: {_version}");
var assemblyInfo = SourceDirectory / "AssemblyInfo.cs";
if (File.Exists(assemblyInfo))
{
Logger.Info($"Update version for '{assemblyInfo}'");
var fileContent = File.ReadAllText(assemblyInfo);
fileContent = fileContent.Replace("1.0.0.0", _version);
File.WriteAllText(assemblyInfo, fileContent);
}
var rcFile = SourceDirectory / "aimp_dotnet" / "aimp_dotnet.rc";
if (File.Exists(rcFile))
{
Logger.Info($"Update version for '{rcFile}'");
Logger.Info($"Assembly version: {GitVersion.AssemblySemVer}");
var fileContent = File.ReadAllText(rcFile);
fileContent = fileContent.Replace("1,0,0,1", _version.Replace(".", ",")).Replace("1.0.0.1",_version);
File.WriteAllText(rcFile, fileContent);
}
});
Target Compile => _ => _
.DependsOn(Restore, Version)
.Executes(() =>
{
MSBuild(_ => _
.SetTargetPath(Solution)
.SetTargets("Rebuild")
.SetConfiguration(Configuration)
.SetAssemblyVersion(_version)
.SetFileVersion(_version)
.SetInformationalVersion($"{_version}-{GitRepository.Commit}")
.SetMaxCpuCount(Environment.ProcessorCount)
.SetNodeReuse(IsLocalBuild));
});
Target SonarQube => _ => _
.Requires(() => SonarUrl, () => SonarUser, () => SonarProjectKey, () => SonarProjectName)
.DependsOn(Restore)
.Executes(() =>
{
var framework = "sonar-scanner-msbuild-4.8.0.12008-net46";
var configuration = new SonarBeginSettings()
.SetProjectKey(SonarProjectKey)
.SetIssueTrackerUrl(SonarUrl)
.SetServer(SonarUrl)
.SetVersion(_version)
//.SetHomepage(SonarUrl)
.SetLogin(SonarUser)
.SetPassword(SonarPassword)
.SetName(SonarProjectName)
//.SetWorkingDirectory(SourceDirectory)
.SetBranchName(GitRepository.Branch)
.SetFramework(framework)
.SetVerbose(false);
if (GitRepository.Branch != null && !GitRepository.Branch.Contains(ReleaseBranchPrefix))
{
configuration = configuration.SetVersion(GitVersion.SemVer);
}
configuration = configuration.SetProjectBaseDir(SourceDirectory);
if (!string.IsNullOrWhiteSpace(RequestSourceBranch) && !string.IsNullOrWhiteSpace(RequestTargetBranch))
{
configuration = configuration
.SetPullRequestBase(RequestSourceBranch)
.SetPullRequestBranch(RequestTargetBranch)
.SetPullRequestKey(RequestId);
}
var path = ToolPathResolver.GetPackageExecutable(
packageId: "dotnet-sonarscanner|MSBuild.SonarQube.Runner.Tool",
packageExecutable: "SonarScanner.MSBuild.exe",
framework: framework);
configuration = configuration.SetProcessToolPath(path);
SonarScannerTasks.SonarScannerBegin(c => configuration);
}, () =>
{
MSBuild(c => c
.SetConfiguration(Configuration)
.SetTargets("Rebuild")
.SetSolutionFile(Solution)
.SetNodeReuse(true));
},
() =>
{
var framework = "sonar-scanner-msbuild-4.8.0.12008-net46";
var path = ToolPathResolver.GetPackageExecutable(
packageId: "dotnet-sonarscanner|MSBuild.SonarQube.Runner.Tool",
packageExecutable: "SonarScanner.MSBuild.exe",
framework: framework);
SonarScannerTasks.SonarScannerEnd(c => c
.SetLogin(SonarUser)
.SetPassword(SonarPassword)
//.SetWorkingDirectory(SourceDirectory)
.SetFramework(framework)
.SetProcessToolPath(path));
});
Target Pack => _ => _
.DependsOn(Version)
.Executes(() =>
{
Logger.Info("Start build Nuget packages");
var nugetFolder = RootDirectory / "Nuget";
var config = new NuGetPackSettings()
.SetBasePath(RootDirectory)
.SetConfiguration(Configuration)
.SetVersion(_version)
.SetOutputDirectory(OutputDirectory);
if (GitRepository.Branch != null && !GitRepository.Branch.Contains(ReleaseBranchPrefix))
{
config = config.SetSuffix("preview");
}
if (Configuration == Configuration.Debug)
{
config = config.SetSuffix("debug");
}
NuGetTasks.NuGetPack(config
.SetTargetPath(nugetFolder / "AimpSDK.nuspec"));
NuGetTasks.NuGetPack(config
.SetTargetPath(nugetFolder / "AimpSDK.symbols.nuspec")
.AddProperty("Symbols", string.Empty));
NuGetTasks.NuGetPack(config
.SetTargetPath(nugetFolder / "AimpSDK.sources.nuspec"));
});
Target Publish => _ => _
.Requires(() => Configuration.Equals(Configuration.Release))
.Requires(() => NugetApiKey)
.Executes(() =>
{
Logger.Info("Deploying Nuget packages");
GlobFiles(OutputDirectory, "*.nupkg").NotEmpty()
.Where(c => !c.EndsWith("symbols.nupkg"))
.ForEach(c => NuGetTasks.NuGetPush(s => s
.SetTargetPath(c)
.SetApiKey(NugetApiKey)
.SetSource(Source)));
});
Target Artifacts => _ => _
.Executes(() =>
{
List<string> plugins = new List<string>();
EnsureCleanDirectory(OutputDirectory / "Artifacts");
Directory.CreateDirectory(OutputDirectory / "Artifacts");
Logger.Info("Copy plugins to artifacts folder");
var directories = GlobDirectories(SourceDirectory / "Plugins", $"**/bin/{Configuration}");
foreach (var directory in directories)
{
var di = new DirectoryInfo(directory);
var pluginName = di.Parent?.Parent?.Name;
plugins.Add(pluginName);
Directory.CreateDirectory(OutputDirectory / "Artifacts" / "Plugins" / pluginName);
Logger.Info(pluginName);
var files = di.GetFiles("*.dll");
foreach (var file in files)
{
string outFile = string.Empty;
if (file.Name.StartsWith(pluginName))
{
outFile = OutputDirectory / "Artifacts" / "Plugins" / pluginName / $"{Path.GetFileNameWithoutExtension(file.Name)}_plugin.dll";
}
else
{
outFile = OutputDirectory / "Artifacts" / "Plugins" / pluginName / file.Name;
}
if (file.Name.StartsWith("aimp_dotnet"))
{
outFile = OutputDirectory / "Artifacts" / "Plugins" / pluginName / $"{pluginName}.dll";
}
Logger.Normal($"Copy '{file.FullName}' to '{outFile}'");
file.CopyTo(outFile, true);
}
}
Logger.Info("Copy SDK files to artifacts folder");
var sdkFolder = new DirectoryInfo(SourceDirectory / $"{Configuration}");
Directory.CreateDirectory(OutputDirectory / "Artifacts" / "SDK");
var sdkFiles = sdkFolder.GetFiles("*.dll");
foreach (var file in sdkFiles)
{
var outFile = OutputDirectory / "Artifacts" / "SDK" / file.Name;
file.CopyTo(outFile, true);
}
Logger.Info("Validate output");
bool validatePluginFolder(string plugin, IEnumerable<FileInfo> files)
{
var isValid = true;
isValid &= files.Any(c => c.Name.StartsWith("AIMP.SDK"));
isValid &= files.Any(c => c.Name == $"{plugin}.dll");
isValid &= files.Any(c => c.Name == $"{plugin}_plugin.dll");
return isValid;
}
var isValid = true;
foreach (var plugin in plugins)
{
var pluginFolder = OutputDirectory / "Artifacts" / "Plugins" / plugin;
var di = new DirectoryInfo(pluginFolder);
var files = di.GetFiles("*.dll");
if (!validatePluginFolder(plugin, files))
{
Logger.Error($"Plugin {plugin} not valid.");
isValid = false;
}
}
ControlFlow.Assert(isValid, "Artifacts not valid");
Logger.Info("Compress artifacts");
ZipFile.CreateFromDirectory(OutputDirectory / "Artifacts", OutputDirectory / "aimp.sdk.zip");
});
}
| |
//
// UsbDevice.cs
//
// Author:
// Alex Launi <[email protected]>
//
// Copyright (c) 2010 Alex Launi
//
// 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 ENABLE_GIO_HARDWARE
using System;
using Banshee.Hardware;
using GUdev;
using System.Globalization;
namespace Banshee.Hardware.Gio
{
class UsbDevice : IUsbDevice, IRawDevice
{
const string UdevUsbBusNumber = "BUSNUM";
const string UdevUsbDeviceNumber = "DEVNUM";
const string UdevVendorId = "ID_VENDOR_ID";
const string UdevProductId = "ID_MODEL_ID";
internal static UsbDevice ResolveRootDevice (IDevice device)
{
// Now walk up the device tree to see if we can find a usb device
// NOTE: We walk up the tree to find a UDevMetadataSource which
// exposes the right usb properties, but we never use it. Maybe we
// should be constructing and wrapping a new RawUsbDevice using the
// correct metadata. Maybe it doesn't matter. I'm not sure. At the
// moment we re-use the same RawDevice except wrap it in a UsbDevice.
IRawDevice raw = device as IRawDevice;
if (raw != null) {
var metadata = ResolveUsingUsbBusAndPort (raw.Device.UdevMetadata, true);
if (metadata == null)
metadata = ResolveUsingBusType (raw.Device.UdevMetadata, true);
if (metadata != null)
return new UsbDevice (raw.Device);
}
return null;
}
public IUsbDevice ResolveRootUsbDevice ()
{
return this;
}
public IUsbPortInfo ResolveUsbPortInfo ()
{
return new UsbPortInfo (BusNumber, DeviceNumber);
}
public static int GetBusNumber (IUsbDevice device)
{
var raw = device as IRawDevice;
return raw == null ? 0 : int.Parse (raw.Device.UdevMetadata.GetPropertyString (UdevUsbBusNumber));
}
public static int GetDeviceNumber (IUsbDevice device)
{
var raw = device as IRawDevice;
return raw == null ? 0 : int.Parse (raw.Device.UdevMetadata.GetPropertyString (UdevUsbDeviceNumber));
}
public static int GetProductId (IUsbDevice device)
{
var raw = device as IRawDevice;
return raw == null ? 0 : int.Parse (raw.Device.UdevMetadata.GetPropertyString (UdevProductId), NumberStyles.HexNumber);
}
public static int GetSpeed (IUsbDevice device)
{
throw new NotImplementedException ();
}
public static int GetVendorId (IUsbDevice device)
{
var raw = device as IRawDevice;
return raw == null ? 0 : int.Parse (raw.Device.UdevMetadata.GetPropertyString (UdevVendorId), NumberStyles.HexNumber);
}
public static int GetVersion (IUsbDevice device)
{
throw new NotImplementedException ();
}
public static UsbDevice Resolve (IDevice device)
{
IRawDevice raw = device as IRawDevice;
if (raw != null) {
if (ResolveUsingUsbBusAndPort (raw.Device.UdevMetadata, false) != null)
return new UsbDevice (raw.Device);
else if (ResolveUsingBusType (raw.Device.UdevMetadata, false) != null)
return new UsbDevice (raw.Device);
}
return null;
}
static UdevMetadataSource ResolveUsingUsbBusAndPort (UdevMetadataSource metadata, bool recurse)
{
do {
if (metadata.PropertyExists (UdevUsbBusNumber) && metadata.PropertyExists (UdevUsbDeviceNumber))
return metadata;
} while (recurse && (metadata = metadata.Parent) != null);
return null;
}
static UdevMetadataSource ResolveUsingBusType (UdevMetadataSource metadata, bool recurse)
{
var comparer = StringComparer.OrdinalIgnoreCase;
do {
if (metadata.PropertyExists ("ID_BUS") && comparer.Equals ("usb", metadata.GetPropertyString ("ID_BUS")))
return metadata;
} while (recurse && (metadata = metadata.Parent) != null);
return null;
}
public RawDevice Device {
get; set;
}
public int BusNumber {
get { return GetBusNumber (this); }
}
public int DeviceNumber {
get { return GetDeviceNumber (this); }
}
public string Name {
get { return Device.Name; }
}
public IDeviceMediaCapabilities MediaCapabilities {
get { return Device.MediaCapabilities; }
}
public string Product {
get { return Device.Product;}
}
public int ProductId {
get { return GetProductId (this); }
}
public string Serial {
get { return Device.Serial; }
}
// What is this and why do we want it?
public double Speed {
get { return GetSpeed (this); }
}
public string Uuid {
get { return Device.Uuid; }
}
public string Vendor {
get { return Device.Vendor; }
}
public int VendorId {
get { return GetVendorId (this); }
}
// What is this and why do we want it?
public double Version {
get { return GetVersion (this); }
}
UsbDevice (RawDevice device)
{
Device = device;
}
bool IDevice.PropertyExists (string key)
{
return Device.PropertyExists (key);
}
string IDevice.GetPropertyString (string key)
{
return Device.GetPropertyString (key);
}
double IDevice.GetPropertyDouble (string key)
{
return Device.GetPropertyDouble (key);
}
bool IDevice.GetPropertyBoolean (string key)
{
return Device.GetPropertyBoolean (key);
}
int IDevice.GetPropertyInteger (string key)
{
return Device.GetPropertyInteger (key);
}
ulong IDevice.GetPropertyUInt64 (string key)
{
return Device.GetPropertyUInt64 (key);
}
public string[] GetPropertyStringList (string key)
{
return Device.GetPropertyStringList (key);
}
}
}
#endif
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Serialization.External;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Timers;
namespace OpenSim.Region.CoreModules.World.Archiver
{
/// <summary>
/// Encapsulate the asynchronous requests for the assets required for an archive operation
/// </summary>
internal class AssetsRequest
{
/// <value>
/// If a timeout does occur, limit the amount of UUID information put to the console.
/// </value>
protected const int MAX_UUID_DISPLAY_ON_TIMEOUT = 3;
/// <value>
/// Timeout threshold if we still need assets or missing asset notifications but have stopped receiving them
/// from the asset service
/// </value>
protected const int TIMEOUT = 60 * 1000;
protected AssetsArchiver m_assetsArchiver;
/// <value>
/// Asset service used to request the assets
/// </value>
protected IAssetService m_assetService;
/// <value>
/// Callback used when all the assets requested have been received.
/// </value>
protected AssetsRequestCallback m_assetsRequestCallback;
/// <value>
/// List of assets that were found. This will be passed back to the requester.
/// </value>
protected List<UUID> m_foundAssetUuids = new List<UUID>();
/// <value>
/// Maintain a list of assets that could not be found. This will be passed back to the requester.
/// </value>
protected List<UUID> m_notFoundAssetUuids = new List<UUID>();
protected Dictionary<string, object> m_options;
protected System.Timers.Timer m_requestCallbackTimer;
protected UUID m_scopeID;
protected IUserAccountService m_userAccountService;
/// <value>
/// uuids to request
/// </value>
protected IDictionary<UUID, sbyte> m_uuids;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <value>
/// Record the number of asset replies required so we know when we've finished
/// </value>
private int m_repliesRequired;
/// <value>
/// State of this request
/// </value>
private RequestState m_requestState = RequestState.Initial;
// the grid ID
protected internal AssetsRequest(
AssetsArchiver assetsArchiver, IDictionary<UUID, sbyte> uuids,
IAssetService assetService, IUserAccountService userService,
UUID scope, Dictionary<string, object> options,
AssetsRequestCallback assetsRequestCallback)
{
m_assetsArchiver = assetsArchiver;
m_uuids = uuids;
m_assetsRequestCallback = assetsRequestCallback;
m_assetService = assetService;
m_userAccountService = userService;
m_scopeID = scope;
m_options = options;
m_repliesRequired = uuids.Count;
// FIXME: This is a really poor way of handling the timeout since it will always leave the original requesting thread
// hanging. Need to restructure so an original request thread waits for a ManualResetEvent on asset received
// so we can properly abort that thread. Or request all assets synchronously, though that would be a more
// radical change
m_requestCallbackTimer = new System.Timers.Timer(TIMEOUT);
m_requestCallbackTimer.AutoReset = false;
m_requestCallbackTimer.Elapsed += new ElapsedEventHandler(OnRequestCallbackTimeout);
}
/// <summary>
/// Method called when all the necessary assets for an archive request have been received.
/// </summary>
public delegate void AssetsRequestCallback(
ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids, bool timedOut);
private enum RequestState
{
Initial,
Running,
Completed,
Aborted
};
/// <summary>
/// Called back by the asset cache when it has the asset
/// </summary>
/// <param name="assetID"></param>
/// <param name="asset"></param>
public void AssetRequestCallback(string id, object sender, AssetBase asset)
{
Culture.SetCurrentCulture();
try
{
lock (this)
{
//m_log.DebugFormat("[ARCHIVER]: Received callback for asset {0}", id);
m_requestCallbackTimer.Stop();
if ((m_requestState == RequestState.Aborted) || (m_requestState == RequestState.Completed))
{
m_log.WarnFormat(
"[ARCHIVER]: Received information about asset {0} while in state {1}. Ignoring.",
id, m_requestState);
return;
}
if (asset != null)
{
if (m_options.ContainsKey("verbose"))
m_log.InfoFormat("[ARCHIVER]: Writing asset {0}", id);
m_foundAssetUuids.Add(asset.FullID);
m_assetsArchiver.WriteAsset(PostProcess(asset));
}
else
{
if (m_options.ContainsKey("verbose"))
m_log.InfoFormat("[ARCHIVER]: Recording asset {0} as not found", id);
m_notFoundAssetUuids.Add(new UUID(id));
}
if (m_foundAssetUuids.Count + m_notFoundAssetUuids.Count >= m_repliesRequired)
{
m_requestState = RequestState.Completed;
m_log.DebugFormat(
"[ARCHIVER]: Successfully added {0} assets ({1} assets not found but these may be expected invalid references)",
m_foundAssetUuids.Count, m_notFoundAssetUuids.Count);
// We want to stop using the asset cache thread asap
// as we now need to do the work of producing the rest of the archive
Util.RunThreadNoTimeout(PerformAssetsRequestCallback, "AssetsRequestCallback", false);
}
else
{
m_requestCallbackTimer.Start();
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[ARCHIVER]: AssetRequestCallback failed with {0}", e);
}
}
protected internal void Execute()
{
m_requestState = RequestState.Running;
m_log.DebugFormat("[ARCHIVER]: AssetsRequest executed looking for {0} possible assets", m_repliesRequired);
// We can stop here if there are no assets to fetch
if (m_repliesRequired == 0)
{
m_requestState = RequestState.Completed;
PerformAssetsRequestCallback(false);
return;
}
m_requestCallbackTimer.Enabled = true;
foreach (KeyValuePair<UUID, sbyte> kvp in m_uuids)
{
// m_log.DebugFormat("[ARCHIVER]: Requesting asset {0}", kvp.Key);
// m_assetService.Get(kvp.Key.ToString(), kvp.Value, PreAssetRequestCallback);
AssetBase asset = m_assetService.Get(kvp.Key.ToString());
PreAssetRequestCallback(kvp.Key.ToString(), kvp.Value, asset);
}
}
protected void OnRequestCallbackTimeout(object source, ElapsedEventArgs args)
{
bool timedOut = true;
try
{
lock (this)
{
// Take care of the possibilty that this thread started but was paused just outside the lock before
// the final request came in (assuming that such a thing is possible)
if (m_requestState == RequestState.Completed)
{
timedOut = false;
return;
}
m_requestState = RequestState.Aborted;
}
// Calculate which uuids were not found. This is an expensive way of doing it, but this is a failure
// case anyway.
List<UUID> uuids = new List<UUID>();
foreach (UUID uuid in m_uuids.Keys)
{
uuids.Add(uuid);
}
foreach (UUID uuid in m_foundAssetUuids)
{
uuids.Remove(uuid);
}
foreach (UUID uuid in m_notFoundAssetUuids)
{
uuids.Remove(uuid);
}
m_log.ErrorFormat(
"[ARCHIVER]: Asset service failed to return information about {0} requested assets", uuids.Count);
int i = 0;
foreach (UUID uuid in uuids)
{
m_log.ErrorFormat("[ARCHIVER]: No information about asset {0} received", uuid);
if (++i >= MAX_UUID_DISPLAY_ON_TIMEOUT)
break;
}
if (uuids.Count > MAX_UUID_DISPLAY_ON_TIMEOUT)
m_log.ErrorFormat(
"[ARCHIVER]: (... {0} more not shown)", uuids.Count - MAX_UUID_DISPLAY_ON_TIMEOUT);
m_log.Error("[ARCHIVER]: Archive save aborted. PLEASE DO NOT USE THIS ARCHIVE, IT WILL BE INCOMPLETE.");
}
catch (Exception e)
{
m_log.ErrorFormat("[ARCHIVER]: Timeout handler exception {0}{1}", e.Message, e.StackTrace);
}
finally
{
if (timedOut)
Util.RunThreadNoTimeout(PerformAssetsRequestCallback, "AssetsRequestCallback", true);
}
}
/// <summary>
/// Perform the callback on the original requester of the assets
/// </summary>
protected void PerformAssetsRequestCallback(object o)
{
Culture.SetCurrentCulture();
Boolean timedOut = (Boolean)o;
try
{
m_assetsRequestCallback(m_foundAssetUuids, m_notFoundAssetUuids, timedOut);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ARCHIVER]: Terminating archive creation since asset requster callback failed with {0}", e);
}
}
protected AssetBase PostProcess(AssetBase asset)
{
if (asset.Type == (sbyte)AssetType.Object && asset.Data != null && m_options.ContainsKey("home"))
{
//m_log.DebugFormat("[ARCHIVER]: Rewriting object data for {0}", asset.ID);
string xml = ExternalRepresentationUtils.RewriteSOP(Utils.BytesToString(asset.Data), m_options["home"].ToString(), m_userAccountService, m_scopeID);
asset.Data = Utils.StringToBytes(xml);
}
return asset;
}
protected void PreAssetRequestCallback(string fetchedAssetID, object assetType, AssetBase fetchedAsset)
{
// Check for broken asset types and fix them with the AssetType gleaned by UuidGatherer
if (fetchedAsset != null && fetchedAsset.Type == (sbyte)AssetType.Unknown)
{
m_log.InfoFormat("[ARCHIVER]: Rewriting broken asset type for {0} to {1}", fetchedAsset.ID, SLUtil.AssetTypeFromCode((sbyte)assetType));
fetchedAsset.Type = (sbyte)assetType;
}
AssetRequestCallback(fetchedAssetID, this, fetchedAsset);
}
}
}
| |
#define USE_TRACING
using System;
using Google.GData.AccessControl;
using Google.GData.Client;
using Google.GData.Extensions;
namespace Google.GData.Documents
{
public class MetadataEntry : DocumentEntry
{
/// <summary>
/// AdditionalRoleInfo collection
/// </summary>
private ExtensionCollection<AdditionalRoleInfo> additionalRoleInfos;
/// <summary>
/// ExportFormat collection
/// </summary>
private ExtensionCollection<ExportFormat> exportFormats;
/// <summary>
/// Feature collection
/// </summary>
private ExtensionCollection<Feature> features;
/// <summary>
/// ImportFormat collection
/// </summary>
private ExtensionCollection<ImportFormat> importFormats;
/// <summary>
/// MaxUploadSize collection
/// </summary>
private ExtensionCollection<MaxUploadSize> maxUploadSizes;
/// <summary>
/// Constructs a new MetadataEntry instance.
/// </summary>
public MetadataEntry()
{
AddExtension(new QuotaBytesTotal());
AddExtension(new QuotaBytesUsedInTrash());
AddExtension(new LargestChangestamp());
AddExtension(new RemainingChangestamps());
AddExtension(new ImportFormat());
AddExtension(new ExportFormat());
AddExtension(new Feature());
AddExtension(new MaxUploadSize());
AddExtension(new AdditionalRoleInfo());
}
/// <summary>
/// QuotaBytesTotal.
/// </summary>
/// <returns></returns>
public ulong QuotaBytesTotal
{
get
{
return Convert.ToUInt64(GetStringValue<QuotaBytesTotal>(DocumentslistNametable.QuotaBytesTotal,
BaseNameTable.gNamespace));
}
}
/// <summary>
/// QuotaBytesUsed.
/// </summary>
/// <returns></returns>
public ulong QuotaBytesUsed
{
get { return QuotaUsed.UnsignedLongValue; }
}
/// <summary>
/// QuotaBytesUsedInTrash.
/// </summary>
/// <returns></returns>
public ulong QuotaBytesUsedInTrash
{
get
{
return
Convert.ToUInt64(GetStringValue<QuotaBytesUsedInTrash>(DocumentslistNametable.QuotaBytesUsedInTrash,
DocumentslistNametable.NSDocumentslist));
}
}
/// <summary>
/// LargestChangestamp.
/// </summary>
/// <returns></returns>
public int LargestChangestamp
{
get
{
LargestChangestamp changestamp =
FindExtension(DocumentslistNametable.LargestChangestamp, DocumentslistNametable.NSDocumentslist) as
LargestChangestamp;
if (changestamp != null)
{
return changestamp.IntegerValue;
}
return 0;
}
}
/// <summary>
/// RemainingChangestamps.
/// </summary>
/// <returns></returns>
public int RemainingChangestamps
{
get
{
RemainingChangestamps element =
FindExtension(DocumentslistNametable.RemainingChangestamps, DocumentslistNametable.NSDocumentslist)
as RemainingChangestamps;
if (element != null)
{
return element.IntegerValue;
}
return 0;
}
}
/// <summary>
/// ImportFormat collection.
/// </summary>
public ExtensionCollection<ImportFormat> ImportFormats
{
get
{
if (importFormats == null)
{
importFormats = new ExtensionCollection<ImportFormat>(this);
}
return importFormats;
}
}
/// <summary>
/// ExportFormat collection.
/// </summary>
public ExtensionCollection<ExportFormat> ExportFormats
{
get
{
if (exportFormats == null)
{
exportFormats = new ExtensionCollection<ExportFormat>(this);
}
return exportFormats;
}
}
/// <summary>
/// Feature collection.
/// </summary>
public ExtensionCollection<Feature> Features
{
get
{
if (features == null)
{
features = new ExtensionCollection<Feature>(this);
}
return features;
}
}
/// <summary>
/// MaxUploadSize collection.
/// </summary>
public ExtensionCollection<MaxUploadSize> MaxUploadSizes
{
get
{
if (maxUploadSizes == null)
{
maxUploadSizes = new ExtensionCollection<MaxUploadSize>(this);
}
return maxUploadSizes;
}
}
/// <summary>
/// AdditionalRoleInfo collection.
/// </summary>
public ExtensionCollection<AdditionalRoleInfo> AdditionalRoleInfos
{
get
{
if (additionalRoleInfos == null)
{
additionalRoleInfos = new ExtensionCollection<AdditionalRoleInfo>(this);
}
return additionalRoleInfos;
}
}
}
public class QuotaBytesTotal : SimpleElement
{
/// <summary>
/// default constructor for gd:quotaBytesTotal
/// </summary>
public QuotaBytesTotal()
: base(DocumentslistNametable.QuotaBytesTotal,
BaseNameTable.gDataPrefix,
BaseNameTable.gNamespace)
{
}
}
public class QuotaBytesUsedInTrash : SimpleElement
{
/// <summary>
/// default constructor for docs:quotaBytesUsedInTrash
/// </summary>
public QuotaBytesUsedInTrash()
: base(DocumentslistNametable.QuotaBytesUsedInTrash,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
}
public class LargestChangestamp : SimpleAttribute
{
/// <summary>
/// default constructor for docs:largestChangestamp
/// </summary>
public LargestChangestamp()
: base(DocumentslistNametable.LargestChangestamp,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
}
public class RemainingChangestamps : SimpleAttribute
{
/// <summary>
/// default constructor for docs:remainingChangestamps
/// </summary>
public RemainingChangestamps()
: base(DocumentslistNametable.RemainingChangestamps,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
}
public abstract class ConversionFormat : SimpleElement
{
/// <summary>
/// base class for docs:importFormat and docs:exportFormat
/// </summary>
public ConversionFormat(string elementName)
: base(elementName,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
/// <summary>
/// Source property accessor
/// </summary>
public string Source
{
get { return Convert.ToString(Attributes[DocumentslistNametable.Source]); }
}
/// <summary>
/// Target property accessor
/// </summary>
public string Target
{
get { return Convert.ToString(Attributes[DocumentslistNametable.Target]); }
}
}
public class ImportFormat : ConversionFormat
{
/// <summary>
/// default constructor for docs:importFormat
/// </summary>
public ImportFormat()
: base(DocumentslistNametable.ImportFormat)
{
}
}
public class ExportFormat : ConversionFormat
{
/// <summary>
/// default constructor for docs:emportFormat
/// </summary>
public ExportFormat()
: base(DocumentslistNametable.ExportFormat)
{
}
}
public class Feature : SimpleContainer
{
/// <summary>
/// base class for docs:importFormat and docs:exportFormat
/// </summary>
public Feature()
: base(DocumentslistNametable.Feature,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
ExtensionFactories.Add(new FeatureName());
ExtensionFactories.Add(new FeatureRate());
}
/// <summary>
/// FeatureName property accessor
/// </summary>
public string Name
{
get
{
return GetStringValue<FeatureName>(DocumentslistNametable.FeatureName,
DocumentslistNametable.NSDocumentslist);
}
}
/// <summary>
/// FeatureRate property accessor
/// </summary>
public string Rate
{
get
{
return GetStringValue<FeatureRate>(DocumentslistNametable.FeatureRate,
DocumentslistNametable.NSDocumentslist);
}
}
}
public class FeatureName : SimpleAttribute
{
/// <summary>
/// default constructor for docs:featureName
/// </summary>
public FeatureName()
: base(DocumentslistNametable.FeatureName,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
}
public class FeatureRate : SimpleAttribute
{
/// <summary>
/// default constructor for docs:featureRate
/// </summary>
public FeatureRate()
: base(DocumentslistNametable.FeatureRate,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
}
public class MaxUploadSize : SimpleElement
{
/// <summary>
/// default constructor for docs:maxUploadSize
/// </summary>
public MaxUploadSize()
: base(DocumentslistNametable.MaxUploadSize,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
}
/// <summary>
/// Kind property accessor
/// </summary>
public string Kind
{
get { return Convert.ToString(Attributes[DocumentslistNametable.Kind]); }
}
}
public class AdditionalRoleInfo : SimpleContainer
{
/// <summary>
/// default constructor for docs:additionalRoleInfo
/// </summary>
public AdditionalRoleInfo()
: base(DocumentslistNametable.AdditionalRoleInfo,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
ExtensionFactories.Add(new AdditionalRoleSet());
}
/// <summary>
/// Kind property accessor
/// </summary>
public string Kind
{
get { return Convert.ToString(Attributes[DocumentslistNametable.Kind]); }
}
public AdditionalRoleSet AdditionalRoleSet
{
get
{
return FindExtension(DocumentslistNametable.AdditionalRoleSet,
DocumentslistNametable.NSDocumentslist) as AdditionalRoleSet;
}
}
}
public class AdditionalRoleSet : SimpleContainer
{
/// <summary>
/// default constructor for docs:additionalRoleSet
/// </summary>
public AdditionalRoleSet()
: base(DocumentslistNametable.AdditionalRoleSet,
DocumentslistNametable.Prefix,
DocumentslistNametable.NSDocumentslist)
{
ExtensionFactories.Add(new AdditionalRole());
}
/// <summary>
/// PrimaryRole property accessor
/// </summary>
public string PrimaryRole
{
get { return Convert.ToString(Attributes[DocumentslistNametable.PrimaryRole]); }
}
public AdditionalRole AdditionalRole
{
get
{
return FindExtension(DocumentslistNametable.AdditionalRole,
AclNameTable.gAclNamespace) as AdditionalRole;
}
}
}
public class AdditionalRole : SimpleAttribute
{
/// <summary>
/// default constructor for docs:additionalRole
/// </summary>
public AdditionalRole()
: base(DocumentslistNametable.AdditionalRole,
DocumentslistNametable.Prefix,
AclNameTable.gAclNamespace)
{
}
}
}
| |
//-----------------------------------------------------------------------------
//
// <copyright file="XmlStreamStore.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// An AnnotationStore subclass based on XML streams. Processes XML
// streams and returns CAF 2.0 OM objects. Useful to other
// AnnotationStore subclass who can get an XML stream of their
// content.
// Spec: http://team/sites/ag/Specifications/CAF%20Storage%20Spec.doc
//
// History:
// 10/04/2002: rruiz: Added header comment to XmlStreamStore.cs.
// 05/29/2003: LGolding: Ported to WCP tree.
// 07/17/2003: rruiz: Made this a real AnnotationStore subclass; updated with
// new APIs; renamed class.
// 01/13/2004 ssimova: Added revert events
// 02/12/2004 ssimova: Added locks for thread safety
// 08/18/2004: magedz: Modify the add/delete/querying capabilities to use the map
//
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Annotations;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Serialization;
using MS.Internal;
using MS.Internal.Annotations;
using MS.Internal.Annotations.Storage;
using MS.Utility;
using System.Windows.Markup;
using MS.Internal.Controls.StickyNote;
using System.Windows.Controls;
namespace System.Windows.Annotations.Storage
{
/// <summary>
/// An AnnotationStore subclass based on XML streams. Processes XML
/// streams and returns CAF 2.0 OM objects. Useful to other
/// AnnotationStore subclass who can get an XML stream of their
/// content.
/// </summary>
public sealed class XmlStreamStore : AnnotationStore
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// This ctor initializes the Dictionary with predefined namespases
/// and their compatibility
/// </summary>
static XmlStreamStore()
{
_predefinedNamespaces = new Dictionary<Uri, IList<Uri>>(6);
_predefinedNamespaces.Add(new Uri(AnnotationXmlConstants.Namespaces.CoreSchemaNamespace), null);
_predefinedNamespaces.Add(new Uri(AnnotationXmlConstants.Namespaces.BaseSchemaNamespace), null);
_predefinedNamespaces.Add(new Uri(XamlReaderHelper.DefaultNamespaceURI), null);
}
/// <summary>
/// Creates an instance using the XML stream passed in as the
/// content. The XML in the stream must be valid XML and conform
/// to the CAF 2.0 schema.
/// </summary>
/// <param name="stream">stream containing annotation data in XML format</param>
/// <exception cref="ArgumentNullException">stream is null</exception>
/// <exception cref="XmlException">stream contains invalid XML</exception>
public XmlStreamStore(Stream stream)
: base()
{
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanSeek)
throw new ArgumentException(SR.Get(SRID.StreamDoesNotSupportSeek));
SetStream(stream, null);
}
/// <summary>
/// Creates an instance using the XML stream passed in as the
/// content. The XML in the stream must be valid XML and conform
/// to the Annotations V1 schema or a valid future version XML which
/// compatibility rules are that when applied they will produce
/// a valid Annotations V1 XML. This .ctor allows registration of
/// application specific known namespaces.
/// </summary>
/// <param name="stream">stream containing annotation data in XML format</param>
/// <param name="knownNamespaces">A dictionary with known and compatible namespaces. The keys in
/// this dictionary are known namespaces. The value of each key is a list of namespaces that are compatible with
/// the key one, i.e. each of the namespaces in the value list will be transformed to the
/// key namespace while reading the input XML.</param>
/// <exception cref="ArgumentNullException">stream is null</exception>
/// <exception cref="XmlException">stream contains invalid XML</exception>
/// <exception cref="ArgumentException">duplicate namespace in knownNamespaces dictionary</exception>
/// <exception cref="ArgumentException">null key in knownNamespaces dictionary</exception>
public XmlStreamStore(Stream stream, IDictionary<Uri, IList<Uri>> knownNamespaces)
: base()
{
if (stream == null)
throw new ArgumentNullException("stream");
SetStream(stream, knownNamespaces);
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Add a new annotation to this store. The new annotation's Id
/// is set to a new value.
/// </summary>
/// <param name="newAnnotation">the annotation to be added to the store</param>
/// <exception cref="ArgumentNullException">newAnnotation is null</exception>
/// <exception cref="ArgumentException">newAnnotation already exists in this store, as determined by its Id</exception>
/// <exception cref="InvalidOperationException">if no stream has been set on the store</exception>
/// <exception cref="ObjectDisposedException">if object has been Disposed</exception>
public override void AddAnnotation(Annotation newAnnotation)
{
if (newAnnotation == null)
throw new ArgumentNullException("newAnnotation");
// We are going to modify internal data. Lock the object
// to avoid modifications from other threads
lock (SyncRoot)
{
//fire trace event
EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.AddAnnotationBegin);
try
{
CheckStatus();
XPathNavigator editor = GetAnnotationNodeForId(newAnnotation.Id);
// we are making sure that the newAnnotation doesn't already exist in the store
if (editor != null)
throw new ArgumentException(SR.Get(SRID.AnnotationAlreadyExists), "newAnnotation");
// we are making sure that the newAnnotation doesn't already exist in the store map
if (_storeAnnotationsMap.FindAnnotation(newAnnotation.Id) != null)
throw new ArgumentException(SR.Get(SRID.AnnotationAlreadyExists), "newAnnotation");
// simply add the annotation to the map to save on performance
// notice that we need to tell the map that this instance of the annotation is dirty
_storeAnnotationsMap.AddAnnotation(newAnnotation, true);
}
finally
{
//fire trace event
EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.AddAnnotationEnd);
}
}
OnStoreContentChanged(new StoreContentChangedEventArgs(StoreContentAction.Added, newAnnotation));
}
/// <summary>
/// Delete the specified annotation.
/// </summary>
/// <param name="annotationId">the Id of the annotation to be deleted</param>
/// <returns>the annotation that was deleted, or null if no annotation
/// with the specified Id was found</returns>
/// <exception cref="InvalidOperationException">if no stream has been set on the store</exception>
/// <exception cref="ObjectDisposedException">if object has been disposed</exception>
public override Annotation DeleteAnnotation(Guid annotationId)
{
Annotation annotation = null;
// We are now going to modify internal data. Lock the object
// to avoid modifications from other threads
lock (SyncRoot)
{
//fire trace event
EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.DeleteAnnotationBegin);
try
{
CheckStatus();
annotation = _storeAnnotationsMap.FindAnnotation(annotationId);
XPathNavigator editor = GetAnnotationNodeForId(annotationId);
if (editor != null)
{
// Only deserialize the annotation if its not already in our map
if (annotation == null)
{
annotation = (Annotation)_serializer.Deserialize(editor.ReadSubtree());
}
editor.DeleteSelf();
}
// Remove the instance from the map
_storeAnnotationsMap.RemoveAnnotation(annotationId);
// notice that in Add we add the annotation to the map only
// but in delete we delete it from both to the Xml and the map
}
finally
{
//fire trace event
EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.DeleteAnnotationEnd);
}
}
// Only fire notification if we actually removed an annotation
if (annotation != null)
{
OnStoreContentChanged(new StoreContentChangedEventArgs(StoreContentAction.Deleted, annotation));
}
return annotation;
}
/// <summary>
/// Queries the Xml stream for annotations that have an anchor
/// that contains a locator that begins with the locator parts
/// in anchorLocator.
/// </summary>
/// <param name="anchorLocator">the locator we are looking for</param>
/// <returns>
/// A list of annotations that have locators in their anchors
/// starting with the same locator parts list as of the input locator
/// If no such annotations an empty list will be returned. The method
/// never returns null.
/// </returns>
/// <exception cref="ObjectDisposedException">if object has been Disposed</exception>
/// <exception cref="InvalidOperationException">the stream is null</exception>
public override IList<Annotation> GetAnnotations(ContentLocator anchorLocator)
{
// First we generate the XPath expression
if (anchorLocator == null)
throw new ArgumentNullException("anchorLocator");
if (anchorLocator.Parts == null)
throw new ArgumentNullException("anchorLocator.Parts");
//fire trace event
EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.GetAnnotationByLocBegin);
IList<Annotation> annotations = null;
try
{
string query = @"//" + AnnotationXmlConstants.Prefixes.CoreSchemaPrefix + ":" + AnnotationXmlConstants.Elements.ContentLocator;
if (anchorLocator.Parts.Count > 0)
{
query += @"/child::*[1]/self::";
for (int i = 0; i < anchorLocator.Parts.Count; i++)
{
if (anchorLocator.Parts[i] != null)
{
if (i > 0)
{
query += @"/following-sibling::";
}
string fragment = anchorLocator.Parts[i].GetQueryFragment(_namespaceManager);
if (fragment != null)
{
query += fragment;
}
else
{
query += "*";
}
}
}
}
query += @"/ancestor::" + AnnotationXmlConstants.Prefixes.CoreSchemaPrefix + ":Anchors/ancestor::" + AnnotationXmlConstants.Prefixes.CoreSchemaPrefix + ":Annotation";
annotations = InternalGetAnnotations(query, anchorLocator);
}
finally
{
//fire trace event
EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.GetAnnotationByLocEnd);
}
return annotations;
}
/// <summary>
/// Returns a list of all annotations in the store
/// </summary>
/// <returns>annotations list. Can return an empty list, but never null.</returns>
/// <exception cref="ObjectDisposedException">if object has been disposed</exception>
public override IList<Annotation> GetAnnotations()
{
IList<Annotation> annotations = null;
//fire trace event
EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.GetAnnotationsBegin);
try
{
string query = "//" + AnnotationXmlConstants.Prefixes.CoreSchemaPrefix + ":Annotation";
annotations = InternalGetAnnotations(query, null);
}
finally
{
EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.GetAnnotationsEnd);
}
return annotations;
}
/// <summary>
/// Finds annotation by Id
/// </summary>
/// <param name="annotationId">annotation id</param>
/// <returns>The annotation. Null if the annotation does not exists</returns>
/// <exception cref="ObjectDisposedException">if object has been disposed</exception>
public override Annotation GetAnnotation(Guid annotationId)
{
lock (SyncRoot)
{
Annotation annotation = null;
//fire trace event
EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.GetAnnotationByIdBegin);
try
{
CheckStatus();
annotation = _storeAnnotationsMap.FindAnnotation(annotationId);
// If there is no pre-existing instance, we deserialize and create an instance.
if (annotation != null)
{
return annotation;
}
XPathNavigator editor = GetAnnotationNodeForId(annotationId);
if (editor != null)
{
annotation = (Annotation)_serializer.Deserialize(editor.ReadSubtree());
// Add the new instance to the map
_storeAnnotationsMap.AddAnnotation(annotation, false);
}
}
finally
{
//fire trace event
EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordAnnotation, EventTrace.Event.GetAnnotationByIdEnd);
}
return annotation;
}
}
/// <summary>
/// Causes any buffered data to be written to the underlying
/// storage mechanism. Gets called after each operation if
/// AutoFlush is set to true. The stream is truncated to
/// the length of the data written out by the store.
/// </summary>
/// <exception cref="UnauthorizedAccessException">stream cannot be written to</exception>
/// <exception cref="InvalidOperationException">if no stream has been set on the store</exception>
/// <exception cref="ObjectDisposedException">if object has been disposed</exception>
/// <seealso cref="AutoFlush"/>
public override void Flush()
{
lock (SyncRoot)
{
CheckStatus();
if (!_stream.CanWrite)
{
throw new UnauthorizedAccessException(SR.Get(SRID.StreamCannotBeWritten));
}
if (_dirty)
{
SerializeAnnotations();
_stream.Position = 0;
_stream.SetLength(0);
_document.PreserveWhitespace = true;
_document.Save(_stream);
_stream.Flush();
_dirty = false;
}
}
}
/// <summary>
/// Returns a list of namespaces that are compatible with an input namespace
/// </summary>
/// <param name="name">namespace</param>
/// <returns>a list of compatible namespaces. Can be null</returns>
/// <remarks>This method works only with built-in AnnotationFramework namespaces.
/// For any other input namespace the return value will be null even if it is
/// registered with the XmlStreamStore ctor</remarks>
public static IList<Uri> GetWellKnownCompatibleNamespaces(Uri name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (_predefinedNamespaces.ContainsKey(name))
return _predefinedNamespaces[name];
return null;
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Operators
//
//------------------------------------------------------
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// When set to true an implementation should call Flush()
/// as a side-effect after each operation.
/// </summary>
/// <value>
/// true if the implementation is set to call Flush() after
/// each operation; false otherwise
/// </value>
public override bool AutoFlush
{
get
{
lock (SyncRoot)
{
return _autoFlush;
}
}
set
{
lock (SyncRoot)
{
_autoFlush = value;
// Commit anything that needs to be committed up to this point
if (_autoFlush)
{
Flush();
}
}
}
}
/// <summary>
/// Returns a list of the namespaces that are ignored while loading
/// the Xml stream
/// </summary>
/// <remarks>The value is never null, but can be an empty list if nothing has been ignored</remarks>
public IList<Uri> IgnoredNamespaces
{
get
{
return _ignoredNamespaces;
}
}
/// <summary>
/// Returns a list of all namespaces that are internaly used by the framework
/// </summary>
public static IList<Uri> WellKnownNamespaces
{
get
{
Uri[] res = new Uri[_predefinedNamespaces.Keys.Count];
_predefinedNamespaces.Keys.CopyTo(res, 0);
return res;
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Disposes of the resources (other than memory) used by the store.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged
/// resources; false to release only unmanaged resources</param>
protected override void Dispose(bool disposing)
{
//call the base class first to set _disposed to false
//in order to avoid working with the store when the resources
//are released
base.Dispose(disposing);
if (disposing)
{
Cleanup();
}
}
/// <summary>
/// Called after every annotation action on the store. We override it
/// to update the dirty state of the store.
/// </summary>
/// <param name="e">arguments for the event to fire</param>
protected override void OnStoreContentChanged(StoreContentChangedEventArgs e)
{
lock (SyncRoot)
{
_dirty = true;
}
base.OnStoreContentChanged(e);
}
#endregion Protected Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Applies the specified XPath expression to the store and returns
/// the results.
/// </summary>
/// <param name="queryExpression">the XPath expression to be applied to the store</param>
/// <returns>
/// An IList containing zero or more annotations that match the
/// criteria in the XPath expression; never will return null. If
/// no annotations meet the criteria, an empty list is returned.
/// </returns>
/// <exception cref="InvalidOperationException">if no stream has been set on the store</exception>
/// <exception cref="ObjectDisposedException">if object has been Disposed</exception>
/// <exception cref="ArgumentNullException">queryExpression is null</exception>
/// <exception cref="ArgumentException">queryExpression is empty string</exception>
private List<Guid> FindAnnotationIds(string queryExpression)
{
Invariant.Assert(queryExpression != null && queryExpression.Length > 0,
"Invalid query expression");
Guid annId;
List<Guid> retObj = null;
// Lock the object so nobody can change the document
// while the query is executed
lock (SyncRoot)
{
CheckStatus();
XPathNavigator navigator = _document.CreateNavigator();
XPathNodeIterator iterator = navigator.Select(queryExpression, _namespaceManager);
if (iterator != null && iterator.Count > 0)
{
retObj = new List<Guid>(iterator.Count);
foreach (XPathNavigator node in iterator)
{
string nodeId = node.GetAttribute("Id", "");
if (String.IsNullOrEmpty(nodeId))
{
throw new XmlException(SR.Get(SRID.RequiredAttributeMissing, AnnotationXmlConstants.Attributes.Id, AnnotationXmlConstants.Elements.Annotation));
}
try
{
annId = XmlConvert.ToGuid(nodeId);
}
catch (FormatException fe)
{
throw new InvalidOperationException(SR.Get(SRID.CannotParseId), fe);
}
retObj.Add(annId);
}
}
else
{
retObj = new List<Guid>(0);
}
}
return retObj;
}
/// <summary>
/// Used as AuthorChanged event handler for all annotations
/// handed out by the map.
/// </summary>
/// <param name="sender">annotation that sent the event</param>
/// <param name="e">args for the event</param>
private void HandleAuthorChanged(object sender, AnnotationAuthorChangedEventArgs e)
{
lock (SyncRoot)
{
_dirty = true;
}
OnAuthorChanged(e);
}
/// <summary>
/// Used as AnchorChanged event handler for all annotations
/// handed out by the map.
/// </summary>
/// <param name="sender">annotation that sent the event</param>
/// <param name="e">args for the event</param>
private void HandleAnchorChanged(object sender, AnnotationResourceChangedEventArgs e)
{
lock (SyncRoot)
{
_dirty = true;
}
OnAnchorChanged(e);
}
/// <summary>
/// Used as CargoChanged event handler for all annotations
/// handed out by the map.
/// </summary>
/// <param name="sender">annotation that sent the event</param>
/// <param name="e">args for the event</param>
private void HandleCargoChanged(object sender, AnnotationResourceChangedEventArgs e)
{
lock (SyncRoot)
{
_dirty = true;
}
OnCargoChanged(e);
}
/// <summary>
/// 1- Merge Annotations queried from both the map and the Xml stream
/// 2- Add the annotations found in the Xml stream to the map
/// </summary>
/// <param name="mapAnnotations">A dictionary of map annotations</param>
/// <param name="storeAnnotationsId">A list of annotation ids from the Xml stream</param>
/// <returns></returns>
private IList<Annotation> MergeAndCacheAnnotations(Dictionary<Guid, Annotation> mapAnnotations, List<Guid> storeAnnotationsId)
{
// first put all annotations from the map in the return list
List<Annotation> annotations = new List<Annotation>((IEnumerable<Annotation>)mapAnnotations.Values);
// there three possible conditions
// 1- An annotation exists in xml and in the store map results
// 2- An annotation exists in xml and not in the store map results
// 2-1- The annotation is found in the map
// 2-2- The annotation is not found in the map
// Now, we need to find annotations in the store that are not in the map results
// and verify that they should be serialized
foreach (Guid annotationId in storeAnnotationsId)
{
Annotation annot;
bool foundInMapResults = mapAnnotations.TryGetValue(annotationId, out annot);
if (!foundInMapResults)
{
// it is not in the map - get it from the store
annot = GetAnnotation(annotationId);
annotations.Add(annot);
}
}
return annotations;
}
/// <summary>
/// Do the GetAnnotations work inside a lock statement for thread safety reasons
/// </summary>
/// <param name="query"></param>
/// <param name="anchorLocator"></param>
/// <returns></returns>
private IList<Annotation> InternalGetAnnotations(string query, ContentLocator anchorLocator)
{
// anchorLocator being null is handled appropriately below
Invariant.Assert(query != null, "Parameter 'query' is null.");
lock (SyncRoot)
{
CheckStatus();
List<Guid> annotationIds = FindAnnotationIds(query);
Dictionary<Guid, Annotation> annotations = null;
// Now, get the annotations in the map that satisfies the query criterion
if (anchorLocator == null)
{
annotations = _storeAnnotationsMap.FindAnnotations();
}
else
{
annotations = _storeAnnotationsMap.FindAnnotations(anchorLocator);
}
// merge both query results
return MergeAndCacheAnnotations(annotations, annotationIds);
}
}
/// <summary>
/// Loads the current stream into the XmlDocument used by this
/// store as a backing store. If the stream doesn't contain any
/// data we load up a default XmlDocument for the Annotations schema.
/// The "http://schemas.microsoft.com/windows/annotations/2003/11/core"
/// namespace is registered with "anc" prefix and the
/// "http://schemas.microsoft.com/windows/annotations/2003/11/base" namespace
/// is registered with "anb" prefix as global namespaces.
/// We also select from the newly loaded document the new top
/// level node. This is used later for insertions, etc.
/// </summary>
/// <exception cref="XmlException">if the stream contains invalid XML</exception>
private void LoadStream(IDictionary<Uri, IList<Uri>> knownNamespaces)
{
//check input data first
CheckKnownNamespaces(knownNamespaces);
lock (SyncRoot)
{
_document = new XmlDocument();
_document.PreserveWhitespace = false;
if (_stream.Length == 0)
{
_document.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?> <" +
AnnotationXmlConstants.Prefixes.CoreSchemaPrefix + ":Annotations xmlns:" + AnnotationXmlConstants.Prefixes.CoreSchemaPrefix + "=\"" +
AnnotationXmlConstants.Namespaces.CoreSchemaNamespace + "\" xmlns:" + AnnotationXmlConstants.Prefixes.BaseSchemaPrefix + "=\"" + AnnotationXmlConstants.Namespaces.BaseSchemaNamespace + "\" />");
}
else
{
_xmlCompatibilityReader = SetupReader(knownNamespaces);
_document.Load(_xmlCompatibilityReader);
}
_namespaceManager = new XmlNamespaceManager(_document.NameTable);
_namespaceManager.AddNamespace(AnnotationXmlConstants.Prefixes.CoreSchemaPrefix, AnnotationXmlConstants.Namespaces.CoreSchemaNamespace);
_namespaceManager.AddNamespace(AnnotationXmlConstants.Prefixes.BaseSchemaPrefix, AnnotationXmlConstants.Namespaces.BaseSchemaNamespace);
// This use of an iterator is necessary because SelectSingleNode isn't available in the PD3
// drop of the CLR. Eventually we should be able to call SelectSingleNode and not have to
// use an iterator to get a single node.
XPathNavigator navigator = _document.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("//" + AnnotationXmlConstants.Prefixes.CoreSchemaPrefix + ":Annotations", _namespaceManager);
Invariant.Assert(iterator.Count == 1, "More than one annotation returned for the query");
iterator.MoveNext();
_rootNavigator = (XPathNavigator)iterator.Current;
}
}
/// <summary>
/// Checks if passed external known namespaces are valid
/// </summary>
/// <param name="knownNamespaces">namespaces dictionary</param>
/// <remarks>We do not allow internal namespases in this dictionary nor
/// duplicates</remarks>
private void CheckKnownNamespaces(IDictionary<Uri, IList<Uri>> knownNamespaces)
{
if (knownNamespaces == null)
return;
IList<Uri> allNamespaces = new List<Uri>();
//add AnnotationFramework namespaces
foreach (Uri name in _predefinedNamespaces.Keys)
{
allNamespaces.Add(name);
}
//add external namespaces
foreach (Uri knownNamespace in knownNamespaces.Keys)
{
if (knownNamespace == null)
{
throw new ArgumentException(SR.Get(SRID.NullUri), "knownNamespaces");
}
if (allNamespaces.Contains(knownNamespace))
{
throw new ArgumentException(SR.Get(SRID.DuplicatedUri), "knownNamespaces");
}
allNamespaces.Add(knownNamespace);
}
// check compatible namespaces
foreach (KeyValuePair<Uri, IList<Uri>> item in knownNamespaces)
{
if (item.Value != null)
{
foreach (Uri name in item.Value)
{
if (name == null)
{
throw new ArgumentException(SR.Get(SRID.NullUri), "knownNamespaces");
}
if (allNamespaces.Contains(name))
{
throw new ArgumentException(SR.Get(SRID.DuplicatedCompatibleUri), "knownNamespaces");
}
allNamespaces.Add(name);
}//foreach
}//if
}//foreach
}
/// <summary>
/// Creates and initializes the XmlCompatibilityReader
/// </summary>
/// <param name="knownNamespaces">Dictionary of external known namespaces</param>
/// <returns>The XmlCompatibilityReader</returns>
private XmlCompatibilityReader SetupReader(IDictionary<Uri, IList<Uri>> knownNamespaces)
{
IList<string> supportedNamespaces = new List<string>();
//add AnnotationFramework namespaces
foreach (Uri name in _predefinedNamespaces.Keys)
{
supportedNamespaces.Add(name.ToString());
}
//add external namespaces
if (knownNamespaces != null)
{
foreach (Uri knownNamespace in knownNamespaces.Keys)
{
Debug.Assert(knownNamespace != null, "null knownNamespace");
supportedNamespaces.Add(knownNamespace.ToString());
}
}
//create XmlCompatibilityReader first
XmlCompatibilityReader reader = new XmlCompatibilityReader(new XmlTextReader(_stream),
new IsXmlNamespaceSupportedCallback(IsXmlNamespaceSupported), supportedNamespaces);
// Declare compatibility.
// Skip the Framework ones because they are all null in this version
if (knownNamespaces != null)
{
foreach (KeyValuePair<Uri, IList<Uri>> item in knownNamespaces)
{
if (item.Value != null)
{
foreach (Uri name in item.Value)
{
Debug.Assert(name != null, "null compatible namespace");
reader.DeclareNamespaceCompatibility(item.Key.ToString(), name.ToString());
}//foreach
}//if
}//foreach
}//if
//cleanup the _ignoredNamespaces
_ignoredNamespaces.Clear();
return reader;
}
/// <summary>
/// A callback for XmlCompatibilityReader
/// </summary>
/// <param name="xmlNamespace">inquired namespace</param>
/// <param name="newXmlNamespace">the newer subsumming namespace</param>
/// <returns>true if the namespace is known, false if not</returns>
/// <remarks>This API always returns false because all known namespaces are registered
/// before loading the Xml. It stores the namespace as ignored.</remarks>
private bool IsXmlNamespaceSupported(string xmlNamespace, out string newXmlNamespace)
{
//store the namespace if needed
if (!String.IsNullOrEmpty(xmlNamespace))
{
if (!Uri.IsWellFormedUriString(xmlNamespace, UriKind.RelativeOrAbsolute))
{
throw new ArgumentException(SR.Get(SRID.InvalidNamespace, xmlNamespace), "xmlNamespace");
}
Uri namespaceUri = new Uri(xmlNamespace, UriKind.RelativeOrAbsolute);
if (!_ignoredNamespaces.Contains(namespaceUri))
_ignoredNamespaces.Add(namespaceUri);
}
newXmlNamespace = null;
return false;
}
/// <summary>
/// Selects the annotation XmlElement from the current document
/// with the given id.
/// </summary>
/// <param name="id">the id to query for in the XmlDocument</param>
/// <returns>the XmlElement representing the annotation with the given id</returns>
private XPathNavigator GetAnnotationNodeForId(Guid id)
{
XPathNavigator navigator = null;
lock (SyncRoot)
{
XPathNavigator tempNavigator = _document.CreateNavigator();
// This use of an iterator is necessary because SelectSingleNode isn't available in the PD3
// drop of the CLR. Eventually we should be able to call SelectSingleNode and not have to
// use an iterator to get a single node.
// We use XmlConvert.ToString to turn the Guid into a string because
// that's what is used by the Annotation's serialization methods.
XPathNodeIterator iterator = tempNavigator.Select(@"//" + AnnotationXmlConstants.Prefixes.CoreSchemaPrefix + @":Annotation[@Id=""" + XmlConvert.ToString(id) + @"""]", _namespaceManager);
if (iterator.MoveNext())
{
navigator = (XPathNavigator)iterator.Current;
}
}
return navigator;
}
/// <summary>
/// Verifies the store is in a valid state. Throws exceptions otherwise.
/// </summary>
private void CheckStatus()
{
lock (SyncRoot)
{
if (IsDisposed)
throw new ObjectDisposedException(null, SR.Get(SRID.ObjectDisposed_StoreClosed));
if (_stream == null)
throw new InvalidOperationException(SR.Get(SRID.StreamNotSet));
}
}
/// <summary>
/// Called from flush to serialize all annotations in the map
/// notice that delete takes care of the delete action both in the map
/// and in the store
/// </summary>
private void SerializeAnnotations()
{
List<Annotation> mapAnnotations = _storeAnnotationsMap.FindDirtyAnnotations();
foreach (Annotation annotation in mapAnnotations)
{
XPathNavigator editor = GetAnnotationNodeForId(annotation.Id);
if (editor == null)
{
editor = (XPathNavigator)_rootNavigator.CreateNavigator();
XmlWriter writer = editor.AppendChild();
_serializer.Serialize(writer, annotation);
writer.Close();
}
else
{
XmlWriter writer = editor.InsertBefore();
_serializer.Serialize(writer, annotation);
writer.Close();
editor.DeleteSelf();
}
}
_storeAnnotationsMap.ValidateDirtyAnnotations();
}
/// <summary>
/// Discards changes and cleans up references.
/// </summary>
private void Cleanup()
{
lock (SyncRoot)
{
_xmlCompatibilityReader = null;
_ignoredNamespaces = null;
_stream = null;
_document = null;
_rootNavigator = null;
_storeAnnotationsMap = null;
}
}
/// <summary>
/// Sets the stream for this store. Assumes Cleanup has
/// been previously called (or this is a new store).
/// </summary>
/// <param name="stream">new stream for this store</param>
/// <param name="knownNamespaces">List of known and compatible namespaces used to initialize
/// the XmlCompatibilityReader</param>
private void SetStream(Stream stream, IDictionary<Uri, IList<Uri>> knownNamespaces)
{
try
{
lock (SyncRoot)
{
_storeAnnotationsMap = new StoreAnnotationsMap(HandleAuthorChanged, HandleAnchorChanged, HandleCargoChanged);
_stream = stream;
LoadStream(knownNamespaces);
}
}
catch
{
Cleanup();
throw;
}
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// Dirty bit for the store's in-memory cache
private bool _dirty;
// Boolean flag represents whether the store should perform a flush
// after every operation or not
private bool _autoFlush;
// XmlDocument used as an in-memory cache of the stream's XML content
private XmlDocument _document;
// Namespace manager used for all queries.
private XmlNamespaceManager _namespaceManager;
// Stream passed in by the creator of this instance.
private Stream _stream;
// The xpath navigator used to navigate the annotations Xml stream
private XPathNavigator _rootNavigator;
// map that holds AnnotationId->Annotation
StoreAnnotationsMap _storeAnnotationsMap;
//list of ignored namespaces during XmlLoad
List<Uri> _ignoredNamespaces = new List<Uri>();
//XmlCompatibilityReader - we need to hold that one open, so the underlying stream stays open too
// if the store is disposed the reader will be disposed and the stream will be closed too.
XmlCompatibilityReader _xmlCompatibilityReader;
///
///Static fields
///
//predefined namespaces
private static readonly Dictionary<Uri, IList<Uri>> _predefinedNamespaces;
// Serializer for Annotations
private static readonly Serializer _serializer = new Serializer(typeof(Annotation));
#endregion Private Fields
}
}
| |
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using SIL.IO;
using System.Drawing;
using System;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Xml;
using Bloom.Collection;
using Bloom.ImageProcessing;
using Bloom.web;
using BloomTemp;
using SIL.Progress;
using SIL.Windows.Forms.ImageToolbox;
using SIL.Xml;
namespace Bloom.Book
{
public class BookCompressor
{
public const string ExtensionForDeviceBloomBook = ".bloomd";
// these image files may need to be reduced before being stored in the compressed output file
internal static readonly string[] ImageFileExtensions = { ".tif", ".tiff", ".png", ".bmp", ".jpg", ".jpeg" };
// these files (if encountered) won't be included in the compressed version
internal static readonly string[] ExcludedFileExtensionsLowerCase = { ".db", ".pdf", ".bloompack", ".bak", ".userprefs", ".wav", ".bloombookorder" };
public static void CompressBookForDevice(string outputPath, Book book, BookServer bookServer, Color backColor, IWebSocketProgress progress)
{
using(var temp = new TemporaryFolder())
{
var modifiedBook = BloomReaderFileMaker.PrepareBookForBloomReader(book, bookServer, temp, backColor, progress);
// We want at least 256 for Bloom Reader, because the screens have a high pixel density. And (at the moment) we are asking for
// 64dp in Bloom Reader.
MakeSizedThumbnail(modifiedBook, backColor, temp.FolderPath, 256);
CompressDirectory(outputPath, modifiedBook.FolderPath, "", reduceImages: true, omitMetaJson: false, wrapWithFolder: false,
pathToFileForSha: BookStorage.FindBookHtmlInFolder(book.FolderPath));
}
}
private static void MakeSizedThumbnail(Book book, Color backColor, string destinationFolder, int heightAndWidth)
{
var coverImagePath = book.GetCoverImagePath();
if(coverImagePath != null)
{
var thumbPath = Path.Combine(destinationFolder, "thumbnail.png");
RuntimeImageProcessor.GenerateEBookThumbnail(coverImagePath, thumbPath, heightAndWidth, heightAndWidth, backColor);
}
// else, BR shows a default thumbnail for the book
}
public static Book MakeDeviceXmatterTempBook(Book book, BookServer bookServer, string tempFolderPath)
{
BookStorage.CopyDirectory(book.FolderPath, tempFolderPath);
var bookInfo = new BookInfo(tempFolderPath, true);
bookInfo.XMatterNameOverride = "Device";
var modifiedBook = bookServer.GetBookFromBookInfo(bookInfo);
modifiedBook.BringBookUpToDate(new NullProgress());
modifiedBook.AdjustCollectionStylesToBookFolder();
modifiedBook.Save();
modifiedBook.Storage.UpdateSupportFiles();
// Copy the possibly modified stylesheets after UpdateSupportFiles so that they don't
// get replaced by the factory versions.
BookStorage.CopyCollectionStyles(book.FolderPath, tempFolderPath);
return modifiedBook;
}
public static void CompressDirectory(string outputPath, string directoryToCompress, string dirNamePrefix,
bool forReaderTools = false, bool excludeAudio = false, bool reduceImages = false, bool omitMetaJson = false, bool wrapWithFolder = true,
string pathToFileForSha = null)
{
using (var fsOut = RobustFile.Create(outputPath))
{
using (var zipStream = new ZipOutputStream(fsOut))
{
zipStream.SetLevel(9);
int dirNameOffset;
if (wrapWithFolder)
{
// zip entry names will start with the compressed folder name (zip will contain the
// compressed folder as a folder...we do this in bloompacks, not sure why).
var rootName = Path.GetFileName(directoryToCompress);
dirNameOffset = directoryToCompress.Length - rootName.Length;
}
else
{
// zip entry names will start with the files or directories at the root of the book folder
// (zip root will contain the folder contents...suitable for compressing a single book into
// a zip, as with .bloomd files)
dirNameOffset = directoryToCompress.Length + 1;
}
CompressDirectory(directoryToCompress, zipStream, dirNameOffset, dirNamePrefix, forReaderTools, excludeAudio, reduceImages, omitMetaJson, pathToFileForSha);
zipStream.IsStreamOwner = true; // makes the Close() also close the underlying stream
zipStream.Close();
}
}
}
/// <summary>
/// Adds a directory, along with all files and subdirectories, to the ZipStream.
/// </summary>
/// <param name="directoryToCompress">The directory to add recursively</param>
/// <param name="zipStream">The ZipStream to which the files and directories will be added</param>
/// <param name="dirNameOffset">This number of characters will be removed from the full directory or file name
/// before creating the zip entry name</param>
/// <param name="dirNamePrefix">string to prefix to the zip entry name</param>
/// <param name="forReaderTools">If True, then some pre-processing will be done to the contents of decodable
/// and leveled readers before they are added to the ZipStream</param>
/// <param name="excludeAudio">If true, the contents of the audio directory will not be included</param>
/// <param name="reduceImages">If true, images will be compressed before being added to the zip file</param>
/// <param name="omitMetaJson">If true, meta.json is excluded (typically for HTML readers).</param>
/// <para> name="reduceImages">If true, image files are reduced in size to no larger than 300x300 before saving</para>
/// <remarks>Protected for testing purposes</remarks>
private static void CompressDirectory(string directoryToCompress, ZipOutputStream zipStream, int dirNameOffset, string dirNamePrefix,
bool forReaderTools, bool excludeAudio, bool reduceImages, bool omitMetaJson = false, string pathToFileForSha = null)
{
if (excludeAudio && Path.GetFileName(directoryToCompress).ToLowerInvariant() == "audio")
return;
var files = Directory.GetFiles(directoryToCompress);
var bookFile = BookStorage.FindBookHtmlInFolder(directoryToCompress);
foreach (var filePath in files)
{
if (ExcludedFileExtensionsLowerCase.Contains(Path.GetExtension(filePath.ToLowerInvariant())))
continue; // BL-2246: skip putting this one into the BloomPack
var fileName = Path.GetFileName(filePath).ToLowerInvariant();
if (fileName.StartsWith(BookStorage.PrefixForCorruptHtmFiles))
continue;
// Various stuff we keep in the book folder that is useful for editing or bloom library
// or displaying collections but not needed by the reader. The most important is probably
// eliminating the pdf, which can be very large. Note that we do NOT eliminate the
// basic thumbnail.png, as we want eventually to extract that to use in the Reader UI.
if (fileName == "thumbnail-70.png" || fileName == "thumbnail-256.png")
continue;
if (fileName == "meta.json" && omitMetaJson)
continue;
FileInfo fi = new FileInfo(filePath);
var entryName = dirNamePrefix + filePath.Substring(dirNameOffset); // Makes the name in zip based on the folder
entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
ZipEntry newEntry = new ZipEntry(entryName)
{
DateTime = fi.LastWriteTime,
IsUnicodeText = true
};
// encode filename and comment in UTF8
byte[] modifiedContent = {};
// if this is a ReaderTools book, call GetBookReplacedWithTemplate() to get the contents
if (forReaderTools && (bookFile == filePath))
{
modifiedContent = Encoding.UTF8.GetBytes(GetBookReplacedWithTemplate(filePath));
newEntry.Size = modifiedContent.Length;
}
else if (forReaderTools && (Path.GetFileName(filePath) == "meta.json"))
{
modifiedContent = Encoding.UTF8.GetBytes(GetMetaJsonModfiedForTemplate(filePath));
newEntry.Size = modifiedContent.Length;
}
else if (reduceImages && ImageFileExtensions.Contains(Path.GetExtension(filePath.ToLowerInvariant())))
{
modifiedContent = GetBytesOfReducedImage(filePath);
newEntry.Size = modifiedContent.Length;
}
else if (reduceImages && (bookFile == filePath))
{
var originalContent = File.ReadAllText(bookFile, Encoding.UTF8);
var dom = XmlHtmlConverter.GetXmlDomFromHtml(originalContent);
StripImagesWithMissingSrc(dom, bookFile);
StripContentEditable(dom);
InsertReaderStylesheet(dom);
ConvertImagesToBackground(dom);
var newContent = XmlHtmlConverter.ConvertDomToHtml5(dom);
modifiedContent = Encoding.UTF8.GetBytes(newContent);
newEntry.Size = modifiedContent.Length;
if (pathToFileForSha != null)
{
// Make an extra entry containing the sha
var sha = Book.MakeVersionCode(File.ReadAllText(pathToFileForSha, Encoding.UTF8), pathToFileForSha);
var name = "version.txt"; // must match what BloomReader is looking for in NewBookListenerService.IsBookUpToDate()
MakeExtraEntry(zipStream, name, sha);
}
MakeExtraEntry(zipStream, "readerStyles.css",
File.ReadAllText(FileLocator.GetFileDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot,"publish","android","readerStyles.css"))));
}
else
{
newEntry.Size = fi.Length;
}
zipStream.PutNextEntry(newEntry);
if (modifiedContent.Length > 0)
{
using (var memStream = new MemoryStream(modifiedContent))
{
// There is some minimum buffer size (44 was too small); I don't know exactly what it is,
// but 1024 makes it happy.
StreamUtils.Copy(memStream, zipStream, new byte[Math.Max(modifiedContent.Length, 1024)]);
}
}
else
{
// Zip the file in buffered chunks
byte[] buffer = new byte[4096];
using (var streamReader = RobustFile.OpenRead(filePath))
{
StreamUtils.Copy(streamReader, zipStream, buffer);
}
}
zipStream.CloseEntry();
}
var folders = Directory.GetDirectories(directoryToCompress);
foreach (var folder in folders)
{
var dirName = Path.GetFileName(folder);
if ((dirName == null) || (dirName.ToLowerInvariant() == "sample texts"))
continue; // Don't want to bundle these up
CompressDirectory(folder, zipStream, dirNameOffset, dirNamePrefix, forReaderTools, excludeAudio, reduceImages);
}
}
private static void MakeExtraEntry(ZipOutputStream zipStream, string name, string content)
{
ZipEntry entry = new ZipEntry(name);
var shaBytes = Encoding.UTF8.GetBytes(content);
entry.Size = shaBytes.Length;
zipStream.PutNextEntry(entry);
using (var memStream = new MemoryStream(shaBytes))
{
StreamUtils.Copy(memStream, zipStream, new byte[1024]);
}
zipStream.CloseEntry();
}
private static void StripImagesWithMissingSrc(XmlDocument dom, string bookFile)
{
var folderPath = Path.GetDirectoryName(bookFile);
foreach (var imgElt in dom.SafeSelectNodes("//img[@src]").Cast<XmlElement>().ToArray())
{
var file = UrlPathString.CreateFromUrlEncodedString(imgElt.Attributes["src"].Value).NotEncoded.Split('?')[0];
if (!File.Exists(Path.Combine(folderPath, file)))
{
imgElt.ParentNode.RemoveChild(imgElt);
}
}
}
private static void StripContentEditable(XmlDocument dom)
{
foreach (var editableElt in dom.SafeSelectNodes("//div[@contenteditable]").Cast<XmlElement>().ToArray())
{
editableElt.RemoveAttribute("contenteditable");
}
}
/// <summary>
/// Find every place in the html file where an img element is nested inside a div with class bloom-imageContainer.
/// Convert the img into a background image of the image container div.
/// Specifically, make the following changes:
/// - Copy any data-x attributes from the img element to the div
/// - Convert the src attribute of the img to style="background-image:url('...')" (with the same source) on the div
/// (any pre-existing style attribute on the div is lost)
/// - Add the class bloom-backgroundImage to the div
/// - delete the img element
/// (See oldImg and newImg in unit test CompressBookForDevice_ImgInImgContainer_ConvertedToBackground for an example).
/// </summary>
/// <param name="wholeBookHtml"></param>
/// <returns></returns>
private static void ConvertImagesToBackground(XmlDocument dom)
{
foreach (var imgContainer in dom.SafeSelectNodes("//div[contains(@class, 'bloom-imageContainer')]").Cast<XmlElement>().ToArray())
{
var img = imgContainer.ChildNodes.Cast<XmlNode>().FirstOrDefault(n => n is XmlElement && n.Name == "img");
if (img == null || img.Attributes["src"] == null)
continue;
// The filename should be already urlencoded since src is a url.
var src = img.Attributes["src"].Value;
HtmlDom.SetImageElementUrl(new ElementProxy(imgContainer), UrlPathString.CreateFromUrlEncodedString(src));
foreach (XmlAttribute attr in img.Attributes)
{
if (attr.Name.StartsWith("data-"))
imgContainer.SetAttribute(attr.Name, attr.Value);
}
imgContainer.SetAttribute("class", imgContainer.Attributes["class"].Value + " bloom-backgroundImage");
imgContainer.RemoveChild(img);
}
}
private static string GetMetaJsonModfiedForTemplate(string path)
{
var meta = BookMetaData.FromString(RobustFile.ReadAllText(path));
meta.IsSuitableForMakingShells = true;
return meta.Json;
}
private static void InsertReaderStylesheet(XmlDocument dom)
{
var link = dom.CreateElement("link");
XmlUtils.GetOrCreateElement(dom, "html", "head").AppendChild(link);
link.SetAttribute("rel", "stylesheet");
link.SetAttribute("href", "readerStyles.css");
link.SetAttribute("type", "text/css");
}
/// <summary>
/// Does some pre-processing on reader files
/// </summary>
/// <param name="bookPath"></param>
private static string GetBookReplacedWithTemplate(string bookPath)
{
//TODO: the following, which is the original code before late in 3.6, just modified the tags in the HTML
//Whereas currently, we use the meta.json as the authoritative source.
//TODO Should we just get rid of these tags in the HTML? Can they be accessed from javascript? If so,
//then they will be needed eventually (as we involve c# less in the UI)
var text = RobustFile.ReadAllText(bookPath, Encoding.UTF8);
// Note that we're getting rid of preceding newline but not following one. Hopefully we cleanly remove a whole line.
// I'm not sure the </meta> ever occurs in html files, but just in case we'll match if present.
var regex = new Regex("\\s*<meta\\s+name=(['\\\"])lockedDownAsShell\\1 content=(['\\\"])true\\2>(</meta>)? *");
var match = regex.Match(text);
if (match.Success)
text = text.Substring(0, match.Index) + text.Substring(match.Index + match.Length);
// BL-2476: Readers made from BloomPacks should have the formatting dialog disabled
regex = new Regex("\\s*<meta\\s+name=(['\\\"])pageTemplateSource\\1 content=(['\\\"])(Leveled|Decodable) Reader\\2>(</meta>)? *");
match = regex.Match(text);
if (match.Success)
{
// has the lockFormatting meta tag been added already?
var regexSuppress = new Regex("\\s*<meta\\s+name=(['\\\"])lockFormatting\\1 content=(['\\\"])(.*)\\2>(</meta>)? *");
var matchSuppress = regexSuppress.Match(text);
if (matchSuppress.Success)
{
// the meta tag already exists, make sure the value is "true"
if (matchSuppress.Groups[3].Value.ToLower() != "true")
{
text = text.Substring(0, matchSuppress.Groups[3].Index) + "true"
+ text.Substring(matchSuppress.Groups[3].Index + matchSuppress.Groups[3].Length);
}
}
else
{
// the meta tag has not been added, add it now
text = text.Insert(match.Index + match.Length,
"\r\n <meta name=\"lockFormatting\" content=\"true\"></meta>");
}
}
return text;
}
// See discussion in BL-5385
private const int kMaxWidth = 600;
private const int kMaxHeight = 600;
/// <summary>
/// For electronic books, we want to minimize the actual size of images since they'll
/// be displayed on small screens anyway. So before zipping up the file, we replace its
/// bytes with the bytes of a reduced copy of itself. If the original image is already
/// small enough, we return its bytes directly.
/// We also make png images have transparent backgrounds. This is currently only necessary
/// for cover pages, but it's an additional complication to detect which those are,
/// and doesn't seem likely to cost much extra to do.
/// </summary>
/// <returns>The bytes of the (possibly) reduced image.</returns>
internal static byte[] GetBytesOfReducedImage(string filePath)
{
using (var originalImage = PalasoImage.FromFileRobustly(filePath))
{
var image = originalImage.Image;
int originalWidth = image.Width;
int originalHeight = image.Height;
var appearsToBeJpeg = ImageUtils.AppearsToBeJpeg(originalImage);
if (originalWidth > kMaxWidth || originalHeight > kMaxHeight || !appearsToBeJpeg)
{
// Preserve the aspect ratio
float scaleX = (float)kMaxWidth / (float)originalWidth;
float scaleY = (float)kMaxHeight / (float)originalHeight;
// no point in ever expanding, even if we're making a new image just for transparency.
float scale = Math.Min(1.0f, Math.Min(scaleX, scaleY));
// New width and height maintaining the aspect ratio
int newWidth = (int)(originalWidth * scale);
int newHeight = (int)(originalHeight * scale);
var imagePixelFormat = image.PixelFormat;
switch (imagePixelFormat)
{
// These three formats are not supported for bitmaps to be drawn on using Graphics.FromImage.
// So use the default bitmap format.
// Enhance: if these are common it may be worth research to find out whether there are better options.
// - possibly the 'reduced' image might not be reduced...even though smaller, the indexed format
// might be so much more efficient that it is smaller. However, even if that is true, it doesn't
// necessarily follow that it takes less memory to render on the device. So it's not obvious that
// we should keep the original just because it's a smaller file.
// - possibly we don't need a 32-bit bitmap? Unfortunately the 1bpp/4bpp/8bpp only tells us
// that the image uses two, 16, or 256 distinct colors, not what they are or what precision they have.
case PixelFormat.Format1bppIndexed:
case PixelFormat.Format4bppIndexed:
case PixelFormat.Format8bppIndexed:
imagePixelFormat = PixelFormat.Format32bppArgb;
break;
}
// OTOH, always using 32-bit format for .png files keeps us from having problems in BloomReader
// like BL-5740 (where 24bit format files came out in BR with black backgrounds).
if (!appearsToBeJpeg)
imagePixelFormat = PixelFormat.Format32bppArgb;
using (var newImage = new Bitmap(newWidth, newHeight, imagePixelFormat))
{
// Draws the image in the specified size with quality mode set to HighQuality
using (Graphics graphics = Graphics.FromImage(newImage))
{
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
using (var imageAttributes = new ImageAttributes())
{
// See https://stackoverflow.com/a/11850971/7442826
// Fixes the 50% gray border issue on bright white or dark images
imageAttributes.SetWrapMode(WrapMode.TileFlipXY);
// In addition to possibly scaling, we want PNG images to have transparent backgrounds.
if (!appearsToBeJpeg)
{
// This specifies that all white or very-near-white pixels (all color components at least 253/255)
// will be made transparent.
imageAttributes.SetColorKey(Color.FromArgb(253, 253, 253), Color.White);
}
var destRect = new Rectangle(0, 0, newWidth, newHeight);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height,
GraphicsUnit.Pixel, imageAttributes);
}
}
// Save the file in the same format as the original, and return its bytes.
using (var tempFile = TempFile.WithExtension(Path.GetExtension(filePath)))
{
// This uses default quality settings for jpgs...one site says this is
// 75 quality on a scale that runs from 0-100. For most images, this
// should give a quality barely distinguishable from uncompressed and still save
// about 7/8 of the file size. Lower quality settings rapidly lose quality
// while only saving a little space; higher ones rapidly use more space
// with only marginal quality improvement.
// See https://photo.stackexchange.com/questions/30243/what-quality-to-choose-when-converting-to-jpg
// for more on quality and https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-set-jpeg-compression-level
// for how to control the quality setting if we decide to (RobustImageIO has
// suitable overloads).
RobustImageIO.SaveImage(newImage, tempFile.Path, image.RawFormat);
// Copy the metadata from the original file to the new file.
var metadata = SIL.Windows.Forms.ClearShare.Metadata.FromFile(filePath);
if (!metadata.IsEmpty)
metadata.Write(tempFile.Path);
return RobustFile.ReadAllBytes(tempFile.Path);
}
}
}
}
return RobustFile.ReadAllBytes(filePath);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Abstract base class for all Streams. Provides
** default implementations of asynchronous reads & writes, in
** terms of the synchronous reads & writes (and vice versa).
**
**
===========================================================*/
using System.Buffers;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
public abstract partial class Stream : MarshalByRefObject, IDisposable, IAsyncDisposable
{
public static readonly Stream Null = new NullStream();
// We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
// The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
// improvement in Copy performance.
private const int DefaultCopyBufferSize = 81920;
// To implement Async IO operations on streams that don't support async IO
private ReadWriteTask? _activeReadWriteTask;
private SemaphoreSlim? _asyncActiveSemaphore;
internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
// Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
// WaitHandle, we don't need to worry about Disposing it.
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
public abstract bool CanRead
{
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public abstract bool CanSeek
{
get;
}
public virtual bool CanTimeout => false;
public abstract bool CanWrite
{
get;
}
public abstract long Length
{
get;
}
public abstract long Position
{
get;
set;
}
public virtual int ReadTimeout
{
get => throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
set => throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
public virtual int WriteTimeout
{
get => throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
set => throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
public Task CopyToAsync(Stream destination)
{
int bufferSize = GetCopyBufferSize();
return CopyToAsync(destination, bufferSize);
}
public Task CopyToAsync(Stream destination, int bufferSize)
{
return CopyToAsync(destination, bufferSize, CancellationToken.None);
}
public Task CopyToAsync(Stream destination, CancellationToken cancellationToken)
{
int bufferSize = GetCopyBufferSize();
return CopyToAsync(destination, bufferSize, cancellationToken);
}
public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncInternal(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
while (true)
{
int bytesRead = await ReadAsync(new Memory<byte>(buffer), cancellationToken).ConfigureAwait(false);
if (bytesRead == 0) break;
await destination.WriteAsync(new ReadOnlyMemory<byte>(buffer, 0, bytesRead), cancellationToken).ConfigureAwait(false);
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
// Reads the bytes from the current stream and writes the bytes to
// the destination stream until all bytes are read, starting at
// the current position.
public void CopyTo(Stream destination)
{
int bufferSize = GetCopyBufferSize();
CopyTo(destination, bufferSize);
}
public virtual void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
int read;
while ((read = Read(buffer, 0, buffer.Length)) != 0)
{
destination.Write(buffer, 0, read);
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
private int GetCopyBufferSize()
{
int bufferSize = DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// There are no bytes left in the stream to copy.
// However, because CopyTo{Async} is virtual, we need to
// ensure that any override is still invoked to provide its
// own validation, so we use the smallest legal buffer size here.
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0)
{
// In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
}
return bufferSize;
}
// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable. However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern. We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup now.
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Close();
}
protected virtual void Dispose(bool disposing)
{
// Note: Never change this to call other virtual methods on Stream
// like Write, since the state on subclasses has already been
// torn down. This is the last code to run on cleanup for a stream.
}
public virtual ValueTask DisposeAsync()
{
try
{
Dispose();
return default;
}
catch (Exception exc)
{
return new ValueTask(Task.FromException(exc));
}
}
public abstract void Flush();
public Task FlushAsync()
{
return FlushAsync(CancellationToken.None);
}
public virtual Task FlushAsync(CancellationToken cancellationToken)
{
return Task.Factory.StartNew(state => ((Stream)state!).Flush(), this,
cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")]
protected virtual WaitHandle CreateWaitHandle()
{
return new ManualResetEvent(false);
}
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object? state)
{
return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
internal IAsyncResult BeginReadInternal(
byte[] buffer, int offset, int count, AsyncCallback? callback, object? state,
bool serializeAsynchronously, bool apm)
{
if (!CanRead) throw Error.GetReadNotSupported();
// To avoid a race with a stream's position pointer & generating race conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
SemaphoreSlim semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task? semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync();
}
else
{
semaphore.Wait();
}
// Create the task to asynchronously do a Read. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(true /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Read.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Debug.Assert(thisTask != null && thisTask._stream != null && thisTask._buffer != null,
"Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask, and stream and buffer should be set");
try
{
// Do the Read and return the number of bytes read
return thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count);
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
public virtual int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
ReadWriteTask? readTask = _activeReadWriteTask;
if (readTask == null)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (readTask != asyncResult)
{
throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (!readTask._isRead)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
try
{
return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception
}
finally
{
FinishTrackingAsyncOperation();
}
}
public Task<int> ReadAsync(byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled<int>(cancellationToken)
: BeginEndReadAsync(buffer, offset, count);
}
public virtual ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array))
{
return new ValueTask<int>(ReadAsync(array.Array!, array.Offset, array.Count, cancellationToken));
}
else
{
byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
return FinishReadAsync(ReadAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer, buffer);
static async ValueTask<int> FinishReadAsync(Task<int> readTask, byte[] localBuffer, Memory<byte> localDestination)
{
try
{
int result = await readTask.ConfigureAwait(false);
new Span<byte>(localBuffer, 0, result).CopyTo(localDestination.Span);
return result;
}
finally
{
ArrayPool<byte>.Shared.Return(localBuffer);
}
}
}
}
private Task<int> BeginEndReadAsync(byte[] buffer, int offset, int count)
{
if (!HasOverriddenBeginEndRead())
{
// If the Stream does not override Begin/EndRead, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task<int>)BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<int>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler
}
private struct ReadWriteParameters // struct for arguments to Read and Write calls
{
internal byte[] Buffer;
internal int Offset;
internal int Count;
}
public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object? state)
{
return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
internal IAsyncResult BeginWriteInternal(
byte[] buffer, int offset, int count, AsyncCallback? callback, object? state,
bool serializeAsynchronously, bool apm)
{
if (!CanWrite) throw Error.GetWriteNotSupported();
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
SemaphoreSlim semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task? semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block
}
else
{
semaphore.Wait(); // synchronously wait here
}
// Create the task to asynchronously do a Write. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(false /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Write.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Debug.Assert(thisTask != null && thisTask._stream != null && thisTask._buffer != null,
"Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask, and stream and buffer should be set");
try
{
// Do the Write
thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count);
return 0; // not used, but signature requires a value be returned
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
{
Debug.Assert(readWriteTask != null);
Debug.Assert(asyncWaiter != null);
// If the wait has already completed, run the task.
if (asyncWaiter.IsCompleted)
{
Debug.Assert(asyncWaiter.IsCompletedSuccessfully, "The semaphore wait should always complete successfully.");
RunReadWriteTask(readWriteTask);
}
else // Otherwise, wait for our turn, and then run the task.
{
asyncWaiter.ContinueWith((t, state) =>
{
Debug.Assert(t.IsCompletedSuccessfully, "The semaphore wait should always complete successfully.");
var rwt = (ReadWriteTask)state!;
Debug.Assert(rwt._stream != null);
rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
}, readWriteTask, default, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
}
private void RunReadWriteTask(ReadWriteTask readWriteTask)
{
Debug.Assert(readWriteTask != null);
Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
// Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race.
// Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding
// two interlocked operations. However, if ReadWriteTask is ever changed to use
// a cancellation token, this should be changed to use Start.
_activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one
readWriteTask.m_taskScheduler = TaskScheduler.Default;
readWriteTask.ScheduleAndStart(needsProtection: false);
}
private void FinishTrackingAsyncOperation()
{
_activeReadWriteTask = null;
Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
public virtual void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
ReadWriteTask? writeTask = _activeReadWriteTask;
if (writeTask == null)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask != asyncResult)
{
throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask._isRead)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
try
{
writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion);
}
finally
{
FinishTrackingAsyncOperation();
}
}
// Task used by BeginRead / BeginWrite to do Read / Write asynchronously.
// A single instance of this task serves four purposes:
// 1. The work item scheduled to run the Read / Write operation
// 2. The state holding the arguments to be passed to Read / Write
// 3. The IAsyncResult returned from BeginRead / BeginWrite
// 4. The completion action that runs to invoke the user-provided callback.
// This last item is a bit tricky. Before the AsyncCallback is invoked, the
// IAsyncResult must have completed, so we can't just invoke the handler
// from within the task, since it is the IAsyncResult, and thus it's not
// yet completed. Instead, we use AddCompletionAction to install this
// task as its own completion handler. That saves the need to allocate
// a separate completion handler, it guarantees that the task will
// have completed by the time the handler is invoked, and it allows
// the handler to be invoked synchronously upon the completion of the
// task. This all enables BeginRead / BeginWrite to be implemented
// with a single allocation.
private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction
{
internal readonly bool _isRead;
internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync
internal Stream? _stream;
internal byte[]? _buffer;
internal readonly int _offset;
internal readonly int _count;
private AsyncCallback? _callback;
private ExecutionContext? _context;
internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC
{
_stream = null;
_buffer = null;
}
public ReadWriteTask(
bool isRead,
bool apm,
Func<object?, int> function, object? state,
Stream stream, byte[] buffer, int offset, int count, AsyncCallback? callback) :
base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach)
{
Debug.Assert(function != null);
Debug.Assert(stream != null);
Debug.Assert(buffer != null);
// Store the arguments
_isRead = isRead;
_apm = apm;
_stream = stream;
_buffer = buffer;
_offset = offset;
_count = count;
// If a callback was provided, we need to:
// - Store the user-provided handler
// - Capture an ExecutionContext under which to invoke the handler
// - Add this task as its own completion handler so that the Invoke method
// will run the callback when this task completes.
if (callback != null)
{
_callback = callback;
_context = ExecutionContext.Capture();
base.AddCompletionAction(this);
}
}
private static void InvokeAsyncCallback(object? completedTask)
{
Debug.Assert(completedTask is ReadWriteTask);
var rwc = (ReadWriteTask)completedTask;
AsyncCallback? callback = rwc._callback;
Debug.Assert(callback != null);
rwc._callback = null;
callback(rwc);
}
private static ContextCallback? s_invokeAsyncCallback;
void ITaskCompletionAction.Invoke(Task completingTask)
{
// Get the ExecutionContext. If there is none, just run the callback
// directly, passing in the completed task as the IAsyncResult.
// If there is one, process it with ExecutionContext.Run.
ExecutionContext? context = _context;
if (context == null)
{
AsyncCallback? callback = _callback;
Debug.Assert(callback != null);
_callback = null;
callback(completingTask);
}
else
{
_context = null;
ContextCallback? invokeAsyncCallback = s_invokeAsyncCallback ??= InvokeAsyncCallback;
ExecutionContext.RunInternal(context, invokeAsyncCallback, this);
}
}
bool ITaskCompletionAction.InvokeMayRunArbitraryCode => true;
}
public Task WriteAsync(byte[] buffer, int offset, int count)
{
return WriteAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: BeginEndWriteAsync(buffer, offset, count);
}
public virtual ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array))
{
return new ValueTask(WriteAsync(array.Array!, array.Offset, array.Count, cancellationToken));
}
else
{
byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
buffer.Span.CopyTo(sharedBuffer);
return new ValueTask(FinishWriteAsync(WriteAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer));
}
}
private async Task FinishWriteAsync(Task writeTask, byte[] localBuffer)
{
try
{
await writeTask.ConfigureAwait(false);
}
finally
{
ArrayPool<byte>.Shared.Return(localBuffer);
}
}
private Task BeginEndWriteAsync(byte[] buffer, int offset, int count)
{
if (!HasOverriddenBeginEndWrite())
{
// If the Stream does not override Begin/EndWrite, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task)BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<VoidTaskResult>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => // cached by compiler
{
stream.EndWrite(asyncResult);
return default;
});
}
public abstract long Seek(long offset, SeekOrigin origin);
public abstract void SetLength(long value);
public abstract int Read(byte[] buffer, int offset, int count);
public virtual int Read(Span<byte> buffer)
{
byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
try
{
int numRead = Read(sharedBuffer, 0, buffer.Length);
if ((uint)numRead > (uint)buffer.Length)
{
throw new IOException(SR.IO_StreamTooLong);
}
new Span<byte>(sharedBuffer, 0, numRead).CopyTo(buffer);
return numRead;
}
finally { ArrayPool<byte>.Shared.Return(sharedBuffer); }
}
// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
if (r == 0)
return -1;
return oneByteArray[0];
}
public abstract void Write(byte[] buffer, int offset, int count);
public virtual void Write(ReadOnlySpan<byte> buffer)
{
byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
try
{
buffer.CopyTo(sharedBuffer);
Write(sharedBuffer, 0, buffer.Length);
}
finally { ArrayPool<byte>.Shared.Return(sharedBuffer); }
}
// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are writing one byte at a time.
public virtual void WriteByte(byte value)
{
byte[] oneByteArray = new byte[1];
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
public static Stream Synchronized(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (stream is SyncStream)
return stream;
return new SyncStream(stream);
}
[Obsolete("Do not call or override this method.")]
protected virtual void ObjectInvariant()
{
}
internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object? state)
{
// To avoid a race with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try
{
int numRead = Read(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(numRead, state);
}
catch (IOException ex)
{
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false);
}
callback?.Invoke(asyncResult);
return asyncResult;
}
internal static int BlockingEndRead(IAsyncResult asyncResult)
{
return SynchronousAsyncResult.EndRead(asyncResult);
}
internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object? state)
{
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try
{
Write(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(state);
}
catch (IOException ex)
{
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true);
}
callback?.Invoke(asyncResult);
return asyncResult;
}
internal static void BlockingEndWrite(IAsyncResult asyncResult)
{
SynchronousAsyncResult.EndWrite(asyncResult);
}
private sealed class NullStream : Stream
{
private static readonly Task<int> s_zeroTask = Task.FromResult(0);
internal NullStream() { }
public override bool CanRead => true;
public override bool CanWrite => true;
public override bool CanSeek => true;
public override long Length => 0;
public override long Position
{
get => 0;
set { }
}
public override void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// After we validate arguments this is a nop.
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments here for compat, since previously this method
// was inherited from Stream (which did check its arguments).
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
// Do nothing - we don't want NullStream singleton (static) to be closable
}
public override void Flush()
{
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object? state)
{
if (!CanRead) throw Error.GetReadNotSupported();
return BlockingBeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
return BlockingEndRead(asyncResult);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object? state)
{
if (!CanWrite) throw Error.GetWriteNotSupported();
return BlockingBeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
BlockingEndWrite(asyncResult);
}
public override int Read(byte[] buffer, int offset, int count)
{
return 0;
}
public override int Read(Span<byte> buffer)
{
return 0;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return s_zeroTask;
}
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
return new ValueTask<int>(0);
}
public override int ReadByte()
{
return -1;
}
public override void Write(byte[] buffer, int offset, int count)
{
}
public override void Write(ReadOnlySpan<byte> buffer)
{
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
return cancellationToken.IsCancellationRequested ?
new ValueTask(Task.FromCanceled(cancellationToken)) :
default;
}
public override void WriteByte(byte value)
{
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0;
}
public override void SetLength(long length)
{
}
}
/// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary>
private sealed class SynchronousAsyncResult : IAsyncResult
{
private readonly object? _stateObject;
private readonly bool _isWrite;
private ManualResetEvent? _waitHandle;
private readonly ExceptionDispatchInfo? _exceptionInfo;
private bool _endXxxCalled;
private readonly int _bytesRead;
internal SynchronousAsyncResult(int bytesRead, object? asyncStateObject)
{
_bytesRead = bytesRead;
_stateObject = asyncStateObject;
}
internal SynchronousAsyncResult(object? asyncStateObject)
{
_stateObject = asyncStateObject;
_isWrite = true;
}
internal SynchronousAsyncResult(Exception ex, object? asyncStateObject, bool isWrite)
{
_exceptionInfo = ExceptionDispatchInfo.Capture(ex);
_stateObject = asyncStateObject;
_isWrite = isWrite;
}
public bool IsCompleted => true;
public WaitHandle AsyncWaitHandle =>
LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true));
public object? AsyncState => _stateObject;
public bool CompletedSynchronously => true;
internal void ThrowIfError()
{
if (_exceptionInfo != null)
_exceptionInfo.Throw();
}
internal static int EndRead(IAsyncResult asyncResult)
{
if (!(asyncResult is SynchronousAsyncResult ar) || ar._isWrite)
throw new ArgumentException(SR.Arg_WrongAsyncResult);
if (ar._endXxxCalled)
throw new ArgumentException(SR.InvalidOperation_EndReadCalledMultiple);
ar._endXxxCalled = true;
ar.ThrowIfError();
return ar._bytesRead;
}
internal static void EndWrite(IAsyncResult asyncResult)
{
if (!(asyncResult is SynchronousAsyncResult ar) || !ar._isWrite)
throw new ArgumentException(SR.Arg_WrongAsyncResult);
if (ar._endXxxCalled)
throw new ArgumentException(SR.InvalidOperation_EndWriteCalledMultiple);
ar._endXxxCalled = true;
ar.ThrowIfError();
}
} // class SynchronousAsyncResult
// SyncStream is a wrapper around a stream that takes
// a lock for every operation making it thread safe.
private sealed class SyncStream : Stream, IDisposable
{
private readonly Stream _stream;
internal SyncStream(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
_stream = stream;
}
public override bool CanRead => _stream.CanRead;
public override bool CanWrite => _stream.CanWrite;
public override bool CanSeek => _stream.CanSeek;
public override bool CanTimeout => _stream.CanTimeout;
public override long Length
{
get
{
lock (_stream)
{
return _stream.Length;
}
}
}
public override long Position
{
get
{
lock (_stream)
{
return _stream.Position;
}
}
set
{
lock (_stream)
{
_stream.Position = value;
}
}
}
public override int ReadTimeout
{
get => _stream.ReadTimeout;
set => _stream.ReadTimeout = value;
}
public override int WriteTimeout
{
get => _stream.WriteTimeout;
set => _stream.WriteTimeout = value;
}
// In the off chance that some wrapped stream has different
// semantics for Close vs. Dispose, let's preserve that.
public override void Close()
{
lock (_stream)
{
try
{
_stream.Close();
}
finally
{
base.Dispose(true);
}
}
}
protected override void Dispose(bool disposing)
{
lock (_stream)
{
try
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_stream).Dispose();
}
finally
{
base.Dispose(disposing);
}
}
}
public override ValueTask DisposeAsync()
{
lock (_stream)
return _stream.DisposeAsync();
}
public override void Flush()
{
lock (_stream)
_stream.Flush();
}
public override int Read(byte[] bytes, int offset, int count)
{
lock (_stream)
return _stream.Read(bytes, offset, count);
}
public override int Read(Span<byte> buffer)
{
lock (_stream)
return _stream.Read(buffer);
}
public override int ReadByte()
{
lock (_stream)
return _stream.ReadByte();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object? state)
{
#if CORERT
throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251
#else
bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
lock (_stream)
{
// If the Stream does have its own BeginRead implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginRead ?
_stream.BeginRead(buffer, offset, count, callback, state) :
_stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
#endif
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
lock (_stream)
return _stream.EndRead(asyncResult);
}
public override long Seek(long offset, SeekOrigin origin)
{
lock (_stream)
return _stream.Seek(offset, origin);
}
public override void SetLength(long length)
{
lock (_stream)
_stream.SetLength(length);
}
public override void Write(byte[] bytes, int offset, int count)
{
lock (_stream)
_stream.Write(bytes, offset, count);
}
public override void Write(ReadOnlySpan<byte> buffer)
{
lock (_stream)
_stream.Write(buffer);
}
public override void WriteByte(byte b)
{
lock (_stream)
_stream.WriteByte(b);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object? state)
{
#if CORERT
throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251
#else
bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
lock (_stream)
{
// If the Stream does have its own BeginWrite implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginWrite ?
_stream.BeginWrite(buffer, offset, count, callback, state) :
_stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
#endif
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
lock (_stream)
_stream.EndWrite(asyncResult);
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** File: RemotingAttributes.cs
**
** Purpose: Custom attributes for modifying remoting interactions.
**
**
===========================================================*/
namespace System.Runtime.Remoting.Metadata
{
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Metadata;
using System.Reflection;
using System.Threading;
using System.Runtime.Serialization;
using TypeInfo = System.Runtime.Remoting.TypeInfo;
// This is the data we store in MemberInfo.CachedData, mainly to cache custom
// attributes.
internal abstract class RemotingCachedData
{
private SoapAttribute _soapAttr = null; // Soap related attributes derive from SoapAttribute
// Retrieve SOAP attribute info for _mi (or create for caching if not specified)
internal SoapAttribute GetSoapAttribute()
{
if (_soapAttr == null)
{
lock (this)
{
if (_soapAttr == null)
{
_soapAttr = GetSoapAttributeNoLock();
} // if (_soapAttr == null)
} // lock (this)
}
return _soapAttr;
} // GetSoapAttribute
abstract internal SoapAttribute GetSoapAttributeNoLock();
} // class RemotingCachedData
internal class RemotingFieldCachedData : RemotingCachedData
{
private FieldInfo RI; // reflection structure on which this data structure is stored
internal RemotingFieldCachedData(RuntimeFieldInfo ri)
{
RI = ri;
}
internal RemotingFieldCachedData(SerializationFieldInfo ri)
{
RI = ri;
}
// Retrieve SOAP attribute info for _mi (or create for caching if not specified)
internal override SoapAttribute GetSoapAttributeNoLock()
{
SoapAttribute tempSoapAttr = null;
Object[] attrs = RI.GetCustomAttributes(typeof(SoapFieldAttribute), false);
if ((attrs != null) && (attrs.Length != 0))
tempSoapAttr = (SoapAttribute)attrs[0];
else
tempSoapAttr = new SoapFieldAttribute();
// IMPORTANT: This has to be done for certain values to be automatically
// generated in the attribute.
tempSoapAttr.SetReflectInfo(RI);
return tempSoapAttr;
}
}
internal class RemotingParameterCachedData : RemotingCachedData
{
private RuntimeParameterInfo RI; // reflection structure on which this data structure is stored
internal RemotingParameterCachedData(RuntimeParameterInfo ri)
{
RI = ri;
}
internal override SoapAttribute GetSoapAttributeNoLock()
{
SoapAttribute tempSoapAttr = null;
Object[] attrs = RI.GetCustomAttributes(typeof(SoapParameterAttribute), true);
if ((attrs != null) && (attrs.Length != 0))
tempSoapAttr = (SoapParameterAttribute)attrs[0];
else
tempSoapAttr = new SoapParameterAttribute();
// IMPORTANT: This has to be done for certain values to be automatically
// generated in the attribute.
tempSoapAttr.SetReflectInfo(RI);
return tempSoapAttr;
}
}
internal class RemotingTypeCachedData : RemotingCachedData
{
private RuntimeType RI;
private class LastCalledMethodClass
{
public String methodName;
public MethodBase MB;
}
private LastCalledMethodClass _lastMethodCalled; // cache for last method that was called
private TypeInfo _typeInfo; // type info to be used for ObjRef's of this type
private String _qualifiedTypeName;
private String _assemblyName;
private String _simpleAssemblyName; // (no strong name, version, etc.)
internal RemotingTypeCachedData(RuntimeType ri)
{
RI = ri;
}
internal override SoapAttribute GetSoapAttributeNoLock()
{
SoapAttribute tempSoapAttr = null;
Object[] attrs = RI.GetCustomAttributes(typeof(SoapTypeAttribute), true);
if ((attrs != null) && (attrs.Length != 0))
tempSoapAttr = (SoapAttribute)attrs[0];
else
tempSoapAttr = new SoapTypeAttribute();
// IMPORTANT: This has to be done for certain values to be automatically
// generated in the attribute.
tempSoapAttr.SetReflectInfo(RI);
return tempSoapAttr;
}
internal MethodBase GetLastCalledMethod(String newMeth)
{
LastCalledMethodClass lastMeth = _lastMethodCalled;
if (lastMeth == null)
return null;
String methodName = lastMeth.methodName;
MethodBase mbToReturn = lastMeth.MB;
if (mbToReturn==null || methodName==null)
return null;
if (methodName.Equals(newMeth))
return mbToReturn;
return null;
} // GetLastCalledMethod
internal void SetLastCalledMethod(String newMethName, MethodBase newMB)
{
LastCalledMethodClass lastMeth = new LastCalledMethodClass();
lastMeth.methodName = newMethName;
lastMeth.MB = newMB;
_lastMethodCalled = lastMeth;
} // SetLastCalledMethod
// Retrieve TypeInfo object to be used in ObjRef.
internal TypeInfo TypeInfo
{
[System.Security.SecurityCritical] // auto-generated
get
{
if (_typeInfo == null)
_typeInfo = new TypeInfo(RI);
return _typeInfo;
}
} // TypeInfo
internal String QualifiedTypeName
{
[System.Security.SecurityCritical] // auto-generated
get
{
if (_qualifiedTypeName == null)
_qualifiedTypeName = RemotingServices.DetermineDefaultQualifiedTypeName(RI);
return _qualifiedTypeName;
}
} // QualifiedTypeName
internal String AssemblyName
{
get
{
if (_assemblyName == null)
_assemblyName = RI.Module.Assembly.FullName;
return _assemblyName;
}
} // AssemblyName
internal String SimpleAssemblyName
{
[System.Security.SecurityCritical] // auto-generated
get
{
if (_simpleAssemblyName == null)
_simpleAssemblyName = RI.GetRuntimeAssembly().GetSimpleName();
return _simpleAssemblyName;
}
} // SimpleAssemblyName
} // class RemotingTypeCachedData
internal class RemotingMethodCachedData : RemotingCachedData
{
private MethodBase RI;
private ParameterInfo[] _parameters = null; // list of parameters (cached because reflection always
// generates a new copy of this array)
[Serializable]
[Flags]
private enum MethodCacheFlags
{
None = 0x00,
CheckedOneWay = 0x01, // Have we checked for OneWay attribute?
IsOneWay = 0x02, // Is the OneWay attribute present?
CheckedOverloaded = 0x04, // Have we checked to see if this method is overloaded
IsOverloaded = 0x08, // Is the method overloaded?
CheckedForAsync = 0x10, // Have we looked for async versions of this method?
CheckedForReturnType = 0x20, // Have we looked for the return type?
}
private MethodCacheFlags flags;
// Names
private String _typeAndAssemblyName = null;
private String _methodName = null;
private Type _returnType = null; // null if return type is void or .ctor
// parameter maps
// NOTE: these fields are all initialized at the same time however access to
// the internal property of each field is locked only on that specific field
// having been initialized. - [....]
private int[] _inRefArgMap = null; // parameter map of input and ref parameters
private int[] _outRefArgMap = null; // parameter map of out and ref parameters (exactly all byref parameters)
private int[] _outOnlyArgMap = null; // parameter map of only output parameters
private int[] _nonRefOutArgMap = null; // parameter map of non byref parameters marked with [In, Out] (or [Out])
private int[] _marshalRequestMap = null; // map of parameters that should be marshaled in
private int[] _marshalResponseMap = null; // map of parameters that should be marshaled out
internal RemotingMethodCachedData(RuntimeMethodInfo ri)
{
RI = ri;
}
internal RemotingMethodCachedData(RuntimeConstructorInfo ri)
{
RI = ri;
}
internal override SoapAttribute GetSoapAttributeNoLock()
{
SoapAttribute tempSoapAttr = null;
Object[] attrs = RI.GetCustomAttributes(typeof(SoapMethodAttribute), true);
if ((attrs != null) && (attrs.Length != 0))
tempSoapAttr = (SoapAttribute)attrs[0];
else
tempSoapAttr = new SoapMethodAttribute();
// IMPORTANT: This has to be done for certain values to be automatically
// generated in the attribute.
tempSoapAttr.SetReflectInfo(RI);
return tempSoapAttr;
}
internal String TypeAndAssemblyName
{
[System.Security.SecurityCritical] // auto-generated
get
{
if (_typeAndAssemblyName == null)
UpdateNames();
return _typeAndAssemblyName;
}
} // TypeAndAssemblyName
internal String MethodName
{
[System.Security.SecurityCritical] // auto-generated
get
{
if (_methodName == null)
UpdateNames();
return _methodName;
}
} // MethodName
[System.Security.SecurityCritical] // auto-generated
private void UpdateNames()
{
MethodBase mb = RI;
_methodName = mb.Name;
if (mb.DeclaringType != null) {
_typeAndAssemblyName = RemotingServices.GetDefaultQualifiedTypeName((RuntimeType)mb.DeclaringType);
}
} // UpdateNames
internal ParameterInfo[] Parameters
{
get
{
if (_parameters == null)
_parameters = RI.GetParameters();
return _parameters;
}
} // Parameters
// contains index of all byref parameters (marked as "out" or "ref")
internal int[] OutRefArgMap
{
get
{
if (_outRefArgMap == null)
GetArgMaps();
return _outRefArgMap;
}
} // OutRefArgMap
// contains index of parameters marked as out
internal int[] OutOnlyArgMap
{
get
{
if (_outOnlyArgMap == null)
GetArgMaps();
return _outOnlyArgMap;
}
} // OutOnlyArgMap
// contains index of non byref parameters marked with [In, Out]
internal int[] NonRefOutArgMap
{
get
{
if (_nonRefOutArgMap == null)
GetArgMaps();
return _nonRefOutArgMap;
}
} // NonRefOutArgMap
// contains index of parameters that should be marshalled for a request
internal int[] MarshalRequestArgMap
{
get
{
if (_marshalRequestMap == null)
GetArgMaps();
return _marshalRequestMap;
}
} // MarshalRequestMap
// contains index of parameters that should be marshalled for a response
internal int[] MarshalResponseArgMap
{
get
{
if (_marshalResponseMap == null)
GetArgMaps();
return _marshalResponseMap;
}
} // MarshalResponseArgMap
private void GetArgMaps()
{
lock (this)
{
if (_inRefArgMap == null)
{
int[] inRefArgMap = null;
int[] outRefArgMap = null;
int[] outOnlyArgMap = null;
int[] nonRefOutArgMap = null;
int[] marshalRequestMap = null;
int[] marshalResponseMap = null;
ArgMapper.GetParameterMaps(Parameters,
out inRefArgMap, out outRefArgMap, out outOnlyArgMap,
out nonRefOutArgMap,
out marshalRequestMap, out marshalResponseMap);
_inRefArgMap = inRefArgMap;
_outRefArgMap = outRefArgMap;
_outOnlyArgMap = outOnlyArgMap;
_nonRefOutArgMap = nonRefOutArgMap;
_marshalRequestMap = marshalRequestMap;
_marshalResponseMap = marshalResponseMap;
}
}
} // GetArgMaps
internal bool IsOneWayMethod()
{
// We are not protecting against a ----
// If there is a ---- while setting flags
// we will have to compute the result again,
// but we will always return the correct result
//
if ((flags & MethodCacheFlags.CheckedOneWay) == 0)
{
MethodCacheFlags isOneWay = MethodCacheFlags.CheckedOneWay;
Object[] attrs = RI.GetCustomAttributes(typeof(OneWayAttribute), true);
if ((attrs != null) && (attrs.Length > 0))
isOneWay |= MethodCacheFlags.IsOneWay;
flags |= isOneWay;
return (isOneWay & MethodCacheFlags.IsOneWay) != 0;
}
return (flags & MethodCacheFlags.IsOneWay) != 0;
} // IsOneWayMethod
internal bool IsOverloaded()
{
// We are not protecting against a ----
// If there is a ---- while setting flags
// we will have to compute the result again,
// but we will always return the correct result
//
if ((flags & MethodCacheFlags.CheckedOverloaded) == 0)
{
MethodCacheFlags isOverloaded = MethodCacheFlags.CheckedOverloaded;
MethodBase mb = RI;
RuntimeMethodInfo rmi = null;
RuntimeConstructorInfo rci = null;
if ((rmi = mb as RuntimeMethodInfo) != null)
{
if (rmi.IsOverloaded)
isOverloaded |= MethodCacheFlags.IsOverloaded;
}
else if ((rci = mb as RuntimeConstructorInfo) != null)
{
if (rci.IsOverloaded)
isOverloaded |= MethodCacheFlags.IsOverloaded;
}
else
{
throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_Method"));
}
flags |= isOverloaded;
}
return (flags & MethodCacheFlags.IsOverloaded) != 0;
} // IsOverloaded
// This will return the return type of the method, or null
// if the return type is void or this is a .ctor.
internal Type ReturnType
{
get
{
if ((flags & MethodCacheFlags.CheckedForReturnType) == 0)
{
MethodInfo mi = RI as MethodInfo;
if (mi != null)
{
Type returnType = mi.ReturnType;
if (returnType != typeof(void))
_returnType = returnType;
}
flags |= MethodCacheFlags.CheckedForReturnType;
}
return _returnType;
} // get
} // ReturnType
} // class RemotingMethodCachedData
//
// SOAP ATTRIBUTES
//
// Options for use with SoapOptionAttribute (combine with OR to get any combination)
[Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum SoapOption
{
None = 0x0,
AlwaysIncludeTypes = 0x1, // xsi:type always included on SOAP elements
XsdString = 0x2, // xsi:type always included on SOAP elements
EmbedAll = 0x4, // Soap will be generated without references
/// <internalonly/>
Option1 = 0x8, // Option for temporary interop conditions, the use will change over time
/// <internalonly/>
Option2 = 0x10, // Option for temporary interop conditions, the use will change over time
} // SoapOption
/// <internalonly/>
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum XmlFieldOrderOption
{
All,
Sequence,
Choice
} // XmlFieldOrderOption
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SoapTypeAttribute : SoapAttribute
{
// Used to track which values have been explicitly set. Information needed
// by SoapServices.
[Serializable]
[Flags]
private enum ExplicitlySet
{
None = 0x0,
XmlElementName = 0x1,
XmlNamespace = 0x2,
XmlTypeName = 0x4,
XmlTypeNamespace = 0x8
}
private ExplicitlySet _explicitlySet = ExplicitlySet.None;
private SoapOption _SoapOptions = SoapOption.None;
private String _XmlElementName = null;
private String _XmlTypeName = null;
private String _XmlTypeNamespace = null;
private XmlFieldOrderOption _XmlFieldOrder = XmlFieldOrderOption.All;
// Returns true if this attribute specifies interop xml element values.
internal bool IsInteropXmlElement()
{
return (_explicitlySet & (ExplicitlySet.XmlElementName | ExplicitlySet.XmlNamespace)) != 0;
} // IsInteropXmlElement
internal bool IsInteropXmlType()
{
return (_explicitlySet & (ExplicitlySet.XmlTypeName | ExplicitlySet.XmlTypeNamespace)) != 0;
} // IsInteropXmlType
public SoapOption SoapOptions
{
get { return _SoapOptions; }
set { _SoapOptions = value; }
} // SoapOptions
public String XmlElementName
{
get
{
// generate this if it hasn't been set yet
if ((_XmlElementName == null) && (ReflectInfo != null))
_XmlElementName = GetTypeName((Type)ReflectInfo);
return _XmlElementName;
}
set
{
_XmlElementName = value;
_explicitlySet |= ExplicitlySet.XmlElementName;
}
} // XmlElementName
public override String XmlNamespace
{
get
{
// generate this if it hasn't been set
if ((ProtXmlNamespace == null) && (ReflectInfo != null))
{
ProtXmlNamespace = XmlTypeNamespace;
}
return ProtXmlNamespace;
}
set
{
ProtXmlNamespace = value;
_explicitlySet |= ExplicitlySet.XmlNamespace;
}
} // XmlNamespace
public String XmlTypeName // value for xml type name (this should always be valid)
{
get
{
// generate this if it hasn't been set yet
if ((_XmlTypeName == null) && (ReflectInfo != null))
_XmlTypeName = GetTypeName((Type)ReflectInfo);
return _XmlTypeName;
}
set
{
_XmlTypeName = value;
_explicitlySet |= ExplicitlySet.XmlTypeName;
}
} // XmlTypeName
public String XmlTypeNamespace // value for xml type namespace (this should always be valid)
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
// generate this if it hasn't been set yet
if ((_XmlTypeNamespace == null) && (ReflectInfo != null))
{
_XmlTypeNamespace =
XmlNamespaceEncoder.GetXmlNamespaceForTypeNamespace((RuntimeType)ReflectInfo, null);
}
return _XmlTypeNamespace;
}
set
{
_XmlTypeNamespace = value;
_explicitlySet |= ExplicitlySet.XmlTypeNamespace;
}
} // XmlTypeNamespace
/// <internalonly/>
public XmlFieldOrderOption XmlFieldOrder
{
get { return _XmlFieldOrder; }
set { _XmlFieldOrder = value; }
} // XmlFieldOrder
public override bool UseAttribute
{
get { return false; }
set { throw new RemotingException(
Environment.GetResourceString("Remoting_Attribute_UseAttributeNotsettable")); }
} // UseAttribute
private static string GetTypeName(Type t) {
if (t.IsNested) {
string name = t.FullName;
string ns = t.Namespace;
if (ns == null || ns.Length == 0) {
return name;
}
else {
name = name.Substring(ns.Length + 1);
return name;
}
}
return t.Name;
}
} // class SoapTypeAttribute
[AttributeUsage(AttributeTargets.Method)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SoapMethodAttribute : SoapAttribute
{
private String _SoapAction = null;
private String _responseXmlElementName = null;
private String _responseXmlNamespace = null;
private String _returnXmlElementName = null;
private bool _bSoapActionExplicitySet = false; // Needed by SoapServices to determine if
// SoapAction was actually set (otherwise,
// accessing it will return a generated
// value)
internal bool SoapActionExplicitySet { get { return _bSoapActionExplicitySet; } }
public String SoapAction // SoapAction value to place in protocol headers.
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
// generate this if it hasn't been set
if (_SoapAction == null)
{
_SoapAction = XmlTypeNamespaceOfDeclaringType + "#" +
((MemberInfo)ReflectInfo).Name; // This will be the method name.
}
return _SoapAction;
}
set
{
_SoapAction = value;
_bSoapActionExplicitySet = true;
}
}
public override bool UseAttribute
{
get { return false; }
set { throw new RemotingException(
Environment.GetResourceString("Remoting_Attribute_UseAttributeNotsettable")); }
}
public override String XmlNamespace
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
// generate this if it hasn't been set
if (ProtXmlNamespace == null)
{
ProtXmlNamespace = XmlTypeNamespaceOfDeclaringType;
}
return ProtXmlNamespace;
}
set { ProtXmlNamespace = value; }
} // XmlNamespace
public String ResponseXmlElementName
{
get
{
// generate this if it hasn't been set yet
if ((_responseXmlElementName == null) && (ReflectInfo != null))
_responseXmlElementName = ((MemberInfo)ReflectInfo).Name + "Response";
return _responseXmlElementName;
}
set { _responseXmlElementName = value; }
} // ResponseXmlElementName
public String ResponseXmlNamespace
{
get
{
// generate this if it hasn't been set
if (_responseXmlNamespace == null)
_responseXmlNamespace = XmlNamespace;
return _responseXmlNamespace;
}
set { _responseXmlNamespace = value; }
} // ResponseXmlNamespace
public String ReturnXmlElementName
{
get
{
// generate this if it hasn't been set yet
if (_returnXmlElementName == null)
_returnXmlElementName = "return";
return _returnXmlElementName;
}
set { _returnXmlElementName = value; }
} // ReturnXmlElementName
private String XmlTypeNamespaceOfDeclaringType
{
[System.Security.SecurityCritical] // auto-generated
get
{
if (ReflectInfo != null)
{
Type declaringType = ((MemberInfo)ReflectInfo).DeclaringType;
return XmlNamespaceEncoder.GetXmlNamespaceForType((RuntimeType)declaringType, null);
}
else
return null;
}
} // XmlTypeNamespaceOfDeclaringType
} // class SoapMethodAttribute
[AttributeUsage(AttributeTargets.Field)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SoapFieldAttribute : SoapAttribute
{
// Used to track which values have been explicitly set. Information needed
// by SoapServices.
[Serializable]
[Flags]
private enum ExplicitlySet
{
None = 0x0,
XmlElementName = 0x1
}
private ExplicitlySet _explicitlySet = ExplicitlySet.None;
private String _xmlElementName = null;
private int _order; // order in which fields should be serialized
// (if Sequence is specified on containing type's SoapTypeAttribute
// Returns true if this attribute specifies interop xml element values.
public bool IsInteropXmlElement()
{
return (_explicitlySet & ExplicitlySet.XmlElementName) != 0;
} // GetInteropXmlElement
public String XmlElementName
{
get
{
// generate this if it hasn't been set yet
if ((_xmlElementName == null) && (ReflectInfo != null))
_xmlElementName = ((FieldInfo)ReflectInfo).Name;
return _xmlElementName;
}
set
{
_xmlElementName = value;
_explicitlySet |= ExplicitlySet.XmlElementName;
}
} // XmlElementName
/// <internalonly/>
public int Order
{
get { return _order; }
set { _order = value; }
}
} // class SoapFieldAttribute
[AttributeUsage(AttributeTargets.Parameter)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SoapParameterAttribute : SoapAttribute
{
} // SoapParameterAttribute
// Not actually used as an attribute (just the base for the rest of them)
[System.Runtime.InteropServices.ComVisible(true)]
public class SoapAttribute : Attribute
{
/// <internalonly/>
protected String ProtXmlNamespace = null;
private bool _bUseAttribute = false;
private bool _bEmbedded = false;
/// <internalonly/>
protected Object ReflectInfo = null; // Reflection structure on which this attribute was defined
// IMPORTANT: The caching mechanism is required to set this value before
// handing back a SoapAttribute, so that certain values can be automatically
// generated.
internal void SetReflectInfo(Object info)
{
ReflectInfo = info;
}
public virtual String XmlNamespace // If this returns null, then this shouldn't be namespace qualified.
{
get { return ProtXmlNamespace; }
set { ProtXmlNamespace = value; }
}
public virtual bool UseAttribute
{
get { return _bUseAttribute; }
set { _bUseAttribute = value; }
}
public virtual bool Embedded // Determines if type should be nested when serializing for SOAP.
{
get { return _bEmbedded; }
set { _bEmbedded = value; }
}
} // class SoapAttribute
//
// END OF SOAP ATTRIBUTES
//
} // namespace System.Runtime.Remoting
| |
// ----------------------------------------------------------------------------------
//
// 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 AutoMapper;
using Microsoft.Azure.Commands.Network.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Microsoft.Azure.Management.Network;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using MNM = Microsoft.Azure.Management.Network.Models;
namespace Microsoft.Azure.Commands.Network
{
[Cmdlet(VerbsCommon.New, "AzureRmVirtualNetworkGateway", SupportsShouldProcess = true),
OutputType(typeof(PSVirtualNetworkGateway))]
public class NewAzureVirtualNetworkGatewayCommand : VirtualNetworkGatewayBaseCmdlet
{
[Alias("ResourceName")]
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource name.")]
[ValidateNotNullOrEmpty]
public virtual string Name { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ValidateNotNullOrEmpty]
public virtual string ResourceGroupName { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "location.")]
[ValidateNotNullOrEmpty]
public string Location { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The IpConfigurations for Virtual network gateway.")]
[ValidateNotNullOrEmpty]
public List<PSVirtualNetworkGatewayIpConfiguration> IpConfigurations { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The type of this virtual network gateway: Vpn, ExoressRoute")]
[ValidateSet(
MNM.VirtualNetworkGatewayType.Vpn,
MNM.VirtualNetworkGatewayType.ExpressRoute,
IgnoreCase = true)]
public string GatewayType { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The type of the Vpn:PolicyBased/RouteBased")]
[ValidateSet(
MNM.VpnType.PolicyBased,
MNM.VpnType.RouteBased,
IgnoreCase = true)]
public string VpnType { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "EnableBgp Flag")]
public bool EnableBgp { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Active-Active feature flag")]
public bool ActiveActive { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The type of the Vpn:PolicyBased/RouteBased")]
[ValidateSet(
MNM.VirtualNetworkGatewaySkuTier.Basic,
MNM.VirtualNetworkGatewaySkuTier.Standard,
MNM.VirtualNetworkGatewaySkuTier.HighPerformance,
IgnoreCase = true)]
public string GatewaySku { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResource",
HelpMessage = "GatewayDefaultSite")]
public PSLocalNetworkGateway GatewayDefaultSite { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "P2S VpnClient AddressPool")]
[ValidateNotNullOrEmpty]
public List<string> VpnClientAddressPool { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of VpnClientRootCertificates to be added.")]
public List<PSVpnClientRootCertificate> VpnClientRootCertificates { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of VpnClientCertificates to be revoked.")]
public List<PSVpnClientRevokedCertificate> VpnClientRevokedCertificates { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The virtual network gateway's ASN for BGP over VPN")]
public uint Asn { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The weight added to routes learned over BGP from this virtual network gateway")]
public int PeerWeight { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "A hashtable which represents resource tags.")]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "Do not ask for confirmation if you want to overrite a resource")]
public SwitchParameter Force { get; set; }
public override void Execute()
{
base.Execute();
WriteWarning("The output object type of this cmdlet will be modified in a future release.");
var present = this.IsVirtualNetworkGatewayPresent(this.ResourceGroupName, this.Name);
ConfirmAction(
Force.IsPresent,
string.Format(Properties.Resources.OverwritingResource, Name),
Properties.Resources.CreatingResourceMessage,
Name,
() =>
{
var virtualNetworkGateway = CreateVirtualNetworkGateway();
WriteObject(virtualNetworkGateway);
},
() => present);
}
private PSVirtualNetworkGateway CreateVirtualNetworkGateway()
{
var vnetGateway = new PSVirtualNetworkGateway();
vnetGateway.Name = this.Name;
vnetGateway.ResourceGroupName = this.ResourceGroupName;
vnetGateway.Location = this.Location;
if (this.ActiveActive && !this.GatewaySku.Equals(MNM.VirtualNetworkGatewaySkuTier.HighPerformance))
{
throw new ArgumentException("Virtual Network Gateway Sku should be " + MNM.VirtualNetworkGatewaySkuTier.HighPerformance + " when Active-Active feature flag is set to True.");
}
if (this.ActiveActive && !this.VpnType.Equals(MNM.VpnType.RouteBased))
{
throw new ArgumentException("Virtual Network Gateway VpnType should be " + MNM.VpnType.RouteBased + " when Active-Active feature flag is set to True.");
}
if (this.ActiveActive && this.IpConfigurations.Count != 2)
{
throw new ArgumentException("Virtual Network Gateway should have 2 Gateway IpConfigurations specified when Active-Active feature flag is True.");
}
if (!this.ActiveActive && this.IpConfigurations.Count == 2)
{
throw new ArgumentException("Virtual Network Gateway should have Active-Active feature flag set to True as there are 2 Gateway IpConfigurations specified. OR there should be only one Gateway IpConfiguration specified.");
}
if (this.IpConfigurations != null)
{
vnetGateway.IpConfigurations = this.IpConfigurations;
}
vnetGateway.GatewayType = this.GatewayType;
vnetGateway.VpnType = this.VpnType;
vnetGateway.EnableBgp = this.EnableBgp;
vnetGateway.ActiveActive = this.ActiveActive;
if (this.GatewayDefaultSite != null)
{
vnetGateway.GatewayDefaultSite = new PSResourceId();
vnetGateway.GatewayDefaultSite.Id = this.GatewayDefaultSite.Id;
}
else
{
vnetGateway.GatewayDefaultSite = null;
}
if (this.GatewaySku != null)
{
vnetGateway.Sku = new PSVirtualNetworkGatewaySku();
vnetGateway.Sku.Tier = this.GatewaySku;
vnetGateway.Sku.Name = this.GatewaySku;
}
else
{
vnetGateway.Sku = null;
}
if (this.VpnClientAddressPool != null || this.VpnClientRootCertificates != null || this.VpnClientRevokedCertificates != null)
{
vnetGateway.VpnClientConfiguration = new PSVpnClientConfiguration();
if (this.VpnClientAddressPool != null)
{
// Make sure passed Virtual Network gateway type is RouteBased if P2S VpnClientAddressPool is specified.
if (this.VpnType == null || !this.VpnType.Equals(MNM.VpnType.RouteBased))
{
throw new ArgumentException("Virtual Network Gateway VpnType should be :" + MNM.VpnType.RouteBased + " when P2S VpnClientAddressPool is specified.");
}
vnetGateway.VpnClientConfiguration.VpnClientAddressPool = new PSAddressSpace();
vnetGateway.VpnClientConfiguration.VpnClientAddressPool.AddressPrefixes = this.VpnClientAddressPool;
}
if (this.VpnClientRootCertificates != null)
{
vnetGateway.VpnClientConfiguration.VpnClientRootCertificates = this.VpnClientRootCertificates;
}
if (this.VpnClientRevokedCertificates != null)
{
vnetGateway.VpnClientConfiguration.VpnClientRevokedCertificates = this.VpnClientRevokedCertificates;
}
}
else
{
vnetGateway.VpnClientConfiguration = null;
}
if (this.Asn > 0 || this.PeerWeight > 0)
{
vnetGateway.BgpSettings = new PSBgpSettings();
vnetGateway.BgpSettings.BgpPeeringAddress = null; // We block modifying the gateway's BgpPeeringAddress (CA)
if (this.Asn > 0)
{
vnetGateway.BgpSettings.Asn = this.Asn;
}
if (this.PeerWeight > 0)
{
vnetGateway.BgpSettings.PeerWeight = this.PeerWeight;
}
else if (this.PeerWeight < 0)
{
throw new ArgumentException("PeerWeight must be a positive integer");
}
}
// Map to the sdk object
var vnetGatewayModel = Mapper.Map<MNM.VirtualNetworkGateway>(vnetGateway);
vnetGatewayModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true);
// Execute the Create VirtualNetwork call
this.VirtualNetworkGatewayClient.CreateOrUpdate(this.ResourceGroupName, this.Name, vnetGatewayModel);
var getVirtualNetworkGateway = this.GetVirtualNetworkGateway(this.ResourceGroupName, this.Name);
return getVirtualNetworkGateway;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for PacketCapturesOperations.
/// </summary>
public static partial class PacketCapturesOperationsExtensions
{
/// <summary>
/// Create and start a packet capture on the specified VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='parameters'>
/// Parameters that define the create packet capture operation.
/// </param>
public static PacketCaptureResult Create(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters)
{
return operations.CreateAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Create and start a packet capture on the specified VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='parameters'>
/// Parameters that define the create packet capture operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PacketCaptureResult> CreateAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a packet capture session by name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
public static PacketCaptureResult Get(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName)
{
return operations.GetAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a packet capture session by name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PacketCaptureResult> GetAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified packet capture session.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
public static void Delete(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName)
{
operations.DeleteAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified packet capture session.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Stops a specified packet capture session.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
public static void Stop(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName)
{
operations.StopAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult();
}
/// <summary>
/// Stops a specified packet capture session.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task StopAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.StopWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Query the status of a running packet capture session.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='packetCaptureName'>
/// The name given to the packet capture session.
/// </param>
public static PacketCaptureQueryStatusResult GetStatus(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName)
{
return operations.GetStatusAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult();
}
/// <summary>
/// Query the status of a running packet capture session.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='packetCaptureName'>
/// The name given to the packet capture session.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PacketCaptureQueryStatusResult> GetStatusAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetStatusWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all packet capture sessions within the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
public static IEnumerable<PacketCaptureResult> List(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName)
{
return operations.ListAsync(resourceGroupName, networkWatcherName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all packet capture sessions within the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<PacketCaptureResult>> ListAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, networkWatcherName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create and start a packet capture on the specified VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='parameters'>
/// Parameters that define the create packet capture operation.
/// </param>
public static PacketCaptureResult BeginCreate(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters)
{
return operations.BeginCreateAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Create and start a packet capture on the specified VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='parameters'>
/// Parameters that define the create packet capture operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PacketCaptureResult> BeginCreateAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified packet capture session.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
public static void BeginDelete(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName)
{
operations.BeginDeleteAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified packet capture session.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Stops a specified packet capture session.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
public static void BeginStop(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName)
{
operations.BeginStopAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult();
}
/// <summary>
/// Stops a specified packet capture session.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginStopAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginStopWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Query the status of a running packet capture session.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='packetCaptureName'>
/// The name given to the packet capture session.
/// </param>
public static PacketCaptureQueryStatusResult BeginGetStatus(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName)
{
return operations.BeginGetStatusAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult();
}
/// <summary>
/// Query the status of a running packet capture session.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='packetCaptureName'>
/// The name given to the packet capture session.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PacketCaptureQueryStatusResult> BeginGetStatusAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetStatusWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFGP;
using DotNetMatrix;
namespace AutoDiff
{
/// <summary>
/// A collection of static methods to build new terms
/// </summary>
public static class TermBuilder
{
/// <summary>
/// Builds a new constant term.
/// </summary>
/// <param name="value">The constant value</param>
/// <returns>The constant term.</returns>
public static Term Constant(double value)
{
//Contract.Ensures(Contract.Result<Term>() != null);
if (value == 0)
return new Zero();
else
return new Constant(value);
}
/// <summary>
/// Builds a sum of given terms.
/// </summary>
/// <param name="terms">The collection of terms in the sum.</param>
/// <returns>A term representing the sum of the terms in <paramref name="terms"/>.</returns>
public static Sum Sum(IEnumerable<Term> terms)
{
//Contract.Requires(terms.Where(term => !(term is Zero)).Count() >= 2); // require at-least two non-zero terms.
//Contract.Requires(Contract.ForAll(terms, term => term != null));
//Contract.Ensures(Contract.Result<Sum>() != null);
terms = terms.Where(term => !(term is Zero));
return new Sum(terms);
}
/// <summary>
/// Builds a sum of given terms.
/// </summary>
/// <param name="v1">The first term in the sum</param>
/// <param name="v2">The second term in the sum</param>
/// <param name="rest">The rest of the terms in the sum.</param>
/// <returns>A term representing the sum of <paramref name="v1"/>, <paramref name="v2"/> and the terms in <paramref name="rest"/>.</returns>
public static Sum Sum(Term v1, Term v2, params Term[] rest)
{
if(v1 == null) throw new Exception("v1 == null");
if(v2 == null) throw new Exception("v2 == null");
//Contract.Requires(v1 != null);
//Contract.Requires(v2 != null);
//Contract.Requires(Contract.ForAll(rest, term => term != null));
//Contract.Ensures(Contract.Result<Sum>() != null);
var allTerms = new Term[] { v1, v2 }.Concat(rest);
return Sum(allTerms);
}
/// <summary>
/// Builds a product of given terms.
/// </summary>
/// <param name="v1">The first term in the product</param>
/// <param name="v2">The second term in the product</param>
/// <param name="rest">The rest of the terms in the product</param>
/// <returns>A term representing the product of <paramref name="v1"/>, <paramref name="v2"/> and the terms in <paramref name="rest"/>.</returns>
public static Term Product(Term v1, Term v2, params Term[] rest)
{
if(v1 == null) throw new Exception("v1 == null");
if(v2 == null) throw new Exception("v2 == null");
//Contract.Requires(v1 != null);
//Contract.Requires(v2 != null);
//Contract.Requires(Contract.ForAll(rest, term => term != null));
//Contract.Ensures(Contract.Result<Term>() != null);
var result = new Product(v1, v2);
foreach (var item in rest)
result = new Product(result, item);
return result;
}
/// <summary>
/// Builds a power terms given a base and a constant exponent
/// </summary>
/// <param name="t">The power base term</param>
/// <param name="power">The exponent</param>
/// <returns>A term representing <c>t^power</c>.</returns>
public static Term Power(Term t, double power)
{
if(t == null) throw new Exception("t == null");
//Contract.Requires(t != null);
//Contract.Ensures(Contract.Result<Term>() != null);
return new ConstPower(t, power);
}
/// <summary>
/// Builds a power term given a base term and an exponent term.
/// </summary>
/// <param name="baseTerm">The base term</param>
/// <param name="exponent">The exponent term</param>
/// <returns></returns>
public static Term Power(Term baseTerm, Term exponent)
{
/*
Contract.Requires(baseTerm != null);
Contract.Requires(exponent != null);
Contract.Ensures(Contract.Result<Term>() != null);
*/
return new TermPower(baseTerm, exponent);
}
/// <summary>
/// Builds a term representing the exponential function e^x.
/// </summary>
/// <param name="arg">The function's exponent</param>
/// <returns>A term representing e^arg.</returns>
public static Term Exp(Term arg)
{
//Contract.Requires(arg != null);
//Contract.Ensures(Contract.Result<Term>() != null);
return new Exp(arg);
}
/// <summary>
/// Builds a term representing the natural logarithm.
/// </summary>
/// <param name="arg">The natural logarithm's argument.</param>
/// <returns>A term representing the natural logarithm of <paramref name="arg"/></returns>
public static Term Log(Term arg)
{
// Contract.Requires(arg != null);
//Contract.Ensures(Contract.Result<Term>() != null);
return new Log(arg);
}
/// <summary>
/// Builds a term representing the sine function.
/// </summary>
/// <param name="arg">The sine argument.</param>
/// <returns>A term representing the sine of <paramref name="arg"/></returns>
public static Term Sin(Term arg)
{
return new Sin(arg);
}
/// <summary>
/// Builds a term representing the cosine function.
/// </summary>
/// <param name="arg">The cosine argument.</param>
/// <returns>A term representing the cosine of <paramref name="arg"/></returns>
public static Term Cos(Term arg)
{
return new Cos(arg);
}
/// <summary>
/// Constructs a 2D quadratic form given the vector components x1, x2 and the matrix coefficients a11, a12, a21, a22.
/// </summary>
/// <param name="x1">First vector component</param>
/// <param name="x2">Second vector component</param>
/// <param name="a11">First row, first column matrix component</param>
/// <param name="a12">First row, second column matrix component</param>
/// <param name="a21">Second row, first column matrix component</param>
/// <param name="a22">Second row, second column matrix component</param>
/// <returns>A term describing the quadratic form</returns>
public static Term QuadForm(Term x1, Term x2, Term a11, Term a12, Term a21, Term a22)
{
/* Contract.Requires(x1 != null);
Contract.Requires(x2 != null);
Contract.Requires(a11 != null);
Contract.Requires(a12 != null);
Contract.Requires(a21 != null);
Contract.Requires(a22 != null);
Contract.Ensures(Contract.Result<Term>() != null);
*/
return Sum(a11 * Power(x1, 2), (a12 + a21) * x1 * x2, a22 * Power(x2, 2));
}
public static Term NormalDistribution(TVec args, TVec mean, double variance) {
return Exp(((args-mean).NormSquared)*(-0.5/variance)) * (1/Math.Sqrt(2.0*Math.PI*variance));
}
public static Term Gaussian(TVec args, TVec mean, double variance) {
return Exp(((args-mean).NormSquared)*(-0.5/variance));
}
public static Term Sigmoid(Term arg,Term upperBound, Term lowerBound, Term mid, double steepness) {
//return (upperBound-lowerBound)*Power(1+Exp(steepness*(-arg+mid)),-1)+lowerBound;
return (upperBound-lowerBound)*(new Sigmoid(arg,mid,steepness))+lowerBound;
}
public static Term BoundedValue(Term arg, Term leftBound,Term rightBound, double steepness) {
//return (upperValue-lowerValue)*Power(1+Exp(steepness*(-arg+leftBound)),-1)*Power(1+Exp(steepness*(arg-rightBound)),-1)+lowerValue;
return ((new LTConstraint(leftBound,arg,steepness)) & (new LTConstraint(arg,rightBound,steepness)));
//return (upperValue-lowerValue)*((new Sigmoid(arg,leftBound,steepness))&(1-(new Sigmoid(arg,rightBound,steepness))))+lowerValue;
}
public static Term BoundedRectangle(TVec arg, TVec leftLower, TVec rightUpper, double steepness) {
return (BoundedValue(arg.X,leftLower.X,rightUpper.X,steepness) & BoundedValue(arg.Y,leftLower.Y,rightUpper.Y,steepness));
}
public static Term EuclidianDistanceSqr(TVec one, TVec two) {
return (one-two).NormSquared;
}
public static Term EuclidianDistance(TVec one, TVec two) {
return Power(EuclidianDistanceSqr(one,two),0.5);
}
public static Term Polynom(Term[] input, int degree, Term[] param) {
Term ret = 0;
for(int i=0; i<input.Length; i++) {
Term t=1;
for(int j=1; j<degree; j++) {
t *= input[i];
}
ret += t*param[i];
}
return ret;
}
}
}
| |
#region License
/* Copyright (c) 2005 Leslie Sanford
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contact
/*
* Leslie Sanford
* Email: [email protected]
*/
#endregion
using System;
namespace Sanford.Multimedia.Midi
{
public abstract class MidiMessageBase
{
/// <summary>
/// Delta samples when the event should be processed in the next audio buffer.
/// Leave at 0 for realtime input to play as fast as possible.
/// Set to the desired sample in the next buffer if you play a midi sequence synchronized to the audio callback
/// </summary>
public int DeltaFrames
{
get;
set;
}
}
/// <summary>
/// Represents the basic class for all MIDI short messages.
/// </summary>
/// <remarks>
/// MIDI short messages represent all MIDI messages except meta messages
/// and system exclusive messages. This includes channel messages, system
/// realtime messages, and system common messages.
/// </remarks>
public class ShortMessage : MidiMessageBase, IMidiMessage
{
#region ShortMessage Members
#region Constants
public const int DataMaxValue= 127;
public const int StatusMaxValue = 255;
//
// Bit manipulation constants.
//
private const int StatusMask = ~255;
protected const int DataMask = ~StatusMask;
private const int Data1Mask = ~65280;
private const int Data2Mask = ~Data1Mask + DataMask;
private const int Shift = 8;
#endregion
protected int msg = 0;
byte[] message;
bool rawMessageBuilt;
#region Methods
public byte[] GetBytes()
{
return Bytes;
}
public ShortMessage()
{
//sub classes will fill the msg field
}
public ShortMessage(int message)
{
this.msg = message;
}
public ShortMessage(byte status, byte data1, byte data2)
{
this.message = new byte[] { status, data1, data2 };
rawMessageBuilt = true;
msg = BuildIntMessage(this.message);
}
private static byte[] BuildByteMessage(int intMessage)
{
unchecked
{
return new byte[] { (byte)ShortMessage.UnpackStatus(intMessage),
(byte)ShortMessage.UnpackData1(intMessage),
(byte)ShortMessage.UnpackData2(intMessage) };
}
}
private static int BuildIntMessage(byte[] message)
{
var intMessage = 0;
intMessage = ShortMessage.PackStatus(intMessage, message[0]);
intMessage = ShortMessage.PackData1(intMessage, message[1]);
intMessage = ShortMessage.PackData2(intMessage, message[2]);
return intMessage;
}
internal static int PackStatus(int message, int status)
{
#region Require
if(status < 0 || status > StatusMaxValue)
{
throw new ArgumentOutOfRangeException("status", status,
"Status value out of range.");
}
#endregion
return (message & StatusMask) | status;
}
internal static int PackData1(int message, int data1)
{
#region Require
if(data1 < 0 || data1 > DataMaxValue)
{
throw new ArgumentOutOfRangeException("data1", data1,
"Data 1 value out of range.");
}
#endregion
return (message & Data1Mask) | (data1 << Shift);
}
internal static int PackData2(int message, int data2)
{
#region Require
if(data2 < 0 || data2 > DataMaxValue)
{
throw new ArgumentOutOfRangeException("data2", data2,
"Data 2 value out of range.");
}
#endregion
return (message & Data2Mask) | (data2 << (Shift * 2));
}
internal static int UnpackStatus(int message)
{
return message & DataMask;
}
internal static int UnpackData1(int message)
{
return (message & ~Data1Mask) >> Shift;
}
internal static int UnpackData2(int message)
{
return (message & ~Data2Mask) >> (Shift * 2);
}
#endregion
#region Properties
/// <summary>
/// Gets the timestamp of the midi input driver in milliseconds since the midi input driver was started.
/// </summary>
/// <value>
/// The timestamp in milliseconds since the midi input driver was started.
/// </value>
public int Timestamp
{
get;
internal set;
}
/// <summary>
/// Gets the short message as a packed integer.
/// </summary>
/// <remarks>
/// The message is packed into an integer value with the low-order byte
/// of the low-word representing the status value. The high-order byte
/// of the low-word represents the first data value, and the low-order
/// byte of the high-word represents the second data value.
/// </remarks>
public int Message
{
get
{
return msg;
}
}
/// <summary>
/// Gets the messages's status value.
/// </summary>
public int Status
{
get
{
return UnpackStatus(msg);
}
}
public byte[] Bytes
{
get
{
if (!rawMessageBuilt)
{
this.message = BuildByteMessage(msg);
rawMessageBuilt = true;
}
return message;
}
}
public virtual MessageType MessageType
{
get
{
return MessageType.Short;
}
}
#endregion
#endregion
}
}
| |
// spline equation courtesy Andeeee's CRSpline (http://forum.unity3d.com/threads/32954-Waypoints-and-constant-variable-speed-problems?p=213942&viewfull=1#post213942)
using UnityEngine;
using System.IO;
using System.Collections;
using System.Collections.Generic;
public class GoSpline
{
public int currentSegment { get; private set; }
public bool isClosed { get; private set; }
public GoSplineType splineType { get; private set; }
// used by the visual path editor
public List<Vector3> nodes { get { return _solver.nodes; } }
private bool _isReversed; // internal flag that lets us know if our nodes are reversed or not
private AbstractGoSplineSolver _solver;
// default constructor
public GoSpline( List<Vector3> nodes, bool useStraightLines = false )
{
// determine spline type and solver based on number of nodes
if( useStraightLines || nodes.Count == 2 )
{
splineType = GoSplineType.StraightLine;
_solver = new GoSplineStraightLineSolver( nodes );
}
else if( nodes.Count == 3 )
{
splineType = GoSplineType.QuadraticBezier;
_solver = new GoSplineQuadraticBezierSolver( nodes );
}
else if( nodes.Count == 4 )
{
splineType = GoSplineType.CubicBezier;
_solver = new GoSplineCubicBezierSolver( nodes );
}
else
{
splineType = GoSplineType.CatmullRom;
_solver = new GoSplineCatmullRomSolver( nodes );
}
}
public GoSpline( Vector3[] nodes, bool useStraightLines = false ) : this( new List<Vector3>( nodes ), useStraightLines )
{}
public GoSpline( string pathAssetName, bool useStraightLines = false ) : this( nodeListFromAsset( pathAssetName ), useStraightLines )
{}
/// <summary>
/// helper to get a node list from an asset created with the visual editor
/// </summary>
private static List<Vector3> nodeListFromAsset( string pathAssetName )
{
if( Application.platform == RuntimePlatform.OSXWebPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer )
{
Debug.LogError( "The Web Player does not support loading files from disk." );
return null;
}
var path = string.Empty;
if( !pathAssetName.EndsWith( ".asset" ) )
pathAssetName += ".asset";
if( Application.platform == RuntimePlatform.Android )
{
path = Path.Combine( "jar:file://" + Application.dataPath + "!/assets/", pathAssetName );
WWW loadAsset = new WWW( path );
while( !loadAsset.isDone ) { } // maybe make a safety check here
return bytesToVector3List( loadAsset.bytes );
}
else if( Application.platform == RuntimePlatform.IPhonePlayer )
{
// at runtime on iOS, we load from the dataPath
path = Path.Combine( Path.Combine( Application.dataPath, "Raw" ), pathAssetName );
}
else
{
// in the editor we default to looking in the StreamingAssets folder
path = Path.Combine( Path.Combine( Application.dataPath, "StreamingAssets" ), pathAssetName );
}
#if UNITY_WEBPLAYER || NETFX_CORE || UNITY_WINRT
// it isnt possible to get here but the compiler needs it to be here anyway
return null;
#else
var bytes = File.ReadAllBytes( path );
return bytesToVector3List( bytes );
#endif
}
/// <summary>
/// helper to get a node list from an asset created with the visual editor
/// </summary>
public static List<Vector3> bytesToVector3List( byte[] bytes )
{
var vecs = new List<Vector3>();
for( var i = 0; i < bytes.Length; i += 12 )
{
var newVec = new Vector3( System.BitConverter.ToSingle( bytes, i ), System.BitConverter.ToSingle( bytes, i + 4 ), System.BitConverter.ToSingle( bytes, i + 8 ) );
vecs.Add( newVec );
}
return vecs;
}
/// <summary>
/// gets the last node. used to setup relative tweens
/// </summary>
public Vector3 getLastNode()
{
return _solver.nodes[_solver.nodes.Count];
}
/// <summary>
/// responsible for calculating total length, segmentStartLocations and segmentDistances
/// </summary>
public void buildPath()
{
_solver.buildPath();
}
/// <summary>
/// directly gets the point for the current spline type with no lookup table to adjust for constant speed
/// </summary>
private Vector3 getPoint( float t )
{
return _solver.getPoint( t );
}
/// <summary>
/// returns the point that corresponds to the given t where t >= 0 and t <= 1 making sure that the
/// path is traversed at a constant speed.
/// </summary>
public Vector3 getPointOnPath( float t )
{
// if the path is closed, we will allow t to wrap. if is not we need to clamp t
if( t < 0 || t > 1 )
{
if( isClosed )
{
if( t < 0 )
t += 1;
else
t -= 1;
}
else
{
t = Mathf.Clamp01( t );
}
}
return _solver.getPointOnPath( t );
}
/// <summary>
/// closes the path adding a new node at the end that is equal to the start node if it isn't already equal
/// </summary>
public void closePath()
{
// dont let this get closed twice!
if( isClosed )
return;
isClosed = true;
_solver.closePath();
}
/// <summary>
/// reverses the order of the nodes
/// </summary>
public void reverseNodes()
{
if( !_isReversed )
{
_solver.reverseNodes();
_isReversed = true;
}
}
/// <summary>
/// unreverses the order of the nodes if they were reversed
/// </summary>
public void unreverseNodes()
{
if( _isReversed )
{
_solver.reverseNodes();
_isReversed = false;
}
}
public void drawGizmos( float resolution )
{
_solver.drawGizmos();
var previousPoint = _solver.getPoint( 0 );
resolution *= _solver.nodes.Count;
for( var i = 1; i <= resolution; i++ )
{
var t = (float)i / resolution;
var currentPoint = _solver.getPoint( t );
Gizmos.DrawLine( currentPoint, previousPoint );
previousPoint = currentPoint;
}
}
/// <summary>
/// helper for drawing gizmos in the editor
/// </summary>
public static void drawGizmos( Vector3[] path, float resolution = 50 )
{
// horribly inefficient but it only runs in the editor
var spline = new GoSpline( path );
spline.drawGizmos( resolution );
}
}
| |
using System;
using System.Threading;
namespace Amib.Threading.Internal
{
public abstract class WorkItemsGroupBase : IWorkItemsGroup
{
#region Private Fields
/// <summary>
/// Contains the name of this instance of SmartThreadPool.
/// Can be changed by the user.
/// </summary>
private string _name = "WorkItemsGroupBase";
public WorkItemsGroupBase()
{
IsIdle = true;
}
#endregion
#region IWorkItemsGroup Members
#region Public Methods
/// <summary>
/// Get/Set the name of the SmartThreadPool/WorkItemsGroup instance
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
#endregion
#region Abstract Methods
public abstract int Concurrency { get; set; }
public abstract int WaitingCallbacks { get; }
public abstract object[] GetStates();
public abstract WIGStartInfo WIGStartInfo { get; }
public abstract void Start();
public abstract void Cancel(bool abortExecution);
public abstract bool WaitForIdle(int millisecondsTimeout);
public abstract event WorkItemsGroupIdleHandler OnIdle;
internal abstract void Enqueue(WorkItem workItem);
internal virtual void PreQueueWorkItem() { }
#endregion
#region Common Base Methods
/// <summary>
/// Cancel all the work items.
/// Same as Cancel(false)
/// </summary>
public virtual void Cancel()
{
Cancel(false);
}
/// <summary>
/// Wait for the SmartThreadPool/WorkItemsGroup to be idle
/// </summary>
public void WaitForIdle()
{
WaitForIdle(Timeout.Infinite);
}
/// <summary>
/// Wait for the SmartThreadPool/WorkItemsGroup to be idle
/// </summary>
public bool WaitForIdle(TimeSpan timeout)
{
return WaitForIdle((int)timeout.TotalMilliseconds);
}
/// <summary>
/// IsIdle is true when there are no work items running or queued.
/// </summary>
public bool IsIdle { get; protected set; }
#endregion
#region QueueWorkItem
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback)
{
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="workItemPriority">The priority of the work item</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="workItemInfo">Work item info</param>
/// <param name="callback">A callback to execute</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, workItemInfo, callback);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state)
{
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="workItemInfo">Work item information</param>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback, object state)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, workItemInfo, callback, state);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
CallToPostExecute callToPostExecute)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
/// <summary>
/// Queue a work item
/// </summary>
/// <param name="callback">A callback to execute</param>
/// <param name="state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name="postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
/// <param name="workItemPriority">The work item priority</param>
/// <returns>Returns a work item result</returns>
public IWorkItemResult QueueWorkItem(
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
CallToPostExecute callToPostExecute,
WorkItemPriority workItemPriority)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(this, WIGStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute, workItemPriority);
Enqueue(workItem);
return workItem.GetWorkItemResult();
}
#endregion
#region QueueWorkItem(Action<...>)
public IWorkItemResult QueueWorkItem(Action action)
{
return QueueWorkItem (action, SmartThreadPool.DefaultWorkItemPriority);
}
public IWorkItemResult QueueWorkItem (Action action, WorkItemPriority priority)
{
PreQueueWorkItem ();
WorkItem workItem = WorkItemFactory.CreateWorkItem (
this,
WIGStartInfo,
delegate
{
action.Invoke ();
return null;
}, priority);
Enqueue (workItem);
return workItem.GetWorkItemResult ();
}
public IWorkItemResult QueueWorkItem<T>(Action<T> action, T arg)
{
return QueueWorkItem<T> (action, arg, SmartThreadPool.DefaultWorkItemPriority);
}
public IWorkItemResult QueueWorkItem<T> (Action<T> action, T arg, WorkItemPriority priority)
{
PreQueueWorkItem ();
WorkItem workItem = WorkItemFactory.CreateWorkItem (
this,
WIGStartInfo,
state =>
{
action.Invoke (arg);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg } : null, priority);
Enqueue (workItem);
return workItem.GetWorkItemResult ();
}
public IWorkItemResult QueueWorkItem<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2)
{
return QueueWorkItem<T1, T2> (action, arg1, arg2, SmartThreadPool.DefaultWorkItemPriority);
}
public IWorkItemResult QueueWorkItem<T1, T2> (Action<T1, T2> action, T1 arg1, T2 arg2, WorkItemPriority priority)
{
PreQueueWorkItem ();
WorkItem workItem = WorkItemFactory.CreateWorkItem (
this,
WIGStartInfo,
state =>
{
action.Invoke (arg1, arg2);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2 } : null, priority);
Enqueue (workItem);
return workItem.GetWorkItemResult ();
}
public IWorkItemResult QueueWorkItem<T1, T2, T3>(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3)
{
return QueueWorkItem<T1, T2, T3> (action, arg1, arg2, arg3, SmartThreadPool.DefaultWorkItemPriority);
;
}
public IWorkItemResult QueueWorkItem<T1, T2, T3> (Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3, WorkItemPriority priority)
{
PreQueueWorkItem ();
WorkItem workItem = WorkItemFactory.CreateWorkItem (
this,
WIGStartInfo,
state =>
{
action.Invoke (arg1, arg2, arg3);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3 } : null, priority);
Enqueue (workItem);
return workItem.GetWorkItemResult ();
}
public IWorkItemResult QueueWorkItem<T1, T2, T3, T4>(
Action<T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
return QueueWorkItem<T1, T2, T3, T4> (action, arg1, arg2, arg3, arg4,
SmartThreadPool.DefaultWorkItemPriority);
}
public IWorkItemResult QueueWorkItem<T1, T2, T3, T4> (
Action<T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4, WorkItemPriority priority)
{
PreQueueWorkItem ();
WorkItem workItem = WorkItemFactory.CreateWorkItem (
this,
WIGStartInfo,
state =>
{
action.Invoke (arg1, arg2, arg3, arg4);
return null;
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3, arg4 } : null, priority);
Enqueue (workItem);
return workItem.GetWorkItemResult ();
}
#endregion
#region QueueWorkItem(Func<...>)
public IWorkItemResult<TResult> QueueWorkItem<TResult>(Func<TResult> func)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke();
});
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
public IWorkItemResult<TResult> QueueWorkItem<T, TResult>(Func<T, TResult> func, T arg)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg } : null);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, TResult>(Func<T1, T2, TResult> func, T1 arg1, T2 arg2)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg1, arg2);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2 } : null);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, TResult>(
Func<T1, T2, T3, TResult> func, T1 arg1, T2 arg2, T3 arg3)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg1, arg2, arg3);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3 } : null);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
public IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, T4, TResult>(
Func<T1, T2, T3, T4, TResult> func, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
PreQueueWorkItem();
WorkItem workItem = WorkItemFactory.CreateWorkItem(
this,
WIGStartInfo,
state =>
{
return func.Invoke(arg1, arg2, arg3, arg4);
},
WIGStartInfo.FillStateWithArgs ? new object[] { arg1, arg2, arg3, arg4 } : null);
Enqueue(workItem);
return new WorkItemResultTWrapper<TResult>(workItem.GetWorkItemResult());
}
#endregion
#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.Text;
using Xunit;
namespace System.Tests
{
public class ConvertFromBase64Tests
{
[Fact]
public static void Roundtrip1()
{
string input = "test";
Verify(input, result =>
{
// See Freed, N. and N. Borenstein, RFC2045, Section 6.8 for a description of why this check is necessary.
Assert.Equal(3, result.Length);
uint triplet = (uint)((result[0] << 16) | (result[1] << 8) | result[2]);
Assert.Equal<uint>(45, triplet >> 18); // 't'
Assert.Equal<uint>(30, (triplet << 14) >> 26); // 'e'
Assert.Equal<uint>(44, (triplet << 20) >> 26); // 's'
Assert.Equal<uint>(45, (triplet << 26) >> 26); // 't'
Assert.Equal(input, Convert.ToBase64String(result));
});
}
[Fact]
public static void Roundtrip2()
{
VerifyRoundtrip("AAAA");
}
[Fact]
public static void Roundtrip3()
{
VerifyRoundtrip("AAAAAAAA");
}
[Fact]
public static void EmptyString()
{
string input = string.Empty;
Verify(input, result =>
{
Assert.NotNull(result);
Assert.Equal(0, result.Length);
});
}
[Fact]
public static void ZeroLengthArray()
{
string input = "test";
char[] inputChars = input.ToCharArray();
byte[] result = Convert.FromBase64CharArray(inputChars, 0, 0);
Assert.NotNull(result);
Assert.Equal(0, result.Length);
}
[Fact]
public static void RoundtripWithPadding1()
{
VerifyRoundtrip("abc=");
}
[Fact]
public static void RoundtripWithPadding2()
{
VerifyRoundtrip("BQYHCA==");
}
[Fact]
public static void PartialRoundtripWithPadding1()
{
string input = "ab==";
Verify(input, result =>
{
Assert.Equal(1, result.Length);
string roundtrippedString = Convert.ToBase64String(result);
Assert.NotEqual(input, roundtrippedString);
Assert.Equal(input[0], roundtrippedString[0]);
});
}
[Fact]
public static void PartialRoundtripWithPadding2()
{
string input = "789=";
Verify(input, result =>
{
Assert.Equal(2, result.Length);
string roundtrippedString = Convert.ToBase64String(result);
Assert.NotEqual(input, roundtrippedString);
Assert.Equal(input[0], roundtrippedString[0]);
Assert.Equal(input[1], roundtrippedString[1]);
});
}
[Fact]
public static void ParseWithWhitespace()
{
Verify("abc= \t \r\n =");
}
[Fact]
public static void RoundtripWithWhitespace2()
{
string input = "abc= \t\n\t\r ";
VerifyRoundtrip(input, input.Trim());
}
[Fact]
public static void RoundtripWithWhitespace3()
{
string input = "abc \r\n\t = \t\n\t\r ";
VerifyRoundtrip(input, "abc=");
}
[Fact]
public static void RoundtripWithWhitespace4()
{
string expected = "test";
string input = expected.Insert(1, new string(' ', 17)).PadLeft(31, ' ').PadRight(12, ' ');
VerifyRoundtrip(input, expected, expectedLengthBytes: 3);
}
[Fact]
public static void RoundtripWithWhitespace5()
{
string expected = "test";
string input = expected.Insert(2, new string('\t', 9)).PadLeft(37, '\t').PadRight(8, '\t');
VerifyRoundtrip(input, expected, expectedLengthBytes: 3);
}
[Fact]
public static void RoundtripWithWhitespace6()
{
string expected = "test";
string input = expected.Insert(2, new string('\r', 13)).PadLeft(7, '\r').PadRight(29, '\r');
VerifyRoundtrip(input, expected, expectedLengthBytes: 3);
}
[Fact]
public static void RoundtripWithWhitespace7()
{
string expected = "test";
string input = expected.Insert(2, new string('\n', 23)).PadLeft(17, '\n').PadRight(34, '\n');
VerifyRoundtrip(input, expected, expectedLengthBytes: 3);
}
[Fact]
public static void RoundtripLargeString()
{
string input = new string('a', 10000);
VerifyRoundtrip(input, input);
}
[Fact]
public static void InvalidOffset()
{
string input = "test";
char[] inputChars = input.ToCharArray();
Assert.Throws<ArgumentOutOfRangeException>(() => Convert.FromBase64CharArray(inputChars, -1, inputChars.Length));
Assert.Throws<ArgumentOutOfRangeException>(() => Convert.FromBase64CharArray(inputChars, inputChars.Length, inputChars.Length));
}
[Fact]
public static void InvalidLength()
{
string input = "test";
char[] inputChars = input.ToCharArray();
Assert.Throws<ArgumentOutOfRangeException>(() => Convert.FromBase64CharArray(inputChars, 0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => Convert.FromBase64CharArray(inputChars, 0, inputChars.Length + 1));
Assert.Throws<ArgumentOutOfRangeException>(() => Convert.FromBase64CharArray(inputChars, 1, inputChars.Length));
}
[Fact]
public static void InvalidInput()
{
Assert.Throws<ArgumentNullException>("inArray", () => Convert.FromBase64CharArray(null, 0, 3));
Assert.Throws<ArgumentNullException>("s", () => Convert.FromBase64String(null));
// Input must be at least 4 characters long
VerifyInvalidInput("No");
// Length of input must be a multiple of 4
VerifyInvalidInput("NoMore");
// Input must not contain invalid characters
VerifyInvalidInput("2-34");
// Input must not contain 3 or more padding characters in a row
VerifyInvalidInput("a===");
VerifyInvalidInput("abc=====");
VerifyInvalidInput("a===\r \t \n");
// Input must not contain padding characters in the middle of the string
VerifyInvalidInput("No=n");
VerifyInvalidInput("abcdabc=abcd");
VerifyInvalidInput("abcdab==abcd");
VerifyInvalidInput("abcda===abcd");
VerifyInvalidInput("abcd====abcd");
// Input must not contain extra trailing padding characters
VerifyInvalidInput("=");
VerifyInvalidInput("abc===");
}
[Fact]
public static void ExtraPaddingCharacter()
{
VerifyInvalidInput("abcdxyz=" + "=");
}
[Fact]
public static void InvalidCharactersInInput()
{
ushort[] invalidChars = { 30122, 62608, 13917, 19498, 2473, 40845, 35988, 2281, 51246, 36372 };
foreach (char ch in invalidChars)
{
var builder = new StringBuilder("abc");
builder.Insert(1, ch);
VerifyInvalidInput(builder.ToString());
}
}
private static void VerifyRoundtrip(string input, string expected = null, int? expectedLengthBytes = null)
{
if (expected == null)
{
expected = input;
}
Verify(input, result =>
{
if (expectedLengthBytes.HasValue)
{
Assert.Equal(expectedLengthBytes.Value, result.Length);
}
Assert.Equal(expected, Convert.ToBase64String(result));
Assert.Equal(expected, Convert.ToBase64String(result, 0, result.Length));
});
}
private static void VerifyInvalidInput(string input)
{
char[] inputChars = input.ToCharArray();
Assert.Throws<FormatException>(() => Convert.FromBase64CharArray(inputChars, 0, inputChars.Length));
Assert.Throws<FormatException>(() => Convert.FromBase64String(input));
}
private static void Verify(string input, Action<byte[]> action = null)
{
if (action != null)
{
action(Convert.FromBase64CharArray(input.ToCharArray(), 0, input.Length));
action(Convert.FromBase64String(input));
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the RisEntidad class.
/// </summary>
[Serializable]
public partial class RisEntidadCollection : ActiveList<RisEntidad, RisEntidadCollection>
{
public RisEntidadCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>RisEntidadCollection</returns>
public RisEntidadCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
RisEntidad o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the RIS_Entidad table.
/// </summary>
[Serializable]
public partial class RisEntidad : ActiveRecord<RisEntidad>, IActiveRecord
{
#region .ctors and Default Settings
public RisEntidad()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public RisEntidad(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public RisEntidad(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public RisEntidad(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("RIS_Entidad", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdEntidad = new TableSchema.TableColumn(schema);
colvarIdEntidad.ColumnName = "idEntidad";
colvarIdEntidad.DataType = DbType.Int32;
colvarIdEntidad.MaxLength = 0;
colvarIdEntidad.AutoIncrement = true;
colvarIdEntidad.IsNullable = false;
colvarIdEntidad.IsPrimaryKey = true;
colvarIdEntidad.IsForeignKey = false;
colvarIdEntidad.IsReadOnly = false;
colvarIdEntidad.DefaultSetting = @"";
colvarIdEntidad.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdEntidad);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = 100;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarCaracter = new TableSchema.TableColumn(schema);
colvarCaracter.ColumnName = "caracter";
colvarCaracter.DataType = DbType.AnsiString;
colvarCaracter.MaxLength = 100;
colvarCaracter.AutoIncrement = false;
colvarCaracter.IsNullable = true;
colvarCaracter.IsPrimaryKey = false;
colvarCaracter.IsForeignKey = false;
colvarCaracter.IsReadOnly = false;
colvarCaracter.DefaultSetting = @"";
colvarCaracter.ForeignKeyTableName = "";
schema.Columns.Add(colvarCaracter);
TableSchema.TableColumn colvarDomicilio = new TableSchema.TableColumn(schema);
colvarDomicilio.ColumnName = "domicilio";
colvarDomicilio.DataType = DbType.AnsiString;
colvarDomicilio.MaxLength = 100;
colvarDomicilio.AutoIncrement = false;
colvarDomicilio.IsNullable = true;
colvarDomicilio.IsPrimaryKey = false;
colvarDomicilio.IsForeignKey = false;
colvarDomicilio.IsReadOnly = false;
colvarDomicilio.DefaultSetting = @"";
colvarDomicilio.ForeignKeyTableName = "";
schema.Columns.Add(colvarDomicilio);
TableSchema.TableColumn colvarEmail = new TableSchema.TableColumn(schema);
colvarEmail.ColumnName = "email";
colvarEmail.DataType = DbType.AnsiString;
colvarEmail.MaxLength = 100;
colvarEmail.AutoIncrement = false;
colvarEmail.IsNullable = true;
colvarEmail.IsPrimaryKey = false;
colvarEmail.IsForeignKey = false;
colvarEmail.IsReadOnly = false;
colvarEmail.DefaultSetting = @"";
colvarEmail.ForeignKeyTableName = "";
schema.Columns.Add(colvarEmail);
TableSchema.TableColumn colvarTipo = new TableSchema.TableColumn(schema);
colvarTipo.ColumnName = "tipo";
colvarTipo.DataType = DbType.AnsiString;
colvarTipo.MaxLength = 100;
colvarTipo.AutoIncrement = false;
colvarTipo.IsNullable = true;
colvarTipo.IsPrimaryKey = false;
colvarTipo.IsForeignKey = false;
colvarTipo.IsReadOnly = false;
colvarTipo.DefaultSetting = @"";
colvarTipo.ForeignKeyTableName = "";
schema.Columns.Add(colvarTipo);
TableSchema.TableColumn colvarTipoEntidad = new TableSchema.TableColumn(schema);
colvarTipoEntidad.ColumnName = "tipoEntidad";
colvarTipoEntidad.DataType = DbType.AnsiString;
colvarTipoEntidad.MaxLength = 100;
colvarTipoEntidad.AutoIncrement = false;
colvarTipoEntidad.IsNullable = true;
colvarTipoEntidad.IsPrimaryKey = false;
colvarTipoEntidad.IsForeignKey = false;
colvarTipoEntidad.IsReadOnly = false;
colvarTipoEntidad.DefaultSetting = @"";
colvarTipoEntidad.ForeignKeyTableName = "";
schema.Columns.Add(colvarTipoEntidad);
TableSchema.TableColumn colvarCaracteristicas = new TableSchema.TableColumn(schema);
colvarCaracteristicas.ColumnName = "caracteristicas";
colvarCaracteristicas.DataType = DbType.AnsiString;
colvarCaracteristicas.MaxLength = 100;
colvarCaracteristicas.AutoIncrement = false;
colvarCaracteristicas.IsNullable = true;
colvarCaracteristicas.IsPrimaryKey = false;
colvarCaracteristicas.IsForeignKey = false;
colvarCaracteristicas.IsReadOnly = false;
colvarCaracteristicas.DefaultSetting = @"";
colvarCaracteristicas.ForeignKeyTableName = "";
schema.Columns.Add(colvarCaracteristicas);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("RIS_Entidad",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdEntidad")]
[Bindable(true)]
public int IdEntidad
{
get { return GetColumnValue<int>(Columns.IdEntidad); }
set { SetColumnValue(Columns.IdEntidad, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
[XmlAttribute("Caracter")]
[Bindable(true)]
public string Caracter
{
get { return GetColumnValue<string>(Columns.Caracter); }
set { SetColumnValue(Columns.Caracter, value); }
}
[XmlAttribute("Domicilio")]
[Bindable(true)]
public string Domicilio
{
get { return GetColumnValue<string>(Columns.Domicilio); }
set { SetColumnValue(Columns.Domicilio, value); }
}
[XmlAttribute("Email")]
[Bindable(true)]
public string Email
{
get { return GetColumnValue<string>(Columns.Email); }
set { SetColumnValue(Columns.Email, value); }
}
[XmlAttribute("Tipo")]
[Bindable(true)]
public string Tipo
{
get { return GetColumnValue<string>(Columns.Tipo); }
set { SetColumnValue(Columns.Tipo, value); }
}
[XmlAttribute("TipoEntidad")]
[Bindable(true)]
public string TipoEntidad
{
get { return GetColumnValue<string>(Columns.TipoEntidad); }
set { SetColumnValue(Columns.TipoEntidad, value); }
}
[XmlAttribute("Caracteristicas")]
[Bindable(true)]
public string Caracteristicas
{
get { return GetColumnValue<string>(Columns.Caracteristicas); }
set { SetColumnValue(Columns.Caracteristicas, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre,string varCaracter,string varDomicilio,string varEmail,string varTipo,string varTipoEntidad,string varCaracteristicas)
{
RisEntidad item = new RisEntidad();
item.Nombre = varNombre;
item.Caracter = varCaracter;
item.Domicilio = varDomicilio;
item.Email = varEmail;
item.Tipo = varTipo;
item.TipoEntidad = varTipoEntidad;
item.Caracteristicas = varCaracteristicas;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdEntidad,string varNombre,string varCaracter,string varDomicilio,string varEmail,string varTipo,string varTipoEntidad,string varCaracteristicas)
{
RisEntidad item = new RisEntidad();
item.IdEntidad = varIdEntidad;
item.Nombre = varNombre;
item.Caracter = varCaracter;
item.Domicilio = varDomicilio;
item.Email = varEmail;
item.Tipo = varTipo;
item.TipoEntidad = varTipoEntidad;
item.Caracteristicas = varCaracteristicas;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdEntidadColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn CaracterColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn DomicilioColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn EmailColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn TipoColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn TipoEntidadColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn CaracteristicasColumn
{
get { return Schema.Columns[7]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdEntidad = @"idEntidad";
public static string Nombre = @"nombre";
public static string Caracter = @"caracter";
public static string Domicilio = @"domicilio";
public static string Email = @"email";
public static string Tipo = @"tipo";
public static string TipoEntidad = @"tipoEntidad";
public static string Caracteristicas = @"caracteristicas";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.ServiceModel.Description;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.ComponentModel;
using System.ServiceModel.Transactions;
using System.Xml;
public sealed class TransactionFlowBindingElement : BindingElement, IPolicyExportExtension
{
bool transactions;
TransactionFlowOption issuedTokens;
TransactionProtocol transactionProtocol;
public TransactionFlowBindingElement()
: this(true, TransactionFlowDefaults.TransactionProtocol)
{
}
public TransactionFlowBindingElement(TransactionProtocol transactionProtocol)
: this(true, transactionProtocol)
{
}
internal TransactionFlowBindingElement(bool transactions)
: this(transactions, TransactionFlowDefaults.TransactionProtocol)
{
}
internal TransactionFlowBindingElement(bool transactions, TransactionProtocol transactionProtocol)
{
this.transactions = transactions;
this.issuedTokens = transactions ? TransactionFlowOption.Allowed : TransactionFlowOption.NotAllowed;
if (!TransactionProtocol.IsDefined(transactionProtocol))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.ConfigInvalidTransactionFlowProtocolValue, transactionProtocol.ToString()));
}
this.transactionProtocol = transactionProtocol;
}
TransactionFlowBindingElement(TransactionFlowBindingElement elementToBeCloned)
: base(elementToBeCloned)
{
this.transactions = elementToBeCloned.transactions;
this.issuedTokens = elementToBeCloned.issuedTokens;
if (!TransactionProtocol.IsDefined(elementToBeCloned.transactionProtocol))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.ConfigInvalidTransactionFlowProtocolValue, elementToBeCloned.transactionProtocol.ToString()));
}
this.transactionProtocol = elementToBeCloned.transactionProtocol;
this.AllowWildcardAction = elementToBeCloned.AllowWildcardAction;
}
internal bool Transactions
{
get
{
return this.transactions;
}
set
{
this.transactions = value;
this.issuedTokens = value ? TransactionFlowOption.Allowed : TransactionFlowOption.NotAllowed;
}
}
internal TransactionFlowOption IssuedTokens
{
get
{
return this.issuedTokens;
}
set
{
ValidateOption(value);
this.issuedTokens = value;
}
}
public override BindingElement Clone()
{
return new TransactionFlowBindingElement(this);
}
bool IsFlowEnabled(Dictionary<DirectionalAction, TransactionFlowOption> dictionary)
{
if (this.issuedTokens != TransactionFlowOption.NotAllowed)
{
return true;
}
if (!this.transactions)
{
return false;
}
foreach (TransactionFlowOption option in dictionary.Values)
{
if (option != TransactionFlowOption.NotAllowed)
{
return true;
}
}
return false;
}
internal bool IsFlowEnabled(ContractDescription contract)
{
if (this.issuedTokens != TransactionFlowOption.NotAllowed)
{
return true;
}
if (!this.transactions)
{
return false;
}
foreach (OperationDescription operation in contract.Operations)
{
TransactionFlowAttribute parameter = operation.Behaviors.Find<TransactionFlowAttribute>();
if (parameter != null)
{
if (parameter.Transactions != TransactionFlowOption.NotAllowed)
{
return true;
}
}
}
return false;
}
public TransactionProtocol TransactionProtocol
{
get
{
return this.transactionProtocol;
}
set
{
if (!TransactionProtocol.IsDefined(value))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
this.transactionProtocol = value;
}
}
[DefaultValue(false)]
public bool AllowWildcardAction
{
get;
set;
}
internal static void ValidateOption(TransactionFlowOption opt)
{
if (!TransactionFlowOptionHelper.IsDefined(opt))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.TransactionFlowBadOption)));
}
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeTransactionProtocol()
{
return this.TransactionProtocol != TransactionProtocol.Default;
}
public override bool CanBuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("context"));
}
if (typeof(TChannel) == typeof(IOutputChannel)
|| typeof(TChannel) == typeof(IDuplexChannel)
|| typeof(TChannel) == typeof(IRequestChannel)
|| typeof(TChannel) == typeof(IOutputSessionChannel)
|| typeof(TChannel) == typeof(IRequestSessionChannel)
|| typeof(TChannel) == typeof(IDuplexSessionChannel))
{
return context.CanBuildInnerChannelFactory<TChannel>();
}
return false;
}
// The BuildChannelFactory and BuildListenerFactory methods looks for this BindingParameter
// in the BindingContext:
// - Dictionary<DirectionalAction, TransactionFlowOption>
// which has the per-operation TransactionFlowOptions
public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
if (!this.CanBuildChannelFactory<TChannel>(context))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)));
}
Dictionary<DirectionalAction, TransactionFlowOption> dictionary = GetDictionary(context);
if (!this.IsFlowEnabled(dictionary))
{
return context.BuildInnerChannelFactory<TChannel>();
}
if (this.issuedTokens == TransactionFlowOption.NotAllowed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TransactionFlowRequiredIssuedTokens)));
}
TransactionChannelFactory<TChannel> channelFactory =
new TransactionChannelFactory<TChannel>(this.transactionProtocol, context, dictionary, this.AllowWildcardAction);
channelFactory.FlowIssuedTokens = this.IssuedTokens;
return channelFactory;
}
public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("context"));
}
if (!context.CanBuildInnerChannelListener<TChannel>())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)));
}
Dictionary<DirectionalAction, TransactionFlowOption> dictionary = GetDictionary(context);
if (!this.IsFlowEnabled(dictionary))
{
return context.BuildInnerChannelListener<TChannel>();
}
if (this.issuedTokens == TransactionFlowOption.NotAllowed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TransactionFlowRequiredIssuedTokens)));
}
IChannelListener<TChannel> innerListener = context.BuildInnerChannelListener<TChannel>();
TransactionChannelListener<TChannel> listener = new TransactionChannelListener<TChannel>(this.transactionProtocol, context.Binding, dictionary, innerListener);
listener.FlowIssuedTokens = this.IssuedTokens;
return listener;
}
public override bool CanBuildChannelListener<TChannel>(BindingContext context)
{
if (!context.CanBuildInnerChannelListener<TChannel>())
return false;
return (typeof(TChannel) == typeof(IInputChannel) ||
typeof(TChannel) == typeof(IReplyChannel) ||
typeof(TChannel) == typeof(IDuplexChannel) ||
typeof(TChannel) == typeof(IInputSessionChannel) ||
typeof(TChannel) == typeof(IReplySessionChannel) ||
typeof(TChannel) == typeof(IDuplexSessionChannel));
}
Dictionary<DirectionalAction, TransactionFlowOption> GetDictionary(BindingContext context)
{
Dictionary<DirectionalAction, TransactionFlowOption> dictionary =
context.BindingParameters.Find<Dictionary<DirectionalAction, TransactionFlowOption>>();
if (dictionary == null)
dictionary = new Dictionary<DirectionalAction, TransactionFlowOption>();
return dictionary;
}
internal static MessagePartSpecification GetIssuedTokenHeaderSpecification(SecurityStandardsManager standardsManager)
{
MessagePartSpecification result;
if (standardsManager.TrustDriver.IsIssuedTokensSupported)
result = new MessagePartSpecification(new XmlQualifiedName(standardsManager.TrustDriver.IssuedTokensHeaderName, standardsManager.TrustDriver.IssuedTokensHeaderNamespace));
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TrustDriverVersionDoesNotSupportIssuedTokens)));
}
return result;
}
public override T GetProperty<T>(BindingContext context)
{
if (typeof(T) == typeof(ChannelProtectionRequirements))
{
ChannelProtectionRequirements myRequirements = this.GetProtectionRequirements();
if (myRequirements != null)
{
myRequirements.Add(context.GetInnerProperty<ChannelProtectionRequirements>() ?? new ChannelProtectionRequirements());
return (T)(object)myRequirements;
}
else
{
return (T)(object)context.GetInnerProperty<ChannelProtectionRequirements>();
}
}
else
{
return context.GetInnerProperty<T>();
}
}
ChannelProtectionRequirements GetProtectionRequirements()
{
if (this.Transactions || (this.IssuedTokens != TransactionFlowOption.NotAllowed))
{
ChannelProtectionRequirements requirements = new ChannelProtectionRequirements();
if (this.Transactions)
{
MessagePartSpecification p = new MessagePartSpecification(
new XmlQualifiedName(CoordinationExternalStrings.CoordinationContext, CoordinationExternal10Strings.Namespace),
new XmlQualifiedName(CoordinationExternalStrings.CoordinationContext, CoordinationExternal11Strings.Namespace),
new XmlQualifiedName(OleTxTransactionExternalStrings.OleTxTransaction, OleTxTransactionExternalStrings.Namespace));
p.MakeReadOnly();
requirements.IncomingSignatureParts.AddParts(p);
requirements.OutgoingSignatureParts.AddParts(p);
requirements.IncomingEncryptionParts.AddParts(p);
requirements.OutgoingEncryptionParts.AddParts(p);
}
if (this.IssuedTokens != TransactionFlowOption.NotAllowed)
{
MessagePartSpecification trustParts = GetIssuedTokenHeaderSpecification(SecurityStandardsManager.DefaultInstance);
trustParts.MakeReadOnly();
requirements.IncomingSignatureParts.AddParts(trustParts);
requirements.IncomingEncryptionParts.AddParts(trustParts);
requirements.OutgoingSignatureParts.AddParts(trustParts);
requirements.OutgoingEncryptionParts.AddParts(trustParts);
}
MessagePartSpecification body = new MessagePartSpecification(true);
body.MakeReadOnly();
requirements.OutgoingSignatureParts.AddParts(body, FaultCodeConstants.Actions.Transactions);
requirements.OutgoingEncryptionParts.AddParts(body, FaultCodeConstants.Actions.Transactions);
return requirements;
}
else
{
return null;
}
}
XmlElement GetAssertion(XmlDocument doc, TransactionFlowOption option, string prefix, string name, string ns, string policyNs)
{
if (doc == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("doc");
XmlElement result = null;
switch (option)
{
case TransactionFlowOption.NotAllowed:
// Don't generate an assertion
break;
case TransactionFlowOption.Allowed:
result = doc.CreateElement(prefix, name, ns);
// Always insert the real wsp:Optional attribute
XmlAttribute attr = doc.CreateAttribute(TransactionPolicyStrings.OptionalPrefix11,
TransactionPolicyStrings.OptionalLocal, policyNs);
attr.Value = TransactionPolicyStrings.TrueValue;
result.Attributes.Append(attr);
// For legacy protocols, also insert the legacy attribute for backward compat
if (this.transactionProtocol == TransactionProtocol.OleTransactions ||
this.transactionProtocol == TransactionProtocol.WSAtomicTransactionOctober2004)
{
XmlAttribute attrLegacy = doc.CreateAttribute(TransactionPolicyStrings.OptionalPrefix10,
TransactionPolicyStrings.OptionalLocal, TransactionPolicyStrings.OptionalNamespaceLegacy);
attrLegacy.Value = TransactionPolicyStrings.TrueValue;
result.Attributes.Append(attrLegacy);
}
break;
case TransactionFlowOption.Mandatory:
result = doc.CreateElement(prefix, name, ns);
break;
}
return result;
}
void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
{
if (exporter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exporter");
}
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
TransactionFlowBindingElement bindingElement = context.BindingElements.Find<TransactionFlowBindingElement>();
if (bindingElement == null || !bindingElement.Transactions)
return;
XmlDocument doc = new XmlDocument();
XmlElement assertion = null;
foreach (OperationDescription operation in context.Contract.Operations)
{
TransactionFlowAttribute contextParam = operation.Behaviors.Find<TransactionFlowAttribute>();
TransactionFlowOption txFlowOption = contextParam == null ? TransactionFlowOption.NotAllowed : contextParam.Transactions;
// Transactions
if (bindingElement.TransactionProtocol == TransactionProtocol.OleTransactions)
{
assertion = GetAssertion(doc, txFlowOption,
TransactionPolicyStrings.OleTxTransactionsPrefix, TransactionPolicyStrings.OleTxTransactionsLocal,
TransactionPolicyStrings.OleTxTransactionsNamespace, exporter.PolicyVersion.Namespace);
}
else if (bindingElement.TransactionProtocol == TransactionProtocol.WSAtomicTransactionOctober2004)
{
assertion = GetAssertion(doc, txFlowOption,
TransactionPolicyStrings.WsatTransactionsPrefix, TransactionPolicyStrings.WsatTransactionsLocal,
TransactionPolicyStrings.WsatTransactionsNamespace10, exporter.PolicyVersion.Namespace);
}
else if (bindingElement.TransactionProtocol == TransactionProtocol.WSAtomicTransaction11)
{
assertion = GetAssertion(doc, txFlowOption,
TransactionPolicyStrings.WsatTransactionsPrefix, TransactionPolicyStrings.WsatTransactionsLocal,
TransactionPolicyStrings.WsatTransactionsNamespace11, exporter.PolicyVersion.Namespace);
}
if (assertion != null)
context.GetOperationBindingAssertions(operation).Add(assertion);
}
}
internal override bool IsMatch(BindingElement b)
{
if (b == null)
return false;
TransactionFlowBindingElement txFlow = b as TransactionFlowBindingElement;
if (txFlow == null)
return false;
if (this.transactions != txFlow.transactions)
return false;
if (this.issuedTokens != txFlow.issuedTokens)
return false;
if (this.transactionProtocol != txFlow.transactionProtocol)
return false;
return true;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: login.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Msg {
/// <summary>Holder for reflection information generated from login.proto</summary>
public static partial class LoginReflection {
#region Descriptor
/// <summary>File descriptor for login.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static LoginReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cgtsb2dpbi5wcm90bxIDbXNnIjQKDlNpZ25VcFJlc3BvbnNlEhEKCWVycm9y",
"Q29kZRgBIAEoBRIPCgd2ZXJzaW9uGAIgASgCIigKB1Rvc0NoYXQSDAoEbmFt",
"ZRgBIAEoCRIPCgdjb250ZW50GAIgASgJIigKB1RvY0NoYXQSDAoEbmFtZRgB",
"IAEoCRIPCgdjb250ZW50GAIgASgJIioKBUxvZ2luEg8KB2FjY291bnQYASAB",
"KAkSEAoIcGFzc3dhcmQYAiABKAkiMAoOUGxheWVyQmFzZUluZm8SEAoIUGxh",
"eWVySUQYASABKA0SDAoETmFtZRgCIAEoCSI/ChBMb2dpblN1Y2Nlc3NmdWxs",
"EisKDnBsYXllckJhc2VJbmZvGAEgASgLMhMubXNnLlBsYXllckJhc2VJbmZv",
"IpQBCgpMb2dpbkZhaWxkEicKBGNvZGUYASABKA4yGS5tc2cuTG9naW5GYWls",
"ZC5FcnJvckNvZGUiXQoJRXJyb3JDb2RlEh0KGUFjY291bnRPclBhc3N3YXJk",
"Tm90TWF0Y2gQABIQCgxBY2NJREludmFsaWQQARIPCgtMb2dpblJlcGVhdBAC",
"Eg4KCklubmVyRXJyb3IQA2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Msg.SignUpResponse), global::Msg.SignUpResponse.Parser, new[]{ "ErrorCode", "Version" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Msg.TosChat), global::Msg.TosChat.Parser, new[]{ "Name", "Content" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Msg.TocChat), global::Msg.TocChat.Parser, new[]{ "Name", "Content" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Msg.Login), global::Msg.Login.Parser, new[]{ "Account", "Passward" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Msg.PlayerBaseInfo), global::Msg.PlayerBaseInfo.Parser, new[]{ "PlayerID", "Name" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Msg.LoginSuccessfull), global::Msg.LoginSuccessfull.Parser, new[]{ "PlayerBaseInfo" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Msg.LoginFaild), global::Msg.LoginFaild.Parser, new[]{ "Code" }, null, new[]{ typeof(global::Msg.LoginFaild.Types.ErrorCode) }, null)
}));
}
#endregion
}
#region Messages
public sealed partial class SignUpResponse : pb::IMessage<SignUpResponse> {
private static readonly pb::MessageParser<SignUpResponse> _parser = new pb::MessageParser<SignUpResponse>(() => new SignUpResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<SignUpResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Msg.LoginReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SignUpResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SignUpResponse(SignUpResponse other) : this() {
errorCode_ = other.errorCode_;
version_ = other.version_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public SignUpResponse Clone() {
return new SignUpResponse(this);
}
/// <summary>Field number for the "errorCode" field.</summary>
public const int ErrorCodeFieldNumber = 1;
private int errorCode_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int ErrorCode {
get { return errorCode_; }
set {
errorCode_ = value;
}
}
/// <summary>Field number for the "version" field.</summary>
public const int VersionFieldNumber = 2;
private float version_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float Version {
get { return version_; }
set {
version_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as SignUpResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(SignUpResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ErrorCode != other.ErrorCode) return false;
if (Version != other.Version) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ErrorCode != 0) hash ^= ErrorCode.GetHashCode();
if (Version != 0F) hash ^= Version.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ErrorCode != 0) {
output.WriteRawTag(8);
output.WriteInt32(ErrorCode);
}
if (Version != 0F) {
output.WriteRawTag(21);
output.WriteFloat(Version);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ErrorCode != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(ErrorCode);
}
if (Version != 0F) {
size += 1 + 4;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(SignUpResponse other) {
if (other == null) {
return;
}
if (other.ErrorCode != 0) {
ErrorCode = other.ErrorCode;
}
if (other.Version != 0F) {
Version = other.Version;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
ErrorCode = input.ReadInt32();
break;
}
case 21: {
Version = input.ReadFloat();
break;
}
}
}
}
}
public sealed partial class TosChat : pb::IMessage<TosChat> {
private static readonly pb::MessageParser<TosChat> _parser = new pb::MessageParser<TosChat>(() => new TosChat());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TosChat> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Msg.LoginReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TosChat() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TosChat(TosChat other) : this() {
name_ = other.name_;
content_ = other.content_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TosChat Clone() {
return new TosChat(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "content" field.</summary>
public const int ContentFieldNumber = 2;
private string content_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Content {
get { return content_; }
set {
content_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TosChat);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TosChat other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Content != other.Content) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Content.Length != 0) hash ^= Content.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Content.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Content);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Content.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Content);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TosChat other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Content.Length != 0) {
Content = other.Content;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
Content = input.ReadString();
break;
}
}
}
}
}
public sealed partial class TocChat : pb::IMessage<TocChat> {
private static readonly pb::MessageParser<TocChat> _parser = new pb::MessageParser<TocChat>(() => new TocChat());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TocChat> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Msg.LoginReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TocChat() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TocChat(TocChat other) : this() {
name_ = other.name_;
content_ = other.content_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TocChat Clone() {
return new TocChat(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "content" field.</summary>
public const int ContentFieldNumber = 2;
private string content_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Content {
get { return content_; }
set {
content_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TocChat);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TocChat other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Content != other.Content) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Content.Length != 0) hash ^= Content.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Content.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Content);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Content.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Content);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TocChat other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Content.Length != 0) {
Content = other.Content;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
Content = input.ReadString();
break;
}
}
}
}
}
public sealed partial class Login : pb::IMessage<Login> {
private static readonly pb::MessageParser<Login> _parser = new pb::MessageParser<Login>(() => new Login());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Login> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Msg.LoginReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Login() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Login(Login other) : this() {
account_ = other.account_;
passward_ = other.passward_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Login Clone() {
return new Login(this);
}
/// <summary>Field number for the "account" field.</summary>
public const int AccountFieldNumber = 1;
private string account_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Account {
get { return account_; }
set {
account_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "passward" field.</summary>
public const int PasswardFieldNumber = 2;
private string passward_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Passward {
get { return passward_; }
set {
passward_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Login);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Login other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Account != other.Account) return false;
if (Passward != other.Passward) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Account.Length != 0) hash ^= Account.GetHashCode();
if (Passward.Length != 0) hash ^= Passward.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Account.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Account);
}
if (Passward.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Passward);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Account.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Account);
}
if (Passward.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Passward);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Login other) {
if (other == null) {
return;
}
if (other.Account.Length != 0) {
Account = other.Account;
}
if (other.Passward.Length != 0) {
Passward = other.Passward;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Account = input.ReadString();
break;
}
case 18: {
Passward = input.ReadString();
break;
}
}
}
}
}
public sealed partial class PlayerBaseInfo : pb::IMessage<PlayerBaseInfo> {
private static readonly pb::MessageParser<PlayerBaseInfo> _parser = new pb::MessageParser<PlayerBaseInfo>(() => new PlayerBaseInfo());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PlayerBaseInfo> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Msg.LoginReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlayerBaseInfo() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlayerBaseInfo(PlayerBaseInfo other) : this() {
playerID_ = other.playerID_;
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlayerBaseInfo Clone() {
return new PlayerBaseInfo(this);
}
/// <summary>Field number for the "PlayerID" field.</summary>
public const int PlayerIDFieldNumber = 1;
private uint playerID_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint PlayerID {
get { return playerID_; }
set {
playerID_ = value;
}
}
/// <summary>Field number for the "Name" field.</summary>
public const int NameFieldNumber = 2;
private string name_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PlayerBaseInfo);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PlayerBaseInfo other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (PlayerID != other.PlayerID) return false;
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (PlayerID != 0) hash ^= PlayerID.GetHashCode();
if (Name.Length != 0) hash ^= Name.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (PlayerID != 0) {
output.WriteRawTag(8);
output.WriteUInt32(PlayerID);
}
if (Name.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (PlayerID != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(PlayerID);
}
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PlayerBaseInfo other) {
if (other == null) {
return;
}
if (other.PlayerID != 0) {
PlayerID = other.PlayerID;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
PlayerID = input.ReadUInt32();
break;
}
case 18: {
Name = input.ReadString();
break;
}
}
}
}
}
public sealed partial class LoginSuccessfull : pb::IMessage<LoginSuccessfull> {
private static readonly pb::MessageParser<LoginSuccessfull> _parser = new pb::MessageParser<LoginSuccessfull>(() => new LoginSuccessfull());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<LoginSuccessfull> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Msg.LoginReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LoginSuccessfull() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LoginSuccessfull(LoginSuccessfull other) : this() {
PlayerBaseInfo = other.playerBaseInfo_ != null ? other.PlayerBaseInfo.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LoginSuccessfull Clone() {
return new LoginSuccessfull(this);
}
/// <summary>Field number for the "playerBaseInfo" field.</summary>
public const int PlayerBaseInfoFieldNumber = 1;
private global::Msg.PlayerBaseInfo playerBaseInfo_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Msg.PlayerBaseInfo PlayerBaseInfo {
get { return playerBaseInfo_; }
set {
playerBaseInfo_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as LoginSuccessfull);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(LoginSuccessfull other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(PlayerBaseInfo, other.PlayerBaseInfo)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (playerBaseInfo_ != null) hash ^= PlayerBaseInfo.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (playerBaseInfo_ != null) {
output.WriteRawTag(10);
output.WriteMessage(PlayerBaseInfo);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (playerBaseInfo_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PlayerBaseInfo);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(LoginSuccessfull other) {
if (other == null) {
return;
}
if (other.playerBaseInfo_ != null) {
if (playerBaseInfo_ == null) {
playerBaseInfo_ = new global::Msg.PlayerBaseInfo();
}
PlayerBaseInfo.MergeFrom(other.PlayerBaseInfo);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (playerBaseInfo_ == null) {
playerBaseInfo_ = new global::Msg.PlayerBaseInfo();
}
input.ReadMessage(playerBaseInfo_);
break;
}
}
}
}
}
public sealed partial class LoginFaild : pb::IMessage<LoginFaild> {
private static readonly pb::MessageParser<LoginFaild> _parser = new pb::MessageParser<LoginFaild>(() => new LoginFaild());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<LoginFaild> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Msg.LoginReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LoginFaild() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LoginFaild(LoginFaild other) : this() {
code_ = other.code_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LoginFaild Clone() {
return new LoginFaild(this);
}
/// <summary>Field number for the "code" field.</summary>
public const int CodeFieldNumber = 1;
private global::Msg.LoginFaild.Types.ErrorCode code_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Msg.LoginFaild.Types.ErrorCode Code {
get { return code_; }
set {
code_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as LoginFaild);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(LoginFaild other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Code != other.Code) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Code != 0) hash ^= Code.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Code != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) Code);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Code != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Code);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(LoginFaild other) {
if (other == null) {
return;
}
if (other.Code != 0) {
Code = other.Code;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
code_ = (global::Msg.LoginFaild.Types.ErrorCode) input.ReadEnum();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the LoginFaild message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
public enum ErrorCode {
[pbr::OriginalName("AccountOrPasswardNotMatch")] AccountOrPasswardNotMatch = 0,
[pbr::OriginalName("AccIDInvalid")] AccIdinvalid = 1,
[pbr::OriginalName("LoginRepeat")] LoginRepeat = 2,
[pbr::OriginalName("InnerError")] InnerError = 3,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Drawing;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
public class ShadedMapTileRenderer : IMapTileTerrainRenderer
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
//private IConfigSource m_config; // not used currently
public void Initialize(Scene scene, IConfigSource config)
{
m_scene = scene;
// m_config = config; // not used currently
}
public void TerrainToBitmap(Bitmap mapbmp)
{
int tc = Environment.TickCount;
m_log.Info("[MAPTILE]: Generating Maptile Step 1: Terrain");
double[,] hm = m_scene.Heightmap.GetDoubles();
bool ShadowDebugContinue = true;
bool terraincorruptedwarningsaid = false;
float low = 255;
float high = 0;
for (int x = 0; x < 256; x++)
{
for (int y = 0; y < 256; y++)
{
float hmval = (float)hm[x, y];
if (hmval < low)
low = hmval;
if (hmval > high)
high = hmval;
}
}
float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
for (int x = 0; x < 256; x++)
{
for (int y = 0; y < 256; y++)
{
// Y flip the cordinates for the bitmap: hf origin is lower left, bm origin is upper left
int yr = 255 - y;
float heightvalue = (float)hm[x, y];
if (heightvalue > waterHeight)
{
// scale height value
// No, that doesn't scale it:
// heightvalue = low + mid * (heightvalue - low) / mid; => low + (heightvalue - low) * mid / mid = low + (heightvalue - low) * 1 = low + heightvalue - low = heightvalue
if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
heightvalue = 0;
else if (heightvalue > 255f)
heightvalue = 255f;
else if (heightvalue < 0f)
heightvalue = 0f;
Color color = Color.FromArgb((int)heightvalue, 100, (int)heightvalue);
mapbmp.SetPixel(x, yr, color);
try
{
//X
// .
//
// Shade the terrain for shadows
if (x < 255 && yr < 255)
{
float hfvalue = (float)hm[x, y];
float hfvaluecompare = 0f;
if ((x + 1 < 256) && (y + 1 < 256))
{
hfvaluecompare = (float)hm[x + 1, y + 1]; // light from north-east => look at land height there
}
if (Single.IsInfinity(hfvalue) || Single.IsNaN(hfvalue))
hfvalue = 0f;
if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare))
hfvaluecompare = 0f;
float hfdiff = hfvalue - hfvaluecompare; // => positive if NE is lower, negative if here is lower
int hfdiffi = 0;
int hfdiffihighlight = 0;
float highlightfactor = 0.18f;
try
{
// hfdiffi = Math.Abs((int)((hfdiff * 4) + (hfdiff * 0.5))) + 1;
hfdiffi = Math.Abs((int)(hfdiff * 4.5f)) + 1;
if (hfdiff % 1f != 0)
{
// hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1);
hfdiffi = hfdiffi + Math.Abs((int)((hfdiff % 1f) * 5f) - 1);
}
hfdiffihighlight = Math.Abs((int)((hfdiff * highlightfactor) * 4.5f)) + 1;
if (hfdiff % 1f != 0)
{
// hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1);
hfdiffihighlight = hfdiffihighlight + Math.Abs((int)(((hfdiff * highlightfactor) % 1f) * 5f) - 1);
}
}
catch (OverflowException)
{
m_log.Debug("[MAPTILE]: Shadow failed at value: " + hfdiff.ToString());
ShadowDebugContinue = false;
}
if (hfdiff > 0.3f)
{
// NE is lower than here
// We have to desaturate and lighten the land at the same time
// we use floats, colors use bytes, so shrink are space down to
// 0-255
if (ShadowDebugContinue)
{
int r = color.R;
int g = color.G;
int b = color.B;
color = Color.FromArgb((r + hfdiffihighlight < 255) ? r + hfdiffihighlight : 255,
(g + hfdiffihighlight < 255) ? g + hfdiffihighlight : 255,
(b + hfdiffihighlight < 255) ? b + hfdiffihighlight : 255);
}
}
else if (hfdiff < -0.3f)
{
// here is lower than NE:
// We have to desaturate and blacken the land at the same time
// we use floats, colors use bytes, so shrink are space down to
// 0-255
if (ShadowDebugContinue)
{
if ((x - 1 > 0) && (yr + 1 < 256))
{
color = mapbmp.GetPixel(x - 1, yr + 1);
int r = color.R;
int g = color.G;
int b = color.B;
color = Color.FromArgb((r - hfdiffi > 0) ? r - hfdiffi : 0,
(g - hfdiffi > 0) ? g - hfdiffi : 0,
(b - hfdiffi > 0) ? b - hfdiffi : 0);
mapbmp.SetPixel(x-1, yr+1, color);
}
}
}
}
}
catch (ArgumentException)
{
if (!terraincorruptedwarningsaid)
{
m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", m_scene.RegionInfo.RegionName);
terraincorruptedwarningsaid = true;
}
color = Color.Black;
mapbmp.SetPixel(x, yr, color);
}
}
else
{
// We're under the water level with the terrain, so paint water instead of land
// Y flip the cordinates
heightvalue = waterHeight - heightvalue;
if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
heightvalue = 0f;
else if (heightvalue > 19f)
heightvalue = 19f;
else if (heightvalue < 0f)
heightvalue = 0f;
heightvalue = 100f - (heightvalue * 100f) / 19f;
try
{
Color water = Color.FromArgb((int)heightvalue, (int)heightvalue, 255);
mapbmp.SetPixel(x, yr, water);
}
catch (ArgumentException)
{
if (!terraincorruptedwarningsaid)
{
m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", m_scene.RegionInfo.RegionName);
terraincorruptedwarningsaid = true;
}
Color black = Color.Black;
mapbmp.SetPixel(x, (256 - y) - 1, black);
}
}
}
}
m_log.Info("[MAPTILE]: Generating Maptile Step 1: Done in " + (Environment.TickCount - tc) + " ms");
}
}
}
| |
namespace XenAdmin.Controls.Wlb
{
partial class WlbReportSubscriptionView
{
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WlbReportSubscriptionView));
this.btnDelete = new System.Windows.Forms.Button();
this.btnChange = new System.Windows.Forms.Button();
this.labelSubscription = new System.Windows.Forms.Label();
this.btnClose = new System.Windows.Forms.Button();
this.tableLayoutPanelSubscriptionDetails = new System.Windows.Forms.TableLayoutPanel();
this.pdSectionParameters = new XenAdmin.Controls.PDSection();
this.pdSectionGeneral = new XenAdmin.Controls.PDSection();
this.pdSectionDelivery = new XenAdmin.Controls.PDSection();
this.pdSectionSchedule = new XenAdmin.Controls.PDSection();
this.pdSectionHistory = new XenAdmin.Controls.PDSection();
this.panelTopControls = new System.Windows.Forms.Panel();
this.flowLayoutPanelTopButtons = new System.Windows.Forms.FlowLayoutPanel();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.flowLayoutPanelLowerButtons = new System.Windows.Forms.FlowLayoutPanel();
this.panelCenter = new System.Windows.Forms.Panel();
this.panel1 = new System.Windows.Forms.Panel();
this.tableLayoutPanelSubscriptionDetails.SuspendLayout();
this.panelTopControls.SuspendLayout();
this.flowLayoutPanelTopButtons.SuspendLayout();
this.flowLayoutPanelLowerButtons.SuspendLayout();
this.panelCenter.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// btnDelete
//
resources.ApplyResources(this.btnDelete, "btnDelete");
this.btnDelete.Name = "btnDelete";
this.btnDelete.UseVisualStyleBackColor = true;
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// btnChange
//
resources.ApplyResources(this.btnChange, "btnChange");
this.btnChange.Name = "btnChange";
this.btnChange.UseVisualStyleBackColor = true;
this.btnChange.Click += new System.EventHandler(this.btnChange_Click);
//
// labelSubscription
//
resources.ApplyResources(this.labelSubscription, "labelSubscription");
this.labelSubscription.Name = "labelSubscription";
//
// btnClose
//
resources.ApplyResources(this.btnClose, "btnClose");
this.btnClose.Name = "btnClose";
this.btnClose.UseVisualStyleBackColor = true;
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// tableLayoutPanelSubscriptionDetails
//
resources.ApplyResources(this.tableLayoutPanelSubscriptionDetails, "tableLayoutPanelSubscriptionDetails");
this.tableLayoutPanelSubscriptionDetails.BackColor = System.Drawing.Color.Transparent;
this.tableLayoutPanelSubscriptionDetails.Controls.Add(this.pdSectionParameters, 0, 1);
this.tableLayoutPanelSubscriptionDetails.Controls.Add(this.pdSectionGeneral, 0, 0);
this.tableLayoutPanelSubscriptionDetails.Controls.Add(this.pdSectionDelivery, 0, 2);
this.tableLayoutPanelSubscriptionDetails.Controls.Add(this.pdSectionSchedule, 0, 3);
this.tableLayoutPanelSubscriptionDetails.Controls.Add(this.pdSectionHistory, 0, 4);
this.tableLayoutPanelSubscriptionDetails.Name = "tableLayoutPanelSubscriptionDetails";
//
// pdSectionParameters
//
this.pdSectionParameters.BackColor = System.Drawing.Color.Gainsboro;
resources.ApplyResources(this.pdSectionParameters, "pdSectionParameters");
this.pdSectionParameters.MinimumSize = new System.Drawing.Size(0, 34);
this.pdSectionParameters.Name = "pdSectionParameters";
this.pdSectionParameters.ShowCellToolTips = false;
//
// pdSectionGeneral
//
this.pdSectionGeneral.BackColor = System.Drawing.Color.Gainsboro;
resources.ApplyResources(this.pdSectionGeneral, "pdSectionGeneral");
this.pdSectionGeneral.MinimumSize = new System.Drawing.Size(0, 34);
this.pdSectionGeneral.Name = "pdSectionGeneral";
this.pdSectionGeneral.ShowCellToolTips = false;
//
// pdSectionDelivery
//
this.pdSectionDelivery.BackColor = System.Drawing.Color.Gainsboro;
resources.ApplyResources(this.pdSectionDelivery, "pdSectionDelivery");
this.pdSectionDelivery.MinimumSize = new System.Drawing.Size(0, 34);
this.pdSectionDelivery.Name = "pdSectionDelivery";
this.pdSectionDelivery.ShowCellToolTips = false;
//
// pdSectionSchedule
//
this.pdSectionSchedule.BackColor = System.Drawing.Color.Gainsboro;
resources.ApplyResources(this.pdSectionSchedule, "pdSectionSchedule");
this.pdSectionSchedule.MinimumSize = new System.Drawing.Size(0, 34);
this.pdSectionSchedule.Name = "pdSectionSchedule";
this.pdSectionSchedule.ShowCellToolTips = false;
//
// pdSectionHistory
//
this.pdSectionHistory.BackColor = System.Drawing.Color.Gainsboro;
resources.ApplyResources(this.pdSectionHistory, "pdSectionHistory");
this.pdSectionHistory.MinimumSize = new System.Drawing.Size(0, 34);
this.pdSectionHistory.Name = "pdSectionHistory";
this.pdSectionHistory.ShowCellToolTips = false;
//
// panelTopControls
//
this.panelTopControls.Controls.Add(this.flowLayoutPanelTopButtons);
this.panelTopControls.Controls.Add(this.flowLayoutPanel1);
this.panelTopControls.Controls.Add(this.labelSubscription);
resources.ApplyResources(this.panelTopControls, "panelTopControls");
this.panelTopControls.Name = "panelTopControls";
//
// flowLayoutPanelTopButtons
//
resources.ApplyResources(this.flowLayoutPanelTopButtons, "flowLayoutPanelTopButtons");
this.flowLayoutPanelTopButtons.Controls.Add(this.btnDelete);
this.flowLayoutPanelTopButtons.Controls.Add(this.btnChange);
this.flowLayoutPanelTopButtons.Name = "flowLayoutPanelTopButtons";
//
// flowLayoutPanel1
//
resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1");
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
//
// flowLayoutPanelLowerButtons
//
resources.ApplyResources(this.flowLayoutPanelLowerButtons, "flowLayoutPanelLowerButtons");
this.flowLayoutPanelLowerButtons.Controls.Add(this.btnClose);
this.flowLayoutPanelLowerButtons.Name = "flowLayoutPanelLowerButtons";
//
// panelCenter
//
resources.ApplyResources(this.panelCenter, "panelCenter");
this.panelCenter.Controls.Add(this.tableLayoutPanelSubscriptionDetails);
this.panelCenter.Name = "panelCenter";
//
// panel1
//
this.panel1.Controls.Add(this.flowLayoutPanelLowerButtons);
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Name = "panel1";
//
// WlbReportSubscriptionView
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.panelCenter);
this.Controls.Add(this.panelTopControls);
this.Controls.Add(this.panel1);
this.MinimumSize = new System.Drawing.Size(671, 278);
this.Name = "WlbReportSubscriptionView";
this.Load += new System.EventHandler(this.ReportSubscriptionView_Load);
this.Resize += new System.EventHandler(this.WlbReportSubscriptionView_Resize);
this.tableLayoutPanelSubscriptionDetails.ResumeLayout(false);
this.panelTopControls.ResumeLayout(false);
this.panelTopControls.PerformLayout();
this.flowLayoutPanelTopButtons.ResumeLayout(false);
this.flowLayoutPanelLowerButtons.ResumeLayout(false);
this.panelCenter.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
internal System.Windows.Forms.Button btnDelete;
internal System.Windows.Forms.Button btnChange;
private System.Windows.Forms.Label labelSubscription;
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelSubscriptionDetails;
private PDSection pdSectionGeneral;
private PDSection pdSectionParameters;
private PDSection pdSectionDelivery;
private PDSection pdSectionSchedule;
private PDSection pdSectionHistory;
private System.Windows.Forms.Panel panelTopControls;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanelLowerButtons;
private System.Windows.Forms.Panel panelCenter;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanelTopButtons;
private System.Windows.Forms.Panel panel1;
}
}
| |
// Copyright 2020 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 CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.Util;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using Google.Protobuf;
using System;
using System.Collections.Generic;
using static Google.Ads.GoogleAds.V10.Enums.ChangeEventResourceTypeEnum.Types;
using static Google.Ads.GoogleAds.V10.Enums.ResourceChangeOperationEnum.Types;
using static Google.Ads.GoogleAds.V10.Resources.ChangeEvent.Types;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example gets the changes in an account during the last 25 days.
/// </summary>
public class GetChangeDetails : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="GetChangeDetails"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public long CustomerId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
return 0;
});
GetChangeDetails codeExample = new GetChangeDetails();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(),
options.CustomerId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description => "This code example gets the changes in an account " +
"during the last 25 days.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
// [START get_change_details]
public void Run(GoogleAdsClient client, long customerId)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V10.GoogleAdsService);
// Construct a query to find details for recent changes in your account.
// The LIMIT clause is required for the change_event resource.
// The maximum size is 10000, but a low limit was set here for demonstrative
// purposes.
// The WHERE clause on change_date_time is also required. It must specify a
// window of at most 30 days within the past 30 days.
string startDate = DateTime.Today.Subtract(TimeSpan.FromDays(25)).ToString("yyyyMMdd");
string endDate = DateTime.Today.Add(TimeSpan.FromDays(1)).ToString("yyyyMMdd");
string searchQuery = $@"
SELECT
change_event.resource_name,
change_event.change_date_time,
change_event.change_resource_name,
change_event.user_email,
change_event.client_type,
change_event.change_resource_type,
change_event.old_resource,
change_event.new_resource,
change_event.resource_change_operation,
change_event.changed_fields
FROM
change_event
WHERE
change_event.change_date_time >= '{startDate}' AND
change_event.change_date_time <= '{endDate}'
ORDER BY
change_event.change_date_time DESC
LIMIT 5";
try
{
// Issue a search request.
googleAdsService.SearchStream(customerId.ToString(), searchQuery,
delegate (SearchGoogleAdsStreamResponse resp)
{
// Display the results.
foreach (GoogleAdsRow googleAdsRow in resp.Results)
{
ChangeEvent changeEvent = googleAdsRow.ChangeEvent;
ChangedResource oldResource = changeEvent.OldResource;
ChangedResource newResource = changeEvent.NewResource;
bool knownResourceType = true;
IMessage oldResourceEntity = null;
IMessage newResourceEntity = null;
switch (changeEvent.ChangeResourceType)
{
case ChangeEventResourceType.Ad:
oldResourceEntity = oldResource.Ad;
newResourceEntity = newResource.Ad;
break;
case ChangeEventResourceType.AdGroup:
oldResourceEntity = oldResource.AdGroup;
newResourceEntity = newResource.AdGroup;
break;
case ChangeEventResourceType.AdGroupAd:
oldResourceEntity = oldResource.AdGroupAd;
newResourceEntity = newResource.AdGroupAd;
break;
case ChangeEventResourceType.AdGroupAsset:
oldResourceEntity = oldResource.AdGroupAsset;
newResourceEntity = newResource.AdGroupAsset;
break;
case ChangeEventResourceType.AdGroupBidModifier:
oldResourceEntity = oldResource.AdGroupBidModifier;
newResourceEntity = newResource.AdGroupBidModifier;
break;
case ChangeEventResourceType.AdGroupCriterion:
oldResourceEntity = oldResource.AdGroupCriterion;
newResourceEntity = newResource.AdGroupCriterion;
break;
case ChangeEventResourceType.AdGroupFeed:
oldResourceEntity = oldResource.AdGroupFeed;
newResourceEntity = newResource.AdGroupFeed;
break;
case ChangeEventResourceType.Asset:
oldResourceEntity = oldResource.Asset;
newResourceEntity = newResource.Asset;
break;
case ChangeEventResourceType.Campaign:
oldResourceEntity = oldResource.Campaign;
newResourceEntity = newResource.Campaign;
break;
case ChangeEventResourceType.CampaignAsset:
oldResourceEntity = oldResource.CampaignAsset;
newResourceEntity = newResource.CampaignAsset;
break;
case ChangeEventResourceType.CampaignBudget:
oldResourceEntity = oldResource.CampaignBudget;
newResourceEntity = newResource.CampaignBudget;
break;
case ChangeEventResourceType.CampaignCriterion:
oldResourceEntity = oldResource.CampaignCriterion;
newResourceEntity = newResource.CampaignCriterion;
break;
case ChangeEventResourceType.CampaignFeed:
oldResourceEntity = oldResource.CampaignFeed;
newResourceEntity = newResource.CampaignFeed;
break;
case ChangeEventResourceType.CustomerAsset:
oldResourceEntity = oldResource.CustomerAsset;
newResourceEntity = newResource.CustomerAsset;
break;
case ChangeEventResourceType.Feed:
oldResourceEntity = oldResource.Feed;
newResourceEntity = newResource.Feed;
break;
case ChangeEventResourceType.FeedItem:
oldResourceEntity = oldResource.FeedItem;
newResourceEntity = newResource.FeedItem;
break;
default:
knownResourceType = false;
break;
}
if (!knownResourceType)
{
Console.WriteLine($"Unknown change_resource_type " +
$"'{changeEvent.ChangeResourceType}'.");
continue;
}
Console.WriteLine($"On #{changeEvent.ChangeDateTime}, user " +
$"{changeEvent.UserEmail} used interface {changeEvent.ClientType} " +
$"to perform a(n) '{changeEvent.ResourceChangeOperation}' " +
$"operation on a '{changeEvent.ChangeResourceType}' with " +
$"resource name {changeEvent.ChangeResourceName}.");
foreach (string fieldMaskPath in changeEvent.ChangedFields.Paths)
{
if (changeEvent.ResourceChangeOperation ==
ResourceChangeOperation.Create)
{
object newValue = FieldMasks.GetFieldValue(
fieldMaskPath, newResourceEntity);
Console.WriteLine($"\t{fieldMaskPath} set to '{newValue}'.");
}
else if (changeEvent.ResourceChangeOperation ==
ResourceChangeOperation.Update)
{
object oldValue = FieldMasks.GetFieldValue(fieldMaskPath,
oldResourceEntity);
object newValue = FieldMasks.GetFieldValue(fieldMaskPath,
newResourceEntity);
Console.WriteLine($"\t{fieldMaskPath} changed from " +
$"'{oldValue}' to '{newValue}'.");
}
}
}
});
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
// [END get_change_details]
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
namespace OpenSim.Tests.Common
{
public class MockScriptEngine : INonSharedRegionModule, IScriptModule, IScriptEngine
{
public IConfigSource ConfigSource { get; private set; }
public IConfig Config { get; private set; }
private Scene m_scene;
/// <summary>
/// Expose posted events to tests.
/// </summary>
public Dictionary<UUID, List<EventParams>> PostedEvents { get; private set; }
/// <summary>
/// A very primitive way of hooking text cose to a posed event.
/// </summary>
/// <remarks>
/// May be replaced with something that uses more original code in the future.
/// </remarks>
public event Action<UUID, EventParams> PostEventHook;
public void Initialise(IConfigSource source)
{
ConfigSource = source;
// Can set later on if required
Config = new IniConfig("MockScriptEngine", ConfigSource);
PostedEvents = new Dictionary<UUID, List<EventParams>>();
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.StackModuleInterface<IScriptModule>(this);
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
}
public string Name { get { return "Mock Script Engine"; } }
public string ScriptEngineName { get { return Name; } }
public Type ReplaceableInterface { get { return null; } }
#pragma warning disable 0067
public event ScriptRemoved OnScriptRemoved;
public event ObjectRemoved OnObjectRemoved;
#pragma warning restore 0067
public string GetXMLState (UUID itemID)
{
throw new System.NotImplementedException ();
}
public bool SetXMLState(UUID itemID, string xml)
{
throw new System.NotImplementedException ();
}
public bool PostScriptEvent(UUID itemID, string name, object[] args)
{
// Console.WriteLine("Posting event {0} for {1}", name, itemID);
return PostScriptEvent(itemID, new EventParams(name, args, null));
}
public bool PostScriptEvent(UUID itemID, EventParams evParams)
{
List<EventParams> eventsForItem;
if (!PostedEvents.ContainsKey(itemID))
{
eventsForItem = new List<EventParams>();
PostedEvents.Add(itemID, eventsForItem);
}
else
{
eventsForItem = PostedEvents[itemID];
}
eventsForItem.Add(evParams);
if (PostEventHook != null)
PostEventHook(itemID, evParams);
return true;
}
public bool PostObjectEvent(uint localID, EventParams evParams)
{
return PostObjectEvent(m_scene.GetSceneObjectPart(localID), evParams);
}
public bool PostObjectEvent(UUID itemID, string name, object[] args)
{
return PostObjectEvent(m_scene.GetSceneObjectPart(itemID), new EventParams(name, args, null));
}
private bool PostObjectEvent(SceneObjectPart part, EventParams evParams)
{
foreach (TaskInventoryItem item in part.Inventory.GetInventoryItems(InventoryType.LSL))
PostScriptEvent(item.ItemID, evParams);
return true;
}
public void SuspendScript(UUID itemID)
{
throw new System.NotImplementedException ();
}
public void ResumeScript(UUID itemID)
{
throw new System.NotImplementedException ();
}
public ArrayList GetScriptErrors(UUID itemID)
{
throw new System.NotImplementedException ();
}
public bool HasScript(UUID itemID, out bool running)
{
throw new System.NotImplementedException ();
}
public bool GetScriptState(UUID itemID)
{
throw new System.NotImplementedException ();
}
public void SaveAllState()
{
throw new System.NotImplementedException ();
}
public void StartProcessing()
{
throw new System.NotImplementedException ();
}
public float GetScriptExecutionTime(List<UUID> itemIDs)
{
throw new System.NotImplementedException ();
}
public Dictionary<uint, float> GetObjectScriptsExecutionTimes()
{
throw new System.NotImplementedException ();
}
public IScriptWorkItem QueueEventHandler(object parms)
{
throw new System.NotImplementedException ();
}
public DetectParams GetDetectParams(UUID item, int number)
{
throw new System.NotImplementedException ();
}
public void SetMinEventDelay(UUID itemID, double delay)
{
throw new System.NotImplementedException ();
}
public int GetStartParameter(UUID itemID)
{
throw new System.NotImplementedException ();
}
public void SetScriptState(UUID itemID, bool state, bool self)
{
throw new System.NotImplementedException ();
}
public void SetState(UUID itemID, string newState)
{
throw new System.NotImplementedException ();
}
public void ApiResetScript(UUID itemID)
{
throw new System.NotImplementedException ();
}
public void ResetScript (UUID itemID)
{
throw new System.NotImplementedException ();
}
public IScriptApi GetApi(UUID itemID, string name)
{
throw new System.NotImplementedException ();
}
public Scene World { get { return m_scene; } }
public IScriptModule ScriptModule { get { return this; } }
public string ScriptEnginePath { get { throw new System.NotImplementedException (); }}
public string ScriptClassName { get { throw new System.NotImplementedException (); } }
public string ScriptBaseClassName { get { throw new System.NotImplementedException (); } }
public string[] ScriptReferencedAssemblies { get { throw new System.NotImplementedException (); } }
public ParameterInfo[] ScriptBaseClassParameters { get { throw new System.NotImplementedException (); } }
public void ClearPostedEvents()
{
PostedEvents.Clear();
}
public void SleepScript(UUID itemID, int delay)
{
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.