context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Entities.DynamicQuery;
using System.Linq.Expressions;
using System.Reflection;
using Signum.Utilities.Reflection;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
using Signum.Engine.Linq;
using Signum.Entities;
using Signum.Entities.Reflection;
using Signum.Entities.Basics;
using DQ = Signum.Engine.DynamicQuery;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
namespace Signum.Engine.DynamicQuery
{
public class DynamicQueryBucket
{
public ResetLazy<IDynamicQueryCore> Core { get; private set; }
public object QueryName { get; private set; }
public Implementations EntityImplementations { get; private set; }
public DynamicQueryBucket(object queryName, Func<IDynamicQueryCore> lazyQueryCore, Implementations entityImplementations)
{
if (lazyQueryCore == null)
throw new ArgumentNullException(nameof(lazyQueryCore));
this.QueryName = queryName ?? throw new ArgumentNullException(nameof(queryName));
this.EntityImplementations = entityImplementations;
this.Core = new ResetLazy<IDynamicQueryCore>(() =>
{
var core = lazyQueryCore();
core.QueryName = QueryName;
core.StaticColumns.Where(sc => sc.IsEntity).SingleEx(() => "Entity column on {0}".FormatWith(QueryUtils.GetKey(QueryName)));
core.EntityColumnFactory().Implementations = entityImplementations;
var errors = core.StaticColumns.Where(sc => sc.Implementations == null && sc.Type.CleanType().IsIEntity());
if (errors.Any())
throw new InvalidOperationException("Column {0} of query '{1}' do(es) not have implementations defined. Use Column extension method".FormatWith(errors.CommaAnd(a => $"'{a.Name}'"), QueryUtils.GetKey(QueryName)));
return core;
});
}
public QueryDescription GetDescription()
{
return Core.Value.GetQueryDescription();
}
}
public interface IDynamicQueryCore
{
object QueryName { get; set; }
ColumnDescriptionFactory[] StaticColumns { get; }
Expression? Expression { get; }
ColumnDescriptionFactory EntityColumnFactory();
QueryDescription GetQueryDescription();
ResultTable ExecuteQuery(QueryRequest request);
Task<ResultTable> ExecuteQueryAsync(QueryRequest request, CancellationToken cancellationToken);
ResultTable ExecuteQueryGroup(QueryRequest request);
Task<ResultTable> ExecuteQueryGroupAsync(QueryRequest request, CancellationToken cancellationToken);
object? ExecuteQueryValue(QueryValueRequest request);
Task<object?> ExecuteQueryValueAsync(QueryValueRequest request, CancellationToken cancellationToken);
Lite<Entity>? ExecuteUniqueEntity(UniqueEntityRequest request);
Task<Lite<Entity>?> ExecuteUniqueEntityAsync(UniqueEntityRequest request, CancellationToken cancellationToken);
IQueryable<Lite<Entity>> GetEntities(QueryEntitiesRequest request);
DQueryable<object> GetDQueryable(DQueryableRequest request);
}
public static class DynamicQueryCore
{
public static AutoDynamicQueryCore<T> Auto<T>(IQueryable<T> query)
{
return new AutoDynamicQueryCore<T>(query);
}
public static ManualDynamicQueryCore<T> Manual<T>(Func<QueryRequest, QueryDescription, CancellationToken, Task<DEnumerableCount<T>>> execute)
{
return new ManualDynamicQueryCore<T>(execute);
}
internal static IDynamicQueryCore FromSelectorUntyped<T>(Expression<Func<T, object?>> expression)
where T : Entity
{
var eType = expression.Parameters.SingleEx().Type;
var tType = expression.Body.Type;
var typedSelector = Expression.Lambda(expression.Body, expression.Parameters);
return giAutoPrivate.GetInvoker(eType, tType)(typedSelector);
}
static readonly GenericInvoker<Func<LambdaExpression, IDynamicQueryCore>> giAutoPrivate =
new GenericInvoker<Func<LambdaExpression, IDynamicQueryCore>>(lambda => FromSelector<TypeEntity, object?>((Expression<Func<TypeEntity, object?>>)lambda));
public static AutoDynamicQueryCore<T> FromSelector<E, T>(Expression<Func<E, T>> selector)
where E : Entity
{
return new AutoDynamicQueryCore<T>(Database.Query<E>().Select(selector));
}
public static Dictionary<string, Meta?>? QueryMetadata(IQueryable query)
{
return MetadataVisitor.GatherMetadata(query.Expression);
}
}
public abstract class DynamicQueryCore<T> : IDynamicQueryCore
{
public object QueryName { get; set; } = null!;
public ColumnDescriptionFactory[] StaticColumns { get; protected set; } = null!;
public abstract ResultTable ExecuteQuery(QueryRequest request);
public abstract Task<ResultTable> ExecuteQueryAsync(QueryRequest request, CancellationToken cancellationToken);
public abstract ResultTable ExecuteQueryGroup(QueryRequest request);
public abstract Task<ResultTable> ExecuteQueryGroupAsync(QueryRequest request, CancellationToken cancellationToken);
public abstract object? ExecuteQueryValue(QueryValueRequest request);
public abstract Task<object?> ExecuteQueryValueAsync(QueryValueRequest request, CancellationToken cancellationToken);
public abstract Lite<Entity>? ExecuteUniqueEntity(UniqueEntityRequest request);
public abstract Task<Lite<Entity>?> ExecuteUniqueEntityAsync(UniqueEntityRequest request, CancellationToken cancellationToken);
public abstract IQueryable<Lite<Entity>> GetEntities(QueryEntitiesRequest request);
public abstract DQueryable<object> GetDQueryable(DQueryableRequest request);
protected virtual ColumnDescriptionFactory[] InitializeColumns()
{
var result = MemberEntryFactory.GenerateList<T>(MemberOptions.Properties | MemberOptions.Fields)
.Select((e, i) => new ColumnDescriptionFactory(i, e.MemberInfo, null)).ToArray();
return result;
}
public DynamicQueryCore<T> ColumnDisplayName<S>(Expression<Func<T, S>> column, Enum messageValue)
{
return this.Column(column, c => c.OverrideDisplayName = () => messageValue.NiceToString());
}
public DynamicQueryCore<T> ColumnDisplayName<S>(Expression<Func<T, S>> column, Func<string> messageValue)
{
return this.Column(column, c => c.OverrideDisplayName = messageValue);
}
public DynamicQueryCore<T> ColumnProperyRoutes<S>(Expression<Func<T, S>> column, params PropertyRoute[] routes)
{
return this.Column(column, c => c.PropertyRoutes = routes);
}
public DynamicQueryCore<T> Column<S>(Expression<Func<T, S>> column, Action<ColumnDescriptionFactory> change)
{
MemberInfo member = ReflectionTools.GetMemberInfo(column);
ColumnDescriptionFactory col = StaticColumns.SingleEx(a => a.Name == member.Name);
change(col);
return this;
}
public ColumnDescriptionFactory EntityColumnFactory()
{
return StaticColumns.Where(c => c.IsEntity).SingleEx(() => "Entity column on {0}".FormatWith(QueryUtils.GetKey(QueryName)));
}
public virtual Expression? Expression
{
get { return null; }
}
public QueryDescription GetQueryDescription()
{
var entity = EntityColumnFactory();
string? allowed = entity.IsAllowed();
if (allowed != null)
throw new InvalidOperationException(
"Not authorized to see Entity column on {0} because {1}".FormatWith(QueryUtils.GetKey(QueryName), allowed));
var columns = StaticColumns.Where(f => f.IsAllowed() == null).Select(f => f.BuildColumnDescription()).ToList();
return new QueryDescription(QueryName, columns);
}
}
public interface IDynamicInfo
{
BuildExpressionContext Context { get; }
}
public class DQueryable<T> : IDynamicInfo
{
public DQueryable(IQueryable<object> query, BuildExpressionContext context)
{
this.Query = query;
this.Context = context;
}
public IQueryable<object> Query { get; private set; }
public BuildExpressionContext Context { get; private set; }
}
public class DQueryableCount<T> : DEnumerable<T>
{
public DQueryableCount(IQueryable<object> query, BuildExpressionContext context, int totalElements) :
base(query, context)
{
this.TotalElements = totalElements;
}
public int TotalElements { get; private set; }
}
public class DEnumerable<T> : IDynamicInfo
{
public DEnumerable(IEnumerable<object> collection, BuildExpressionContext context)
{
this.Collection = collection;
this.Context = context;
}
public IEnumerable<object> Collection { get; private set; }
public BuildExpressionContext Context { get; private set; }
public Expression<Func<object, V>> GetLambdaExpression<V>(QueryToken token)
{
return Expression.Lambda<Func<object, V>>(Expression.Convert(token.BuildExpression(Context), typeof(V)), Context.Parameter);
}
}
public class DEnumerableCount<T> : DEnumerable<T>
{
public DEnumerableCount(IEnumerable<object> collection, BuildExpressionContext context, int? totalElements) :
base(collection, context)
{
this.TotalElements = totalElements;
}
public int? TotalElements {get; private set;}
}
public static class DQueryable
{
#region ToDQueryable
public static DQueryable<T> ToDQueryable<T>(this IQueryable<T> query, QueryDescription description)
{
ParameterExpression pe = Expression.Parameter(typeof(object));
var dic = description.Columns.ToDictionary(
cd => (QueryToken)new ColumnToken(cd, description.QueryName),
cd => Expression.PropertyOrField(Expression.Convert(pe, typeof(T)), cd.Name).BuildLiteNulifyUnwrapPrimaryKey(cd.PropertyRoutes!));
return new DQueryable<T>(query.Select(a => (object)a!), new BuildExpressionContext(typeof(T), pe, dic));
}
public static Task<DEnumerableCount<T>> AllQueryOperationsAsync<T>(this DQueryable<T> query, QueryRequest request, CancellationToken token)
{
return query
.SelectMany(request.Multiplications())
.Where(request.Filters)
.OrderBy(request.Orders)
.Select(request.Columns)
.TryPaginateAsync(request.Pagination, request.SystemTime, token);
}
public static DEnumerableCount<T> AllQueryOperations<T>(this DQueryable<T> query, QueryRequest request)
{
return query
.SelectMany(request.Multiplications())
.Where(request.Filters)
.OrderBy(request.Orders)
.Select(request.Columns)
.TryPaginate(request.Pagination, request.SystemTime);
}
#endregion
#region Select
public static IEnumerable<object?> SelectOne<T>(this DEnumerable<T> collection, QueryToken token)
{
var exp = Expression.Lambda<Func<object, object?>>(Expression.Convert(token.BuildExpression(collection.Context), typeof(object)), collection.Context.Parameter);
return collection.Collection.Select(exp.Compile());
}
public static IQueryable<object?> SelectOne<T>(this DQueryable<T> query, QueryToken token)
{
var exp = Expression.Lambda<Func<object, object?>>(Expression.Convert(token.BuildExpression(query.Context), typeof(object)), query.Context.Parameter);
return query.Query.Select(exp);
}
public static DQueryable<T> Select<T>(this DQueryable<T> query, List<Column> columns)
{
return Select<T>(query, new HashSet<QueryToken>(columns.Select(c => c.Token)));
}
public static DQueryable<T> Select<T>(this DQueryable<T> query, HashSet<QueryToken> columns)
{
var selector = SelectTupleConstructor(query.Context, columns, out BuildExpressionContext newContext);
return new DQueryable<T>(query.Query.Select(selector), newContext);
}
public static DEnumerable<T> Select<T>(this DEnumerable<T> collection, List<Column> columns)
{
return Select<T>(collection, new HashSet<QueryToken>(columns.Select(c => c.Token)));
}
public static DEnumerable<T> Select<T>(this DEnumerable<T> collection, HashSet<QueryToken> columns)
{
var selector = SelectTupleConstructor(collection.Context, columns, out BuildExpressionContext newContext);
return new DEnumerable<T>(collection.Collection.Select(selector.Compile()), newContext);
}
public static DEnumerable<T> Concat<T>(this DEnumerable<T> collection, DEnumerable<T> other)
{
if (collection.Context.TupleType != other.Context.TupleType)
throw new InvalidOperationException("Enumerable's TupleType does not match Other's one.\r\n Enumerable: {0}: \r\n Other: {1}".FormatWith(
collection.Context.TupleType.TypeName(),
other.Context.TupleType.TypeName()));
return new DEnumerable<T>(collection.Collection.Concat(other.Collection), collection.Context);
}
public static DEnumerableCount<T> Concat<T>(this DEnumerableCount<T> collection, DEnumerableCount<T> other)
{
if (collection.Context.TupleType != other.Context.TupleType)
throw new InvalidOperationException("Enumerable's TupleType does not match Other's one.\r\n Enumerable: {0}: \r\n Other: {1}".FormatWith(
collection.Context.TupleType.TypeName(),
other.Context.TupleType.TypeName()));
return new DEnumerableCount<T>(collection.Collection.Concat(other.Collection), collection.Context, collection.TotalElements + other.TotalElements);
}
static Expression<Func<object, object>> SelectTupleConstructor(BuildExpressionContext context, HashSet<QueryToken> tokens, out BuildExpressionContext newContext)
{
string str = tokens.Select(t => QueryUtils.CanColumn(t)).NotNull().ToString("\r\n");
if (str == null)
throw new ApplicationException(str);
List<Expression> expressions = tokens.Select(t => t.BuildExpression(context)).ToList();
Expression ctor = TupleReflection.TupleChainConstructor(expressions);
var pe = Expression.Parameter(typeof(object));
newContext = new BuildExpressionContext(
ctor.Type, pe,
tokens.Select((t, i) => new { Token = t, Expr = TupleReflection.TupleChainProperty(Expression.Convert(pe, ctor.Type), i) }).ToDictionary(t => t.Token!, t => t.Expr!)); /*CSBUG*/
return Expression.Lambda<Func<object, object>>(
(Expression)Expression.Convert(ctor, typeof(object)), context.Parameter);
}
#endregion
public static DEnumerable<T> ToDEnumerable<T>(this DQueryable<T> query)
{
return new DEnumerable<T>(query.Query.ToList(), query.Context);
}
public static async Task<DEnumerable<T>> ToDEnumerableAsync<T>(this DQueryable<T> query, CancellationToken token)
{
var list = await query.Query.ToListAsync(token);
return new DEnumerable<T>(list, query.Context);
}
#region SelectMany
public static DQueryable<T> SelectMany<T>(this DQueryable<T> query, List<CollectionElementToken> elementTokens)
{
foreach (var cet in elementTokens)
{
query = query.SelectMany(cet);
}
return query;
}
static MethodInfo miSelectMany = ReflectionTools.GetMethodInfo(() => Database.Query<TypeEntity>().SelectMany(t => t.Namespace, (t, c) => t)).GetGenericMethodDefinition();
static MethodInfo miDefaultIfEmptyE = ReflectionTools.GetMethodInfo(() => Database.Query<TypeEntity>().AsEnumerable().DefaultIfEmpty()).GetGenericMethodDefinition();
public static DQueryable<T> SelectMany<T>(this DQueryable<T> query, CollectionElementToken cet)
{
Type elementType = cet.Parent!.Type.ElementType()!;
var collectionSelector = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(object), typeof(IEnumerable<>).MakeGenericType(elementType)),
Expression.Call(miDefaultIfEmptyE.MakeGenericMethod(elementType),
cet.Parent!.BuildExpression(query.Context)),
query.Context.Parameter);
var elementParameter = cet.CreateParameter();
var properties = query.Context.Replacemens.Values.And(cet.CreateExpression(elementParameter));
var ctor = TupleReflection.TupleChainConstructor(properties);
var resultSelector = Expression.Lambda(Expression.Convert(ctor, typeof(object)), query.Context.Parameter, elementParameter);
var resultQuery = query.Query.Provider.CreateQuery<object>(Expression.Call(null, miSelectMany.MakeGenericMethod(typeof(object), elementType, typeof(object)),
new Expression[] { query.Query.Expression, Expression.Quote(collectionSelector), Expression.Quote(resultSelector) }));
var parameter = Expression.Parameter(typeof(object));
var newReplacements = query.Context.Replacemens.Keys.And(cet).Select((a, i) => new
{
Token = a,
Expression = TupleReflection.TupleChainProperty(Expression.Convert(parameter, ctor.Type), i)
}).ToDictionary(a => a.Token!, a => a.Expression!); /*CSBUG*/
return new DQueryable<T>(resultQuery,
new BuildExpressionContext(ctor.Type, parameter, newReplacements));
}
#endregion
#region Where
public static DQueryable<T> Where<T>(this DQueryable<T> query, params Filter[] filters)
{
return Where(query, filters.NotNull().ToList());
}
public static DQueryable<T> Where<T>(this DQueryable<T> query, List<Filter> filters)
{
Expression<Func<object, bool>>? where = GetWhereExpression(query.Context, filters);
if (where == null)
return query;
return new DQueryable<T>(query.Query.Where(where), query.Context);
}
public static DQueryable<T> Where<T>(this DQueryable<T> query, Expression<Func<object, bool>> filter)
{
return new DQueryable<T>(query.Query.Where(filter), query.Context);
}
public static DEnumerable<T> Where<T>(this DEnumerable<T> collection, params Filter[] filters)
{
return Where(collection, filters.NotNull().ToList());
}
public static DEnumerable<T> Where<T>(this DEnumerable<T> collection, List<Filter> filters)
{
Expression<Func<object, bool>>? where = GetWhereExpression(collection.Context, filters);
if (where == null)
return collection;
return new DEnumerable<T>(collection.Collection.Where(where.Compile()), collection.Context);
}
public static DEnumerable<T> Where<T>(this DEnumerable<T> collection, Func<object?, bool> filter)
{
return new DEnumerable<T>(collection.Collection.Where(filter).ToList(), collection.Context);
}
static Expression<Func<object, bool>>? GetWhereExpression(BuildExpressionContext context, List<Filter> filters)
{
if (filters == null || filters.Count == 0)
return null;
string str = filters
.SelectMany(f => f.GetFilterConditions())
.Select(f => QueryUtils.CanFilter(f.Token))
.NotNull()
.ToString("\r\n");
if (str == null)
throw new ApplicationException(str);
Expression body = filters.Select(f => f.GetExpression(context)).AggregateAnd();
return Expression.Lambda<Func<object, bool>>(body, context.Parameter);
}
#endregion
#region OrderBy
static MethodInfo miOrderByQ = ReflectionTools.GetMethodInfo(() => Database.Query<TypeEntity>().OrderBy(t => t.Id)).GetGenericMethodDefinition();
static MethodInfo miThenByQ = ReflectionTools.GetMethodInfo(() => Database.Query<TypeEntity>().OrderBy(t => t.Id).ThenBy(t => t.Id)).GetGenericMethodDefinition();
static MethodInfo miOrderByDescendingQ = ReflectionTools.GetMethodInfo(() => Database.Query<TypeEntity>().OrderByDescending(t => t.Id)).GetGenericMethodDefinition();
static MethodInfo miThenByDescendingQ = ReflectionTools.GetMethodInfo(() => Database.Query<TypeEntity>().OrderBy(t => t.Id).ThenByDescending(t => t.Id)).GetGenericMethodDefinition();
public static DQueryable<T> OrderBy<T>(this DQueryable<T> query, List<Order> orders)
{
string str = orders.Select(f => QueryUtils.CanOrder(f.Token)).NotNull().ToString("\r\n");
if (str == null)
throw new ApplicationException(str);
var pairs = orders.Select(o => (
lambda: QueryUtils.CreateOrderLambda(o.Token, query.Context),
orderType: o.OrderType
)).ToList();
return new DQueryable<T>(query.Query.OrderBy(pairs), query.Context);
}
public static IQueryable<object> OrderBy(this IQueryable<object> query, List<(LambdaExpression lambda, OrderType orderType)> orders)
{
if (orders == null || orders.Count == 0)
return query;
IOrderedQueryable<object> result = query.OrderBy(orders[0].lambda, orders[0].orderType);
foreach (var order in orders.Skip(1))
{
result = result.ThenBy(order.lambda, order.orderType);
}
return result;
}
static IOrderedQueryable<object> OrderBy(this IQueryable<object> query, LambdaExpression lambda, OrderType orderType)
{
MethodInfo mi = (orderType == OrderType.Ascending ? miOrderByQ : miOrderByDescendingQ).MakeGenericMethod(lambda.Type.GetGenericArguments());
return (IOrderedQueryable<object>)query.Provider.CreateQuery<object?>(Expression.Call(null, mi, new Expression[] { query.Expression, Expression.Quote(lambda) }));
}
static IOrderedQueryable<object> ThenBy(this IOrderedQueryable<object> query, LambdaExpression lambda, OrderType orderType)
{
MethodInfo mi = (orderType == OrderType.Ascending ? miThenByQ : miThenByDescendingQ).MakeGenericMethod(lambda.Type.GetGenericArguments());
return (IOrderedQueryable<object>)query.Provider.CreateQuery<object?>(Expression.Call(null, mi, new Expression[] { query.Expression, Expression.Quote(lambda) }));
}
static readonly GenericInvoker<Func<IEnumerable<object>, Delegate, IOrderedEnumerable<object>>> miOrderByE = new GenericInvoker<Func<IEnumerable<object>, Delegate, IOrderedEnumerable<object>>>((col, del) => col.OrderBy((Func<object, object?>)del));
static readonly GenericInvoker<Func<IOrderedEnumerable<object>, Delegate, IOrderedEnumerable<object>>> miThenByE = new GenericInvoker<Func<IOrderedEnumerable<object>, Delegate, IOrderedEnumerable<object>>>((col, del) => col.ThenBy((Func<object, object?>)del));
static readonly GenericInvoker<Func<IEnumerable<object>, Delegate, IOrderedEnumerable<object>>> miOrderByDescendingE = new GenericInvoker<Func<IEnumerable<object>, Delegate, IOrderedEnumerable<object>>>((col, del) => col.OrderByDescending((Func<object, object?>)del));
static readonly GenericInvoker<Func<IOrderedEnumerable<object>, Delegate, IOrderedEnumerable<object>>> miThenByDescendingE = new GenericInvoker<Func<IOrderedEnumerable<object>, Delegate, IOrderedEnumerable<object>>>((col, del) => col.ThenByDescending((Func<object, object?>)del));
public static DEnumerable<T> OrderBy<T>(this DEnumerable<T> collection, List<Order> orders)
{
var pairs = orders.Select(o => (
lambda: QueryUtils.CreateOrderLambda(o.Token, collection.Context),
orderType: o.OrderType
)).ToList();
return new DEnumerable<T>(collection.Collection.OrderBy(pairs), collection.Context);
}
public static DEnumerableCount<T> OrderBy<T>(this DEnumerableCount<T> collection, List<Order> orders)
{
var pairs = orders.Select(o => (
lambda: QueryUtils.CreateOrderLambda(o.Token, collection.Context),
orderType: o.OrderType
)).ToList();
return new DEnumerableCount<T>(collection.Collection.OrderBy(pairs), collection.Context, collection.TotalElements);
}
public static IEnumerable<object> OrderBy(this IEnumerable<object> collection, List<(LambdaExpression lambda, OrderType orderType)> orders)
{
if (orders == null || orders.Count == 0)
return collection;
IOrderedEnumerable<object> result = collection.OrderBy(orders[0].lambda, orders[0].orderType);
foreach (var order in orders.Skip(1))
{
result = result.ThenBy(order.lambda, order.orderType);
}
return result;
}
static IOrderedEnumerable<object> OrderBy(this IEnumerable<object> collection, LambdaExpression lambda, OrderType orderType)
{
var mi = orderType == OrderType.Ascending ? miOrderByE : miOrderByDescendingE;
return mi.GetInvoker(lambda.Type.GetGenericArguments())(collection, lambda.Compile());
}
static IOrderedEnumerable<object> ThenBy(this IOrderedEnumerable<object> collection, LambdaExpression lambda, OrderType orderType)
{
var mi = orderType == OrderType.Ascending ? miThenByE : miThenByDescendingE;
return mi.GetInvoker(lambda.Type.GetGenericArguments())(collection, lambda.Compile());
}
#endregion
#region Unique
[return: MaybeNull]
public static T Unique<T>(this IEnumerable<T> collection, UniqueType uniqueType)
{
switch (uniqueType)
{
case UniqueType.First: return collection.First();
case UniqueType.FirstOrDefault: return collection.FirstOrDefault();
case UniqueType.Single: return collection.SingleEx();
case UniqueType.SingleOrDefault: return collection.SingleOrDefaultEx();
case UniqueType.Only: return collection.Only();
default: throw new InvalidOperationException();
}
}
//[return: MaybeNull]
public static Task<T> UniqueAsync<T>(this IQueryable<T> collection, UniqueType uniqueType, CancellationToken token)
{
switch (uniqueType)
{
case UniqueType.First: return collection.FirstAsync(token);
case UniqueType.FirstOrDefault: return collection.FirstOrDefaultAsync(token)!;
case UniqueType.Single: return collection.SingleAsync(token);
case UniqueType.SingleOrDefault: return collection.SingleOrDefaultAsync(token)!;
case UniqueType.Only: return collection.Take(2).ToListAsync(token).ContinueWith(l => l.Result.Only()!);
default: throw new InvalidOperationException();
}
}
#endregion
#region TryTake
public static DQueryable<T> TryTake<T>(this DQueryable<T> query, int? num)
{
if (num.HasValue)
return new DQueryable<T>(query.Query.Take(num.Value), query.Context);
return query;
}
public static DEnumerable<T> TryTake<T>(this DEnumerable<T> collection, int? num)
{
if (num.HasValue)
return new DEnumerable<T>(collection.Collection.Take(num.Value), collection.Context);
return collection;
}
#endregion
#region TryPaginate
public static async Task<DEnumerableCount<T>> TryPaginateAsync<T>(this DQueryable<T> query, Pagination pagination, SystemTime? systemTime, CancellationToken token)
{
if (pagination == null)
throw new ArgumentNullException(nameof(pagination));
if (pagination is Pagination.All)
{
var allList = await query.Query.ToListAsync();
return new DEnumerableCount<T>(allList, query.Context, allList.Count);
}
else if (pagination is Pagination.Firsts top)
{
var topList = await query.Query.Take(top.TopElements).ToListAsync();
return new DEnumerableCount<T>(topList, query.Context, null);
}
else if (pagination is Pagination.Paginate pag)
{
if (systemTime is SystemTime.Interval) //Results multipy due to Joins, not easy to change LINQ provider because joins are delayed
{
var q = query.Query.OrderAlsoByKeys();
var list = await query.Query.ToListAsync();
var elements = list;
if (pag.CurrentPage != 1)
elements = elements.Skip((pag.CurrentPage - 1) * pag.ElementsPerPage).ToList();
elements = elements.Take(pag.ElementsPerPage).ToList();
return new DEnumerableCount<T>(elements, query.Context, list.Count);
}
else
{
var q = query.Query.OrderAlsoByKeys();
if (pag.CurrentPage != 1)
q = q.Skip((pag.CurrentPage - 1) * pag.ElementsPerPage);
q = q.Take(pag.ElementsPerPage);
var listTask = await q.ToListAsync();
var countTask = systemTime is SystemTime.Interval ?
(await query.Query.ToListAsync()).Count : //Results multipy due to Joins, not easy to change LINQ provider because joins are delayed
await query.Query.CountAsync();
return new DEnumerableCount<T>(listTask, query.Context, countTask);
}
}
throw new InvalidOperationException("pagination type {0} not expexted".FormatWith(pagination.GetType().Name));
}
public static DEnumerableCount<T> TryPaginate<T>(this DQueryable<T> query, Pagination pagination, SystemTime? systemTime)
{
if (pagination == null)
throw new ArgumentNullException(nameof(pagination));
if (pagination is Pagination.All)
{
var allList = query.Query.ToList();
return new DEnumerableCount<T>(allList, query.Context, allList.Count);
}
else if (pagination is Pagination.Firsts top)
{
var topList = query.Query.Take(top.TopElements).ToList();
return new DEnumerableCount<T>(topList, query.Context, null);
}
else if (pagination is Pagination.Paginate pag)
{
if(systemTime is SystemTime.Interval) //Results multipy due to Joins, not easy to change LINQ provider because joins are delayed
{
var q = query.Query.OrderAlsoByKeys();
var list = query.Query.ToList();
var elements = list;
if (pag.CurrentPage != 1)
elements = elements.Skip((pag.CurrentPage - 1) * pag.ElementsPerPage).ToList();
elements = elements.Take(pag.ElementsPerPage).ToList();
return new DEnumerableCount<T>(elements, query.Context, list.Count);
}
else
{
var q = query.Query.OrderAlsoByKeys();
if (pag.CurrentPage != 1)
q = q.Skip((pag.CurrentPage - 1) * pag.ElementsPerPage);
q = q.Take(pag.ElementsPerPage);
var list = q.ToList();
var count = list.Count < pag.ElementsPerPage ? pag.ElementsPerPage :
query.Query.Count();
return new DEnumerableCount<T>(list, query.Context, count);
}
}
throw new InvalidOperationException("pagination type {0} not expexted".FormatWith(pagination.GetType().Name));
}
public static DEnumerableCount<T> TryPaginate<T>(this DEnumerable<T> collection, Pagination pagination, SystemTime? systemTime)
{
if (pagination == null)
throw new ArgumentNullException(nameof(pagination));
if (pagination is Pagination.All)
{
var allList = collection.Collection.ToList();
return new DEnumerableCount<T>(allList, collection.Context, allList.Count);
}
else if (pagination is Pagination.Firsts top)
{
var topList = collection.Collection.Take(top.TopElements).ToList();
return new DEnumerableCount<T>(topList, collection.Context, null);
}
else if (pagination is Pagination.Paginate pag)
{
int? totalElements = null;
var q = collection.Collection;
if (pag.CurrentPage != 1)
q = q.Skip((pag.CurrentPage - 1) * pag.ElementsPerPage);
q = q.Take(pag.ElementsPerPage);
var list = q.ToList();
if (list.Count < pag.ElementsPerPage && pag.CurrentPage == 1)
totalElements = list.Count;
return new DEnumerableCount<T>(list, collection.Context, totalElements ?? collection.Collection.Count());
}
throw new InvalidOperationException("pagination type {0} not expexted".FormatWith(pagination.GetType().Name));
}
public static DEnumerableCount<T> TryPaginate<T>(this DEnumerableCount<T> collection, Pagination pagination, SystemTime? systemTime)
{
if (pagination == null)
throw new ArgumentNullException(nameof(pagination));
if (pagination is Pagination.All)
{
return new DEnumerableCount<T>(collection.Collection, collection.Context, collection.TotalElements);
}
else if (pagination is Pagination.Firsts top)
{
var topList = collection.Collection.Take(top.TopElements).ToList();
return new DEnumerableCount<T>(topList, collection.Context, null);
}
else if (pagination is Pagination.Paginate pag)
{
var c = collection.Collection;
if (pag.CurrentPage != 1)
c = c.Skip((pag.CurrentPage - 1) * pag.ElementsPerPage);
c = c.Take(pag.ElementsPerPage);
return new DEnumerableCount<T>(c, collection.Context, collection.TotalElements);
}
throw new InvalidOperationException("pagination type {0} not expexted".FormatWith(pagination.GetType().Name));
}
#endregion
#region GroupBy
static readonly GenericInvoker<Func<IEnumerable<object>, Delegate, Delegate, IEnumerable<object>>> giGroupByE =
new GenericInvoker<Func<IEnumerable<object>, Delegate, Delegate, IEnumerable<object>>>(
(col, ks, rs) => (IEnumerable<object>)Enumerable.GroupBy<string, int, double>((IEnumerable<string>)col, (Func<string, int>)ks, (Func<int, IEnumerable<string>, double>)rs));
public static DEnumerable<T> GroupBy<T>(this DEnumerable<T> collection, HashSet<QueryToken> keyTokens, HashSet<AggregateToken> aggregateTokens)
{
var keySelector = KeySelector(collection.Context, keyTokens);
LambdaExpression resultSelector = ResultSelectSelectorAndContext(collection.Context, keyTokens, aggregateTokens, keySelector.Body.Type, out BuildExpressionContext newContext);
var resultCollection = giGroupByE.GetInvoker(typeof(object), keySelector.Body.Type, typeof(object))(collection.Collection, keySelector.Compile(), resultSelector.Compile());
return new DEnumerable<T>(resultCollection, newContext);
}
static MethodInfo miGroupByQ = ReflectionTools.GetMethodInfo(() => Queryable.GroupBy<string, int, double>((IQueryable<string>)null!, (Expression<Func<string, int>>)null!, (Expression<Func<int, IEnumerable<string>, double>>)null!)).GetGenericMethodDefinition();
public static DQueryable<T> GroupBy<T>(this DQueryable<T> query, HashSet<QueryToken> keyTokens, HashSet<AggregateToken> aggregateTokens)
{
var keySelector = KeySelector(query.Context, keyTokens);
LambdaExpression resultSelector = ResultSelectSelectorAndContext(query.Context, keyTokens, aggregateTokens, keySelector.Body.Type, out BuildExpressionContext newContext);
var resultQuery = (IQueryable<object>)query.Query.Provider.CreateQuery<object?>(Expression.Call(null, miGroupByQ.MakeGenericMethod(typeof(object), keySelector.Body.Type, typeof(object)),
new Expression[] { query.Query.Expression, Expression.Quote(keySelector), Expression.Quote(resultSelector) }));
return new DQueryable<T>(resultQuery, newContext);
}
static LambdaExpression ResultSelectSelectorAndContext(BuildExpressionContext context, HashSet<QueryToken> keyTokens, HashSet<AggregateToken> aggregateTokens, Type keyTupleType, out BuildExpressionContext newContext)
{
Dictionary<QueryToken, Expression> resultExpressions = new Dictionary<QueryToken, Expression>();
ParameterExpression pk = Expression.Parameter(keyTupleType, "key");
resultExpressions.AddRange(keyTokens.Select((kt, i) => KeyValuePair.Create(kt,
TupleReflection.TupleChainProperty(pk, i))));
ParameterExpression pe = Expression.Parameter(typeof(IEnumerable<object>), "e");
resultExpressions.AddRange(aggregateTokens.Select(at => KeyValuePair.Create((QueryToken)at, BuildAggregateExpressionEnumerable(pe, at, context))));
var resultConstructor = TupleReflection.TupleChainConstructor(resultExpressions.Values);
ParameterExpression pg = Expression.Parameter(typeof(object), "gr");
newContext = new BuildExpressionContext(resultConstructor.Type, pg,
resultExpressions.Keys.Select((t, i) => KeyValuePair.Create(t, TupleReflection.TupleChainProperty(Expression.Convert(pg, resultConstructor.Type), i))).ToDictionary());
return Expression.Lambda(Expression.Convert(resultConstructor, typeof(object)), pk, pe);
}
static LambdaExpression KeySelector(BuildExpressionContext context, HashSet<QueryToken> keyTokens)
{
var keySelector = Expression.Lambda(
TupleReflection.TupleChainConstructor(keyTokens.Select(t => t.BuildExpression(context)).ToList()),
context.Parameter);
return keySelector;
}
static Expression BuildAggregateExpressionEnumerable(Expression collection, AggregateToken at, BuildExpressionContext context)
{
Type elementType = collection.Type.ElementType()!;
if (at.AggregateFunction == AggregateFunction.Count && at.Parent == null)
return Expression.Call(typeof(Enumerable), "Count", new[] { elementType }, new[] { collection });
var body = at.Parent!.BuildExpression(context);
if (at.AggregateFunction == AggregateFunction.Count)
{
if (at.FilterOperation.HasValue)
{
var condition = QueryUtils.GetCompareExpression(at.FilterOperation.Value, body.Nullify(), Expression.Constant(at.Value, body.Type.Nullify()));
var lambda = Expression.Lambda(condition, context.Parameter);
return Expression.Call(typeof(Enumerable), AggregateFunction.Count.ToString(), new[] { elementType }, new[] { collection, lambda });
}
else if (at.Distinct)
{
var lambda = Expression.Lambda(body, context.Parameter);
var select = Expression.Call(typeof(Enumerable), "Select", new[] { elementType, body.Type }, new[] { collection, lambda });
var distinct = Expression.Call(typeof(Enumerable), "Distinct", new[] { body.Type }, new[] { select });
var param = Expression.Parameter(lambda.Body.Type);
LambdaExpression notNull = Expression.Lambda(Expression.NotEqual(param, Expression.Constant(null, param.Type.Nullify())), param);
var count = Expression.Call(typeof(Enumerable), "Count", new[] { body.Type }, new Expression[] { distinct, notNull });
return count;
}
else
throw new InvalidOperationException();
}
else
{
if (body.Type != at.Type)
body = body.TryConvert(at.Type);
var lambda = Expression.Lambda(body, context.Parameter);
if (at.AggregateFunction == AggregateFunction.Min || at.AggregateFunction == AggregateFunction.Max)
return Expression.Call(typeof(Enumerable), at.AggregateFunction.ToString(), new[] { elementType, lambda.Body.Type }, new[] { collection, lambda });
return Expression.Call(typeof(Enumerable), at.AggregateFunction.ToString(), new[] { elementType }, new[] { collection, lambda });
}
}
static Expression BuildAggregateExpressionQueryable(Expression collection, AggregateToken at, BuildExpressionContext context)
{
Type elementType = collection.Type.ElementType()!;
if (at.AggregateFunction == AggregateFunction.Count)
return Expression.Call(typeof(Queryable), "Count", new[] { elementType }, new[] { collection });
var body = at.Parent!.BuildExpression(context);
var type = at.Type;
if (body.Type != type)
body = body.TryConvert(type);
var lambda = Expression.Lambda(body, context.Parameter);
var quotedLambda = Expression.Quote(lambda);
if (at.AggregateFunction == AggregateFunction.Min || at.AggregateFunction == AggregateFunction.Max)
return Expression.Call(typeof(Queryable), at.AggregateFunction.ToString(), new[] { elementType, lambda.Body.Type }, new[] { collection, quotedLambda });
return Expression.Call(typeof(Queryable), at.AggregateFunction.ToString(), new[] { elementType }, new[] { collection, quotedLambda });
}
static Expression BuildAggregateExpressionQueryableAsync(Expression collection, AggregateToken at, BuildExpressionContext context, CancellationToken token)
{
var tokenConstant = Expression.Constant(token);
Type elementType = collection.Type.ElementType()!;
if (at.AggregateFunction == AggregateFunction.Count)
return Expression.Call(typeof(QueryableAsyncExtensions), "CountAsync", new[] { elementType }, new[] { collection, tokenConstant });
var body = at.Parent!.BuildExpression(context);
var type = at.AggregateFunction == AggregateFunction.Sum ? at.Type.UnNullify() : at.Type;
if (body.Type != type)
body = body.TryConvert(type);
var lambda = Expression.Lambda(body, context.Parameter);
var quotedLambda = Expression.Quote(lambda);
if (at.AggregateFunction == AggregateFunction.Min || at.AggregateFunction == AggregateFunction.Max)
return Expression.Call(typeof(QueryableAsyncExtensions), at.AggregateFunction.ToString() + "Async", new[] { elementType, lambda.Body.Type }, new[] { collection, quotedLambda, tokenConstant });
return Expression.Call(typeof(QueryableAsyncExtensions), at.AggregateFunction.ToString() + "Async", new[] { elementType }, new[] { collection, quotedLambda, tokenConstant });
}
#endregion
#region SimpleAggregate
public static object? SimpleAggregate<T>(this DEnumerable<T> collection, AggregateToken simpleAggregate)
{
var expr = BuildAggregateExpressionEnumerable(Expression.Constant(collection.Collection), simpleAggregate, collection.Context);
return Expression.Lambda<Func<object?>>(Expression.Convert(expr, typeof(object))).Compile()();
}
public static object? SimpleAggregate<T>(this DQueryable<T> query, AggregateToken simpleAggregate)
{
var expr = BuildAggregateExpressionQueryable(query.Query.Expression, simpleAggregate, query.Context);
return Expression.Lambda<Func<object?>>(Expression.Convert(expr, typeof(object))).Compile()();
}
public static Task<object?> SimpleAggregateAsync<T>(this DQueryable<T> query, AggregateToken simpleAggregate, CancellationToken token)
{
var expr = BuildAggregateExpressionQueryableAsync(query.Query.Expression, simpleAggregate, query.Context, token);
var func = (Func<Task>)Expression.Lambda(expr).Compile();
var task = func();
return CastTask<object?>(task);
}
public static async Task<T> CastTask<T>(this Task task)
{
if (task == null)
throw new ArgumentNullException(nameof(task));
await task.ConfigureAwait(false);
object? result = task.GetType().GetProperty(nameof(Task<object>.Result))!.GetValue(task);
return (T)result!;
}
#endregion
public struct ExpandColumn<T> : IExpandColumn
{
public QueryToken Token { get; private set; }
public readonly Func<Lite<Entity>, T> GetValue;
public ExpandColumn(QueryToken token, Func<Lite<Entity>, T> getValue)
{
Token = token;
GetValue = getValue;
}
Expression IExpandColumn.GetExpression(Expression entitySelector)
{
return Expression.Invoke(Expression.Constant(GetValue), entitySelector);
}
}
public interface IExpandColumn
{
public QueryToken Token { get;}
Expression GetExpression(Expression entitySelector);
}
public static DEnumerable<T> ReplaceColumns<T>(this DEnumerable<T> query, params IExpandColumn[] newColumns)
{
var entity = query.Context.Replacemens.Single(a => a.Key.FullKey() == "Entity").Value;
var newColumnsDic = newColumns.ToDictionary(a => a.Token, a => a.GetExpression(entity));
List<QueryToken> tokens = query.Context.Replacemens.Keys.Union(newColumns.Select(a => a.Token)).ToList();
List<Expression> expressions = tokens.Select(t => newColumnsDic.TryGetC(t) ?? query.Context.Replacemens.GetOrThrow(t)).ToList();
Expression ctor = TupleReflection.TupleChainConstructor(expressions);
var pe = Expression.Parameter(typeof(object));
var newContext = new BuildExpressionContext(
ctor.Type, pe,
tokens.Select((t, i) => new { Token = t, Expr = TupleReflection.TupleChainProperty(Expression.Convert(pe, ctor.Type), i) }).ToDictionary(t => t.Token!, t => t.Expr!)); /*CSBUG*/
var selector = Expression.Lambda<Func<object, object>>(
(Expression)Expression.Convert(ctor, typeof(object)), query.Context.Parameter);
return new DEnumerable<T>(query.Collection.Select(selector.Compile()), newContext);
}
public static ResultTable ToResultTable<T>(this DEnumerableCount<T> collection, QueryRequest req)
{
object[] array = collection.Collection as object[] ?? collection.Collection.ToArray();
var columnAccesors = req.Columns.Select(c => (
column: c,
lambda: Expression.Lambda(c.Token.BuildExpression(collection.Context), collection.Context.Parameter)
)).ToList();
return ToResultTable(array, columnAccesors, collection.TotalElements, req.Pagination);
}
public static ResultTable ToResultTable(object[] result, List<(Column column, LambdaExpression lambda)> columnAccesors, int? totalElements, Pagination pagination)
{
var columnValues = columnAccesors.Select(c => new ResultColumn(
c.column,
miGetValues.GetInvoker(c.column.Type)(result, c.lambda.Compile()))
).ToArray();
return new ResultTable(columnValues, totalElements, pagination);
}
static readonly GenericInvoker<Func<object[], Delegate, Array>> miGetValues = new GenericInvoker<Func<object[], Delegate, Array>>((objs, del) => GetValues<int>(objs, (Func<object, int>)del));
static S[] GetValues<S>(object[] collection, Func<object, S> getter)
{
S[] array = new S[collection.Length];
for (int i = 0; i < collection.Length; i++)
{
array[i] = getter(collection[i]);
}
return array;
}
}
}
| |
using System;
using System.Collections.Generic;
using GXPEngine.Core;
namespace GXPEngine
{
/// <summary>
/// GameObject is the base class for all display objects.
/// </summary>
public abstract class GameObject : Transformable
{
public string name;
private Collider _collider;
private List<GameObject> _children = new List<GameObject>();
private GameObject _parent = null;
public bool visible = true;
//------------------------------------------------------------------------------------------------------------------------
// GameObject()
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Initializes a new instance of the <see cref="GXPEngine.GameObject"/> class.
/// Since GameObjects contain a display hierarchy, a GameObject can be used as a container for other objects.
/// Other objects can be added using child commands as AddChild.
/// </summary>
public GameObject()
{
_collider = createCollider();
if (Game.main != null) Game.main.Add(this);
}
/// <summary>
/// Return the collider to use for this game object, null is allowed
/// </summary>
protected virtual Collider createCollider () {
return null;
}
//------------------------------------------------------------------------------------------------------------------------
// Index
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Gets the index of this object in the parent's hierarchy list.
/// Returns -1 if no parent is defined.
/// </summary>
/// <value>
/// The index.
/// </value>
public int Index {
get {
if (parent == null) return -1;
return parent._children.IndexOf(this);
}
}
//------------------------------------------------------------------------------------------------------------------------
// collider
//------------------------------------------------------------------------------------------------------------------------
internal Collider collider {
get { return _collider; }
}
//------------------------------------------------------------------------------------------------------------------------
// game
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Gets the game that this object belongs to.
/// This is a unique instance throughout the runtime of the game.
/// Use this to access the top of the displaylist hierarchy, and to retreive the width and height of the screen.
/// </summary>
public Game game {
get {
return Game.main;
}
}
//------------------------------------------------------------------------------------------------------------------------
// OnDestroy()
//------------------------------------------------------------------------------------------------------------------------
//subclasses can use this call to clean up resources once on destruction
protected virtual void OnDestroy ()
{
//empty
}
//------------------------------------------------------------------------------------------------------------------------
// Destroy()
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Destroy this instance, and removes it from the game. To complete garbage collection, you must nullify all
/// your own references to this object.
/// </summary>
public virtual void Destroy ()
{
if (!game.Contains (this)) return;
OnDestroy();
//detach all children
while (_children.Count > 0) {
GameObject child = _children[0];
if (child != null) child.Destroy();
}
//detatch from parent
if (parent != null) parent = null;
//remove from game
if (Game.main != null) Game.main.Remove (this);
}
//------------------------------------------------------------------------------------------------------------------------
// Render
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Get all a list of all objects that currently overlap this one.
/// Calling this method will test collisions between this object and all other colliders in the scene.
/// It can be called mid-step and is included for convenience, not performance.
/// </summary>
public GameObject[] GetCollisions ()
{
return game.GetGameObjectCollisions(this);
}
//------------------------------------------------------------------------------------------------------------------------
// Render
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// This function is called by the renderer. You can override it to change this object's rendering behaviour.
/// When not inside the GXPEngine package, specify the parameter as GXPEngine.Core.GLContext.
/// This function was made public to accomoadate split screen rendering. Use SetViewPort for that.
/// </summary>
/// <param name='glContext'>
/// Gl context, will be supplied by internal caller.
/// </param>
public virtual void Render(GLContext glContext) {
if (visible) {
glContext.PushMatrix(matrix);
RenderSelf (glContext);
foreach (GameObject child in GetChildren()) {
child.Render(glContext);
}
glContext.PopMatrix();
}
}
//------------------------------------------------------------------------------------------------------------------------
// RenderSelf
//------------------------------------------------------------------------------------------------------------------------
protected virtual void RenderSelf(GLContext glContext) {
if (visible == false) return;
glContext.PushMatrix(matrix);
glContext.PopMatrix();
}
//------------------------------------------------------------------------------------------------------------------------
// parent
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Gets or sets the parent GameObject.
/// When the parent moves, this object moves along.
/// </summary>
public GameObject parent {
get { return _parent; }
set {
if (_parent != null) {
_parent.removeChild(this);
_parent = null;
}
_parent = value;
if (value != null) {
_parent.addChild(this);
}
}
}
//------------------------------------------------------------------------------------------------------------------------
// AddChild()
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Adds the specified GameObject as a child to this one.
/// </summary>
/// <param name='child'>
/// Child object to add.
/// </param>
public void AddChild(GameObject child) {
child.parent = this;
}
//------------------------------------------------------------------------------------------------------------------------
// RemoveChild()
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Removes the specified child GameObject from this object.
/// </summary>
/// <param name='child'>
/// Child object to remove.
/// </param>
public void RemoveChild (GameObject child)
{
if (child.parent == this) {
child.parent = null;
}
}
//------------------------------------------------------------------------------------------------------------------------
// removeChild()
//------------------------------------------------------------------------------------------------------------------------
private void removeChild(GameObject child) {
_children.Remove(child);
}
//------------------------------------------------------------------------------------------------------------------------
// addChild()
//------------------------------------------------------------------------------------------------------------------------
private void addChild(GameObject child) {
if (child.HasChild(this)) return; //no recursive adding
_children.Add(child);
return;
}
//------------------------------------------------------------------------------------------------------------------------
// AddChildAt()
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Adds the specified GameObject as a child to this object at an specified index.
/// This will alter the position of other objects as well.
/// You can use this to determine the layer order (z-order) of child objects.
/// </summary>
/// <param name='child'>
/// Child object to add.
/// </param>
/// <param name='index'>
/// Index in the child list where the object should be added.
/// </param>
public void AddChildAt(GameObject child, int index) {
if (child.parent != this) {
AddChild(child);
}
if (index < 0) index = 0;
if (index >= _children.Count) index = _children.Count - 1;
_children.Remove(child);
_children.Insert(index, child);
}
//------------------------------------------------------------------------------------------------------------------------
// HasChild()
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Returns 'true' if the specified object is a child of this object.
/// </summary>
/// <param name='gameObject'>
/// The GameObject that should be tested.
/// </param>
public bool HasChild(GameObject gameObject) {
GameObject par = gameObject;
while (par != null) {
if (par == this) return true;
par = par.parent;
}
return false;
}
//------------------------------------------------------------------------------------------------------------------------
// GetChildren()
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Returns a list of all children that belong to this object.
/// The function returns System.Collections.Generic.List<GameObject>.
/// </summary>
public List<GameObject> GetChildren() {
return _children;
}
//------------------------------------------------------------------------------------------------------------------------
// SetChildIndex()
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Inserts the specified object in this object's child list at given location.
/// This will alter the position of other objects as well.
/// You can use this to determine the layer order (z-order) of child objects.
/// </summary>
/// <param name='child'>
/// Child.
/// </param>
/// <param name='index'>
/// Index.
/// </param>
public void SetChildIndex(GameObject child, int index) {
if (child.parent != this) AddChild(child);
if (index < 0) index = 0;
if (index >= _children.Count) index = _children.Count - 1;
_children.Remove(child);
_children.Insert(index, child);
}
//------------------------------------------------------------------------------------------------------------------------
// HitTest()
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Tests if this object overlaps the one specified.
/// </summary>
/// <returns>
/// <c>true</c>, if test was hit, <c>false</c> otherwise.
/// </returns>
/// <param name='other'>
/// Other.
/// </param>
virtual public bool HitTest(GameObject other) {
return _collider != null && other._collider != null && _collider.HitTest (other._collider);
}
//------------------------------------------------------------------------------------------------------------------------
// HitTestPoint()
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Returns 'true' if a 2D point overlaps this object, false otherwise
/// You could use this for instance to check if the mouse (Input.mouseX, Input.mouseY) is over the object.
/// </summary>
/// <param name='x'>
/// The x coordinate to test.
/// </param>
/// <param name='y'>
/// The y coordinate to test.
/// </param>
virtual public bool HitTestPoint(float x, float y) {
return _collider != null && _collider.HitTestPoint(x, y);
}
//------------------------------------------------------------------------------------------------------------------------
// TransformPoint()
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Transforms the point from local to global space.
/// If you insert a point relative to the object, it will return that same point relative to the game.
/// </summary>
/// <param name='x'>
/// The x coordinate to transform.
/// </param>
/// <param name='y'>
/// The y coordinate to transform.
/// </param>
public override Vector2 TransformPoint(float x, float y) {
Vector2 ret = base.TransformPoint (x, y);
if (parent == null) {
return ret;
} else {
return parent.TransformPoint (ret.x, ret.y);
}
}
//------------------------------------------------------------------------------------------------------------------------
// InverseTransformPoint()
//------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Transforms the point from global into local space.
/// If you insert a point relative to the stage, it will return that same point relative to this GameObject.
/// </summary>
/// <param name='x'>
/// The x coordinate to transform.
/// </param>
/// <param name='y'>
/// The y coordinate to transform.
/// </param>
public override Vector2 InverseTransformPoint(float x, float y) {
Vector2 ret = base.InverseTransformPoint (x, y);
if (parent == null) {
return ret;
} else {
return parent.InverseTransformPoint (ret.x, ret.y);
}
}
//------------------------------------------------------------------------------------------------------------------------
// ToString()
//------------------------------------------------------------------------------------------------------------------------
public override string ToString() {
return "[" + this.GetType().Name + "::" + name + "]";
}
}
}
| |
/*
* 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.Diagnostics;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using log4net;
namespace OpenSim.Framework.Console
{
/// <summary>
/// A console that uses cursor control and color
/// </summary>
public class LocalConsole : CommandConsole
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private readonly object m_syncRoot = new object();
private const string LOGLEVEL_NONE = "(none)";
private int m_cursorYPosition = -1;
private int m_cursorXPosition = 0;
private StringBuilder m_commandLine = new StringBuilder();
private bool m_echo = true;
private List<string> m_history = new List<string>();
private static readonly ConsoleColor[] Colors = {
// the dark colors don't seem to be visible on some black background terminals like putty :(
//ConsoleColor.DarkBlue,
//ConsoleColor.DarkGreen,
//ConsoleColor.DarkCyan,
//ConsoleColor.DarkMagenta,
//ConsoleColor.DarkYellow,
ConsoleColor.Gray,
//ConsoleColor.DarkGray,
ConsoleColor.Blue,
ConsoleColor.Green,
ConsoleColor.Cyan,
ConsoleColor.Magenta,
ConsoleColor.Yellow
};
private static ConsoleColor DeriveColor(string input)
{
// it is important to do Abs, hash values can be negative
return Colors[(Math.Abs(input.ToUpper().GetHashCode()) % Colors.Length)];
}
public LocalConsole(string defaultPrompt) : base(defaultPrompt)
{
}
private void AddToHistory(string text)
{
while (m_history.Count >= 100)
m_history.RemoveAt(0);
m_history.Add(text);
}
/// <summary>
/// Set the cursor row.
/// </summary>
///
/// <param name="top">
/// Row to set. If this is below 0, then the row is set to 0. If it is equal to the buffer height or greater
/// then it is set to one less than the height.
/// </param>
/// <returns>
/// The new cursor row.
/// </returns>
private int SetCursorTop(int top)
{
// From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try
// to set a cursor row position with a currently invalid column, mono will throw an exception.
// Therefore, we need to make sure that the column position is valid first.
int left = System.Console.CursorLeft;
if (left < 0)
{
System.Console.CursorLeft = 0;
}
else
{
int bufferWidth = System.Console.BufferWidth;
// On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
if (bufferWidth > 0 && left >= bufferWidth)
System.Console.CursorLeft = bufferWidth - 1;
}
if (top < 0)
{
top = 0;
}
else
{
int bufferHeight = System.Console.BufferHeight;
// On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
if (bufferHeight > 0 && top >= bufferHeight)
top = bufferHeight - 1;
}
System.Console.CursorTop = top;
return top;
}
/// <summary>
/// Set the cursor column.
/// </summary>
///
/// <param name="left">
/// Column to set. If this is below 0, then the column is set to 0. If it is equal to the buffer width or greater
/// then it is set to one less than the width.
/// </param>
/// <returns>
/// The new cursor column.
/// </returns>
private int SetCursorLeft(int left)
{
// From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try
// to set a cursor column position with a currently invalid row, mono will throw an exception.
// Therefore, we need to make sure that the row position is valid first.
int top = System.Console.CursorTop;
if (top < 0)
{
System.Console.CursorTop = 0;
}
else
{
int bufferHeight = System.Console.BufferHeight;
// On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
if (bufferHeight > 0 && top >= bufferHeight)
System.Console.CursorTop = bufferHeight - 1;
}
if (left < 0)
{
left = 0;
}
else
{
int bufferWidth = System.Console.BufferWidth;
// On Mono 2.4.2.3 (and possibly above), the buffer value is sometimes erroneously zero (Mantis 4657)
if (bufferWidth > 0 && left >= bufferWidth)
left = bufferWidth - 1;
}
System.Console.CursorLeft = left;
return left;
}
private void Show()
{
lock (m_commandLine)
{
if (m_cursorYPosition == -1 || System.Console.BufferWidth == 0)
return;
int xc = prompt.Length + m_cursorXPosition;
int new_x = xc % System.Console.BufferWidth;
int new_y = m_cursorYPosition + xc / System.Console.BufferWidth;
int end_y = m_cursorYPosition + (m_commandLine.Length + prompt.Length) / System.Console.BufferWidth;
if (end_y >= System.Console.BufferHeight) // wrap
{
m_cursorYPosition--;
new_y--;
SetCursorLeft(0);
SetCursorTop(System.Console.BufferHeight - 1);
System.Console.WriteLine(" ");
}
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
SetCursorLeft(0);
if (m_echo)
System.Console.Write("{0}{1}", prompt, m_commandLine);
else
System.Console.Write("{0}", prompt);
SetCursorTop(new_y);
SetCursorLeft(new_x);
}
}
public override void LockOutput()
{
Monitor.Enter(m_commandLine);
try
{
if (m_cursorYPosition != -1)
{
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
System.Console.CursorLeft = 0;
int count = m_commandLine.Length + prompt.Length;
while (count-- > 0)
System.Console.Write(" ");
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
SetCursorLeft(0);
}
}
catch (Exception)
{
}
}
public override void UnlockOutput()
{
if (m_cursorYPosition != -1)
{
m_cursorYPosition = System.Console.CursorTop;
Show();
}
Monitor.Exit(m_commandLine);
}
private void WriteColorText(ConsoleColor color, string sender)
{
try
{
lock (this)
{
try
{
System.Console.ForegroundColor = color;
System.Console.Write(sender);
System.Console.ResetColor();
}
catch (ArgumentNullException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(sender);
}
}
}
catch (ObjectDisposedException)
{
}
}
private void WriteLocalText(string text, string level)
{
string outText = text;
if (level != LOGLEVEL_NONE)
{
string regex = @"^(?<Front>.*?)\[(?<Category>[^\]]+)\]:?(?<End>.*)";
Regex RE = new Regex(regex, RegexOptions.Multiline);
MatchCollection matches = RE.Matches(text);
if (matches.Count == 1)
{
outText = matches[0].Groups["End"].Value;
System.Console.Write(matches[0].Groups["Front"].Value);
System.Console.Write("[");
WriteColorText(DeriveColor(matches[0].Groups["Category"].Value),
matches[0].Groups["Category"].Value);
System.Console.Write("]:");
}
else
{
outText = outText.Trim();
}
}
if (level == "error")
WriteColorText(ConsoleColor.Red, outText);
else if (level == "warn")
WriteColorText(ConsoleColor.Yellow, outText);
else
System.Console.Write(outText);
System.Console.WriteLine();
}
public override void Output(string text)
{
Output(text, LOGLEVEL_NONE);
}
public override void Output(string text, string level)
{
FireOnOutput(text);
lock (m_commandLine)
{
if (m_cursorYPosition == -1)
{
WriteLocalText(text, level);
return;
}
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
SetCursorLeft(0);
int count = m_commandLine.Length + prompt.Length;
while (count-- > 0)
System.Console.Write(" ");
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
SetCursorLeft(0);
WriteLocalText(text, level);
m_cursorYPosition = System.Console.CursorTop;
Show();
}
}
private bool ContextHelp()
{
string[] words = Parser.Parse(m_commandLine.ToString());
bool trailingSpace = m_commandLine.ToString().EndsWith(" ");
// Allow ? through while typing a URI
//
if (words.Length > 0 && words[words.Length-1].StartsWith("http") && !trailingSpace)
return false;
string[] opts = Commands.FindNextOption(words, trailingSpace);
if (opts[0].StartsWith("Command help:"))
Output(opts[0]);
else
Output(String.Format("Options: {0}", String.Join(" ", opts)));
return true;
}
public override string ReadLine(string p, bool isCommand, bool e)
{
m_cursorXPosition = 0;
prompt = p;
m_echo = e;
int historyLine = m_history.Count;
SetCursorLeft(0); // Needed for mono
System.Console.Write(" "); // Needed for mono
lock (m_commandLine)
{
m_cursorYPosition = System.Console.CursorTop;
m_commandLine.Remove(0, m_commandLine.Length);
}
while (true)
{
Show();
ConsoleKeyInfo key = System.Console.ReadKey(true);
char enteredChar = key.KeyChar;
if (!Char.IsControl(enteredChar))
{
if (m_cursorXPosition >= 318)
continue;
if (enteredChar == '?' && isCommand)
{
if (ContextHelp())
continue;
}
m_commandLine.Insert(m_cursorXPosition, enteredChar);
m_cursorXPosition++;
}
else
{
switch (key.Key)
{
case ConsoleKey.Backspace:
if (m_cursorXPosition == 0)
break;
m_commandLine.Remove(m_cursorXPosition-1, 1);
m_cursorXPosition--;
SetCursorLeft(0);
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
if (m_echo)
System.Console.Write("{0}{1} ", prompt, m_commandLine);
else
System.Console.Write("{0}", prompt);
break;
case ConsoleKey.Delete:
if (m_cursorXPosition == m_commandLine.Length)
break;
m_commandLine.Remove(m_cursorXPosition, 1);
SetCursorLeft(0);
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
if (m_echo)
System.Console.Write("{0}{1} ", prompt, m_commandLine);
else
System.Console.Write("{0}", prompt);
break;
case ConsoleKey.End:
m_cursorXPosition = m_commandLine.Length;
break;
case ConsoleKey.Home:
m_cursorXPosition = 0;
break;
case ConsoleKey.UpArrow:
if (historyLine < 1)
break;
historyLine--;
LockOutput();
m_commandLine.Remove(0, m_commandLine.Length);
m_commandLine.Append(m_history[historyLine]);
m_cursorXPosition = m_commandLine.Length;
UnlockOutput();
break;
case ConsoleKey.DownArrow:
if (historyLine >= m_history.Count)
break;
historyLine++;
LockOutput();
if (historyLine == m_history.Count)
{
m_commandLine.Remove(0, m_commandLine.Length);
}
else
{
m_commandLine.Remove(0, m_commandLine.Length);
m_commandLine.Append(m_history[historyLine]);
}
m_cursorXPosition = m_commandLine.Length;
UnlockOutput();
break;
case ConsoleKey.LeftArrow:
if (m_cursorXPosition > 0)
m_cursorXPosition--;
break;
case ConsoleKey.RightArrow:
if (m_cursorXPosition < m_commandLine.Length)
m_cursorXPosition++;
break;
case ConsoleKey.Enter:
SetCursorLeft(0);
m_cursorYPosition = SetCursorTop(m_cursorYPosition);
System.Console.WriteLine();
//Show();
lock (m_commandLine)
{
m_cursorYPosition = -1;
}
string commandLine = m_commandLine.ToString();
if (isCommand)
{
string[] cmd = Commands.Resolve(Parser.Parse(commandLine));
if (cmd.Length != 0)
{
int index;
for (index=0 ; index < cmd.Length ; index++)
{
if (cmd[index].Contains(" "))
cmd[index] = "\"" + cmd[index] + "\"";
}
AddToHistory(String.Join(" ", cmd));
return String.Empty;
}
}
// If we're not echoing to screen (e.g. a password) then we probably don't want it in history
if (m_echo && commandLine != "")
AddToHistory(commandLine);
return commandLine;
default:
break;
}
}
}
}
}
}
| |
// 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 System.Diagnostics;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Platform;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Input.Bindings;
using osu.Game.IO;
using osu.Game.Online.API;
using osu.Game.Overlays;
using osu.Game.Rulesets;
using osu.Game.Screens.Backgrounds;
using osu.Game.Screens.Edit;
using osu.Game.Screens.OnlinePlay.Multiplayer;
using osu.Game.Screens.OnlinePlay.Playlists;
using osu.Game.Screens.Select;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Menu
{
public class MainMenu : OsuScreen, IHandlePresentBeatmap, IKeyBindingHandler<GlobalAction>
{
public const float FADE_IN_DURATION = 300;
public const float FADE_OUT_DURATION = 400;
public override bool HideOverlaysOnEnter => buttons == null || buttons.State == ButtonSystemState.Initial;
public override bool AllowBackButton => false;
public override bool AllowExternalScreenChange => true;
private Screen songSelect;
private MenuSideFlashes sideFlashes;
private ButtonSystem buttons;
[Resolved]
private GameHost host { get; set; }
[Resolved]
private MusicController musicController { get; set; }
[Resolved(canBeNull: true)]
private LoginOverlay login { get; set; }
[Resolved]
private IAPIProvider api { get; set; }
[Resolved(canBeNull: true)]
private DialogOverlay dialogOverlay { get; set; }
private BackgroundScreenDefault background;
protected override BackgroundScreen CreateBackground() => background;
private Bindable<double> holdDelay;
private Bindable<bool> loginDisplayed;
private ExitConfirmOverlay exitConfirmOverlay;
private ParallaxContainer buttonsContainer;
private SongTicker songTicker;
[BackgroundDependencyLoader(true)]
private void load(BeatmapListingOverlay beatmapListing, SettingsOverlay settings, OsuConfigManager config, SessionStatics statics)
{
holdDelay = config.GetBindable<double>(OsuSetting.UIHoldActivationDelay);
loginDisplayed = statics.GetBindable<bool>(Static.LoginOverlayDisplayed);
if (host.CanExit)
{
AddInternal(exitConfirmOverlay = new ExitConfirmOverlay
{
Action = () =>
{
if (holdDelay.Value > 0)
confirmAndExit();
else
this.Exit();
}
});
}
AddRangeInternal(new[]
{
buttonsContainer = new ParallaxContainer
{
ParallaxAmount = 0.01f,
Children = new Drawable[]
{
buttons = new ButtonSystem
{
OnEdit = delegate
{
Beatmap.SetDefault();
this.Push(new EditorLoader());
},
OnSolo = loadSoloSongSelect,
OnMultiplayer = () => this.Push(new Multiplayer()),
OnPlaylists = () => this.Push(new Playlists()),
OnExit = confirmAndExit,
}
}
},
sideFlashes = new MenuSideFlashes(),
songTicker = new SongTicker
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Margin = new MarginPadding { Right = 15, Top = 5 }
},
exitConfirmOverlay?.CreateProxy() ?? Empty()
});
buttons.StateChanged += state =>
{
switch (state)
{
case ButtonSystemState.Initial:
case ButtonSystemState.Exit:
ApplyToBackground(b => b.FadeColour(Color4.White, 500, Easing.OutSine));
break;
default:
ApplyToBackground(b => b.FadeColour(OsuColour.Gray(0.8f), 500, Easing.OutSine));
break;
}
};
buttons.OnSettings = () => settings?.ToggleVisibility();
buttons.OnBeatmapListing = () => beatmapListing?.ToggleVisibility();
LoadComponentAsync(background = new BackgroundScreenDefault());
preloadSongSelect();
}
[Resolved(canBeNull: true)]
private OsuGame game { get; set; }
private void confirmAndExit()
{
if (exitConfirmed) return;
exitConfirmed = true;
game?.PerformFromScreen(menu => menu.Exit());
}
private void preloadSongSelect()
{
if (songSelect == null)
LoadComponentAsync(songSelect = new PlaySongSelect());
}
private void loadSoloSongSelect() => this.Push(consumeSongSelect());
private Screen consumeSongSelect()
{
var s = songSelect;
songSelect = null;
return s;
}
[Resolved]
private Storage storage { get; set; }
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
buttons.FadeInFromZero(500);
if (last is IntroScreen && musicController.TrackLoaded)
{
var track = musicController.CurrentTrack;
// presume the track is the current beatmap's track. not sure how correct this assumption is but it has worked until now.
if (!track.IsRunning)
{
Beatmap.Value.PrepareTrackForPreviewLooping();
track.Restart();
}
}
if (storage is OsuStorage osuStorage && osuStorage.Error != OsuStorageError.None)
dialogOverlay?.Push(new StorageErrorDialog(osuStorage, osuStorage.Error));
}
private bool exitConfirmed;
protected override void LogoArriving(OsuLogo logo, bool resuming)
{
base.LogoArriving(logo, resuming);
buttons.SetOsuLogo(logo);
logo.FadeColour(Color4.White, 100, Easing.OutQuint);
logo.FadeIn(100, Easing.OutQuint);
if (resuming)
{
buttons.State = ButtonSystemState.TopLevel;
this.FadeIn(FADE_IN_DURATION, Easing.OutQuint);
buttonsContainer.MoveTo(new Vector2(0, 0), FADE_IN_DURATION, Easing.OutQuint);
sideFlashes.Delay(FADE_IN_DURATION).FadeIn(64, Easing.InQuint);
}
else if (!api.IsLoggedIn)
{
// copy out old action to avoid accidentally capturing logo.Action in closure, causing a self-reference loop.
var previousAction = logo.Action;
// we want to hook into logo.Action to display the login overlay, but also preserve the return value of the old action.
// therefore pass the old action to displayLogin, so that it can return that value.
// this ensures that the OsuLogo sample does not play when it is not desired.
logo.Action = () => displayLogin(previousAction);
}
bool displayLogin(Func<bool> originalAction)
{
if (!loginDisplayed.Value)
{
Scheduler.AddDelayed(() => login?.Show(), 500);
loginDisplayed.Value = true;
}
return originalAction.Invoke();
}
}
protected override void LogoSuspending(OsuLogo logo)
{
var seq = logo.FadeOut(300, Easing.InSine)
.ScaleTo(0.2f, 300, Easing.InSine);
seq.OnComplete(_ => buttons.SetOsuLogo(null));
seq.OnAbort(_ => buttons.SetOsuLogo(null));
}
public override void OnSuspending(IScreen next)
{
base.OnSuspending(next);
buttons.State = ButtonSystemState.EnteringMode;
this.FadeOut(FADE_OUT_DURATION, Easing.InSine);
buttonsContainer.MoveTo(new Vector2(-800, 0), FADE_OUT_DURATION, Easing.InSine);
sideFlashes.FadeOut(64, Easing.OutQuint);
}
public override void OnResuming(IScreen last)
{
base.OnResuming(last);
ApplyToBackground(b => (b as BackgroundScreenDefault)?.Next());
// we may have consumed our preloaded instance, so let's make another.
preloadSongSelect();
musicController.EnsurePlayingSomething();
}
public override bool OnExiting(IScreen next)
{
if (!exitConfirmed && dialogOverlay != null)
{
if (dialogOverlay.CurrentDialog is ConfirmExitDialog exitDialog)
exitDialog.PerformOkAction();
else
dialogOverlay.Push(new ConfirmExitDialog(confirmAndExit, () => exitConfirmOverlay.Abort()));
return true;
}
buttons.State = ButtonSystemState.Exit;
OverlayActivationMode.Value = OverlayActivation.Disabled;
songTicker.Hide();
this.FadeOut(3000);
return base.OnExiting(next);
}
public void PresentBeatmap(WorkingBeatmap beatmap, RulesetInfo ruleset)
{
Beatmap.Value = beatmap;
Ruleset.Value = ruleset;
Schedule(loadSoloSongSelect);
}
public bool OnPressed(KeyBindingPressEvent<GlobalAction> e)
{
if (e.Repeat)
return false;
switch (e.Action)
{
case GlobalAction.Back:
// In the case of a host being able to exit, the back action is handled by ExitConfirmOverlay.
Debug.Assert(!host.CanExit);
return host.SuspendToBackground();
}
return false;
}
public void OnReleased(KeyBindingReleaseEvent<GlobalAction> e)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.AspNetCore.Http;
using Xunit;
namespace Microsoft.AspNetCore.Routing
{
public class RoutePatternMatcherTest
{
[Fact]
public void TryMatch_Success()
{
// Arrange
var matcher = CreateMatcher("{controller}/{action}/{id}");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/Bank/DoAction/123", values);
// Assert
Assert.True(match);
Assert.Equal("Bank", values["controller"]);
Assert.Equal("DoAction", values["action"]);
Assert.Equal("123", values["id"]);
}
[Fact]
public void TryMatch_Fails()
{
// Arrange
var matcher = CreateMatcher("{controller}/{action}/{id}");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/Bank/DoAction", values);
// Assert
Assert.False(match);
}
[Fact]
public void TryMatch_WithDefaults_Success()
{
// Arrange
var matcher = CreateMatcher("{controller}/{action}/{id}", new { id = "default id" });
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/Bank/DoAction", values);
// Assert
Assert.True(match);
Assert.Equal("Bank", values["controller"]);
Assert.Equal("DoAction", values["action"]);
Assert.Equal("default id", values["id"]);
}
[Fact]
public void TryMatch_WithDefaults_Fails()
{
// Arrange
var matcher = CreateMatcher("{controller}/{action}/{id}", new { id = "default id" });
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/Bank", values);
// Assert
Assert.False(match);
}
[Fact]
public void TryMatch_WithLiterals_Success()
{
// Arrange
var matcher = CreateMatcher("moo/{p1}/bar/{p2}", new { p2 = "default p2" });
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/moo/111/bar/222", values);
// Assert
Assert.True(match);
Assert.Equal("111", values["p1"]);
Assert.Equal("222", values["p2"]);
}
[Fact]
public void TryMatch_RouteWithLiteralsAndDefaults_Success()
{
// Arrange
var matcher = CreateMatcher("moo/{p1}/bar/{p2}", new { p2 = "default p2" });
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/moo/111/bar/", values);
// Assert
Assert.True(match);
Assert.Equal("111", values["p1"]);
Assert.Equal("default p2", values["p2"]);
}
[Theory]
[InlineData(@"{p1:regex(^\d{{3}}-\d{{3}}-\d{{4}}$)}", "/123-456-7890")] // ssn
[InlineData(@"{p1:regex(^\w+\@\w+\.\w+)}", "/[email protected]")] // email
[InlineData(@"{p1:regex(([}}])\w+)}", "/}sda")] // Not balanced }
[InlineData(@"{p1:regex(([{{)])\w+)}", "/})sda")] // Not balanced {
public void TryMatch_RegularExpressionConstraint_Valid(
string template,
string path)
{
// Arrange
var matcher = CreateMatcher(template);
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch(path, values);
// Assert
Assert.True(match);
}
[Theory]
[InlineData("moo/{p1}.{p2?}", "/moo/foo.bar", true, "foo", "bar")]
[InlineData("moo/{p1?}", "/moo/foo", true, "foo", null)]
[InlineData("moo/{p1?}", "/moo", true, null, null)]
[InlineData("moo/{p1}.{p2?}", "/moo/foo", true, "foo", null)]
[InlineData("moo/{p1}.{p2?}", "/moo/foo..bar", true, "foo.", "bar")]
[InlineData("moo/{p1}.{p2?}", "/moo/foo.moo.bar", true, "foo.moo", "bar")]
[InlineData("moo/{p1}.{p2}", "/moo/foo.bar", true, "foo", "bar")]
[InlineData("moo/foo.{p1}.{p2?}", "/moo/foo.moo.bar", true, "moo", "bar")]
[InlineData("moo/foo.{p1}.{p2?}", "/moo/foo.moo", true, "moo", null)]
[InlineData("moo/.{p2?}", "/moo/.foo", true, null, "foo")]
[InlineData("moo/.{p2?}", "/moo", false, null, null)]
[InlineData("moo/{p1}.{p2?}", "/moo/....", true, "..", ".")]
[InlineData("moo/{p1}.{p2?}", "/moo/.bar", true, ".bar", null)]
public void TryMatch_OptionalParameter_FollowedByPeriod_Valid(
string template,
string path,
bool expectedMatch,
string p1,
string p2)
{
// Arrange
var matcher = CreateMatcher(template);
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch(path, values);
// Assert
Assert.Equal(expectedMatch, match);
if (p1 != null)
{
Assert.Equal(p1, values["p1"]);
}
if (p2 != null)
{
Assert.Equal(p2, values["p2"]);
}
}
[Theory]
[InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo.moo.bar", "foo", "moo", "bar")]
[InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo.moo", "foo", "moo", null)]
[InlineData("moo/{p1}.{p2}.{p3}.{p4?}", "/moo/foo.moo.bar", "foo", "moo", "bar")]
[InlineData("{p1}.{p2?}/{p3}", "/foo.moo/bar", "foo", "moo", "bar")]
[InlineData("{p1}.{p2?}/{p3}", "/foo/bar", "foo", null, "bar")]
[InlineData("{p1}.{p2?}/{p3}", "/.foo/bar", ".foo", null, "bar")]
[InlineData("{p1}/{p2}/{p3?}", "/foo/bar/baz", "foo", "bar", "baz")]
public void TryMatch_OptionalParameter_FollowedByPeriod_3Parameters_Valid(
string template,
string path,
string p1,
string p2,
string p3)
{
// Arrange
var matcher = CreateMatcher(template);
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch(path, values);
// Assert
Assert.True(match);
Assert.Equal(p1, values["p1"]);
if (p2 != null)
{
Assert.Equal(p2, values["p2"]);
}
if (p3 != null)
{
Assert.Equal(p3, values["p3"]);
}
}
[Theory]
[InlineData("moo/{p1}.{p2?}", "/moo/foo.")]
[InlineData("moo/{p1}.{p2?}", "/moo/.")]
[InlineData("moo/{p1}.{p2}", "/foo.")]
[InlineData("moo/{p1}.{p2}", "/foo")]
[InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo.moo.")]
[InlineData("moo/foo.{p2}.{p3?}", "/moo/bar.foo.moo")]
[InlineData("moo/foo.{p2}.{p3?}", "/moo/kungfoo.moo.bar")]
[InlineData("moo/foo.{p2}.{p3?}", "/moo/kungfoo.moo")]
[InlineData("moo/{p1}.{p2}.{p3?}", "/moo/foo")]
[InlineData("{p1}.{p2?}/{p3}", "/foo./bar")]
[InlineData("moo/.{p2?}", "/moo/.")]
[InlineData("{p1}.{p2}/{p3}", "/.foo/bar")]
public void TryMatch_OptionalParameter_FollowedByPeriod_Invalid(string template, string path)
{
// Arrange
var matcher = CreateMatcher(template);
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch(path, values);
// Assert
Assert.False(match);
}
[Fact]
public void TryMatch_RouteWithOnlyLiterals_Success()
{
// Arrange
var matcher = CreateMatcher("moo/bar");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/moo/bar", values);
// Assert
Assert.True(match);
Assert.Empty(values);
}
[Fact]
public void TryMatch_RouteWithOnlyLiterals_Fails()
{
// Arrange
var matcher = CreateMatcher("moo/bars");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/moo/bar", values);
// Assert
Assert.False(match);
}
[Fact]
public void TryMatch_RouteWithExtraSeparators_Success()
{
// Arrange
var matcher = CreateMatcher("moo/bar");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/moo/bar/", values);
// Assert
Assert.True(match);
Assert.Empty(values);
}
[Fact]
public void TryMatch_UrlWithExtraSeparators_Success()
{
// Arrange
var matcher = CreateMatcher("moo/bar/");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/moo/bar", values);
// Assert
Assert.True(match);
Assert.Empty(values);
}
[Fact]
public void TryMatch_RouteWithParametersAndExtraSeparators_Success()
{
// Arrange
var matcher = CreateMatcher("{p1}/{p2}/");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/moo/bar", values);
// Assert
Assert.True(match);
Assert.Equal("moo", values["p1"]);
Assert.Equal("bar", values["p2"]);
}
[Fact]
public void TryMatch_RouteWithDifferentLiterals_Fails()
{
// Arrange
var matcher = CreateMatcher("{p1}/{p2}/baz");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/moo/bar/boo", values);
// Assert
Assert.False(match);
}
[Fact]
public void TryMatch_LongerUrl_Fails()
{
// Arrange
var matcher = CreateMatcher("{p1}");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/moo/bar", values);
// Assert
Assert.False(match);
}
[Fact]
public void TryMatch_SimpleFilename_Success()
{
// Arrange
var matcher = CreateMatcher("DEFAULT.ASPX");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/default.aspx", values);
// Assert
Assert.True(match);
}
[Theory]
[InlineData("{prefix}x{suffix}", "/xxxxxxxxxx")]
[InlineData("{prefix}xyz{suffix}", "/xxxxyzxyzxxxxxxyz")]
[InlineData("{prefix}xyz{suffix}", "/abcxxxxyzxyzxxxxxxyzxx")]
[InlineData("{prefix}xyz{suffix}", "/xyzxyzxyzxyzxyz")]
[InlineData("{prefix}xyz{suffix}", "/xyzxyzxyzxyzxyz1")]
[InlineData("{prefix}xyz{suffix}", "/xyzxyzxyz")]
[InlineData("{prefix}aa{suffix}", "/aaaaa")]
[InlineData("{prefix}aaa{suffix}", "/aaaaa")]
public void TryMatch_RouteWithComplexSegment_Success(string template, string path)
{
var matcher = CreateMatcher(template);
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch(path, values);
// Assert
Assert.True(match);
}
[Fact]
public void TryMatch_RouteWithExtraDefaultValues_Success()
{
// Arrange
var matcher = CreateMatcher("{p1}/{p2}", new { p2 = (string)null, foo = "bar" });
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/v1", values);
// Assert
Assert.True(match);
Assert.Equal<int>(3, values.Count);
Assert.Equal("v1", values["p1"]);
Assert.Null(values["p2"]);
Assert.Equal("bar", values["foo"]);
}
[Fact]
public void TryMatch_PrettyRouteWithExtraDefaultValues_Success()
{
// Arrange
var matcher = CreateMatcher(
"date/{y}/{m}/{d}",
new { controller = "blog", action = "showpost", m = (string)null, d = (string)null });
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/date/2007/08", values);
// Assert
Assert.True(match);
Assert.Equal<int>(5, values.Count);
Assert.Equal("blog", values["controller"]);
Assert.Equal("showpost", values["action"]);
Assert.Equal("2007", values["y"]);
Assert.Equal("08", values["m"]);
Assert.Null(values["d"]);
}
[Fact]
public void TryMatch_WithMultiSegmentParamsOnBothEndsMatches()
{
RunTest(
"language/{lang}-{region}",
"/language/en-US",
null,
new RouteValueDictionary(new { lang = "en", region = "US" }));
}
[Fact]
public void TryMatch_WithMultiSegmentParamsOnLeftEndMatches()
{
RunTest(
"language/{lang}-{region}a",
"/language/en-USa",
null,
new RouteValueDictionary(new { lang = "en", region = "US" }));
}
[Fact]
public void TryMatch_WithMultiSegmentParamsOnRightEndMatches()
{
RunTest(
"language/a{lang}-{region}",
"/language/aen-US",
null,
new RouteValueDictionary(new { lang = "en", region = "US" }));
}
[Fact]
public void TryMatch_WithMultiSegmentParamsOnNeitherEndMatches()
{
RunTest(
"language/a{lang}-{region}a",
"/language/aen-USa",
null,
new RouteValueDictionary(new { lang = "en", region = "US" }));
}
[Fact]
public void TryMatch_WithMultiSegmentParamsOnNeitherEndDoesNotMatch()
{
RunTest(
"language/a{lang}-{region}a",
"/language/a-USa",
null,
null);
}
[Fact]
public void TryMatch_WithMultiSegmentParamsOnNeitherEndDoesNotMatch2()
{
RunTest(
"language/a{lang}-{region}a",
"/language/aen-a",
null,
null);
}
[Fact]
public void TryMatch_WithSimpleMultiSegmentParamsOnBothEndsMatches()
{
RunTest(
"language/{lang}",
"/language/en",
null,
new RouteValueDictionary(new { lang = "en" }));
}
[Fact]
public void TryMatch_WithSimpleMultiSegmentParamsOnBothEndsTrailingSlashDoesNotMatch()
{
RunTest(
"language/{lang}",
"/language/",
null,
null);
}
[Fact]
public void TryMatch_WithSimpleMultiSegmentParamsOnBothEndsDoesNotMatch()
{
RunTest(
"language/{lang}",
"/language",
null,
null);
}
[Fact]
public void TryMatch_WithSimpleMultiSegmentParamsOnLeftEndMatches()
{
RunTest(
"language/{lang}-",
"/language/en-",
null,
new RouteValueDictionary(new { lang = "en" }));
}
[Fact]
public void TryMatch_WithSimpleMultiSegmentParamsOnRightEndMatches()
{
RunTest(
"language/a{lang}",
"/language/aen",
null,
new RouteValueDictionary(new { lang = "en" }));
}
[Fact]
public void TryMatch_WithSimpleMultiSegmentParamsOnNeitherEndMatches()
{
RunTest(
"language/a{lang}a",
"/language/aena",
null,
new RouteValueDictionary(new { lang = "en" }));
}
[Fact]
public void TryMatch_WithMultiSegmentStandamatchMvcRouteMatches()
{
RunTest(
"{controller}.mvc/{action}/{id}",
"/home.mvc/index",
new RouteValueDictionary(new { action = "Index", id = (string)null }),
new RouteValueDictionary(new { controller = "home", action = "index", id = (string)null }));
}
[Fact]
public void TryMatch_WithMultiSegmentParamsOnBothEndsWithDefaultValuesMatches()
{
RunTest(
"language/{lang}-{region}",
"/language/-",
new RouteValueDictionary(new { lang = "xx", region = "yy" }),
null);
}
[Fact]
public void TryMatch_WithUrlWithMultiSegmentWithRepeatedDots()
{
RunTest(
"{Controller}..mvc/{id}/{Param1}",
"/Home..mvc/123/p1",
null,
new RouteValueDictionary(new { Controller = "Home", id = "123", Param1 = "p1" }));
}
[Fact]
public void TryMatch_WithUrlWithTwoRepeatedDots()
{
RunTest(
"{Controller}.mvc/../{action}",
"/Home.mvc/../index",
null,
new RouteValueDictionary(new { Controller = "Home", action = "index" }));
}
[Fact]
public void TryMatch_WithUrlWithThreeRepeatedDots()
{
RunTest(
"{Controller}.mvc/.../{action}",
"/Home.mvc/.../index",
null,
new RouteValueDictionary(new { Controller = "Home", action = "index" }));
}
[Fact]
public void TryMatch_WithUrlWithManyRepeatedDots()
{
RunTest(
"{Controller}.mvc/../../../{action}",
"/Home.mvc/../../../index",
null,
new RouteValueDictionary(new { Controller = "Home", action = "index" }));
}
[Fact]
public void TryMatch_WithUrlWithExclamationPoint()
{
RunTest(
"{Controller}.mvc!/{action}",
"/Home.mvc!/index",
null,
new RouteValueDictionary(new { Controller = "Home", action = "index" }));
}
[Fact]
public void TryMatch_WithUrlWithStartingDotDotSlash()
{
RunTest(
"../{Controller}.mvc",
"/../Home.mvc",
null,
new RouteValueDictionary(new { Controller = "Home" }));
}
[Fact]
public void TryMatch_WithUrlWithStartingBackslash()
{
RunTest(
@"\{Controller}.mvc",
@"/\Home.mvc",
null,
new RouteValueDictionary(new { Controller = "Home" }));
}
[Fact]
public void TryMatch_WithUrlWithBackslashSeparators()
{
RunTest(
@"{Controller}.mvc\{id}\{Param1}",
@"/Home.mvc\123\p1",
null,
new RouteValueDictionary(new { Controller = "Home", id = "123", Param1 = "p1" }));
}
[Fact]
public void TryMatch_WithUrlWithParenthesesLiterals()
{
RunTest(
@"(Controller).mvc",
@"/(Controller).mvc",
null,
new RouteValueDictionary());
}
[Fact]
public void TryMatch_WithUrlWithTrailingSlashSpace()
{
RunTest(
@"Controller.mvc/ ",
@"/Controller.mvc/ ",
null,
new RouteValueDictionary());
}
[Fact]
public void TryMatch_WithUrlWithTrailingSpace()
{
RunTest(
@"Controller.mvc ",
@"/Controller.mvc ",
null,
new RouteValueDictionary());
}
[Fact]
public void TryMatch_WithCatchAllCapturesDots()
{
// DevDiv Bugs 189892: UrlRouting: Catch all parameter cannot capture url segments that contain the "."
RunTest(
"Home/ShowPilot/{missionId}/{*name}",
"/Home/ShowPilot/777/12345./foobar",
new RouteValueDictionary(new
{
controller = "Home",
action = "ShowPilot",
missionId = (string)null,
name = (string)null
}),
new RouteValueDictionary(new { controller = "Home", action = "ShowPilot", missionId = "777", name = "12345./foobar" }));
}
[Fact]
public void TryMatch_RouteWithCatchAll_MatchesMultiplePathSegments()
{
// Arrange
var matcher = CreateMatcher("{p1}/{*p2}");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/v1/v2/v3", values);
// Assert
Assert.True(match);
Assert.Equal<int>(2, values.Count);
Assert.Equal("v1", values["p1"]);
Assert.Equal("v2/v3", values["p2"]);
}
[Fact]
public void TryMatch_RouteWithCatchAll_MatchesTrailingSlash()
{
// Arrange
var matcher = CreateMatcher("{p1}/{*p2}");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/v1/", values);
// Assert
Assert.True(match);
Assert.Equal<int>(2, values.Count);
Assert.Equal("v1", values["p1"]);
Assert.Null(values["p2"]);
}
[Fact]
public void TryMatch_RouteWithCatchAll_MatchesEmptyContent()
{
// Arrange
var matcher = CreateMatcher("{p1}/{*p2}");
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch("/v1", values);
// Assert
Assert.True(match);
Assert.Equal<int>(2, values.Count);
Assert.Equal("v1", values["p1"]);
Assert.Null(values["p2"]);
}
[Fact]
public void TryMatch_RouteWithCatchAll_MatchesEmptyContent_DoesNotReplaceExistingRouteValue()
{
// Arrange
var matcher = CreateMatcher("{p1}/{*p2}");
var values = new RouteValueDictionary(new { p2 = "hello" });
// Act
var match = matcher.TryMatch("/v1", values);
// Assert
Assert.True(match);
Assert.Equal<int>(2, values.Count);
Assert.Equal("v1", values["p1"]);
Assert.Equal("hello", values["p2"]);
}
[Fact]
public void TryMatch_RouteWithCatchAll_UsesDefaultValueForEmptyContent()
{
// Arrange
var matcher = CreateMatcher("{p1}/{*p2}", new { p2 = "catchall" });
var values = new RouteValueDictionary(new { p2 = "overridden" });
// Act
var match = matcher.TryMatch("/v1", values);
// Assert
Assert.True(match);
Assert.Equal<int>(2, values.Count);
Assert.Equal("v1", values["p1"]);
Assert.Equal("catchall", values["p2"]);
}
[Fact]
public void TryMatch_RouteWithCatchAll_IgnoresDefaultValueForNonEmptyContent()
{
// Arrange
var matcher = CreateMatcher("{p1}/{*p2}", new { p2 = "catchall" });
var values = new RouteValueDictionary(new { p2 = "overridden" });
// Act
var match = matcher.TryMatch("/v1/hello/whatever", values);
// Assert
Assert.True(match);
Assert.Equal<int>(2, values.Count);
Assert.Equal("v1", values["p1"]);
Assert.Equal("hello/whatever", values["p2"]);
}
[Fact]
public void TryMatch_DoesNotMatchOnlyLeftLiteralMatch()
{
// DevDiv Bugs 191180: UrlRouting: Wrong template getting matched if a url segment is a substring of the requested url
RunTest(
"foo",
"/fooBAR",
null,
null);
}
[Fact]
public void TryMatch_DoesNotMatchOnlyRightLiteralMatch()
{
// DevDiv Bugs 191180: UrlRouting: Wrong template getting matched if a url segment is a substring of the requested url
RunTest(
"foo",
"/BARfoo",
null,
null);
}
[Fact]
public void TryMatch_DoesNotMatchMiddleLiteralMatch()
{
// DevDiv Bugs 191180: UrlRouting: Wrong template getting matched if a url segment is a substring of the requested url
RunTest(
"foo",
"/BARfooBAR",
null,
null);
}
[Fact]
public void TryMatch_DoesMatchesExactLiteralMatch()
{
// DevDiv Bugs 191180: UrlRouting: Wrong template getting matched if a url segment is a substring of the requested url
RunTest(
"foo",
"/foo",
null,
new RouteValueDictionary());
}
[Fact]
public void TryMatch_WithWeimatchParameterNames()
{
RunTest(
"foo/{ }/{.!$%}/{dynamic.data}/{op.tional}",
"/foo/space/weimatch/omatcherid",
new RouteValueDictionary() { { " ", "not a space" }, { "op.tional", "default value" }, { "ran!dom", "va@lue" } },
new RouteValueDictionary() { { " ", "space" }, { ".!$%", "weimatch" }, { "dynamic.data", "omatcherid" }, { "op.tional", "default value" }, { "ran!dom", "va@lue" } });
}
[Fact]
public void TryMatch_DoesNotMatchRouteWithLiteralSeparatomatchefaultsButNoValue()
{
RunTest(
"{controller}/{language}-{locale}",
"/foo",
new RouteValueDictionary(new { language = "en", locale = "US" }),
null);
}
[Fact]
public void TryMatch_DoesNotMatchesRouteWithLiteralSeparatomatchefaultsAndLeftValue()
{
RunTest(
"{controller}/{language}-{locale}",
"/foo/xx-",
new RouteValueDictionary(new { language = "en", locale = "US" }),
null);
}
[Fact]
public void TryMatch_DoesNotMatchesRouteWithLiteralSeparatomatchefaultsAndRightValue()
{
RunTest(
"{controller}/{language}-{locale}",
"/foo/-yy",
new RouteValueDictionary(new { language = "en", locale = "US" }),
null);
}
[Fact]
public void TryMatch_MatchesRouteWithLiteralSeparatomatchefaultsAndValue()
{
RunTest(
"{controller}/{language}-{locale}",
"/foo/xx-yy",
new RouteValueDictionary(new { language = "en", locale = "US" }),
new RouteValueDictionary { { "language", "xx" }, { "locale", "yy" }, { "controller", "foo" } });
}
[Fact]
public void TryMatch_SetsOptionalParameter()
{
// Arrange
var route = CreateMatcher("{controller}/{action?}");
var url = "/Home/Index";
var values = new RouteValueDictionary();
// Act
var match = route.TryMatch(url, values);
// Assert
Assert.True(match);
Assert.Equal(2, values.Count);
Assert.Equal("Home", values["controller"]);
Assert.Equal("Index", values["action"]);
}
[Fact]
public void TryMatch_DoesNotSetOptionalParameter()
{
// Arrange
var route = CreateMatcher("{controller}/{action?}");
var url = "/Home";
var values = new RouteValueDictionary();
// Act
var match = route.TryMatch(url, values);
// Assert
Assert.True(match);
Assert.Single(values);
Assert.Equal("Home", values["controller"]);
Assert.False(values.ContainsKey("action"));
}
[Fact]
public void TryMatch_DoesNotSetOptionalParameter_EmptyString()
{
// Arrange
var route = CreateMatcher("{controller?}");
var url = "";
var values = new RouteValueDictionary();
// Act
var match = route.TryMatch(url, values);
// Assert
Assert.True(match);
Assert.Empty(values);
Assert.False(values.ContainsKey("controller"));
}
[Fact]
public void TryMatch__EmptyRouteWith_EmptyString()
{
// Arrange
var route = CreateMatcher("");
var url = "";
var values = new RouteValueDictionary();
// Act
var match = route.TryMatch(url, values);
// Assert
Assert.True(match);
Assert.Empty(values);
}
[Fact]
public void TryMatch_MultipleOptionalParameters()
{
// Arrange
var route = CreateMatcher("{controller}/{action?}/{id?}");
var url = "/Home/Index";
var values = new RouteValueDictionary();
// Act
var match = route.TryMatch(url, values);
// Assert
Assert.True(match);
Assert.Equal(2, values.Count);
Assert.Equal("Home", values["controller"]);
Assert.Equal("Index", values["action"]);
Assert.False(values.ContainsKey("id"));
}
[Theory]
[InlineData("///")]
[InlineData("/a//")]
[InlineData("/a/b//")]
[InlineData("//b//")]
[InlineData("///c")]
[InlineData("///c/")]
public void TryMatch_MultipleOptionalParameters_WithEmptyIntermediateSegmentsDoesNotMatch(string url)
{
// Arrange
var route = CreateMatcher("{controller?}/{action?}/{id?}");
var values = new RouteValueDictionary();
// Act
var match = route.TryMatch(url, values);
// Assert
Assert.False(match);
}
[Theory]
[InlineData("")]
[InlineData("/")]
[InlineData("/a")]
[InlineData("/a/")]
[InlineData("/a/b")]
[InlineData("/a/b/")]
[InlineData("/a/b/c")]
[InlineData("/a/b/c/")]
public void TryMatch_MultipleOptionalParameters_WithIncrementalOptionalValues(string url)
{
// Arrange
var route = CreateMatcher("{controller?}/{action?}/{id?}");
var values = new RouteValueDictionary();
// Act
var match = route.TryMatch(url, values);
// Assert
Assert.True(match);
}
[Theory]
[InlineData("///")]
[InlineData("////")]
[InlineData("/a//")]
[InlineData("/a///")]
[InlineData("//b/")]
[InlineData("//b//")]
[InlineData("///c")]
[InlineData("///c/")]
public void TryMatch_MultipleParameters_WithEmptyValues(string url)
{
// Arrange
var route = CreateMatcher("{controller}/{action}/{id}");
var values = new RouteValueDictionary();
// Act
var match = route.TryMatch(url, values);
// Assert
Assert.False(match);
}
[Theory]
[InlineData("/a/b/c//")]
[InlineData("/a/b/c/////")]
public void TryMatch_CatchAllParameters_WithEmptyValuesAtTheEnd(string url)
{
// Arrange
var route = CreateMatcher("{controller}/{action}/{*id}");
var values = new RouteValueDictionary();
// Act
var match = route.TryMatch(url, values);
// Assert
Assert.True(match);
}
[Theory]
[InlineData("/a/b//")]
[InlineData("/a/b///c")]
public void TryMatch_CatchAllParameters_WithEmptyValues(string url)
{
// Arrange
var route = CreateMatcher("{controller}/{action}/{*id}");
var values = new RouteValueDictionary();
// Act
var match = route.TryMatch(url, values);
// Assert
Assert.False(match);
}
private RoutePatternMatcher CreateMatcher(string template, object defaults = null)
{
return new RoutePatternMatcher(
RoutePatternParser.Parse(template),
new RouteValueDictionary(defaults));
}
private static void RunTest(
string template,
string path,
RouteValueDictionary defaults,
IDictionary<string, object> expected)
{
// Arrange
var matcher = new RoutePatternMatcher(
RoutePatternParser.Parse(template),
defaults ?? new RouteValueDictionary());
var values = new RouteValueDictionary();
// Act
var match = matcher.TryMatch(new PathString(path), values);
// Assert
if (expected == null)
{
Assert.False(match);
}
else
{
Assert.True(match);
Assert.Equal(expected.Count, values.Count);
foreach (string key in values.Keys)
{
Assert.Equal(expected[key], values[key]);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma warning disable 1634, 1691
using System.Collections.Generic;
using System.Transactions;
using System.Management.Automation.Internal;
namespace System.Management.Automation
{
/// <summary>
/// The status of a PowerShell transaction.
/// </summary>
public enum PSTransactionStatus
{
/// <summary>
/// The transaction has been rolled back.
/// </summary>
RolledBack = 0,
/// <summary>
/// The transaction has been committed.
/// </summary>
Committed = 1,
/// <summary>
/// The transaction is currently active.
/// </summary>
Active = 2
}
/// <summary>
/// Represents an active transaction.
/// </summary>
public sealed class PSTransaction : IDisposable
{
/// <summary>
/// Initializes a new instance of the PSTransaction class.
/// </summary>
internal PSTransaction(RollbackSeverity rollbackPreference, TimeSpan timeout)
{
_transaction = new CommittableTransaction(timeout);
RollbackPreference = rollbackPreference;
_subscriberCount = 1;
}
/// <summary>
/// Initializes a new instance of the PSTransaction class using a CommittableTransaction.
/// </summary>
internal PSTransaction(CommittableTransaction transaction, RollbackSeverity severity)
{
_transaction = transaction;
RollbackPreference = severity;
_subscriberCount = 1;
}
private CommittableTransaction _transaction;
/// <summary>
/// Gets the rollback preference for this transaction.
/// </summary>
public RollbackSeverity RollbackPreference { get; }
/// <summary>
/// Gets the number of subscribers to this transaction.
/// </summary>
public int SubscriberCount
{
get
{
// Verify the transaction hasn't been rolled back beneath us
if (this.IsRolledBack)
{
this.SubscriberCount = 0;
}
return _subscriberCount;
}
set { _subscriberCount = value; }
}
private int _subscriberCount;
/// <summary>
/// Returns the status of this transaction.
/// </summary>
public PSTransactionStatus Status
{
get
{
if (IsRolledBack)
{
return PSTransactionStatus.RolledBack;
}
else if (IsCommitted)
{
return PSTransactionStatus.Committed;
}
else
{
return PSTransactionStatus.Active;
}
}
}
/// <summary>
/// Activates the transaction held by this PSTransaction.
/// </summary>
internal void Activate()
{
Transaction.Current = _transaction;
}
/// <summary>
/// Commits the transaction held by this PSTransaction.
/// </summary>
internal void Commit()
{
_transaction.Commit();
IsCommitted = true;
}
/// <summary>
/// Rolls back the transaction held by this PSTransaction.
/// </summary>
internal void Rollback()
{
_transaction.Rollback();
_isRolledBack = true;
}
/// <summary>
/// Determines whether this PSTransaction has been
/// rolled back or not.
/// </summary>
internal bool IsRolledBack
{
get
{
// Check if it's been aborted underneath us
if (
(!_isRolledBack) &&
(_transaction != null) &&
(_transaction.TransactionInformation.Status == TransactionStatus.Aborted))
{
_isRolledBack = true;
}
return _isRolledBack;
}
set
{
_isRolledBack = value;
}
}
private bool _isRolledBack = false;
/// <summary>
/// Determines whether this PSTransaction
/// has been committed or not.
/// </summary>
internal bool IsCommitted { get; set; } = false;
/// <summary>
/// Destructor for the PSTransaction class.
/// </summary>
~PSTransaction()
{
Dispose(false);
}
/// <summary>
/// Disposes the PSTransaction object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the PSTransaction object, which disposes the
/// underlying transaction.
/// <param name="disposing">
/// Whether to actually dispose the object.
/// </param>
/// </summary>
public void Dispose(bool disposing)
{
if (disposing)
{
if (_transaction != null)
{
_transaction.Dispose();
}
}
}
}
/// <summary>
/// Supports the transaction management infrastructure for the PowerShell engine.
/// </summary>
public sealed class PSTransactionContext : IDisposable
{
/// <summary>
/// Initializes a new instance of the PSTransactionManager class.
/// </summary>
internal PSTransactionContext(PSTransactionManager transactionManager)
{
_transactionManager = transactionManager;
transactionManager.SetActive();
}
private PSTransactionManager _transactionManager;
/// <summary>
/// Destructor for the PSTransactionManager class.
/// </summary>
~PSTransactionContext()
{
Dispose(false);
}
/// <summary>
/// Disposes the PSTransactionContext object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the PSTransactionContext object, which resets the
/// active PSTransaction.
/// <param name="disposing">
/// Whether to actually dispose the object.
/// </param>
/// </summary>
private void Dispose(bool disposing)
{
if (disposing)
{
_transactionManager.ResetActive();
}
}
}
/// <summary>
/// The severity of error that causes PowerShell to automatically
/// rollback the transaction.
/// </summary>
public enum RollbackSeverity
{
/// <summary>
/// Non-terminating errors or worse.
/// </summary>
Error,
/// <summary>
/// Terminating errors or worse.
/// </summary>
TerminatingError,
/// <summary>
/// Do not rollback the transaction on error.
/// </summary>
Never
}
}
namespace System.Management.Automation.Internal
{
/// <summary>
/// Supports the transaction management infrastructure for the PowerShell engine.
/// </summary>
internal sealed class PSTransactionManager : IDisposable
{
/// <summary>
/// Initializes a new instance of the PSTransactionManager class.
/// </summary>
internal PSTransactionManager()
{
_transactionStack = new Stack<PSTransaction>();
_transactionStack.Push(null);
}
/// <summary>
/// Called by engine APIs to ensure they are protected from
/// ambient transactions.
/// </summary>
internal static IDisposable GetEngineProtectionScope()
{
if (s_engineProtectionEnabled && (Transaction.Current != null))
{
return new System.Transactions.TransactionScope(
System.Transactions.TransactionScopeOption.Suppress);
}
else
{
return null;
}
}
/// <summary>
/// Called by the transaction manager to enable engine
/// protection the first time a transaction is activated.
/// Engine protection APIs remain protected from this point on.
/// </summary>
internal static void EnableEngineProtection()
{
s_engineProtectionEnabled = true;
}
private static bool s_engineProtectionEnabled = false;
/// <summary>
/// Gets the rollback preference for the active transaction.
/// </summary>
internal RollbackSeverity RollbackPreference
{
get
{
PSTransaction currentTransaction = _transactionStack.Peek();
if (currentTransaction == null)
{
string error = TransactionStrings.NoTransactionActive;
// This is not an expected condition, and is just protective
// coding.
#pragma warning suppress 56503
throw new InvalidOperationException(error);
}
return currentTransaction.RollbackPreference;
}
}
/// <summary>
/// Creates a new Transaction if none are active. Otherwise, increments
/// the subscriber count for the active transaction.
/// </summary>
internal void CreateOrJoin()
{
CreateOrJoin(RollbackSeverity.Error, TimeSpan.FromMinutes(1));
}
/// <summary>
/// Creates a new Transaction if none are active. Otherwise, increments
/// the subscriber count for the active transaction.
/// </summary>
internal void CreateOrJoin(RollbackSeverity rollbackPreference, TimeSpan timeout)
{
PSTransaction currentTransaction = _transactionStack.Peek();
// There is a transaction on the stack
if (currentTransaction != null)
{
// If you are already in a transaction that has been aborted, or committed,
// create it.
if (currentTransaction.IsRolledBack || currentTransaction.IsCommitted)
{
// Clean up the "used" one
_transactionStack.Pop().Dispose();
// And add a new one to the stack
_transactionStack.Push(new PSTransaction(rollbackPreference, timeout));
}
else
{
// This is a usable one. Add a subscriber to it.
currentTransaction.SubscriberCount++;
}
}
else
{
// Add a new transaction to the stack
_transactionStack.Push(new PSTransaction(rollbackPreference, timeout));
}
}
/// <summary>
/// Creates a new Transaction that should be managed independently of
/// any parent transactions.
/// </summary>
internal void CreateNew()
{
CreateNew(RollbackSeverity.Error, TimeSpan.FromMinutes(1));
}
/// <summary>
/// Creates a new Transaction that should be managed independently of
/// any parent transactions.
/// </summary>
internal void CreateNew(RollbackSeverity rollbackPreference, TimeSpan timeout)
{
_transactionStack.Push(new PSTransaction(rollbackPreference, timeout));
}
/// <summary>
/// Completes the current transaction. If only one subscriber is active, this
/// commits the transaction. Otherwise, it reduces the subscriber count by one.
/// </summary>
internal void Commit()
{
PSTransaction currentTransaction = _transactionStack.Peek();
// Should not be able to commit a transaction that is not active
if (currentTransaction == null)
{
string error = TransactionStrings.NoTransactionActiveForCommit;
throw new InvalidOperationException(error);
}
// If you are already in a transaction that has been aborted
if (currentTransaction.IsRolledBack)
{
string error = TransactionStrings.TransactionRolledBackForCommit;
throw new TransactionAbortedException(error);
}
// If you are already in a transaction that has been committed
if (currentTransaction.IsCommitted)
{
string error = TransactionStrings.CommittedTransactionForCommit;
throw new InvalidOperationException(error);
}
if (currentTransaction.SubscriberCount == 1)
{
currentTransaction.Commit();
currentTransaction.SubscriberCount = 0;
}
else
{
currentTransaction.SubscriberCount--;
}
// Now that we've committed, go back to the last available transaction
while ((_transactionStack.Count > 2) &&
(_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted))
{
_transactionStack.Pop().Dispose();
}
}
/// <summary>
/// Aborts the current transaction, no matter how many subscribers are part of it.
/// </summary>
internal void Rollback()
{
Rollback(false);
}
/// <summary>
/// Aborts the current transaction, no matter how many subscribers are part of it.
/// </summary>
internal void Rollback(bool suppressErrors)
{
PSTransaction currentTransaction = _transactionStack.Peek();
// Should not be able to roll back a transaction that is not active
if (currentTransaction == null)
{
string error = TransactionStrings.NoTransactionActiveForRollback;
throw new InvalidOperationException(error);
}
// If you are already in a transaction that has been aborted
if (currentTransaction.IsRolledBack)
{
if (!suppressErrors)
{
// Otherwise, you should not be able to roll it back.
string error = TransactionStrings.TransactionRolledBackForRollback;
throw new TransactionAbortedException(error);
}
}
// See if they've already committed the transaction
if (currentTransaction.IsCommitted)
{
if (!suppressErrors)
{
string error = TransactionStrings.CommittedTransactionForRollback;
throw new InvalidOperationException(error);
}
}
// Roll back the transaction if it hasn't been rolled back
currentTransaction.SubscriberCount = 0;
currentTransaction.Rollback();
// Now that we've rolled back, go back to the last available transaction
while ((_transactionStack.Count > 2) &&
(_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted))
{
_transactionStack.Pop().Dispose();
}
}
/// <summary>
/// Sets the base transaction; any transactions created thereafter will be nested to this instance.
/// </summary>
internal void SetBaseTransaction(CommittableTransaction transaction, RollbackSeverity severity)
{
if (this.HasTransaction)
{
throw new InvalidOperationException(TransactionStrings.BaseTransactionMustBeFirst);
}
PSTransaction currentTransaction = _transactionStack.Peek();
// If there is a "used" transaction at the top of the stack, clean it up
while (_transactionStack.Peek() != null &&
(_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted))
{
_transactionStack.Pop().Dispose();
}
_baseTransaction = new PSTransaction(transaction, severity);
_transactionStack.Push(_baseTransaction);
}
/// <summary>
/// Removes the transaction added by SetBaseTransaction.
/// </summary>
internal void ClearBaseTransaction()
{
if (_baseTransaction == null)
{
throw new InvalidOperationException(TransactionStrings.BaseTransactionNotSet);
}
if (_transactionStack.Peek() != _baseTransaction)
{
throw new InvalidOperationException(TransactionStrings.BaseTransactionNotActive);
}
_transactionStack.Pop().Dispose();
_baseTransaction = null;
}
private Stack<PSTransaction> _transactionStack;
private PSTransaction _baseTransaction;
/// <summary>
/// Returns the current engine transaction.
/// </summary>
internal PSTransaction GetCurrent()
{
return _transactionStack.Peek();
}
/// <summary>
/// Activates the current transaction, both in the engine, and in the Ambient.
/// </summary>
internal void SetActive()
{
PSTransactionManager.EnableEngineProtection();
PSTransaction currentTransaction = _transactionStack.Peek();
// Should not be able to activate a transaction that is not active
if (currentTransaction == null)
{
string error = TransactionStrings.NoTransactionForActivation;
throw new InvalidOperationException(error);
}
// If you are already in a transaction that has been aborted, you should
// not be able to activate it.
if (currentTransaction.IsRolledBack)
{
string error = TransactionStrings.NoTransactionForActivationBecauseRollback;
throw new TransactionAbortedException(error);
}
_previousActiveTransaction = Transaction.Current;
currentTransaction.Activate();
}
private Transaction _previousActiveTransaction;
/// <summary>
/// Deactivates the current transaction in the engine, and restores the
/// ambient transaction.
/// </summary>
internal void ResetActive()
{
// Even if you are in a transaction that has been aborted, you
// should still be able to restore the current transaction.
Transaction.Current = _previousActiveTransaction;
_previousActiveTransaction = null;
}
/// <summary>
/// Determines if you have a transaction that you can set active and work on.
/// </summary>
internal bool HasTransaction
{
get
{
PSTransaction currentTransaction = _transactionStack.Peek();
if ((currentTransaction != null) &&
(!currentTransaction.IsCommitted) &&
(!currentTransaction.IsRolledBack))
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// Determines if the last transaction has been committed.
/// </summary>
internal bool IsLastTransactionCommitted
{
get
{
PSTransaction currentTransaction = _transactionStack.Peek();
if (currentTransaction != null)
{
return currentTransaction.IsCommitted;
}
else
{
return false;
}
}
}
/// <summary>
/// Determines if the last transaction has been rolled back.
/// </summary>
internal bool IsLastTransactionRolledBack
{
get
{
PSTransaction currentTransaction = _transactionStack.Peek();
if (currentTransaction != null)
{
return currentTransaction.IsRolledBack;
}
else
{
return false;
}
}
}
/// <summary>
/// Destructor for the PSTransactionManager class.
/// </summary>
~PSTransactionManager()
{
Dispose(false);
}
/// <summary>
/// Disposes the PSTransactionManager object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the PSTransactionContext object, which resets the
/// active PSTransaction.
/// <param name="disposing">
/// Whether to actually dispose the object.
/// </param>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "baseTransaction", Justification = "baseTransaction should not be disposed since we do not own it - it belongs to the caller")]
public void Dispose(bool disposing)
{
if (disposing)
{
ResetActive();
while (_transactionStack.Peek() != null)
{
PSTransaction currentTransaction = _transactionStack.Pop();
if (currentTransaction != _baseTransaction)
{
currentTransaction.Dispose();
}
}
}
}
}
}
| |
/* ****************************************************************************
*
* 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.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
#if !WIN8
using TypeInfo = System.Type;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using Microsoft.Scripting.Actions.Calls;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using AstUtils = Microsoft.Scripting.Ast.Utils;
namespace Microsoft.Scripting.Actions {
/// <summary>
/// Provides binding semantics for a language. This include conversions as well as support
/// for producing rules for actions. These optimized rules are used for calling methods,
/// performing operators, and getting members using the ActionBinder's conversion semantics.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
public abstract class ActionBinder {
private ScriptDomainManager _manager;
/// <summary>
/// Determines if the binder should allow access to non-public members.
///
/// By default the binder does not allow access to non-public members. Base classes
/// can inherit and override this value to customize whether or not private binding
/// is available.
/// </summary>
public virtual bool PrivateBinding {
get {
if (_manager != null) {
return _manager.Configuration.PrivateBinding;
}
return false;
}
}
protected ActionBinder() {
}
[Obsolete("ScriptDomainManager is no longer required by ActionBinder and will go away, you should call the default constructor instead. You should also override PrivateBinding which is the only thing which previously used the ScriptDomainManager.")]
protected ActionBinder(ScriptDomainManager manager) {
_manager = manager;
}
[Obsolete("ScriptDomainManager is no longer required by ActionBinder and will no longer be available on the base class.")]
public ScriptDomainManager Manager {
get {
return _manager;
}
}
/// <summary>
/// Converts an object at runtime into the specified type.
/// </summary>
public virtual object Convert(object obj, Type toType) {
if (obj == null) {
if (!toType.IsValueType()) {
return null;
}
} else {
if (toType.IsValueType()) {
if (toType == obj.GetType()) {
return obj;
}
} else {
if (toType.IsAssignableFrom(obj.GetType())) {
return obj;
}
}
}
throw Error.InvalidCast(obj != null ? obj.GetType().Name : "(null)", toType.Name);
}
/// <summary>
/// Determines if a conversion exists from fromType to toType at the specified narrowing level.
/// toNotNullable is true if the target variable doesn't allow null values.
/// </summary>
public abstract bool CanConvertFrom(Type fromType, Type toType, bool toNotNullable, NarrowingLevel level);
/// <summary>
/// Provides ordering for two parameter types if there is no conversion between the two parameter types.
/// </summary>
public abstract Candidate PreferConvert(Type t1, Type t2);
// TODO: revisit
/// <summary>
/// Converts the provided expression to the given type. The expression is safe to evaluate multiple times.
/// </summary>
public virtual Expression ConvertExpression(Expression expr, Type toType, ConversionResultKind kind, OverloadResolverFactory resolverFactory) {
ContractUtils.RequiresNotNull(expr, "expr");
ContractUtils.RequiresNotNull(toType, "toType");
Type exprType = expr.Type;
if (toType == typeof(object)) {
if (exprType.IsValueType()) {
return AstUtils.Convert(expr, toType);
} else {
return expr;
}
}
if (toType.IsAssignableFrom(exprType)) {
return expr;
}
return Expression.Convert(expr, CompilerHelpers.GetVisibleType(toType));
}
/// <summary>
/// Gets the members that are visible from the provided type of the specified name.
///
/// The default implemetnation first searches the type, then the flattened heirachy of the type, and then
/// registered extension methods.
/// </summary>
public virtual MemberGroup GetMember(MemberRequestKind action, Type type, string name) {
IEnumerable<MemberInfo> foundMembers = type.GetInheritedMembers(name);
if (!PrivateBinding) {
foundMembers = CompilerHelpers.FilterNonVisibleMembers(type, foundMembers);
}
MemberGroup members = new MemberGroup(foundMembers.ToArray());
// check for generic types w/ arity...
string genName = name + ReflectionUtils.GenericArityDelimiter;
List<TypeInfo> genTypes = null;
foreach (TypeInfo t in type.GetDeclaredNestedTypes()) {
if (t.IsPublic && t.Name.StartsWith(genName)) {
if (genTypes == null) {
genTypes = new List<TypeInfo>();
}
genTypes.Add(t);
}
}
if (genTypes != null) {
List<MemberTracker> mt = new List<MemberTracker>(members);
foreach (TypeInfo t in genTypes) {
mt.Add(MemberTracker.FromMemberInfo(t));
}
return MemberGroup.CreateInternal(mt.ToArray());
}
if (members.Count == 0) {
members = new MemberGroup(
type.GetInheritedMembers(name, flattenHierarchy: true).WithBindingFlags(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).ToArray()
);
if (members.Count == 0) {
members = GetAllExtensionMembers(type, name);
}
}
return members;
}
#region Error Production
public virtual ErrorInfo MakeContainsGenericParametersError(MemberTracker tracker) {
return ErrorInfo.FromException(
Expression.New(
typeof(InvalidOperationException).GetConstructor(new[] { typeof(string) }),
AstUtils.Constant(Strings.InvalidOperation_ContainsGenericParameters(tracker.DeclaringType.Name, tracker.Name))
)
);
}
public virtual ErrorInfo MakeMissingMemberErrorInfo(Type type, string name) {
return ErrorInfo.FromException(
Expression.New(
typeof(MissingMemberException).GetConstructor(new[] { typeof(string) }),
AstUtils.Constant(name)
)
);
}
public virtual ErrorInfo MakeGenericAccessError(MemberTracker info) {
return ErrorInfo.FromException(
Expression.New(
typeof(MemberAccessException).GetConstructor(new[] { typeof(string) }),
AstUtils.Constant(info.Name)
)
);
}
public ErrorInfo MakeStaticPropertyInstanceAccessError(PropertyTracker tracker, bool isAssignment, params DynamicMetaObject[] parameters) {
return MakeStaticPropertyInstanceAccessError(tracker, isAssignment, (IList<DynamicMetaObject>)parameters);
}
/// <summary>
/// Called when a set is attempting to assign to a field or property from a derived class through the base class.
///
/// The default behavior is to allow the assignment.
/// </summary>
public virtual ErrorInfo MakeStaticAssignFromDerivedTypeError(Type accessingType, DynamicMetaObject self, MemberTracker assigning, DynamicMetaObject assignedValue, OverloadResolverFactory context) {
switch (assigning.MemberType) {
case TrackerTypes.Property:
PropertyTracker pt = (PropertyTracker)assigning;
MethodInfo setter = pt.GetSetMethod() ?? pt.GetSetMethod(true);
return ErrorInfo.FromValueNoError(
AstUtils.SimpleCallHelper(
setter,
ConvertExpression(
assignedValue.Expression,
setter.GetParameters()[0].ParameterType,
ConversionResultKind.ExplicitCast,
context
)
)
);
case TrackerTypes.Field:
FieldTracker ft = (FieldTracker)assigning;
return ErrorInfo.FromValueNoError(
Expression.Assign(
Expression.Field(null, ft.Field),
ConvertExpression(assignedValue.Expression, ft.FieldType, ConversionResultKind.ExplicitCast, context)
)
);
default:
throw new InvalidOperationException();
}
}
/// <summary>
/// Creates an ErrorInfo object when a static property is accessed from an instance member. The default behavior is throw
/// an exception indicating that static members properties be accessed via an instance. Languages can override this to
/// customize the exception, message, or to produce an ErrorInfo object which reads or writes to the property being accessed.
/// </summary>
/// <param name="tracker">The static property being accessed through an instance</param>
/// <param name="isAssignment">True if the user is assigning to the property, false if the user is reading from the property</param>
/// <param name="parameters">The parameters being used to access the property. This includes the instance as the first entry, any index parameters, and the
/// value being assigned as the last entry if isAssignment is true.</param>
/// <returns></returns>
public virtual ErrorInfo MakeStaticPropertyInstanceAccessError(PropertyTracker tracker, bool isAssignment, IList<DynamicMetaObject> parameters) {
ContractUtils.RequiresNotNull(tracker, "tracker");
ContractUtils.Requires(tracker.IsStatic, "tracker", Strings.ExpectedStaticProperty);
ContractUtils.RequiresNotNull(parameters, "parameters");
ContractUtils.RequiresNotNullItems(parameters, "parameters");
string message = isAssignment ? Strings.StaticAssignmentFromInstanceError(tracker.Name, tracker.DeclaringType.Name) :
Strings.StaticAccessFromInstanceError(tracker.Name, tracker.DeclaringType.Name);
return ErrorInfo.FromException(
Expression.New(
typeof(MissingMemberException).GetConstructor(new[] { typeof(string) }),
AstUtils.Constant(message)
)
);
}
public virtual ErrorInfo MakeSetValueTypeFieldError(FieldTracker field, DynamicMetaObject instance, DynamicMetaObject value) {
return ErrorInfo.FromException(
Expression.Throw(
Expression.New(
typeof(ArgumentException).GetConstructor(new[] { typeof(string) }),
AstUtils.Constant("cannot assign to value types")
),
typeof(object)
)
);
}
public virtual ErrorInfo MakeConversionError(Type toType, Expression value) {
return ErrorInfo.FromException(
Expression.Call(
new Func<Type, object, Exception>(ScriptingRuntimeHelpers.CannotConvertError).GetMethodInfo(),
AstUtils.Constant(toType),
AstUtils.Convert(value, typeof(object))
)
);
}
/// <summary>
/// Provides a way for the binder to provide a custom error message when lookup fails. Just
/// doing this for the time being until we get a more robust error return mechanism.
///
/// Deprecated, use the non-generic version instead
/// </summary>
public virtual ErrorInfo MakeMissingMemberError(Type type, DynamicMetaObject self, string name) {
return ErrorInfo.FromException(
Expression.New(
typeof(MissingMemberException).GetConstructor(new[] { typeof(string) }),
AstUtils.Constant(name)
)
);
}
public virtual ErrorInfo MakeMissingMemberErrorForAssign(Type type, DynamicMetaObject self, string name) {
return MakeMissingMemberError(type, self, name);
}
public virtual ErrorInfo MakeMissingMemberErrorForAssignReadOnlyProperty(Type type, DynamicMetaObject self, string name) {
return MakeMissingMemberError(type, self, name);
}
public virtual ErrorInfo MakeMissingMemberErrorForDelete(Type type, DynamicMetaObject self, string name) {
return MakeMissingMemberError(type, self, name);
}
#endregion
public virtual string GetTypeName(Type t) {
return t.Name;
}
public virtual string GetObjectTypeName(object arg) {
return GetTypeName(CompilerHelpers.GetType(arg));
}
/// <summary>
/// Gets the extension members of the given name from the provided type. Base classes are also
/// searched for their extension members. Once any of the types in the inheritance hierarchy
/// provide an extension member the search is stopped.
/// </summary>
public MemberGroup GetAllExtensionMembers(Type type, string name) {
foreach (Type ancestor in type.Ancestors()) {
MemberGroup res = GetExtensionMembers(ancestor, name);
if (res.Count != 0) {
return res;
}
}
return MemberGroup.EmptyGroup;
}
/// <summary>
/// Gets the extension members of the given name from the provided type. Subclasses of the
/// type and their extension members are not searched.
/// </summary>
public MemberGroup GetExtensionMembers(Type declaringType, string name) {
IList<Type> extTypes = GetExtensionTypes(declaringType);
List<MemberTracker> members = new List<MemberTracker>();
foreach (Type ext in extTypes) {
foreach (MemberInfo mi in ext.GetDeclaredMembers(name).WithBindingFlags(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
MemberInfo newMember = mi;
if (PrivateBinding || (newMember = CompilerHelpers.TryGetVisibleMember(ext, mi)) != null) {
if (IncludeExtensionMember(newMember)) {
if (ext != declaringType) {
members.Add(MemberTracker.FromMemberInfo(newMember, declaringType));
} else {
members.Add(MemberTracker.FromMemberInfo(newMember));
}
}
}
}
// TODO: Support indexed getters/setters w/ multiple methods
MethodInfo getter = GetExtensionOperator(ext, "Get" + name);
MethodInfo setter = GetExtensionOperator(ext, "Set" + name);
MethodInfo deleter = GetExtensionOperator(ext, "Delete" + name);
if (getter != null || setter != null || deleter != null) {
members.Add(new ExtensionPropertyTracker(name, getter, setter, deleter, declaringType));
}
}
if (members.Count != 0) {
return MemberGroup.CreateInternal(members.ToArray());
}
return MemberGroup.EmptyGroup;
}
private MethodInfo GetExtensionOperator(Type ext, string name) {
return ext.GetInheritedMethods(name)
.WithBindingFlags(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)
.Where(mi => mi.IsDefined(typeof(PropertyMethodAttribute), false))
.SingleOrDefault();
}
public virtual bool IncludeExtensionMember(MemberInfo member) {
return true;
}
public virtual IList<Type> GetExtensionTypes(Type t) {
// None are provided by default, languages need to know how to
// provide these on their own terms.
return new Type[0];
}
/// <summary>
/// Provides an opportunity for languages to replace all MemberTracker's with their own type.
///
/// Alternatlely a language can expose MemberTracker's directly.
/// </summary>
/// <param name="memberTracker">The member which is being returned to the user.</param>
/// <param name="type">Tthe type which the memberTrack was accessed from</param>
/// <returns></returns>
public virtual DynamicMetaObject ReturnMemberTracker(Type type, MemberTracker memberTracker) {
if (memberTracker.MemberType == TrackerTypes.Bound) {
BoundMemberTracker bmt = (BoundMemberTracker)memberTracker;
return new DynamicMetaObject(
Expression.New(
typeof(BoundMemberTracker).GetConstructor(new[] { typeof(MemberTracker), typeof(object) }),
AstUtils.Constant(bmt.BoundTo),
bmt.Instance.Expression
),
BindingRestrictions.Empty
);
}
return new DynamicMetaObject(AstUtils.Constant(memberTracker), BindingRestrictions.Empty, memberTracker);
}
public DynamicMetaObject MakeCallExpression(OverloadResolverFactory resolverFactory, MethodInfo method, params DynamicMetaObject[] parameters) {
OverloadResolver resolver;
if (method.IsStatic) {
resolver = resolverFactory.CreateOverloadResolver(parameters, new CallSignature(parameters.Length), CallTypes.None);
} else {
resolver = resolverFactory.CreateOverloadResolver(parameters, new CallSignature(parameters.Length - 1), CallTypes.ImplicitInstance);
}
BindingTarget target = resolver.ResolveOverload(method.Name, new MethodBase[] { method }, NarrowingLevel.None, NarrowingLevel.All);
if (!target.Success) {
BindingRestrictions restrictions = BindingRestrictions.Combine(parameters);
foreach (DynamicMetaObject mo in parameters) {
restrictions = restrictions.Merge(BindingRestrictionsHelpers.GetRuntimeTypeRestriction(mo.Expression, mo.GetLimitType()));
}
return DefaultBinder.MakeError(
resolver.MakeInvalidParametersError(target),
restrictions,
typeof(object)
);
}
return new DynamicMetaObject(target.MakeExpression(), target.RestrictedArguments.GetAllRestrictions());
}
}
}
| |
// 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.IO;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "SslProtocols not supported on UAP")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "SslProtocols property requires .NET 4.7.2")]
public abstract partial class HttpClientHandler_SslProtocols_Test : HttpClientTestBase
{
[Fact]
public void DefaultProtocols_MatchesExpected()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Equal(SslProtocols.None, handler.SslProtocols);
}
}
[Theory]
[InlineData(SslProtocols.None)]
[InlineData(SslProtocols.Tls)]
[InlineData(SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls11 | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
public void SetGetProtocols_Roundtrips(SslProtocols protocols)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.SslProtocols = protocols;
Assert.Equal(protocols, handler.SslProtocols);
}
}
[Fact]
public async Task SetProtocols_AfterRequest_ThrowsException()
{
if (!BackendSupportsSslConfiguration)
{
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
server.AcceptConnectionSendResponseAndCloseAsync(),
client.GetAsync(url));
});
Assert.Throws<InvalidOperationException>(() => handler.SslProtocols = SslProtocols.Tls12);
}
}
public static IEnumerable<object[]> GetAsync_AllowedSSLVersion_Succeeds_MemberData()
{
// These protocols are all enabled by default, so we can connect with them both when
// explicitly specifying it in the client and when not.
foreach (SslProtocols protocol in new[] { SslProtocols.Tls, SslProtocols.Tls11, SslProtocols.Tls12 })
{
yield return new object[] { protocol, false };
yield return new object[] { protocol, true };
}
// These protocols are disabled by default, so we can only connect with them explicitly.
// On certain platforms these are completely disabled and cannot be used at all.
#pragma warning disable 0618
if (PlatformDetection.IsWindows ||
PlatformDetection.IsOSX ||
(RuntimeInformation.IsOSPlatform(OSPlatform.Linux) &&
PlatformDetection.OpenSslVersion < new Version(1, 0, 2) &&
!PlatformDetection.IsDebian &&
!PlatformDetection.IsRedHatFamily6))
{
// TODO #28790: SSLv3 is supported on RHEL 6, but this test case still fails.
yield return new object[] { SslProtocols.Ssl3, true };
}
if (PlatformDetection.IsWindows && !PlatformDetection.IsWindows10Version1607OrGreater)
{
yield return new object[] { SslProtocols.Ssl2, true };
}
#pragma warning restore 0618
}
[Theory]
[MemberData(nameof(GetAsync_AllowedSSLVersion_Succeeds_MemberData))]
public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol)
{
if (!BackendSupportsSslConfiguration)
{
return;
}
if (UseSocketsHttpHandler)
{
// TODO #26186: SocketsHttpHandler is failing on some OSes.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
if (requestOnlyThisProtocol)
{
handler.SslProtocols = acceptedProtocol;
}
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
server.AcceptConnectionSendResponseAndCloseAsync(),
client.GetAsync(url));
}, options);
}
}
public static IEnumerable<object[]> SupportedSSLVersionServers()
{
#pragma warning disable 0618 // SSL2/3 are deprecated
if (PlatformDetection.IsWindows ||
PlatformDetection.IsOSX ||
(RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && PlatformDetection.OpenSslVersion < new Version(1, 0, 2) && !PlatformDetection.IsDebian))
{
yield return new object[] { SslProtocols.Ssl3, Configuration.Http.SSLv3RemoteServer };
}
#pragma warning restore 0618
yield return new object[] { SslProtocols.Tls, Configuration.Http.TLSv10RemoteServer };
yield return new object[] { SslProtocols.Tls11, Configuration.Http.TLSv11RemoteServer };
yield return new object[] { SslProtocols.Tls12, Configuration.Http.TLSv12RemoteServer };
}
// We have tests that validate with SslStream, but that's limited by what the current OS supports.
// This tests provides additional validation against an external server.
[ActiveIssue(26186)]
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
[Theory]
[MemberData(nameof(SupportedSSLVersionServers))]
public async Task GetAsync_SupportedSSLVersion_Succeeds(SslProtocols sslProtocols, string url)
{
if (UseSocketsHttpHandler)
{
// TODO #26186: SocketsHttpHandler is failing on some OSes.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.SslProtocols = sslProtocols;
using (var client = new HttpClient(handler))
{
(await RemoteServerQuery.Run(() => client.GetAsync(url), remoteServerExceptionWrapper, url)).Dispose();
}
}
}
public Func<Exception, bool> remoteServerExceptionWrapper = (exception) =>
{
Type exceptionType = exception.GetType();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// On linux, taskcanceledexception is thrown.
return exceptionType.Equals(typeof(TaskCanceledException));
}
else
{
// The internal exceptions return operation timed out.
return exceptionType.Equals(typeof(HttpRequestException)) && exception.InnerException.Message.Contains("timed out");
}
};
public static IEnumerable<object[]> NotSupportedSSLVersionServers()
{
#pragma warning disable 0618
if (PlatformDetection.IsWindows10Version1607OrGreater)
{
yield return new object[] { SslProtocols.Ssl2, Configuration.Http.SSLv2RemoteServer };
}
#pragma warning restore 0618
}
// We have tests that validate with SslStream, but that's limited by what the current OS supports.
// This tests provides additional validation against an external server.
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
[Theory]
[MemberData(nameof(NotSupportedSSLVersionServers))]
public async Task GetAsync_UnsupportedSSLVersion_Throws(SslProtocols sslProtocols, string url)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (HttpClient client = new HttpClient(handler))
{
handler.SslProtocols = sslProtocols;
await Assert.ThrowsAsync<HttpRequestException>(() => RemoteServerQuery.Run(() => client.GetAsync(url), remoteServerExceptionWrapper, url));
}
}
[Fact]
public async Task GetAsync_NoSpecifiedProtocol_DefaultsToTls12()
{
if (!BackendSupportsSslConfiguration)
{
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = SslProtocols.Tls12 };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
client.GetAsync(url),
server.AcceptConnectionAsync(async connection =>
{
Assert.Equal(SslProtocols.Tls12, Assert.IsType<SslStream>(connection.Stream).SslProtocol);
await connection.ReadRequestHeaderAndSendResponseAsync();
}));
}, options);
}
}
[Theory]
#pragma warning disable 0618 // SSL2/3 are deprecated
[InlineData(SslProtocols.Ssl2, SslProtocols.Tls12)]
[InlineData(SslProtocols.Ssl3, SslProtocols.Tls12)]
#pragma warning restore 0618
[InlineData(SslProtocols.Tls11, SslProtocols.Tls)]
[InlineData(SslProtocols.Tls11 | SslProtocols.Tls12, SslProtocols.Tls)] // Skip this on WinHttpHandler.
[InlineData(SslProtocols.Tls12, SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls, SslProtocols.Tls12)]
public async Task GetAsync_AllowedClientSslVersionDiffersFromServer_ThrowsException(
SslProtocols allowedClientProtocols, SslProtocols acceptedServerProtocols)
{
if (!BackendSupportsSslConfiguration)
{
return;
}
if (IsWinHttpHandler &&
allowedClientProtocols == (SslProtocols.Tls11 | SslProtocols.Tls12) &&
acceptedServerProtocols == SslProtocols.Tls)
{
// Native WinHTTP sometimes uses multiple TCP connections to try other TLS protocols when
// getting TLS protocol failures as part of its TLS fallback algorithm. The loopback server
// doesn't expect this and stops listening for more connections. This causes unexpected test
// failures. See dotnet/corefx #8538.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.SslProtocols = allowedClientProtocols;
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedServerProtocols };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task serverTask = server.AcceptConnectionSendResponseAndCloseAsync();
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
try
{
await serverTask;
}
catch (Exception e) when (e is IOException || e is AuthenticationException)
{
// Some SSL implementations simply close or reset connection after protocol mismatch.
// Newer OpenSSL sends Fatal Alert message before closing.
return;
}
// We expect negotiation to fail so one or the other expected exception should be thrown.
Assert.True(false, "Expected exception did not happen.");
}, options);
}
}
}
}
| |
// Released to the public domain. Use, modify and relicense at will.
using System;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Audio;
using OpenTK.Audio.OpenAL;
using OpenTK.Input;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
namespace Counter_Strike
{
class Game : GameWindow
{
Environment environment;
float environmentLength = 1500;
float environmentWidth = 2500;
float environmentHeight = 2000;
float environmentFenceThikness = 10;
float environmentFloorThikness = 10;
float environmentFenceHeight = 75;
Person person;
Box shootingBox1;
Box shootingBox2;
Box shootingBox3;
Box shootingBox4;
Box shootingBox5;
Cylinder shootTarget1;
Cylinder shootTarget2;
Cylinder shootTarget3;
Cylinder shootTarget4;
Cylinder shootTarget5;
Cylinder shootTarget6;
Cylinder shootTarget7;
Cylinder shootTarget8;
Box building1;
Box building2;
Box building3;
float yRot = 0;
float shootGunYRot = 0;
float xRot = 0;
float rotStep = 0.02f;
float xTranslation = 0;
float yTranslation = 0;
float zTranslation = 0;
float translationStep = 5;
float initialXPos = 1200;
float initialYPos = 30;
float initialZPos = -1100;
Vector3 pos;
Vector3 prevPos;
Vector3 bulletPos;
float lookDistance = 3;
float fogDensity = 0;
float fogDensityStep = 0.0001f;
Matrix4 xRotMatrix = Matrix4.Identity;
Matrix4 yRotMatrix = Matrix4.Identity;
Matrix4 totalYRotMatrix = Matrix4.Identity;
Matrix4 translatationMatrix = Matrix4.Identity;
Matrix4 PrevModelviewMatrixWithoutXRot = Matrix4.Identity;
Matrix4 modelviewMatrixWithoutXRot = Matrix4.Identity;
Matrix4 modelviewMatrixWithXRot = Matrix4.Identity;
List<Obj> objList = new List<Obj>();
List<Obj> BulletObjList = new List<Obj>();
Vector3 translationVector;
Loader.WavLoader shootSound;
bool playShootSound = true;
Loader.WavLoader goSound;
Loader.WavLoader doorSound;
Loader.WavLoader winSound;
bool playDoor1Sound = true;
bool playDoor2Sound = true;
bool playWinSound = true;
BoundingBox bullet;
bool bulletThrown = false;
Loader.WavLoader bulletSound;
Matrix4 bulletMatrix=Matrix4.Identity;
House1 house1;
House2 house2;
Garden garden;
Lamp lamp1;
Lamp lamp2;
Lamp lamp3;
Lamp lamp4;
bool lightingEnabled=false;
Loader.Model utility_truck;
Loader.Model army_truck;
Loader.Model tree1;
Loader.Model tree2;
/// <summary>Creates a 800x600 window with the specified title.</summary>
public Game(): base(1024, 648, GraphicsMode.Default, "Counter Strike")
{
VSync = VSyncMode.On;
}
/// <summary>Load resources here.</summary>
/// <param name="e">Not used.</param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
GL.ClearColor(0.1f, 0.2f, 0.5f, 0.0f);
GL.Enable(EnableCap.DepthTest);
modelviewMatrixWithoutXRot = Matrix4.LookAt(new Vector3(initialXPos, initialYPos, initialZPos), new Vector3(initialXPos, initialYPos, initialZPos - lookDistance), Vector3.UnitY);
person = new Person(new Vector3(initialXPos, initialYPos, initialZPos), new Vector3(0.5f, 0.5f, 0.5f),shootGunYRot,Vector3.UnitY, 10, 10, 2 * initialYPos,"Media/Models/", "Shotgun.obj", "Shotgun.png");
environment = new Environment(environmentLength, environmentWidth, environmentHeight, environmentFloorThikness, environmentFenceThikness, environmentFenceHeight, "Media/Environment Texture/", "front.jpg", "back.jpg", "right.jpg", "left.jpg", "top.jpg", "down.jpg","fence.jpg");
objList.Add(environment);
house1 = new House1(environmentFenceThikness+30, 0, -600, 300, 1000, 300, "Media/House Texture/", "houseTex1.jpg", "fenceHouseTex.jpg", "doorTex.jpg", "bridge.jpg", "boxTex.jpg", "cylinderTex.jpg", 6);
objList.Add(house1);
house2 = new House2(1050, 0, -650, 400, 700, 100, "Media/House Texture/", "houseTex2.jpg", "fenceHouseTex.jpg", "doorTex.jpg", "bridge.jpg", "boxTex.jpg", "cylinderTex.jpg", 6);
objList.Add(house2);
building1 = new Box(100, 0, -2100, 0, Vector3.Zero, 350, 350, 800, 1,1, 3, "Media/Box Texture/", "b1.jpg", "r1.jpg");
objList.Add(building1);
building2 = new Box(550, 0, -2100, 0, Vector3.Zero, 350, 350, 900, 1, 1, 1, "Media/Box Texture/", "b2.jpg", "r2.jpg");
objList.Add(building2);
building3 = new Box(1000, 0, -2100, 0, Vector3.Zero, 350, 350, 800, 1, 1, 1, "Media/Box Texture/", "b3.jpg", "r3.jpg");
objList.Add(building3);
lamp1 = new Lamp(50, 0, -2200, 0, Vector3.Zero, 100, 2, "Media/Lamp Texture/", "Tex.jpg", "ball_tex.jpg");
objList.Add(lamp1);
lamp2 = new Lamp(500, 0, -2200, 0, Vector3.Zero, 100, 2, "Media/Lamp Texture/", "Tex.jpg", "ball_tex.jpg");
objList.Add(lamp2);
lamp3 = new Lamp(950, 0, -2200, 0, Vector3.Zero, 100, 2, "Media/Lamp Texture/", "Tex.jpg", "ball_tex.jpg");
objList.Add(lamp3);
lamp4 = new Lamp(1450, 0, -1800, 0, Vector3.Zero, 100, 2, "Media/Lamp Texture/", "Tex.jpg", "ball_tex.jpg");
objList.Add(lamp4);
shootingBox1 = new Box(500, 0, -900, 0, new Vector3(0, 0, 0), 200f, 100f, 25f, 1, 1, 1, "Media/Box Texture/", "tex.jpg");
objList.Add(shootingBox1);
shootTarget1 = new Cylinder(600, 25, -950, -90, Vector3.UnitX, 2, 7, "Media/Cylinder Texture/", "CocaCola.jpg");
BulletObjList.Add(shootTarget1);
objList.Add(shootTarget1);
shootTarget2 = new Cylinder(610, 25, -950, -90, Vector3.UnitX, 2, 7, "Media/Cylinder Texture/", "ugaritCola.jpg");
BulletObjList.Add(shootTarget2);
objList.Add(shootTarget2);
shootTarget3 = new Cylinder(620, 25, -950, -90, Vector3.UnitX, 2, 7, "Media/Cylinder Texture/", "bebsiCola.jpg");
BulletObjList.Add(shootTarget3);
objList.Add(shootTarget3);
shootingBox2 = new Box(500, 0, -1400, 0, new Vector3(0, 0, 0), 200f, 100f, 25f, 1, 1, 1, "Media/Box Texture/", "tex.jpg");
objList.Add(shootingBox2);
shootingBox3 = new Box(500, 25, -1400, 0, new Vector3(0, 0, 0), 70f, 90f, 25f, 1, 1, 1, "Media/Box Texture/", "tex.jpg");
objList.Add(shootingBox3);
shootingBox4 = new Box(630, 25, -1400, 0, new Vector3(0, 0, 0), 70f, 90f, 25f, 1, 1, 1, "Media/Box Texture/", "tex.jpg");
objList.Add(shootingBox4);
shootTarget4 = new Cylinder(590, 25, -1440, -90, Vector3.UnitX, 2, 7, "Media/Cylinder Texture/", "CocaCola.jpg");
BulletObjList.Add(shootTarget4);
objList.Add(shootTarget4);
shootTarget5 = new Cylinder(610, 25, -1440, -90, Vector3.UnitX, 2, 7, "Media/Cylinder Texture/", "ugaritCola.jpg");
BulletObjList.Add(shootTarget5);
objList.Add(shootTarget5);
shootingBox5 = new Box(1000, 0, -10, 0, new Vector3(0, 0, 0), 200f, 5f, 75f, 1, 1, 1, "Media/Box Texture/", "tex.jpg");
objList.Add(shootingBox5);
shootTarget6 = new Cylinder(1050, 30, -15, -180, Vector3.UnitX, 10, 2, "Media/Cylinder Texture/", "shootingTarget.jpg");
BulletObjList.Add(shootTarget6);
objList.Add(shootTarget6);
shootTarget7 = new Cylinder(1100, 30, -15, -180, Vector3.UnitX, 10, 2, "Media/Cylinder Texture/", "shootingTarget.jpg");
BulletObjList.Add(shootTarget7);
objList.Add(shootTarget7);
shootTarget8 = new Cylinder(1150, 30, -15, -180, Vector3.UnitX, 10, 2, "Media/Cylinder Texture/", "shootingTarget.jpg");
BulletObjList.Add(shootTarget8);
objList.Add(shootTarget8);
utility_truck = new Loader.Model(new Vector3(200, 0, -1100), new Vector3(1.0f, 1.0f, 1.0f), new Vector3(160, 0, -990), new Vector3(240, 100, -1210), "Media/Models/", "utility_truck.obj", "utility_truck.png");
objList.Add(utility_truck);
army_truck = new Loader.Model(new Vector3(1420, 0, -2350), new Vector3(0.2f, 0.2f, 0.2f), new Vector3(1390, 0, -2240), new Vector3(1450, 0, -2430), "Media/Models/", "army_truck.obj", "army_truck.png");
objList.Add(army_truck);
tree1 = new Loader.Model(new Vector3(1450, 0, -380), new Vector3(10f, 10f, 10f), new Vector3(1425, 0, -360), new Vector3(1475, 100, -400), "Media/Models/", "tree1.obj", "tree1.png");
objList.Add(tree1);
tree2 = new Loader.Model(new Vector3(525, 0, -380), new Vector3(1f, 1f, 1f), new Vector3(500, 0, -360), new Vector3(540, 100, -390), "Media/Models/", "tree2.obj", "tree2.png");
objList.Add(tree2);
garden = new Garden(environmentLength / 4, 0, -environmentFenceThikness + 10, 3 * environmentLength / 4, environmentWidth / 6, environmentFenceHeight, environmentFenceThikness, "Media/Garden Texture/", "grass.png", "garden_fence.jpg", "fence.png", "black.png", "lake.JPG", "roaster.jpg", "candle.png", "ball_tex.jpg", "lamp_Tex.jpg", "rock.jpg");
objList.Add(garden);
bullet = new BoundingBox(new Vector3(initialXPos, initialYPos, initialZPos), 5, 5, 5);
shootSound = new Loader.WavLoader("Media/Audio/", "Shoot.wav");
doorSound = new Loader.WavLoader("Media/Audio/", "Door.wav");
goSound = new Loader.WavLoader("Media/Audio/", "GoGoGo.wav");
goSound.play();
bulletSound = new Loader.WavLoader("Media/Audio/", "bullet.wav");
winSound = new Loader.WavLoader("Media/Audio/", "win.wav");
}
/// <summary>
/// Called when your window is resized. Set your viewport here. It is also
/// a good place to set up your projection matrix (which probably changes
/// along when the aspect ratio of your window).
/// </summary>
/// <param name="e">Not used.</param>
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
GL.Viewport(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width, ClientRectangle.Height);
Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Width / (float)Height, 0.1f, 3000.0f);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadMatrix(ref projection);
}
/// <summary>
/// Called when it is time to setup the next frame. Add you game logic here.
/// </summary>
/// <param name="e">Contains timing information for framerate independent logic.</param>
protected override void OnUpdateFrame(FrameEventArgs e)
{
base.OnUpdateFrame(e);
Helper.EnableFog(fogDensity);
ProcessKeyboard();
UpdateCamera();
PlaySounds();
if ((BulletObjList.Count == 0)&&(playWinSound))
{
winSound.play();
playWinSound = false;
}
}
/// <summary>
/// Called when it is time to render the next frame. Add your rendering code here.
/// </summary>
/// <param name="e">Contains timing information.</param>
protected override void OnRenderFrame(FrameEventArgs e)
{
base.OnRenderFrame(e);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
environment.Draw(translationVector);
EnableLighting();
person.Draw(shootGunYRot, Vector3.UnitY);
foreach (Obj obj in objList)
{
obj.Draw();
}
foreach (Obj target in BulletObjList)
{
target.Draw();
}
DisableLighting();
SwapBuffers();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// The 'using' idiom guarantees proper resource cleanup.
// We request 30 UpdateFrame events per second, and unlimited
// RenderFrame events (as fast as the computer can handle).
using (Game game = new Game())
{
game.Run(30.0);
}
}
private void ProcessKeyboard()
{
yRot = 0;
xTranslation = 0;
yTranslation = 0;
zTranslation = 0;
if (Keyboard[Key.Escape])
Exit();
else if (Keyboard[Key.S])
xRot += rotStep;
else if (Keyboard[Key.W])
xRot -= rotStep;
else if (Keyboard[Key.A])
yRot -= rotStep;
else if (Keyboard[Key.D])
yRot += rotStep;
else if (Keyboard[Key.Down])
zTranslation += translationStep;
else if (Keyboard[Key.Up])
zTranslation -= translationStep;
else if (Keyboard[Key.Left] )
xTranslation -= translationStep;
else if (Keyboard[Key.Right])
xTranslation += translationStep;
if (Keyboard[Key.U])
yTranslation += translationStep;
else if (Keyboard[Key.J])
yTranslation -= translationStep;
if (Keyboard[Key.F])
fogDensity += fogDensityStep;
else if (Keyboard[Key.G])
{
fogDensity -= fogDensityStep;
if (fogDensity < 0)
fogDensity = 0;
}
if (Keyboard[Key.Space])
{
bulletThrown = true;
if (playShootSound)
{
shootSound.play();
playShootSound = false;
}
}
else
{
playShootSound = true;
}
if (Keyboard[Key.L])
{
lightingEnabled = true;
}
else if (Keyboard[Key.K])
{
lightingEnabled = false;
}
}
private void UpdateCamera()
{
PrevModelviewMatrixWithoutXRot = modelviewMatrixWithoutXRot;
xRotMatrix = Matrix4.CreateRotationX(xRot);
yRotMatrix = Matrix4.CreateRotationY(yRot);
shootGunYRot -= MathHelper.RadiansToDegrees(yRot);
totalYRotMatrix *= yRotMatrix;
translatationMatrix = Matrix4.CreateTranslation(-xTranslation, -yTranslation, -zTranslation);
modelviewMatrixWithoutXRot *= yRotMatrix * translatationMatrix;
prevPos = pos;
pos = Helper.GetPositionFromModelViewMatrix(modelviewMatrixWithoutXRot, totalYRotMatrix);
person.setPos(pos);
if (!bulletThrown)
{
bulletPos = pos;
bullet.SetCenter(bulletPos);
bulletMatrix = modelviewMatrixWithoutXRot;
}
else
{
bulletMatrix *= Matrix4.CreateTranslation(new Vector3(0, 0, +10));
bulletPos = Helper.GetPositionFromModelViewMatrix(bulletMatrix, totalYRotMatrix);
bullet.SetCenter(bulletPos);
}
if (CheckCollision(person.boundingBox))
{
modelviewMatrixWithoutXRot = PrevModelviewMatrixWithoutXRot;
pos = prevPos;
person.setPos(pos);
if (!bulletThrown)
{
bulletPos = pos;
bullet.SetCenter(bulletPos);
}
}
else
{
translationVector = pos - new Vector3(initialXPos, initialYPos, initialZPos);
}
ThrowBullet();
modelviewMatrixWithXRot = modelviewMatrixWithoutXRot * xRotMatrix;
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadMatrix(ref modelviewMatrixWithXRot);
}
private bool CheckCollision(BoundingBox targetBoundingBox)
{
for (int i = 0; i < objList.Count; i++)
{
if (objList[i].CheckCollision(targetBoundingBox))
return true;
}
return false;
}
private bool CheckBulletCollision(BoundingBox targetBoundingBox)
{
for (int i = 0; i < BulletObjList.Count; i++)
{
if (BulletObjList[i].CheckCollision(targetBoundingBox))
{
objList.Remove(BulletObjList[i]);
BulletObjList.Remove(BulletObjList[i]);
return true;
}
}
return false;
}
private void ThrowBullet()
{
if (CheckBulletCollision(bullet)&& bulletThrown)
{
bulletSound.play();
bulletThrown = false;
}
if (CheckCollision(bullet))
{
bulletThrown = false;
}
}
private void PlaySounds()
{
if ((house1.door.CheckCollision(person.boundingBox)) && (playDoor1Sound))
{
doorSound.play();
playDoor1Sound = false;
}
else if (!(house1.door.CheckCollision(person.boundingBox)))
{
playDoor1Sound = true;
}
if ((house2.door.CheckCollision(person.boundingBox)) && (playDoor2Sound))
{
doorSound.play();
playDoor2Sound = false;
}
else if (!(house2.door.CheckCollision(person.boundingBox)))
{
playDoor2Sound = true;
}
}
private void EnableLighting()
{
Vector3 lightingPos = pos;
float[] m_ambi = { 0.1f, 0.1f, 0.1f, 1.0f };
float[] m_diff = { 1.0f, 1.0f, 1.0f, 1.0f };
float[] m_spec = { 1.0f, 1.0f, 1.0f, 1.0f };
float m_shin = 0f;
float[] l_ambi = { 1.0f, 1.0f, 1.0f, 0.0f };
float[] l_diff = { 1.0f, 1.0f, 1.0f, 0.0f };
float[] l_spec = { 1.0f, 1.0f, 1.0f, 0.0f };
float[] l_pos = { lightingPos.X, lightingPos.Y,lightingPos.Z, 1};
GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Ambient, m_ambi);
GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Diffuse, m_diff);
GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Specular, m_spec);
GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Shininess, m_shin);
GL.Light(LightName.Light0, LightParameter.Ambient, l_ambi);
GL.Light(LightName.Light0, LightParameter.Diffuse, l_diff);
GL.Light(LightName.Light0, LightParameter.Specular, l_spec);
GL.Light(LightName.Light0, LightParameter.Position, l_pos);
if (lightingEnabled)
{
GL.Enable(EnableCap.Lighting);
GL.Enable(EnableCap.Light0);
}
}
private void DisableLighting()
{
GL.Disable(EnableCap.Lighting);
GL.Disable(EnableCap.Light0);
}
}
}
| |
//
// AudioCdDisc.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2008 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.Threading;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Mono.Unix;
using MusicBrainz;
using Hyena;
using Banshee.Base;
using Banshee.Hardware;
using Banshee.Collection;
using Banshee.Collection.Database;
namespace Banshee.AudioCd
{
public class AudioCdDiscModel : MemoryTrackListModel
{
// 44.1 kHz sample rate * 16 bit channel resolution * 2 channels (stereo)
private const long PCM_FACTOR = 176400;
private IDiscVolume volume;
public event EventHandler MetadataQueryStarted;
public event EventHandler MetadataQueryFinished;
public event EventHandler EnabledCountChanged;
private bool metadata_query_success;
private DateTime metadata_query_start_time;
public bool MetadataQuerySuccess {
get { return metadata_query_success; }
}
private TimeSpan duration;
public TimeSpan Duration {
get { return duration; }
}
private long file_size;
public long FileSize {
get { return file_size; }
}
public AudioCdDiscModel (IDiscVolume volume)
{
this.volume = volume;
disc_title = Catalog.GetString ("Audio CD");
}
public void NotifyUpdated ()
{
OnReloaded ();
}
public void LoadModelFromDisc ()
{
Clear ();
LocalDisc mb_disc = LocalDisc.GetFromDevice (volume.DeviceNode);
if (mb_disc == null) {
throw new ApplicationException ("Could not read contents of the disc. Platform may not be supported.");
}
TimeSpan[] durations = mb_disc.GetTrackDurations ();
for (int i = 0, n = durations.Length; i < n; i++) {
AudioCdTrackInfo track = new AudioCdTrackInfo (this, volume.DeviceNode, i);
track.TrackNumber = i + 1;
track.TrackCount = n;
track.DiscNumber = 1;
track.Duration = durations[i];
track.ArtistName = Catalog.GetString ("Unknown Artist");
track.AlbumTitle = Catalog.GetString ("Unknown Album");
track.TrackTitle = String.Format (Catalog.GetString ("Track {0}"), track.TrackNumber);
track.FileSize = PCM_FACTOR * (uint)track.Duration.TotalSeconds;
Add (track);
duration += track.Duration;
file_size += track.FileSize;
}
EnabledCount = Count;
Reload ();
ThreadPool.QueueUserWorkItem (LoadDiscMetadata, mb_disc);
}
private void LoadDiscMetadata (object state)
{
try {
LocalDisc mb_disc = (LocalDisc)state;
OnMetadataQueryStarted (mb_disc);
Release release = Release.Query (mb_disc).PerfectMatch ();
var tracks = release.GetTracks ();
if (release == null || tracks.Count != Count) {
OnMetadataQueryFinished (false);
return;
}
disc_title = release.GetTitle ();
int disc_number = 1;
int i = 0;
foreach (Disc disc in release.GetDiscs ()) {
i++;
if (disc.Id == mb_disc.Id) {
disc_number = i;
}
}
DateTime release_date = DateTime.MaxValue;
foreach (Event release_event in release.GetEvents ()) {
if (release_event.Date != null) {
try {
// Handle "YYYY" dates
var date_str = release_event.Date;
DateTime date = DateTime.Parse (
date_str.Length > 4 ? date_str : date_str + "-01",
ApplicationContext.InternalCultureInfo
);
if (date < release_date) {
release_date = date;
}
} catch {
}
}
}
DatabaseArtistInfo artist = new DatabaseArtistInfo ();
var mb_artist = release.GetArtist ();
artist.Name = mb_artist.GetName ();
artist.NameSort = mb_artist.GetSortName ();
artist.MusicBrainzId = mb_artist.Id;
bool is_compilation = false;
DatabaseAlbumInfo album = new DatabaseAlbumInfo ();
album.Title = disc_title;
album.ArtistName = artist.Name;
album.MusicBrainzId = release.Id;
album.ReleaseDate = release_date == DateTime.MaxValue ? DateTime.MinValue : release_date;
i = 0;
foreach (Track track in tracks) {
AudioCdTrackInfo model_track = (AudioCdTrackInfo)this[i++];
var mb_track_artist = track.GetArtist ();
model_track.MusicBrainzId = track.Id;
model_track.TrackTitle = track.GetTitle ();
model_track.ArtistName = mb_track_artist.GetName ();
model_track.AlbumTitle = disc_title;
model_track.DiscNumber = disc_number;
model_track.Album = album;
model_track.Artist = new DatabaseArtistInfo ();
model_track.Artist.Name = model_track.ArtistName;
model_track.Artist.NameSort = mb_track_artist.GetSortName ();
model_track.Artist.MusicBrainzId = mb_track_artist.Id;
if (release_date != DateTime.MinValue) {
model_track.Year = release_date.Year;
}
if (!is_compilation && mb_track_artist.Id != artist.MusicBrainzId) {
is_compilation = true;
}
}
if (is_compilation) {
album.IsCompilation = true;
for (i = 0; i < tracks.Count; i++) {
AudioCdTrackInfo model_track = (AudioCdTrackInfo)this[i];
model_track.IsCompilation = true;
model_track.AlbumArtist = artist.Name;
model_track.AlbumArtistSort = artist.NameSort;
}
}
OnMetadataQueryFinished (true);
} catch (Exception ex) {
Log.DebugException (ex);
OnMetadataQueryFinished (false);
}
}
private void OnMetadataQueryStarted (LocalDisc mb_disc)
{
metadata_query_success = false;
metadata_query_start_time = DateTime.Now;
Log.InformationFormat ("Querying MusicBrainz for Disc Release ({0})", mb_disc.Id);
ThreadAssist.ProxyToMain (delegate {
EventHandler handler = MetadataQueryStarted;
if (handler != null) {
handler (this, EventArgs.Empty);
}
});
}
private void OnMetadataQueryFinished (bool success)
{
metadata_query_success = success;
Log.InformationFormat ("Query finished (success: {0}, {1} seconds)",
success, (DateTime.Now - metadata_query_start_time).TotalSeconds);
ThreadAssist.ProxyToMain (delegate {
Reload ();
EventHandler handler = MetadataQueryFinished;
if (handler != null) {
handler (this, EventArgs.Empty);
}
});
}
private void OnEnabledCountChanged ()
{
EventHandler handler = EnabledCountChanged;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
private ICdromDevice Drive {
get { return Volume == null ? null : (Volume.Parent as ICdromDevice); }
}
public bool LockDoor ()
{
ICdromDevice drive = Drive;
return drive != null ? drive.LockDoor () : false;
}
public bool UnlockDoor ()
{
ICdromDevice drive = Drive;
return drive != null ? drive.UnlockDoor () : false;
}
public bool IsDoorLocked {
get {
ICdromDevice drive = Drive;
return drive != null ? drive.IsDoorLocked : false;
}
}
public IDiscVolume Volume {
get { return volume; }
}
private string disc_title;
public string Title {
get { return disc_title; }
}
private int enabled_count;
public int EnabledCount {
get { return enabled_count; }
internal set {
enabled_count = value;
OnEnabledCountChanged ();
}
}
}
}
| |
using System;
using Mono.Cecil.PE;
using NUnit.Framework;
namespace Mono.Cecil.Tests {
[TestFixture]
public class FieldTests : BaseTestFixture {
[Test]
public void TypeDefField ()
{
TestCSharp ("Fields.cs", module => {
var type = module.Types [1];
Assert.AreEqual ("Foo", type.Name);
Assert.AreEqual (1, type.Fields.Count);
var field = type.Fields [0];
Assert.AreEqual ("bar", field.Name);
Assert.AreEqual (1, field.MetadataToken.RID);
Assert.IsNotNull (field.FieldType);
Assert.AreEqual ("Bar", field.FieldType.FullName);
Assert.AreEqual (TokenType.Field, field.MetadataToken.TokenType);
Assert.IsFalse (field.HasConstant);
Assert.IsNull (field.Constant);
});
}
[Test]
public void PrimitiveTypes ()
{
TestCSharp ("Fields.cs", module => {
var type = module.GetType ("Baz");
AssertField (type, "char", typeof (char));
AssertField (type, "bool", typeof (bool));
AssertField (type, "sbyte", typeof (sbyte));
AssertField (type, "byte", typeof (byte));
AssertField (type, "int16", typeof (short));
AssertField (type, "uint16", typeof (ushort));
AssertField (type, "int32", typeof (int));
AssertField (type, "uint32", typeof (uint));
AssertField (type, "int64", typeof (long));
AssertField (type, "uint64", typeof (ulong));
AssertField (type, "single", typeof (float));
AssertField (type, "double", typeof (double));
AssertField (type, "string", typeof (string));
AssertField (type, "object", typeof (object));
});
}
[Test]
public void VolatileField ()
{
TestCSharp ("Fields.cs", module => {
var type = module.GetType ("Bar");
Assert.IsTrue (type.HasFields);
Assert.AreEqual (1, type.Fields.Count);
var field = type.Fields [0];
Assert.AreEqual ("oiseau", field.Name);
Assert.AreEqual ("System.Int32 modreq(System.Runtime.CompilerServices.IsVolatile)", field.FieldType.FullName);
Assert.IsFalse (field.HasConstant);
});
}
[Test]
public void FieldLayout ()
{
TestCSharp ("Layouts.cs", module => {
var foo = module.GetType ("Foo");
Assert.IsNotNull (foo);
Assert.IsTrue (foo.HasFields);
var fields = foo.Fields;
var field = fields [0];
Assert.AreEqual ("Bar", field.Name);
Assert.IsTrue (field.HasLayoutInfo);
Assert.AreEqual (0, field.Offset);
field = fields [1];
Assert.AreEqual ("Baz", field.Name);
Assert.IsTrue (field.HasLayoutInfo);
Assert.AreEqual (2, field.Offset);
field = fields [2];
Assert.AreEqual ("Gazonk", field.Name);
Assert.IsTrue (field.HasLayoutInfo);
Assert.AreEqual (4, field.Offset);
});
}
[Test]
public void FieldRVA ()
{
TestCSharp ("Layouts.cs", module => {
var priv_impl = GetPrivateImplementationType (module);
Assert.IsNotNull (priv_impl);
Assert.AreEqual (1, priv_impl.Fields.Count);
var field = priv_impl.Fields [0];
Assert.IsNotNull (field);
Assert.AreNotEqual (0, field.RVA);
Assert.IsNotNull (field.InitialValue);
Assert.AreEqual (16, field.InitialValue.Length);
var buffer = new ByteBuffer (field.InitialValue);
Assert.AreEqual (1, buffer.ReadUInt32 ());
Assert.AreEqual (2, buffer.ReadUInt32 ());
Assert.AreEqual (3, buffer.ReadUInt32 ());
Assert.AreEqual (4, buffer.ReadUInt32 ());
var intialValue = field.InitialValue;
field.InitialValue = null;
Assert.False (field.Attributes.HasFlag (FieldAttributes.HasFieldRVA));
field.InitialValue = intialValue;
Assert.True (field.Attributes.HasFlag (FieldAttributes.HasFieldRVA));
});
}
[Test]
public void GenericFieldDefinition ()
{
TestCSharp ("Generics.cs", module => {
var bar = module.GetType ("Bar`1");
Assert.IsNotNull (bar);
Assert.IsTrue (bar.HasGenericParameters);
var t = bar.GenericParameters [0];
Assert.AreEqual ("T", t.Name);
Assert.AreEqual (t.Owner, bar);
var bang = bar.GetField ("bang");
Assert.IsNotNull (bang);
Assert.AreEqual (t, bang.FieldType);
});
}
[Test]
public void ArrayFields ()
{
TestIL ("types.il", module => {
var types = module.GetType ("Types");
Assert.IsNotNull (types);
var rank_two = types.GetField ("rank_two");
var array = rank_two.FieldType as ArrayType;
Assert.IsNotNull (array);
Assert.AreEqual (2, array.Rank);
Assert.IsFalse (array.Dimensions [0].IsSized);
Assert.IsFalse (array.Dimensions [1].IsSized);
var rank_two_low_bound_zero = types.GetField ("rank_two_low_bound_zero");
array = rank_two_low_bound_zero.FieldType as ArrayType;
Assert.IsNotNull (array);
Assert.AreEqual (2, array.Rank);
Assert.IsTrue (array.Dimensions [0].IsSized);
Assert.AreEqual (0, array.Dimensions [0].LowerBound);
Assert.AreEqual (null, array.Dimensions [0].UpperBound);
Assert.IsTrue (array.Dimensions [1].IsSized);
Assert.AreEqual (0, array.Dimensions [1].LowerBound);
Assert.AreEqual (null, array.Dimensions [1].UpperBound);
var rank_one_low_bound_m1 = types.GetField ("rank_one_low_bound_m1");
array = rank_one_low_bound_m1.FieldType as ArrayType;
Assert.IsNotNull (array);
Assert.AreEqual (1, array.Rank);
Assert.IsTrue (array.Dimensions [0].IsSized);
Assert.AreEqual (-1, array.Dimensions [0].LowerBound);
Assert.AreEqual (4, array.Dimensions [0].UpperBound);
});
}
[Test]
public void EnumFieldsConstant ()
{
TestCSharp ("Fields.cs", module => {
var pim = module.GetType ("Pim");
Assert.IsNotNull (pim);
var field = pim.GetField ("Pam");
Assert.IsTrue (field.HasConstant);
Assert.AreEqual (1, (int) field.Constant);
field = pim.GetField ("Poum");
Assert.AreEqual (2, (int) field.Constant);
});
}
[Test]
public void StringAndClassConstant ()
{
TestCSharp ("Fields.cs", module => {
var panpan = module.GetType ("PanPan");
Assert.IsNotNull (panpan);
var field = panpan.GetField ("Peter");
Assert.IsTrue (field.HasConstant);
Assert.IsNull (field.Constant);
field = panpan.GetField ("QQ");
Assert.AreEqual ("qq", (string) field.Constant);
field = panpan.GetField ("nil");
Assert.AreEqual (null, (string) field.Constant);
});
}
[Test]
public void ObjectConstant ()
{
TestCSharp ("Fields.cs", module => {
var panpan = module.GetType ("PanPan");
Assert.IsNotNull (panpan);
var field = panpan.GetField ("obj");
Assert.IsTrue (field.HasConstant);
Assert.IsNull (field.Constant);
});
}
[Test]
public void NullPrimitiveConstant ()
{
TestIL ("types.il", module => {
var fields = module.GetType ("Fields");
var field = fields.GetField ("int32_nullref");
Assert.IsTrue (field.HasConstant);
Assert.AreEqual (null, field.Constant);
});
}
[Test]
public void ArrayConstant ()
{
TestCSharp ("Fields.cs", module => {
var panpan = module.GetType ("PanPan");
Assert.IsNotNull (panpan);
var field = panpan.GetField ("ints");
Assert.IsTrue (field.HasConstant);
Assert.IsNull (field.Constant);
});
}
[Test]
public void ConstantCoalescing ()
{
TestIL ("types.il", module => {
var fields = module.GetType ("Fields");
var field = fields.GetField ("int32_int16");
Assert.AreEqual ("System.Int32", field.FieldType.FullName);
Assert.IsTrue (field.HasConstant);
Assert.IsInstanceOf (typeof (short), field.Constant);
Assert.AreEqual ((short) 1, field.Constant);
field = fields.GetField ("int16_int32");
Assert.AreEqual ("System.Int16", field.FieldType.FullName);
Assert.IsTrue (field.HasConstant);
Assert.IsInstanceOf (typeof (int), field.Constant);
Assert.AreEqual (1, field.Constant);
field = fields.GetField ("char_int16");
Assert.AreEqual ("System.Char", field.FieldType.FullName);
Assert.IsTrue (field.HasConstant);
Assert.IsInstanceOf (typeof (short), field.Constant);
Assert.AreEqual ((short) 1, field.Constant);
field = fields.GetField ("int16_char");
Assert.AreEqual ("System.Int16", field.FieldType.FullName);
Assert.IsTrue (field.HasConstant);
Assert.IsInstanceOf (typeof (char), field.Constant);
Assert.AreEqual ('s', field.Constant);
});
}
[Test]
public void NestedEnumOfGenericTypeDefinition ()
{
TestCSharp ("Generics.cs", module => {
var dang = module.GetType ("Bongo`1/Dang");
Assert.IsNotNull (dang);
var field = dang.GetField ("Ding");
Assert.IsNotNull (field);
Assert.AreEqual (2, field.Constant);
field = dang.GetField ("Dong");
Assert.IsNotNull (field);
Assert.AreEqual (12, field.Constant);
});
}
[Test]
public void MarshalAsFixedStr ()
{
TestModule ("marshal.dll", module => {
var boc = module.GetType ("Boc");
var field = boc.GetField ("a");
Assert.IsNotNull (field);
Assert.IsTrue (field.HasMarshalInfo);
var info = (FixedSysStringMarshalInfo) field.MarshalInfo;
Assert.AreEqual (42, info.Size);
});
}
[Test]
public void MarshalAsFixedArray ()
{
TestModule ("marshal.dll", module => {
var boc = module.GetType ("Boc");
var field = boc.GetField ("b");
Assert.IsNotNull (field);
Assert.IsTrue (field.HasMarshalInfo);
var info = (FixedArrayMarshalInfo) field.MarshalInfo;
Assert.AreEqual (12, info.Size);
Assert.AreEqual (NativeType.Boolean, info.ElementType);
});
}
[Test]
public void UnattachedField ()
{
var field = new FieldDefinition ("Field", FieldAttributes.Public, typeof (int).ToDefinition ());
Assert.IsFalse (field.HasConstant);
Assert.IsNull (field.Constant);
}
static TypeDefinition GetPrivateImplementationType (ModuleDefinition module)
{
foreach (var type in module.Types)
if (type.FullName.Contains ("<PrivateImplementationDetails>"))
return type;
return null;
}
static void AssertField (TypeDefinition type, string name, Type expected)
{
var field = type.GetField (name);
Assert.IsNotNull (field, name);
Assert.AreEqual (expected.FullName, field.FieldType.FullName);
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryNullableNotEqualTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableBoolNotEqualTest(bool useInterpreter)
{
bool?[] array = new bool?[] { null, true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableBoolNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableByteNotEqualTest(bool useInterpreter)
{
byte?[] array = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableByteNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableCharNotEqualTest(bool useInterpreter)
{
char?[] array = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableCharNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDecimalNotEqualTest(bool useInterpreter)
{
decimal?[] array = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDecimalNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDoubleNotEqualTest(bool useInterpreter)
{
double?[] array = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDoubleNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableFloatNotEqualTest(bool useInterpreter)
{
float?[] array = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableFloatNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableIntNotEqualTest(bool useInterpreter)
{
int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableIntNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableLongNotEqualTest(bool useInterpreter)
{
long?[] array = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableLongNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableSByteNotEqualTest(bool useInterpreter)
{
sbyte?[] array = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableSByteNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableShortNotEqualTest(bool useInterpreter)
{
short?[] array = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableShortNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUIntNotEqualTest(bool useInterpreter)
{
uint?[] array = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUIntNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableULongNotEqualTest(bool useInterpreter)
{
ulong?[] array = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableULongNotEqual(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUShortNotEqualTest(bool useInterpreter)
{
ushort?[] array = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUShortNotEqual(array[i], array[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyNullableBoolNotEqual(bool? a, bool? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(bool?)),
Expression.Constant(b, typeof(bool?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyNullableByteNotEqual(byte? a, byte? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyNullableCharNotEqual(char? a, char? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyNullableDecimalNotEqual(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyNullableDoubleNotEqual(double? a, double? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyNullableFloatNotEqual(float? a, float? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyNullableIntNotEqual(int? a, int? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyNullableLongNotEqual(long? a, long? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyNullableSByteNotEqual(sbyte? a, sbyte? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyNullableShortNotEqual(short? a, short? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyNullableUIntNotEqual(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyNullableULongNotEqual(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
private static void VerifyNullableUShortNotEqual(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.NotEqual(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a != b, f());
}
#endregion
}
}
| |
// ----------------------------------------------------------------------------
// XmlEquivalencyConstraintTestFixture.cs
//
// Contains the definition of the XmlEquivalencyConstraintTestFixture class.
// Copyright 2009 Steve Guidi.
//
// File created: 7/8/2009 18:53:31
// ----------------------------------------------------------------------------
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using NUnit.Framework;
using NUnit.Framework.Constraints;
using Rhino.Mocks;
namespace Jolt.Testing.Assertions.NUnit.Test
{
using CreateXmlEquivalencyAssertionDelegate = Func<XmlComparisonFlags, XmlEquivalencyAssertion>;
[TestFixture]
public sealed class XmlEquivalencyConstraintTestFixture
{
#region public methods --------------------------------------------------------------------
/// <summary>
/// Verifies the public construction of the class.
/// </summary>
[Test]
public void Construction()
{
ConstraintConstructionTests.XmlEquivalencyConstraint(xml => new XmlEquivalencyConstraint(xml));
}
/// <summary>
/// Verifies the internal construction of the class.
/// </summary>
[Test]
public void Construction_Internal()
{
CreateXmlEquivalencyAssertionDelegate createAssertion = MockRepository.GenerateStub<CreateXmlEquivalencyAssertionDelegate>();
XmlReader expectedXml = XmlReader.Create(Stream.Null);
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(expectedXml, createAssertion);
Assert.That(constraint.ComparisonFlags, Is.EqualTo(XmlComparisonFlags.Strict));
Assert.That(constraint.CreateAssertion, Is.SameAs(createAssertion));
Assert.That(constraint.ExpectedXml, Is.SameAs(expectedXml));
}
/// <summary>
/// Verifies the behavior of the Matches() method, when
/// given an object of an invalid type.
/// </summary>
[Test]
public void Matches_InvalidType()
{
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(null);
Assert.That(!constraint.Matches(String.Empty));
}
/// <summary>
/// Verifies the behavior of the Matches() method,
/// when the contraint assertion succeeds.
/// </summary>
[Test]
public void Matches()
{
CreateXmlEquivalencyAssertionDelegate createAssertion = MockRepository.GenerateMock<CreateXmlEquivalencyAssertionDelegate>();
XmlEquivalencyAssertion assertion = MockRepository.GenerateMock<XmlEquivalencyAssertion>(XmlComparisonFlags.Strict);
using (XmlReader expectedReader = XmlReader.Create(Stream.Null),
actualReader = XmlReader.Create(Stream.Null))
{
createAssertion.Expect(ca => ca(XmlComparisonFlags.Strict)).Return(assertion);
assertion.Expect(a => a.AreEquivalent(expectedReader, actualReader)).Return(new XmlComparisonResult());
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(expectedReader, createAssertion);
Assert.That(constraint.Matches(actualReader));
}
createAssertion.VerifyAllExpectations();
assertion.VerifyAllExpectations();
}
/// <summary>
/// Verifies the behavior of the Matches() method, when the constraint
/// is intialized with a non-default comparison flag.
/// </summary>
[Test]
public void Matches_WithComparisonFlags()
{
XmlComparisonFlags expectedFlags = XmlComparisonFlags.IgnoreSequenceOrder |
XmlComparisonFlags.IgnoreAttributes |
XmlComparisonFlags.IgnoreElementValues;
CreateXmlEquivalencyAssertionDelegate createAssertion = MockRepository.GenerateMock<CreateXmlEquivalencyAssertionDelegate>();
XmlEquivalencyAssertion assertion = MockRepository.GenerateMock<XmlEquivalencyAssertion>(expectedFlags);
using (XmlReader expectedReader = XmlReader.Create(Stream.Null),
actualReader = XmlReader.Create(Stream.Null))
{
createAssertion.Expect(ca => ca(expectedFlags)).Return(assertion);
assertion.Expect(a => a.AreEquivalent(expectedReader, actualReader)).Return(new XmlComparisonResult());
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(expectedReader, createAssertion)
.IgnoreAttributes
.IgnoreElementValues
.IgnoreSequenceOrder;
Assert.That(constraint.Matches(actualReader));
}
createAssertion.VerifyAllExpectations();
assertion.VerifyAllExpectations();
}
/// <summary>
/// Verifies the behavior of the Matches() method,
/// when the constraint assertion fails.
/// </summary>
[Test]
public void Matches_DoesNotMatch()
{
CreateXmlEquivalencyAssertionDelegate createAssertion = MockRepository.GenerateMock<CreateXmlEquivalencyAssertionDelegate>();
XmlEquivalencyAssertion assertion = MockRepository.GenerateMock<XmlEquivalencyAssertion>(XmlComparisonFlags.Strict);
using (XmlReader expectedReader = XmlReader.Create(Stream.Null),
actualReader = XmlReader.Create(Stream.Null))
{
createAssertion.Expect(ca => ca(XmlComparisonFlags.Strict)).Return(assertion);
assertion.Expect(a => a.AreEquivalent(expectedReader, actualReader)).Return(CreateFailedComparisonResult());
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(expectedReader, createAssertion);
Assert.That(!constraint.Matches(actualReader));
}
createAssertion.VerifyAllExpectations();
assertion.VerifyAllExpectations();
}
/// <summary>
/// Verifies the behavior of the Matches() method,
/// when an unexpected exception is raised.
/// </summary>
[Test]
public void Matches_UnexpectedException()
{
CreateXmlEquivalencyAssertionDelegate createAssertion = MockRepository.GenerateMock<CreateXmlEquivalencyAssertionDelegate>();
XmlEquivalencyAssertion assertion = MockRepository.GenerateMock<XmlEquivalencyAssertion>(XmlComparisonFlags.Strict);
using (XmlReader expectedReader = XmlReader.Create(Stream.Null),
actualReader = XmlReader.Create(Stream.Null))
{
Exception expectedException = new InvalidProgramException();
createAssertion.Expect(ca => ca(XmlComparisonFlags.Strict)).Return(assertion);
assertion.Expect(a => a.AreEquivalent(expectedReader, actualReader)).Throw(expectedException);
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(expectedReader, createAssertion);
Assert.That(
() => constraint.Matches(actualReader),
Throws.Exception.SameAs(expectedException));
}
createAssertion.VerifyAllExpectations();
assertion.VerifyAllExpectations();
}
/// <summary>
/// Verifies the behavior of the WriteDescriptionTo() method.
/// </summary>
[Test, ExpectedException(typeof(NotImplementedException))]
public void WriteDescriptionTo()
{
MessageWriter writer = MockRepository.GenerateStub<MessageWriter>();
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(null);
constraint.WriteDescriptionTo(writer);
}
/// <summary>
/// Verifies the behavior of the WriteMessageTo() method.
/// </summary>
[Test]
public void WriteMessageTo()
{
CreateXmlEquivalencyAssertionDelegate createAssertion = MockRepository.GenerateMock<CreateXmlEquivalencyAssertionDelegate>();
XmlEquivalencyAssertion assertion = MockRepository.GenerateMock<XmlEquivalencyAssertion>(XmlComparisonFlags.Strict);
MessageWriter writer = MockRepository.GenerateMock<MessageWriter>();
using (XmlReader expectedReader = XmlReader.Create(Stream.Null),
actualReader = XmlReader.Create(Stream.Null))
{
createAssertion.Expect(ca => ca(XmlComparisonFlags.Strict)).Return(assertion);
XmlComparisonResult assertionResult = CreateFailedComparisonResult();
assertion.Expect(a => a.AreEquivalent(expectedReader, actualReader)).Return(assertionResult);
writer.Expect(w => w.WriteLine("message\r\nXPath: /ns:element"));
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(expectedReader, createAssertion);
constraint.Matches(actualReader);
constraint.WriteMessageTo(writer);
}
createAssertion.VerifyAllExpectations();
assertion.VerifyAllExpectations();
writer.VerifyAllExpectations();
}
/// <summary>
/// Verifies the behavior of the WriteActualValueTo() method.
/// </summary>
[Test]
public void WriteActualValueTo()
{
CreateXmlEquivalencyAssertionDelegate createAssertion = MockRepository.GenerateMock<CreateXmlEquivalencyAssertionDelegate>();
XmlEquivalencyAssertion assertion = MockRepository.GenerateMock<XmlEquivalencyAssertion>(XmlComparisonFlags.Strict);
MessageWriter writer = MockRepository.GenerateMock<MessageWriter>();
using (XmlReader expectedReader = XmlReader.Create(Stream.Null),
actualReader = XmlReader.Create(Stream.Null))
{
createAssertion.Expect(ca => ca(XmlComparisonFlags.Strict)).Return(assertion);
writer.Expect(w => w.WriteActualValue(actualReader));
assertion.Expect(a => a.AreEquivalent(expectedReader, actualReader)).Return(new XmlComparisonResult());
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(expectedReader, createAssertion);
constraint.Matches(actualReader);
constraint.WriteActualValueTo(writer);
}
createAssertion.VerifyAllExpectations();
assertion.VerifyAllExpectations();
writer.VerifyAllExpectations();
}
/// <summary>
/// Verifies the behavior of the IgnoreAttributeNamesapce property.
/// </summary>
[Test]
public void IgnoreAttributeNamespace()
{
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(null);
XmlEquivalencyConstraint newConstraint = constraint.IgnoreAttributeNamespaces;
Assert.That(constraint, Is.SameAs(newConstraint));
Assert.That(constraint.ComparisonFlags, Is.EqualTo(XmlComparisonFlags.IgnoreAttributeNamespaces));
}
/// <summary>
/// Verifies the behavior of the IgnoreAttributes property.
/// </summary>
[Test]
public void IgnoreAttributes()
{
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(null);
XmlEquivalencyConstraint newConstraint = constraint.IgnoreAttributes;
Assert.That(constraint, Is.SameAs(newConstraint));
Assert.That(constraint.ComparisonFlags, Is.EqualTo(XmlComparisonFlags.IgnoreAttributes));
}
/// <summary>
/// Verifies the behavior of the IgnoreElementNamespaces property.
/// </summary>
[Test]
public void IgnoreElementNamespaces()
{
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(null);
XmlEquivalencyConstraint newConstraint = constraint.IgnoreElementNamespaces;
Assert.That(constraint, Is.SameAs(newConstraint));
Assert.That(constraint.ComparisonFlags, Is.EqualTo(XmlComparisonFlags.IgnoreElementNamespaces));
}
/// <summary>
/// Verifies the behavior of the IgnoreElementValues property.
/// </summary>
[Test]
public void IgnoreElementValues()
{
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(null);
XmlEquivalencyConstraint newConstraint = constraint.IgnoreElementValues;
Assert.That(constraint, Is.SameAs(newConstraint));
Assert.That(constraint.ComparisonFlags, Is.EqualTo(XmlComparisonFlags.IgnoreElementValues));
}
/// <summary>
/// Verifies the behavior of the IgnoreSequenceOrder property.
/// </summary>
[Test]
public void IgnoreSequenceOrder()
{
XmlEquivalencyConstraint constraint = new XmlEquivalencyConstraint(null);
XmlEquivalencyConstraint newConstraint = constraint.IgnoreSequenceOrder;
Assert.That(constraint, Is.SameAs(newConstraint));
Assert.That(constraint.ComparisonFlags, Is.EqualTo(XmlComparisonFlags.IgnoreSequenceOrder));
}
#endregion
#region private methods -------------------------------------------------------------------
/// <summary>
/// Creates an <see cref="XmlComparisonResult"/> representing a failed comparison.
/// </summary>
private static XmlComparisonResult CreateFailedComparisonResult()
{
XElement element = new XElement(XName.Get("element", "ns"));
return new XmlComparisonResult(false, "message", element, element);
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// Copyright (c) Lead Pipe Software. All rights reserved.
// Licensed under the MIT License. Please see the LICENSE file in the project root for full license information.
// --------------------------------------------------------------------------------------------------------------------
using LeadPipe.Net.Extensions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
namespace LeadPipe.Net.Collections
{
/// <summary>
/// The tracking observable collection changed event handler delegate.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The args.</param>
public delegate void TrackingObservableCollectionChangedEventHandler(object sender, TrackingObservableCollectionChangedEventArgs args);
/// <summary>
/// An observable collection with change tracking capabilities.
/// </summary>
/// <typeparam name="T">
/// The observable collection type.
/// </typeparam>
public class TrackingObservableCollection<T> : ObservableCollection<T>, ITrackingObservableCollection
where T : INotifyPropertyChanged
{
/// <summary>
/// The tracked items.
/// </summary>
private readonly List<TrackedItem<T>> trackedItems = new List<TrackedItem<T>>();
/// <summary>
/// Initializes a new instance of the <see cref="TrackingObservableCollection{T}"/> class.
/// Initializes a new instance of the <see cref="TrackingObservableCollection<T>"/> class.
/// </summary>
/// <param name="collection">
/// The collection.
/// </param>
public TrackingObservableCollection(IEnumerable<T> collection)
: base(collection)
{
this.SetTrackedItems(collection);
}
/// <summary>
/// Initializes a new instance of the <see cref="TrackingObservableCollection{T}"/> class.
/// Initializes a new instance of the <see cref="TrackingObservableCollection<T>"/> class.
/// </summary>
/// <param name="items">
/// The items.
/// </param>
public TrackingObservableCollection(List<T> items)
: base(items)
{
this.SetTrackedItems(items);
}
/// <summary>
/// Occurs when [tracking observable collection changed].
/// </summary>
public event TrackingObservableCollectionChangedEventHandler TrackingObservableCollectionChanged;
/// <summary>
/// Gets the added and/or changed items.
/// </summary>
public virtual List<T> AddedAndOrChangedItems
{
get
{
return (from trackedItem in this.trackedItems
where trackedItem.TrackingState == TrackingState.Added || trackedItem.TrackingState == TrackingState.Changed
select trackedItem.Item).ToList();
}
}
/// <summary>
/// Gets the added items.
/// </summary>
public virtual List<T> AddedItems
{
get
{
return (from trackedItem in this.trackedItems
where trackedItem.TrackingState == TrackingState.Added
select trackedItem.Item).ToList();
}
}
/// <summary>
/// Gets the changed items.
/// </summary>
public virtual List<T> ChangedItems
{
get
{
return (from trackedItem in this.trackedItems
where trackedItem.TrackingState == TrackingState.Changed
select trackedItem.Item).ToList();
}
}
/// <summary>
/// Gets a value indicating whether this instance has added and/or changed items.
/// </summary>
/// <value>
/// <c>true</c> if this instance has added and/or changed items; otherwise, <c>false</c>.
/// </value>
public virtual bool HasAddedAndOrChangedItems
{
get
{
return
this.trackedItems.Any(
item => item.TrackingState == TrackingState.Added || item.TrackingState == TrackingState.Changed);
}
}
/// <summary>
/// Gets a value indicating whether this instance has added items.
/// </summary>
/// <value>
/// <c>true</c> if this instance has added items; otherwise, <c>false</c>.
/// </value>
public virtual bool HasAddedItems
{
get
{
return this.trackedItems.Any(item => item.TrackingState == TrackingState.Added);
}
}
/// <summary>
/// Gets a value indicating whether this instance has changed items.
/// </summary>
/// <value>
/// <c>true</c> if this instance has changed items; otherwise, <c>false</c>.
/// </value>
public virtual bool HasChangedItems
{
get
{
return this.trackedItems.Any(item => item.TrackingState == TrackingState.Changed);
}
}
/// <summary>
/// Gets a value indicating whether this instance has removed items.
/// </summary>
/// <value>
/// <c>true</c> if this instance has removed items; otherwise, <c>false</c>.
/// </value>
public virtual bool HasRemovedItems
{
get
{
return this.trackedItems.Any(item => item.TrackingState == TrackingState.Removed);
}
}
/// <summary>
/// Gets a value indicating whether this instance has unchanged items.
/// </summary>
/// <value>
/// <c>true</c> if this instance has unchanged items; otherwise, <c>false</c>.
/// </value>
public virtual bool HasUnchangedItems
{
get
{
return this.trackedItems.Any(item => item.TrackingState == TrackingState.Unchanged);
}
}
/// <summary>
/// Gets the removed items.
/// </summary>
public virtual List<T> RemovedItems
{
get
{
return (from trackedItem in this.trackedItems
where trackedItem.TrackingState == TrackingState.Removed
select trackedItem.Item).ToList();
}
}
/// <summary>
/// Gets the unchanged items.
/// </summary>
public virtual List<T> UnchangedItems
{
get
{
return (from trackedItem in this.trackedItems
where trackedItem.TrackingState == TrackingState.Unchanged
select trackedItem.Item).ToList();
}
}
/// <summary>
/// Gets the tracking state for an object.
/// </summary>
/// <param name="obj">The object.</param>
/// <returns>The TrackingState of the object.</returns>
public TrackingState GetTrackingState(object obj)
{
if (!(obj is T))
{
throw new InvalidCastException();
}
return this.GetTrackingState((T)obj);
}
/// <summary>
/// Gets the tracking state for an item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>The TrackingState of the item.</returns>
public TrackingState GetTrackingState(T item)
{
var trackedItem = this.trackedItems.FirstOrDefault(p => p.Item.Equals(item));
if (trackedItem.IsNotNull())
{
return trackedItem.TrackingState;
}
return TrackingState.Unknown;
}
/// <summary>
/// Resets the tracking.
/// </summary>
/// <remarks>
/// <para>
/// A call to this method will result in all the tracked items being marked as unmodified. Handle with care!
/// </para>
/// </remarks>
public virtual void ResetTracking()
{
foreach (var trackedItem in this.trackedItems)
{
trackedItem.TrackingState = TrackingState.Unchanged;
}
}
/// <summary>
/// Resets the collection tracking data.
/// </summary>
/// <param name="collection">
/// The collection.
/// </param>
public virtual void SetTrackedItems(IEnumerable<T> collection)
{
this.SetTrackedItems(collection.ToList());
}
/// <summary>
/// Resets the collection tracking data.
/// </summary>
/// <param name="items">
/// The items.
/// </param>
public virtual void SetTrackedItems(List<T> items)
{
// Clear the existing list...
this.trackedItems.Clear();
// Add each item in the incoming collection to our tracked items list and wire up the event handler...
foreach (T item in items)
{
this.trackedItems.Add(new TrackedItem<T>(item, TrackingState.Unchanged));
item.PropertyChanged += this.TrackedItemPropertyChanged;
}
}
/// <summary>
/// Raises the <see cref="E:CollectionChanged"/> event.
/// </summary>
/// <param name="e">
/// The <see cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs"/> instance containing the event data.
/// </param>
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
base.OnCollectionChanged(e);
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (T item in e.NewItems)
{
this.trackedItems.Add(new TrackedItem<T>(item, TrackingState.Added));
item.PropertyChanged += this.TrackedItemPropertyChanged;
}
this.OnTrackingObservableCollectionChanged(new TrackingObservableCollectionChangedEventArgs(TrackingObservableCollectionChangedAction.Add));
break;
case NotifyCollectionChangedAction.Remove:
foreach (var trackedItem in from T item in e.OldItems select this.trackedItems.Find(t => t.Item.Equals(item)))
{
switch (trackedItem.TrackingState)
{
case TrackingState.Unchanged:
case TrackingState.Changed:
trackedItem.TrackingState = TrackingState.Removed;
break;
case TrackingState.Added:
this.trackedItems.Remove(trackedItem);
break;
default:
break;
}
}
var trackingState = TrackingState.Unchanged;
if (this.HasAddedAndOrChangedItems || this.HasRemovedItems)
{
trackingState = TrackingState.Changed;
}
this.OnTrackingObservableCollectionChanged(new TrackingObservableCollectionChangedEventArgs(TrackingObservableCollectionChangedAction.Remove, trackingState));
break;
case NotifyCollectionChangedAction.Move:
this.OnTrackingObservableCollectionChanged(new TrackingObservableCollectionChangedEventArgs(TrackingObservableCollectionChangedAction.Move));
break;
case NotifyCollectionChangedAction.Replace:
this.OnTrackingObservableCollectionChanged(new TrackingObservableCollectionChangedEventArgs(TrackingObservableCollectionChangedAction.Replace));
break;
case NotifyCollectionChangedAction.Reset:
this.OnTrackingObservableCollectionChanged(new TrackingObservableCollectionChangedEventArgs(TrackingObservableCollectionChangedAction.Reset));
break;
default:
break;
}
}
/// <summary>
/// Raises the <see cref="TrackingObservableCollectionChanged"/> event.
/// </summary>
/// <param name="e">The <see cref="TrackingObservableCollectionChangedEventArgs"/> instance containing the event data.</param>
protected virtual void OnTrackingObservableCollectionChanged(TrackingObservableCollectionChangedEventArgs e)
{
if (this.TrackingObservableCollectionChanged.IsNotNull())
{
this.TrackingObservableCollectionChanged(this, e);
}
}
/// <summary>
/// Occurs when a tracked item changes.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.
/// </param>
private void TrackedItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
TrackedItem<T> trackedItem = this.trackedItems.Find(t => t.Item.Equals(sender));
switch (trackedItem.TrackingState)
{
case TrackingState.Unchanged:
trackedItem.TrackingState = TrackingState.Changed;
this.OnTrackingObservableCollectionChanged(new TrackingObservableCollectionChangedEventArgs(TrackingObservableCollectionChangedAction.ItemChanged));
break;
default:
break;
}
}
/// <summary>
/// Represents a tracked item.
/// </summary>
/// <typeparam name="TTrackedItemType">
/// The type of the tracked item type.
/// </typeparam>
private class TrackedItem<TTrackedItemType>
{
/// <summary>
/// Initializes a new instance of the <see cref="TrackedItem{TTrackedItemType}"/> class.
/// Initializes a new instance of the <see cref="TrackingObservableCollection<T>.TrackedItem<TTrackedItemType>"/> class.
/// </summary>
/// <param name="item">
/// The item.
/// </param>
/// <param name="trackingState">
/// State of the tracking.
/// </param>
public TrackedItem(TTrackedItemType item, TrackingState trackingState)
{
this.Item = item;
this.TrackingState = trackingState;
}
/// <summary>
/// Gets or sets the item.
/// </summary>
/// <value>
/// The item.
/// </value>
public TTrackedItemType Item { get; set; }
/// <summary>
/// Gets or sets the state of the tracking.
/// </summary>
/// <value>
/// The state of the tracking.
/// </value>
public TrackingState TrackingState { get; set; }
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using QuantConnect.Algorithm.CSharp;
using QuantConnect.Brokerages;
using QuantConnect.Brokerages.Backtesting;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine;
using QuantConnect.Lean.Engine.Alpha;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.RealTime;
using QuantConnect.Lean.Engine.Results;
using QuantConnect.Lean.Engine.Server;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Orders;
using QuantConnect.Packets;
using QuantConnect.Scheduling;
using QuantConnect.Securities;
using Log = QuantConnect.Logging.Log;
namespace QuantConnect.Tests.Engine
{
[TestFixture]
public class AlgorithmManagerTests
{
[TestCase(AlgorithmStatus.Deleted)]
[TestCase(AlgorithmStatus.Stopped)]
[TestCase(AlgorithmStatus.Liquidated)]
[TestCase(AlgorithmStatus.RuntimeError)]
public void MonitorsAlgorithmState(AlgorithmStatus algorithmStatus)
{
AlgorithmManagerAlgorithmStatusTest.Loops = 0;
AlgorithmManagerAlgorithmStatusTest.AlgorithmStatus = algorithmStatus;
var parameter = new RegressionTests.AlgorithmStatisticsTestParameters("QuantConnect.Tests.Engine.AlgorithmManagerTests+AlgorithmManagerAlgorithmStatusTest",
new Dictionary<string, string> {
{"Total Trades", "0"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.00"}
},
Language.CSharp,
AlgorithmStatus.Completed);
AlgorithmRunner.RunLocalBacktest(parameter.Algorithm,
parameter.Statistics,
parameter.AlphaStatistics,
parameter.Language,
parameter.ExpectedFinalStatus,
algorithmLocation: "QuantConnect.Tests.dll");
Assert.AreEqual(1, AlgorithmManagerAlgorithmStatusTest.Loops);
}
[Test, Explicit("TravisExclude")]
public void TestAlgorithmManagerSpeed()
{
var algorithm = PerformanceBenchmarkAlgorithms.SingleSecurity_Second;
var algorithmManager = new AlgorithmManager(false);
var job = new BacktestNodePacket(1, 2, "3", null, 9m, $"{nameof(AlgorithmManagerTests)}.{nameof(TestAlgorithmManagerSpeed)}");
var feed = new MockDataFeed();
var marketHoursDatabase = MarketHoursDatabase.FromDataFolder();
var symbolPropertiesDataBase = SymbolPropertiesDatabase.FromDataFolder();
var dataPermissionManager = new DataPermissionManager();
var dataManager = new DataManager(feed,
new UniverseSelection(
algorithm,
new SecurityService(algorithm.Portfolio.CashBook,
marketHoursDatabase,
symbolPropertiesDataBase,
algorithm,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCacheProvider(algorithm.Portfolio)),
dataPermissionManager,
new DefaultDataProvider()),
algorithm,
algorithm.TimeKeeper,
marketHoursDatabase,
false,
RegisteredSecurityDataTypesProvider.Null,
dataPermissionManager);
algorithm.SubscriptionManager.SetDataManager(dataManager);
var transactions = new BacktestingTransactionHandler();
var results = new BacktestingResultHandler();
var realtime = new BacktestingRealTimeHandler();
var leanManager = new NullLeanManager();
var alphas = new NullAlphaHandler();
var token = new CancellationToken();
var nullSynchronizer = new NullSynchronizer(algorithm);
algorithm.Initialize();
algorithm.PostInitialize();
results.Initialize(job, new QuantConnect.Messaging.Messaging(), new Api.Api(), transactions);
results.SetAlgorithm(algorithm, algorithm.Portfolio.TotalPortfolioValue);
transactions.Initialize(algorithm, new BacktestingBrokerage(algorithm), results);
feed.Initialize(algorithm, job, results, null, null, null, dataManager, null, null);
Log.Trace("Starting algorithm manager loop to process " + nullSynchronizer.Count + " time slices");
var sw = Stopwatch.StartNew();
algorithmManager.Run(job, algorithm, nullSynchronizer, transactions, results, realtime, leanManager, alphas, token);
sw.Stop();
realtime.Exit();
results.Exit();
var thousands = nullSynchronizer.Count / 1000d;
var seconds = sw.Elapsed.TotalSeconds;
Log.Trace("COUNT: " + nullSynchronizer.Count + " KPS: " + thousands/seconds);
}
public class NullAlphaHandler : IAlphaHandler
{
public bool IsActive { get; }
public AlphaRuntimeStatistics RuntimeStatistics { get; }
public void Initialize(AlgorithmNodePacket job, IAlgorithm algorithm, IMessagingHandler messagingHandler, IApi api, ITransactionHandler transactionHandler)
{
}
public void OnAfterAlgorithmInitialized(IAlgorithm algorithm)
{
}
public void ProcessSynchronousEvents()
{
}
public void Run()
{
}
public void Exit()
{
}
}
public class NullLeanManager : ILeanManager
{
public void Dispose()
{
}
public void Initialize(LeanEngineSystemHandlers systemHandlers,
LeanEngineAlgorithmHandlers algorithmHandlers,
AlgorithmNodePacket job,
AlgorithmManager algorithmManager)
{
}
public void SetAlgorithm(IAlgorithm algorithm)
{
}
public void Update()
{
}
public void OnAlgorithmStart()
{
}
public void OnAlgorithmEnd()
{
}
}
class NullResultHandler : IResultHandler
{
public ConcurrentQueue<Packet> Messages { get; set; }
public bool IsActive { get; }
public void OnSecuritiesChanged(SecurityChanges changes)
{
}
public void Initialize(AlgorithmNodePacket job,
IMessagingHandler messagingHandler,
IApi api,
ITransactionHandler transactionHandler)
{
}
public void DebugMessage(string message)
{
}
public void SystemDebugMessage(string message)
{
}
public void SecurityType(List<SecurityType> types)
{
}
public void LogMessage(string message)
{
}
public void ErrorMessage(string error, string stacktrace = "")
{
}
public void RuntimeError(string message, string stacktrace = "")
{
}
public void BrokerageMessage(BrokerageMessageEvent brokerageMessageEvent)
{
}
public void Sample(DateTime time, bool force = false)
{
}
public void SetAlgorithm(IAlgorithm algorithm, decimal startingPortfolioValue)
{
}
public void SetAlphaRuntimeStatistics(AlphaRuntimeStatistics statistics)
{
}
public void SendStatusUpdate(AlgorithmStatus status, string message = "")
{
}
public void RuntimeStatistic(string key, string value)
{
}
public void OrderEvent(OrderEvent newEvent)
{
}
public void Exit()
{
}
public void ProcessSynchronousEvents(bool forceProcess = false)
{
}
public void SaveResults(string name, Result result)
{
}
public void SetDataManager(IDataFeedSubscriptionManager dataManager)
{
}
}
class NullRealTimeHandler : IRealTimeHandler
{
public void Add(ScheduledEvent scheduledEvent)
{
}
public void Remove(ScheduledEvent scheduledEvent)
{
}
public bool IsActive { get; }
public void Setup(IAlgorithm algorithm, AlgorithmNodePacket job, IResultHandler resultHandler, IApi api, IIsolatorLimitResultProvider isolatorLimitProvider)
{
}
public void Run()
{
}
public void SetTime(DateTime time)
{
}
public void ScanPastEvents(DateTime time)
{
}
public void Exit()
{
}
public void OnSecuritiesChanged(SecurityChanges changes)
{
}
}
class NullSynchronizer : ISynchronizer
{
private DateTime _frontierUtc;
private readonly DateTime _endTimeUtc;
private readonly List<BaseData> _data = new List<BaseData>();
private readonly List<UpdateData<SubscriptionDataConfig>> _consolidatorUpdateData = new List<UpdateData<SubscriptionDataConfig>>();
private readonly List<TimeSlice> _timeSlices = new List<TimeSlice>();
private readonly TimeSpan _frontierStepSize = TimeSpan.FromSeconds(1);
private readonly List<UpdateData<ISecurityPrice>> _securitiesUpdateData = new List<UpdateData<ISecurityPrice>>();
public int Count => _timeSlices.Count;
public NullSynchronizer(IAlgorithm algorithm)
{
_frontierUtc = algorithm.StartDate.ConvertToUtc(algorithm.TimeZone);
_endTimeUtc = algorithm.EndDate.ConvertToUtc(algorithm.TimeZone);
foreach (var kvp in algorithm.Securities)
{
var security = kvp.Value;
var tick = new Tick
{
Symbol = security.Symbol,
EndTime = _frontierUtc.ConvertFromUtc(security.Exchange.TimeZone)
};
_data.Add(tick);
_securitiesUpdateData.Add(new UpdateData<ISecurityPrice>(security, typeof(Tick), new BaseData[] { tick }, false));
_consolidatorUpdateData.Add(new UpdateData<SubscriptionDataConfig>(security.Subscriptions.First(), typeof(Tick), new BaseData[] { tick }, false));
}
_timeSlices.AddRange(GenerateTimeSlices().Take(int.MaxValue / 1000));
}
public IEnumerable<TimeSlice> StreamData(CancellationToken cancellationToken)
{
return _timeSlices;
}
private IEnumerable<TimeSlice> GenerateTimeSlices()
{
var bars = new TradeBars();
var quotes = new QuoteBars();
var ticks = new Ticks();
var options = new OptionChains();
var futures = new FuturesChains();
var splits = new Splits();
var dividends = new Dividends();
var delistings = new Delistings();
var symbolChanges = new SymbolChangedEvents();
var dataFeedPackets = new List<DataFeedPacket>();
var customData = new List<UpdateData<ISecurityPrice>>();
var changes = SecurityChanges.None;
do
{
var slice = new Slice(default(DateTime), _data, bars, quotes, ticks, options, futures, splits, dividends, delistings, symbolChanges);
var timeSlice = new TimeSlice(_frontierUtc, _data.Count, slice, dataFeedPackets, _securitiesUpdateData, _consolidatorUpdateData, customData, changes, new Dictionary<Universe, BaseDataCollection>());
yield return timeSlice;
_frontierUtc += _frontierStepSize;
}
while (_frontierUtc <= _endTimeUtc);
}
}
public class AlgorithmManagerAlgorithmStatusTest : BasicTemplateDailyAlgorithm
{
public static int Loops { get; set; }
public static AlgorithmStatus AlgorithmStatus { get; set; }
public AlgorithmManagerAlgorithmStatusTest() : base()
{
}
public override void OnData(Slice data)
{
++Loops;
SetStatus(AlgorithmStatus);
}
}
}
}
| |
//
// Copyright (c) 2012-2021 Antmicro
//
// This file is licensed under the MIT License.
// Full license text is available in the LICENSE file.
using System;
using System.IO;
using System.Text;
namespace Antmicro.Migrant
{
/// <summary>
/// Provides the mechanism for writing primitive values into a stream.
/// </summary>
/// <remarks>
/// Can be used as a replacement for the <see cref="System.IO.BinaryWriter" /> . Provides
/// more compact output and reads no more data from the stream than requested. Although
/// the underlying format is not specified at this point, it is guaranteed to be consistent with
/// <see cref="Antmicro.Migrant.PrimitiveReader" />. Writer has to be disposed after used,
/// otherwise stream position corruption and data loss can occur. Writer does not possess the
/// stream and does not close it after dispose.
/// </remarks>
public sealed class PrimitiveWriter : IDisposable
{
/// <summary>
/// Initializes a new instance of the <see cref="Antmicro.Migrant.PrimitiveWriter" /> class.
/// </summary>
/// <param name='stream'>
/// The underlying stream which will be used to write data. Has to be writeable.
/// </param>
/// <param name='buffered'>
/// True if writes should be buffered, false when they should be immediately passed to
/// the stream. With false also no final padding is used. Note that corresponding
/// PrimitiveReader has to use the same value for this parameter.
/// </param>
public PrimitiveWriter(Stream stream, bool buffered = true)
{
this.stream = stream;
#if DEBUG_FORMAT
buffered &= !Serializer.DisableBuffering;
#endif
if(buffered)
{
buffer = new byte[BufferSize];
}
this.buffered = buffered;
}
/// <summary>
/// Gets the current position.
/// </summary>
/// <value>
/// The position, which is the number of bytes written after this object was
/// constructed.
/// </value>
public long Position
{
get
{
return currentPosition + currentBufferPosition;
}
}
/// <summary>
/// Gets current buffering configuration.
/// </summary>
/// <value><c>true</c> if this the data written to stream is buffered; otherwise, <c>false</c>.</value>
public bool IsBuffered
{
get
{
return buffered;
}
}
/// <summary>
/// Writes the specified value of type <see cref="System.Double" />.
/// </summary>
public void Write(double value)
{
Write(BitConverter.DoubleToInt64Bits(value));
}
/// <summary>
/// Writes the specified value of type <see cref="System.Single" />.
/// </summary>
public void Write(float value)
{
Write(BitConverter.DoubleToInt64Bits(value));
}
/// <summary>
/// Writes the specified value of type <see cref="System.DateTime" />.
/// </summary>
public void Write(DateTime value)
{
Write(value - Helpers.DateTimeEpoch);
}
/// <summary>
/// Writes the specified value of type <see cref="System.TimeSpan" />.
/// </summary>
public void Write(TimeSpan value)
{
// first unit, then value in this unit
if(value.Ticks % TimeSpan.TicksPerSecond != 0)
{
Write((byte)Helpers.TickIndicator);
Write(value.Ticks);
return;
}
var type = (byte)(value.Hours);
Write(type);
Write((ushort)(value.Seconds + 60 * value.Minutes));
Write(value.Days);
}
/// <summary>
/// Writes the specified value of type <see cref="System.Byte" />.
/// </summary>
public void Write(byte value)
{
if(buffered)
{
CheckBuffer(1);
buffer[currentBufferPosition++] = value;
}
else
{
currentBufferPosition++;
stream.WriteByte(value);
}
}
/// <summary>
/// Writes the specified value of type <see cref="System.SByte" />.
/// </summary>
public void Write(sbyte value)
{
Write((byte)value);
}
/// <summary>
/// Writes the specified value of type <see cref="System.Int16" />.
/// </summary>
public void Write(short value)
{
#if DEBUG_FORMAT
if(Serializer.DisableVarints)
{
InnerWriteInteger((ushort)value, sizeof(short) + 1);
return;
}
#endif
var valueToWrite = (value << 1) ^ (value >> 15);
InnerWriteInteger((ushort)valueToWrite, sizeof(short) + 1);
}
/// <summary>
/// Writes the specified value of type <see cref="System.UInt16" />.
/// </summary>
public void Write(ushort value)
{
InnerWriteInteger(value, sizeof(ushort) + 1);
}
/// <summary>
/// Writes the specified value of type <see cref="System.Int32" />.
/// </summary>
public void Write(int value)
{
#if DEBUG_FORMAT
if(Serializer.DisableVarints)
{
InnerWriteInteger((uint)value, sizeof(int) + 1);
return;
}
#endif
var valueToWrite = (value << 1) ^ (value >> 31);
InnerWriteInteger((uint)valueToWrite, sizeof(int) + 1);
}
/// <summary>
/// Writes the specified value of type <see cref="System.UInt32" />.
/// </summary>
public void Write(uint value)
{
InnerWriteInteger(value, sizeof(uint) + 1);
}
/// <summary>
/// Writes the specified value of type <see cref="System.Int64" />.
/// </summary>
public void Write(long value)
{
#if DEBUG_FORMAT
if(Serializer.DisableVarints)
{
Write((ulong)value);
return;
}
#endif
//zig-zag notation
var valueToWrite = (value << 1) ^ (value >> 63);
InnerWriteInteger((ulong)valueToWrite, sizeof(long) + 2);
}
/// <summary>
/// Writes the specified value of type <see cref="System.UInt64" />.
/// </summary>
public void Write(ulong value)
{
InnerWriteInteger(value, sizeof(ulong) + 2);
}
/// <summary>
/// Writes the specified value of type <see cref="System.Char" />.
/// </summary>
public void Write(char value)
{
Write((ushort)value);
}
/// <summary>
/// Writes the specified value of type <see cref="System.Boolean" />.
/// </summary>
public void Write(bool value)
{
Write((byte)(value ? 1 : 0));
}
/// <summary>
/// Writes the specified value of type <see cref="System.Guid" />.
/// </summary>
public void Write(Guid guid)
{
InnerChunkWrite(guid.ToByteArray());
}
/// <summary>
/// Writes the specified string.
/// </summary>
public void Write(string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
Write(bytes.Length);
InnerChunkWrite(bytes);
}
/// <summary>
/// Writes the specified <see cref="System.Decimal"/> .
/// </summary>
public void Write(decimal value)
{
var bytes = decimal.GetBits(value);
Write(bytes[0]);
Write(bytes[1]);
Write(bytes[2]);
Write(bytes[3]);
}
/// <summary>
/// Writes the specified bytes array.
/// </summary>
/// <param name='bytes'>
/// The array which content will be written.
/// </param>
public void Write(byte[] bytes)
{
InnerChunkWrite(bytes);
}
/// <summary>
/// Write the specified bytes array, starting at offset and writing count from it.
/// </summary>
/// <param name="bytes">The array which is a source to write.</param>
/// <param name="offset">Index of the array to start writing at.</param>
/// <param name="count">Total bytes to write.</param>
public void Write(byte[] bytes, int offset, int count)
{
InnerChunkWrite(bytes, offset, count);
}
/// <summary>
/// Copies given number of bytes from the source stream to the underlying stream.
/// </summary>
/// <param name='source'>
/// Readable stream, from which data will be copied.
/// </param>
/// <param name='howMuch'>
/// The amount of a data to copy in bytes.
/// </param>
public void CopyFrom(Stream source, long howMuch)
{
var localBuffer = new byte[Helpers.MaximalPadding];
Flush();
int read;
while((read = source.Read(localBuffer, 0, (int)Math.Min(localBuffer.Length, howMuch))) > 0)
{
howMuch -= read;
currentPosition += read;
stream.Write(localBuffer, 0, read);
}
if(howMuch > 0)
{
throw new EndOfStreamException(string.Format("End of stream reached while {0} more bytes expected.", howMuch));
}
}
/// <summary>
/// Flushes the buffer and pads the stream with sufficient amount of data to be compatible
/// with the <see cref="Antmicro.Migrant.PrimitiveReader" />. It is not necessary to call this method
/// when buffering is not used.
/// </summary>
/// <remarks>
/// Call <see cref="Dispose"/> when you are finished using the <see cref="Antmicro.Migrant.PrimitiveWriter"/>. The
/// <see cref="Dispose"/> method leaves the <see cref="Antmicro.Migrant.PrimitiveWriter"/> in an unusable state. After
/// calling <see cref="Dispose"/>, you must release all references to the
/// <see cref="Antmicro.Migrant.PrimitiveWriter"/> so the garbage collector can reclaim the memory that the
/// <see cref="Antmicro.Migrant.PrimitiveWriter"/> was occupying.
/// </remarks>
public void Dispose()
{
Flush();
Pad();
}
/// <summary>
/// Flushes the buffer
/// </summary>
public void Flush()
{
if(!buffered)
{
return;
}
stream.Write(buffer, 0, currentBufferPosition);
currentPosition += currentBufferPosition;
currentBufferPosition = 0;
}
private void InnerWriteInteger(ulong value, int sizeInBytes)
{
byte valueToWrite;
#if DEBUG_FORMAT
if(Serializer.DisableVarints)
{
if(buffered)
{
CheckBuffer(sizeof(ulong));
}
ulong current = 0;
int bitsShift = (sizeof(ulong) - 1) * 8;
ulong mask = ((ulong)0xFF << bitsShift);
for(int i = 0; i < sizeof(ulong); ++i)
{
current = (value & mask) >> bitsShift;
valueToWrite = (byte)current;
if(buffered)
{
buffer[currentBufferPosition + i] = valueToWrite;
}
else
{
stream.WriteByte(valueToWrite);
}
mask >>= 8;
bitsShift -= 8;
}
if(buffered)
{
currentBufferPosition += sizeof(ulong);
}
else
{
currentPosition += sizeof(ulong);
}
return;
}
#endif
if(buffered)
{
CheckBuffer(sizeInBytes);
}
while(value > 127)
{
valueToWrite = (byte)(value | 128);
if(buffered)
{
buffer[currentBufferPosition++] = valueToWrite;
}
else
{
currentPosition++;
stream.WriteByte(valueToWrite);
}
value >>= 7;
}
valueToWrite = (byte)(value & 127);
if(buffered)
{
buffer[currentBufferPosition++] = valueToWrite;
}
else
{
currentPosition++;
stream.WriteByte(valueToWrite);
}
}
private void InnerChunkWrite(byte[] data)
{
InnerChunkWrite(data, 0, data.Length);
}
private void InnerChunkWrite(byte[] data, int offset, int length)
{
if(buffered)
{
CheckBuffer(length);
}
else
{
stream.Write(data, offset, length);
currentPosition += length;
return;
}
if(length > BufferSize)
{
stream.Write(data, offset, length);
currentPosition += length;
}
else
{
Array.Copy(data, offset, buffer, currentBufferPosition, length);
currentBufferPosition += length;
}
}
private void CheckBuffer(int maxBytesToWrite)
{
if(buffer.Length - currentBufferPosition >= maxBytesToWrite)
{
return;
}
// we need to flush the buffer
Flush();
}
private void Pad()
{
if(!buffered)
{
return;
}
var bytesToPad = Helpers.GetCurrentPaddingValue(currentPosition);
var pad = new byte[bytesToPad];
stream.Write(pad, 0, pad.Length);
}
private readonly byte[] buffer;
private int currentBufferPosition;
private long currentPosition;
private readonly Stream stream;
private readonly bool buffered;
private const int BufferSize = 4 * 1024;
}
}
| |
namespace Macabresoft.Macabre2D.UI.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using Macabresoft.AvaloniaEx;
using Macabresoft.Core;
/// <summary>
/// Interface for a directory content node.
/// </summary>
public interface IContentDirectory : IContentNode {
/// <summary>
/// Gets the children of this directory.
/// </summary>
IReadOnlyCollection<IContentNode> Children { get; }
/// <summary>
/// Adds the child node.
/// </summary>
/// <param name="node">The child node to add.</param>
bool AddChild(IContentNode node);
/// <summary>
/// Gets a value indicating whether or not the specified metadata is a descendent of this directory.
/// </summary>
/// <param name="contentId">The metadata identifier.</param>
/// <returns>A value indicating whether or not the specified metadata is a descendent of this directory.</returns>
bool ContainsMetadata(Guid contentId);
/// <summary>
/// Gets all content files that are descendants of this directory.
/// </summary>
/// <returns>All content files that are descendants of this directory.</returns>
IEnumerable<ContentFile> GetAllContentFiles();
/// <summary>
/// Loads the child directories under this node.
/// </summary>
/// <param name="fileSystemService">The file service.</param>
void LoadChildDirectories(IFileSystemService fileSystemService);
/// <summary>
/// Removes the child node.
/// </summary>
/// <param name="node">The child node to remove.</param>
bool RemoveChild(IContentNode node);
/// <summary>
/// Finds a content node if it exists.
/// </summary>
/// <param name="splitContentPath"></param>
/// <returns>The content node or null.</returns>
IContentNode TryFindNode(string[] splitContentPath);
/// <summary>
/// Tries to find a content node by its identifier.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <param name="file">The file.</param>
/// <returns>A value indicating whether or not the file was found.</returns>
bool TryFindNode(Guid contentId, out ContentFile file);
/// <summary>
/// Tries to find a content node.
/// </summary>
/// <param name="splitContentPath">The split content path.</param>
/// <param name="node">The found content node.</param>
/// <returns>A value indicating whether or not the node was found.</returns>
bool TryFindNode(string[] splitContentPath, out IContentNode node);
}
/// <summary>
/// A directory content node.
/// </summary>
[DataContract(Name = "Directory")]
public class ContentDirectory : ContentNode, IContentDirectory {
private readonly ObservableCollectionExtended<IContentNode> _children = new();
/// <summary>
/// Initializes a new instance of the <see cref="ContentNode" /> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="parent">The parent content directory.</param>
public ContentDirectory(string name, IContentDirectory parent) {
this.Initialize(name, parent);
}
/// <inheritdoc />
public IReadOnlyCollection<IContentNode> Children => this._children;
/// <inheritdoc />
public override Guid Id { get; } = Guid.NewGuid();
/// <inheritdoc />
public bool AddChild(IContentNode node) {
var result = false;
if (node != null && !this._children.Contains(node)) {
var directory = node as IContentDirectory;
var isDirectory = directory != null;
if (!(isDirectory && this.IsDescendentOf(directory))) {
for (var i = 0; i < this._children.Count; i++) {
var child = this._children[i];
if (isDirectory) {
if (child is IContentDirectory) {
if (StringComparer.OrdinalIgnoreCase.Compare(node.Name, child.Name) < 0) {
this._children.Insert(i, node);
result = true;
break;
}
}
else {
this._children.Insert(i, node);
result = true;
break;
}
}
else if (child is not IContentDirectory) {
if (StringComparer.OrdinalIgnoreCase.Compare(node.Name, child.Name) < 0) {
this._children.Insert(i, node);
result = true;
break;
}
}
}
if (!result) {
this._children.Add(node);
result = true;
}
node.PathChanged += this.Child_PathChanged;
}
}
return result;
}
/// <inheritdoc />
public bool ContainsMetadata(Guid contentId) {
if (contentId != Guid.Empty) {
for (var i = this._children.Count - 1; i >= 0; i--) {
var child = this._children[i];
switch (child) {
case ContentFile file when file.Metadata?.ContentId == contentId:
case IContentDirectory directory when directory.ContainsMetadata(contentId):
return true;
}
}
}
return false;
}
/// <inheritdoc />
public IEnumerable<ContentFile> GetAllContentFiles() {
var contentFiles = this.Children.OfType<ContentFile>().ToList();
foreach (var child in this.Children.OfType<IContentDirectory>()) {
contentFiles.AddRange(child.GetAllContentFiles());
}
return contentFiles;
}
/// <inheritdoc />
public virtual void LoadChildDirectories(IFileSystemService fileSystemService) {
var currentDirectoryPath = this.GetFullPath();
if (fileSystemService.DoesDirectoryExist(currentDirectoryPath)) {
var directories = fileSystemService.GetDirectories(currentDirectoryPath);
foreach (var directory in directories) {
this.LoadDirectory(fileSystemService, directory);
}
}
}
/// <inheritdoc />
public bool RemoveChild(IContentNode node) {
node.PathChanged -= this.Child_PathChanged;
return this._children.Remove(node);
}
/// <inheritdoc />
public IContentNode TryFindNode(string[] splitContentPath) {
IContentNode node = null;
var parentDepth = splitContentPath.Length - 1;
var currentDepth = this.GetDepth();
if (currentDepth == parentDepth) {
var nodeName = splitContentPath[currentDepth];
node = this.Children.FirstOrDefault(x => x.NameWithoutExtension == nodeName);
}
else if (currentDepth < parentDepth) {
var parentName = splitContentPath[currentDepth];
if (this._children.FirstOrDefault(x => x.Name == parentName) is IContentDirectory child) {
node = child.TryFindNode(splitContentPath);
}
}
return node;
}
/// <inheritdoc />
public bool TryFindNode(Guid contentId, out ContentFile file) {
file = this.Children.FirstOrDefault(x => x.Id == contentId) as ContentFile;
if (file == null) {
foreach (var child in this.Children.OfType<IContentDirectory>()) {
if (child.TryFindNode(contentId, out file)) {
break;
}
}
}
return file != null;
}
/// <inheritdoc />
public bool TryFindNode(string[] splitContentPath, out IContentNode node) {
node = this.TryFindNode(splitContentPath);
return node != null;
}
/// <inheritdoc />
protected override string GetFileExtension() {
return string.Empty;
}
/// <inheritdoc />
protected override string GetNameWithoutExtension() {
return this.Name;
}
/// <summary>
/// Loads a directory.
/// </summary>
/// <param name="fileSystem">The file system.</param>
/// <param name="path">The path to the directory.</param>
protected void LoadDirectory(IFileSystemService fileSystem, string path) {
var splitPath = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
var name = splitPath.Length > 1 ? splitPath.Last() : path;
var node = new ContentDirectory(name, this);
node.LoadChildDirectories(fileSystem);
}
private void Child_PathChanged(object sender, ValueChangedEventArgs<string> e) {
this.RaisePathChanged(sender, e);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SpoolingTask.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.Contracts;
namespace System.Linq.Parallel
{
/// <summary>
/// A factory class to execute spooling logic.
/// </summary>
internal static class SpoolingTask
{
//-----------------------------------------------------------------------------------
// Creates and begins execution of a new spooling task. Executes synchronously,
// and by the time this API has returned all of the results have been produced.
//
// Arguments:
// groupState - values for inter-task communication
// partitions - the producer enumerators
// channels - the producer-consumer channels
// taskScheduler - the task manager on which to execute
//
internal static void SpoolStopAndGo<TInputOutput, TIgnoreKey>(
QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions,
SynchronousChannel<TInputOutput>[] channels, TaskScheduler taskScheduler)
{
Contract.Requires(partitions.PartitionCount == channels.Length);
Contract.Requires(groupState != null);
// Ensure all tasks in this query are parented under a common root.
Task rootTask = new Task(
() =>
{
int maxToRunInParallel = partitions.PartitionCount - 1;
// A stop-and-go merge uses the current thread for one task and then blocks before
// returning to the caller, until all results have been accumulated. We do this by
// running the last partition on the calling thread.
for (int i = 0; i < maxToRunInParallel; i++)
{
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i);
QueryTask asyncTask = new StopAndGoSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i], channels[i]);
asyncTask.RunAsynchronously(taskScheduler);
}
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] synchronously", maxToRunInParallel);
// Run one task synchronously on the current thread.
QueryTask syncTask = new StopAndGoSpoolingTask<TInputOutput, TIgnoreKey>(
maxToRunInParallel, groupState, partitions[maxToRunInParallel], channels[maxToRunInParallel]);
syncTask.RunSynchronously(taskScheduler);
});
// Begin the query on the calling thread.
groupState.QueryBegin(rootTask);
// We don't want to return until the task is finished. Run it on the calling thread.
rootTask.RunSynchronously(taskScheduler);
// Wait for the query to complete, propagate exceptions, and so on.
// For pipelined queries, this step happens in the async enumerator.
groupState.QueryEnd(false);
}
//-----------------------------------------------------------------------------------
// Creates and begins execution of a new spooling task. Runs asynchronously.
//
// Arguments:
// groupState - values for inter-task communication
// partitions - the producer enumerators
// channels - the producer-consumer channels
// taskScheduler - the task manager on which to execute
//
internal static void SpoolPipeline<TInputOutput, TIgnoreKey>(
QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions,
AsynchronousChannel<TInputOutput>[] channels, TaskScheduler taskScheduler)
{
Contract.Requires(partitions.PartitionCount == channels.Length);
Contract.Requires(groupState != null);
// Ensure all tasks in this query are parented under a common root. Because this
// is a pipelined query, we detach it from the parent (to avoid blocking the calling
// thread), and run the query on a separate thread.
Task rootTask = new Task(
() =>
{
// Create tasks that will enumerate the partitions in parallel. Because we're pipelining,
// we will begin running these tasks in parallel and then return.
for (int i = 0; i < partitions.PartitionCount; i++)
{
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i);
QueryTask asyncTask = new PipelineSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i], channels[i]);
asyncTask.RunAsynchronously(taskScheduler);
}
});
// Begin the query on the calling thread.
groupState.QueryBegin(rootTask);
// And schedule it for execution. This is done after beginning to ensure no thread tries to
// end the query before its root task has been recorded properly.
rootTask.Start(taskScheduler);
// We don't call QueryEnd here; when we return, the query is still executing, and the
// last enumerator to be disposed of will call QueryEnd for us.
}
//-----------------------------------------------------------------------------------
// Creates and begins execution of a new spooling task. This is a for-all style
// execution, meaning that the query will be run fully (for effect) before returning
// and that there are no channels into which data will be queued.
//
// Arguments:
// groupState - values for inter-task communication
// partitions - the producer enumerators
// taskScheduler - the task manager on which to execute
//
internal static void SpoolForAll<TInputOutput, TIgnoreKey>(
QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions, TaskScheduler taskScheduler)
{
Contract.Requires(groupState != null);
// Ensure all tasks in this query are parented under a common root.
Task rootTask = new Task(
() =>
{
int maxToRunInParallel = partitions.PartitionCount - 1;
// Create tasks that will enumerate the partitions in parallel "for effect"; in other words,
// no data will be placed into any kind of producer-consumer channel.
for (int i = 0; i < maxToRunInParallel; i++)
{
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i);
QueryTask asyncTask = new ForAllSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i]);
asyncTask.RunAsynchronously(taskScheduler);
}
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] synchronously", maxToRunInParallel);
// Run one task synchronously on the current thread.
QueryTask syncTask = new ForAllSpoolingTask<TInputOutput, TIgnoreKey>(maxToRunInParallel, groupState, partitions[maxToRunInParallel]);
syncTask.RunSynchronously(taskScheduler);
});
// Begin the query on the calling thread.
groupState.QueryBegin(rootTask);
// We don't want to return until the task is finished. Run it on the calling thread.
rootTask.RunSynchronously(taskScheduler);
// Wait for the query to complete, propagate exceptions, and so on.
// For pipelined queries, this step happens in the async enumerator.
groupState.QueryEnd(false);
}
}
/// <summary>
/// A spooling task handles marshaling data from a producer to a consumer. It's given
/// a single enumerator object that contains all of the production algorithms, a single
/// destination channel from which consumers draw results, and (optionally) a
/// synchronization primitive using which to notify asynchronous consumers.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
/// <typeparam name="TIgnoreKey"></typeparam>
internal class StopAndGoSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase
{
// The data source from which to pull data.
private QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source;
// The destination channel into which data is placed. This can be null if we are
// enumerating "for effect", e.g. forall loop.
private SynchronousChannel<TInputOutput> _destination;
//-----------------------------------------------------------------------------------
// Creates, but does not execute, a new spooling task.
//
// Arguments:
// taskIndex - the unique index of this task
// source - the producer enumerator
// destination - the destination channel into which to spool elements
//
// Assumptions:
// Source cannot be null, although the other arguments may be.
//
internal StopAndGoSpoolingTask(
int taskIndex, QueryTaskGroupState groupState,
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, SynchronousChannel<TInputOutput> destination)
: base(taskIndex, groupState)
{
Contract.Requires(source != null);
_source = source;
_destination = destination;
}
//-----------------------------------------------------------------------------------
// This method is responsible for enumerating results and enqueueing them to
// the output channel(s) as appropriate. Each base class implements its own.
//
protected override void SpoolingWork()
{
// We just enumerate over the entire source data stream, placing each element
// into the destination channel.
TInputOutput current = default(TInputOutput);
TIgnoreKey keyUnused = default(TIgnoreKey);
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source = _source;
SynchronousChannel<TInputOutput> destination = _destination;
CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken;
destination.Init();
while (source.MoveNext(ref current, ref keyUnused))
{
// If an abort has been requested, stop this worker immediately.
if (cancelToken.IsCancellationRequested)
{
break;
}
destination.Enqueue(current);
}
}
//-----------------------------------------------------------------------------------
// Ensure we signal that the channel is complete.
//
protected override void SpoolingFinally()
{
// Call the base implementation.
base.SpoolingFinally();
// Signal that we are done, in the case of asynchronous consumption.
if (_destination != null)
{
_destination.SetDone();
}
// Dispose of the source enumerator *after* signaling that the task is done.
// We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock.
_source.Dispose();
}
}
/// <summary>
/// A spooling task handles marshaling data from a producer to a consumer. It's given
/// a single enumerator object that contains all of the production algorithms, a single
/// destination channel from which consumers draw results, and (optionally) a
/// synchronization primitive using which to notify asynchronous consumers.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
/// <typeparam name="TIgnoreKey"></typeparam>
internal class PipelineSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase
{
// The data source from which to pull data.
private QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source;
// The destination channel into which data is placed. This can be null if we are
// enumerating "for effect", e.g. forall loop.
private AsynchronousChannel<TInputOutput> _destination;
//-----------------------------------------------------------------------------------
// Creates, but does not execute, a new spooling task.
//
// Arguments:
// taskIndex - the unique index of this task
// source - the producer enumerator
// destination - the destination channel into which to spool elements
//
// Assumptions:
// Source cannot be null, although the other arguments may be.
//
internal PipelineSpoolingTask(
int taskIndex, QueryTaskGroupState groupState,
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, AsynchronousChannel<TInputOutput> destination)
: base(taskIndex, groupState)
{
Contract.Assert(source != null);
_source = source;
_destination = destination;
}
//-----------------------------------------------------------------------------------
// This method is responsible for enumerating results and enqueueing them to
// the output channel(s) as appropriate. Each base class implements its own.
//
protected override void SpoolingWork()
{
// We just enumerate over the entire source data stream, placing each element
// into the destination channel.
TInputOutput current = default(TInputOutput);
TIgnoreKey keyUnused = default(TIgnoreKey);
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source = _source;
AsynchronousChannel<TInputOutput> destination = _destination;
CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken;
while (source.MoveNext(ref current, ref keyUnused))
{
// If an abort has been requested, stop this worker immediately.
if (cancelToken.IsCancellationRequested)
{
break;
}
destination.Enqueue(current);
}
// Flush remaining data to the query consumer in preparation for channel shutdown.
destination.FlushBuffers();
}
//-----------------------------------------------------------------------------------
// Ensure we signal that the channel is complete.
//
protected override void SpoolingFinally()
{
// Call the base implementation.
base.SpoolingFinally();
// Signal that we are done, in the case of asynchronous consumption.
if (_destination != null)
{
_destination.SetDone();
}
// Dispose of the source enumerator *after* signaling that the task is done.
// We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock.
_source.Dispose();
}
}
/// <summary>
/// A spooling task handles marshaling data from a producer to a consumer. It's given
/// a single enumerator object that contains all of the production algorithms, a single
/// destination channel from which consumers draw results, and (optionally) a
/// synchronization primitive using which to notify asynchronous consumers.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
/// <typeparam name="TIgnoreKey"></typeparam>
internal class ForAllSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase
{
// The data source from which to pull data.
private QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source;
//-----------------------------------------------------------------------------------
// Creates, but does not execute, a new spooling task.
//
// Arguments:
// taskIndex - the unique index of this task
// source - the producer enumerator
// destination - the destination channel into which to spool elements
//
// Assumptions:
// Source cannot be null, although the other arguments may be.
//
internal ForAllSpoolingTask(
int taskIndex, QueryTaskGroupState groupState,
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source)
: base(taskIndex, groupState)
{
Contract.Assert(source != null);
_source = source;
}
//-----------------------------------------------------------------------------------
// This method is responsible for enumerating results and enqueueing them to
// the output channel(s) as appropriate. Each base class implements its own.
//
protected override void SpoolingWork()
{
// We just enumerate over the entire source data stream for effect.
TInputOutput currentUnused = default(TInputOutput);
TIgnoreKey keyUnused = default(TIgnoreKey);
//Note: this only ever runs with a ForAll operator, and ForAllEnumerator performs cancellation checks
while (_source.MoveNext(ref currentUnused, ref keyUnused))
;
}
//-----------------------------------------------------------------------------------
// Ensure we signal that the channel is complete.
//
protected override void SpoolingFinally()
{
// Call the base implementation.
base.SpoolingFinally();
// Dispose of the source enumerator
_source.Dispose();
}
}
}
| |
//Enhanced Sky for Daggerfall Tools for Unity by Lypyl, contact at [email protected]
//http://www.reddit.com/r/dftfu
//http://www.dfworkshop.net/
//Author: LypyL
//Contact: [email protected]
//License: MIT License (http://www.opensource.org/licenses/mit-license.php)
//this file was added by Michael Rauter (Nystul)
/* moon textures by Doubloonz @ nexus mods, w/ permission to use for DFTFU.
*http://www.nexusmods.com/skyrim/mods/40785/
*
*/
// only use this define when not building the mod but using it as sub-project to debug (will trigger different prefab injection for debugging)
// IMPORTANT: if this line is used mod build will fail - so uncomment before building mod
//#define DEBUG
using UnityEngine;
using System.Collections;
using DaggerfallWorkshop.Game;
using DaggerfallWorkshop.Game.UserInterface;
using DaggerfallWorkshop.Game.Utility.ModSupport; //required for modding features
using DaggerfallWorkshop.Game.Utility.ModSupport.ModSettings; //required for mod settings
#if DEBUG
using UnityEditor; // only used for AssetDatabase when debugging from editor - no use in normal mod's execution
#endif
using EnhancedSky;
namespace EnhancedSky
{
public class _startupMod : MonoBehaviour
{
public static Mod mod;
private static GameObject gameobjectEnhancedSky = null;
private static SkyManager componentSkyManager = null;
private static PresetContainer componentPresetContainer = null;
private static CloudGenerator componentCloudGenerator = null;
// Settings
private static float sunSize = 2.0f;
private static bool enableSunFlare = true;
private static int cloudQuality = 400;
private static Shader shaderDepthMask = null;
private static Shader shaderUnlitAlphaWithFade = null;
//private static Object prefabEnhancedSkyController = null;
private static Object containerPrefab = null;
private static Material skyObjMat = null;
private static Material skyMat = null;
//private static Material cloudMat = null;
//private static Material masserMat = null;
//private static Material secundaMat = null;
private static Material starsMat = null;
private static Material starMaskMat = null;
private static Flare sunFlare = null;
//private static Preset presetPresetContainer = null;
[Invoke(StateManager.StateTypes.Start)]
public static void InitStart(InitParams initParams)
{
// check if debug gameobject is present, if so do not initalize mod
if (GameObject.Find("debug_EnhancedSky"))
{
return;
}
// Get this mod
mod = initParams.Mod;
// Load settings. Pass this mod as paramater
ModSettings settings = mod.GetSettings();
// settings
//enableSunFlare = settings.GetBool("GeneralSettings", "UseSunFlare");
//cloudQuality = settings.GetInt("GeneralSettings", "CloudQuality");
sunSize = settings.GetValue<float>("GeneralSettings", "SunSize");
enableSunFlare = settings.GetValue<bool>("GeneralSettings", "UseSunFlare");
cloudQuality = settings.GetValue<int>("GeneralSettings", "CloudQuality");
shaderDepthMask = mod.GetAsset<Shader>("Materials/Resources/DepthMask.shader") as Shader;
shaderUnlitAlphaWithFade = mod.GetAsset<Shader>("Materials/Resources/UnlitAlphaWithFade.shader") as Shader;
starsMat = mod.GetAsset<Material>("Materials/Resources/Stars") as Material;
skyMat = mod.GetAsset<Material>("Materials/Resources/Sky") as Material;
sunFlare = mod.GetAsset<Flare>("LightFlares/Sun.flare") as Flare;
//cloudMesh = mod.GetAsset<Mesh>("Model Imports/Hemisphere_01_smooth.fbx") as Mesh;
containerPrefab = mod.GetAsset<Object>("Prefabs/Resources/NewEnhancedSkyContainer.prefab") as Object;
initMod();
//after finishing, set the mod's IsReady flag to true.
ModManager.Instance.GetMod(initParams.ModTitle).IsReady = true;
}
/*
* used for debugging
* howto debug:
* -) add a dummy GameObject to DaggerfallUnityGame scene
* -) attach this script (_startupMod) as component
* -) deactivate mod in mod list (since dummy gameobject will start up mod)
* -) attach debugger and set breakpoint to one of the mod's cs files and debug
*/
void Awake()
{
shaderDepthMask = Shader.Find("Transparent/DepthMask");
shaderUnlitAlphaWithFade = Shader.Find("Unlit/UnlitAlphaWithFade");
#if DEBUG
if (GameObject.Find("debug_EnhancedSky"))
{
containerPrefab = AssetDatabase.LoadAssetAtPath("Assets/Game/Addons/EnhancedSky_standalone/Prefabs/Resources/NewEnhancedSkyContainer.prefab", typeof(Object));
starsMat = AssetDatabase.LoadAssetAtPath("Assets/Game/Addons/EnhancedSky_standalone/Materials/Resources/Stars.mat", typeof(Material)) as Material;
skyMat = AssetDatabase.LoadAssetAtPath("Assets/Game/Addons/EnhancedSky_standalone/Materials/Resources/Sky.mat", typeof(Material)) as Material;
sunFlare = AssetDatabase.LoadAssetAtPath("Assets/Game/Addons/EnhancedSky_standalone/LightFlares/Sun.flare", typeof(Flare)) as Flare;
}
#endif
initMod();
}
public static void initMod()
{
Debug.Log("init of EnhancedSky standalone");
gameobjectEnhancedSky = new GameObject("EnhancedSkyController");
componentPresetContainer = gameobjectEnhancedSky.AddComponent<PresetContainer>() as PresetContainer;
SetPresetContainerValues(componentPresetContainer);
PresetContainer.Instance = componentPresetContainer;
componentSkyManager = gameobjectEnhancedSky.AddComponent<SkyManager>() as SkyManager;
SkyManager.instance = componentSkyManager;
componentCloudGenerator = gameobjectEnhancedSky.AddComponent<CloudGenerator>() as CloudGenerator;
componentSkyManager.ModSelf = mod;
starMaskMat = new Material(shaderDepthMask);
skyObjMat = new Material(shaderUnlitAlphaWithFade);
componentSkyManager.StarMaskMat = starMaskMat;
componentSkyManager.SkyObjMat = skyObjMat;
componentSkyManager.StarsMat = starsMat;
componentSkyManager.SkyMat = skyMat;
if (containerPrefab)
{
GameObject container = Instantiate(containerPrefab) as GameObject;
container.transform.SetParent(GameManager.Instance.ExteriorParent.transform, true);
componentSkyManager.Container = container;
//container.AddComponent<MoonController>();
//container.AddComponent<AmbientFogLightController>();
//container.transform.Find("SkyCam").gameObject.AddComponent<SkyCam>();
//container.transform.Find("Stars").Find("StarParticles").gameObject.AddComponent<StarController>();
//container.transform.Find("Rotator").gameObject.AddComponent<RotationScript>();
//container.transform.Find("cloudPrefab").gameObject.AddComponent<Cloud>();
GameObject goParticles = container.transform.Find("Stars").Find("StarParticles").gameObject;
goParticles.GetComponent<ParticleSystemRenderer>().sharedMaterial = new Material(shaderUnlitAlphaWithFade);
GameObject goSun = container.transform.Find("Rotator").Find("Sun").gameObject;
goSun.GetComponent<LensFlare>().flare = sunFlare;
goSun.GetComponent<Light>().intensity = sunSize;
}
else
throw new System.NullReferenceException();
componentSkyManager.ToggleEnhancedSky(true);
componentSkyManager.UseSunFlare = enableSunFlare;
componentSkyManager.cloudQuality = cloudQuality;
componentSkyManager.SkyObjectSizeChange(0); // set normal size
}
private static void SetPresetContainerValues(PresetContainer presetContainer)
{
// set color base
Gradient gradient = new Gradient();
GradientAlphaKey[] gak = {
new GradientAlphaKey(55.0f/255.0f, 0.0f),
new GradientAlphaKey(75.0f/255.0f, 0.21f),
new GradientAlphaKey(255.0f/255.0f, 0.31f),
new GradientAlphaKey(255.0f/255.0f, 0.69f),
new GradientAlphaKey(75.0f/255.0f, 0.79f),
new GradientAlphaKey(75.0f/255.0f, 1.0f)
};
string[] colorsAsHex = { "#3C3C3C", "#727272", "#A8553E", "#DAD6D6", "#D6D6D6", "#C5BFBF", "#A8553E", "#3C3C3C" };
Color[] colors = new Color[colorsAsHex.Length];
for (int i = 0; i < colors.Length; i++)
{
UnityEngine.ColorUtility.TryParseHtmlString(colorsAsHex[i], out colors[i]);
}
GradientColorKey[] gck = {
new GradientColorKey(colors[0], 0.0f),
new GradientColorKey(colors[1], 0.159f),
new GradientColorKey(colors[2], 0.244f),
new GradientColorKey(colors[3], 0.318f),
new GradientColorKey(colors[4], 0.5f),
new GradientColorKey(colors[5], 0.694f),
new GradientColorKey(colors[6], 0.762f),
new GradientColorKey(colors[7], 0.835f)
};
gradient.alphaKeys = gak;
gradient.colorKeys = gck;
presetContainer.colorBase = gradient;
// set color over
gradient = new Gradient();
gak = new GradientAlphaKey[] {
new GradientAlphaKey(255.0f/255.0f, 0.0f),
new GradientAlphaKey(255.0f/255.0f, 1.0f)
};
colorsAsHex = new string[] { "#131313", "#656565", "#C5C1C1", "#C2C2C2", "#656565", "#131313" };
colors = new Color[colorsAsHex.Length];
for (int i = 0; i < colors.Length; i++)
{
UnityEngine.ColorUtility.TryParseHtmlString(colorsAsHex[i], out colors[i]);
}
gck = new GradientColorKey[] {
new GradientColorKey(colors[0], 0.0f),
new GradientColorKey(colors[1], 0.203f),
new GradientColorKey(colors[2], 0.303f),
new GradientColorKey(colors[3], 0.674f),
new GradientColorKey(colors[4], 0.752f),
new GradientColorKey(colors[5], 1.0f)
};
gradient.alphaKeys = gak;
gradient.colorKeys = gck;
presetContainer.colorOver = gradient;
// set fog base
gradient = new Gradient();
gak = new GradientAlphaKey[] {
new GradientAlphaKey(255.0f/255.0f, 0.0f),
new GradientAlphaKey(255.0f/255.0f, 1.0f)
};
colorsAsHex = new string[] { "#131313", "#353027", "#5E6E75", "#7C8382", "#6D6D6D", "#765338", "#171717", "#131313" };
colors = new Color[colorsAsHex.Length];
for (int i = 0; i < colors.Length; i++)
{
UnityEngine.ColorUtility.TryParseHtmlString(colorsAsHex[i], out colors[i]);
}
gck = new GradientColorKey[] {
new GradientColorKey(colors[0], 0.0f),
new GradientColorKey(colors[1], 0.25f),
new GradientColorKey(colors[2], 0.309f),
new GradientColorKey(colors[3], 0.5f),
new GradientColorKey(colors[4], 0.7f),
new GradientColorKey(colors[5], 0.744f),
new GradientColorKey(colors[6], 0.776f),
new GradientColorKey(colors[7], 1.0f)
};
gradient.alphaKeys = gak;
gradient.colorKeys = gck;
presetContainer.fogBase = gradient;
// set fog over
gradient = new Gradient();
gak = new GradientAlphaKey[] {
new GradientAlphaKey(255.0f/255.0f, 0.0f),
new GradientAlphaKey(255.0f/255.0f, 1.0f)
};
colorsAsHex = new string[] { "#090808", "#7C7777", "#8E9396", "#7D706C", "#151515", "#131313" };
colors = new Color[colorsAsHex.Length];
for (int i = 0; i < colors.Length; i++)
{
UnityEngine.ColorUtility.TryParseHtmlString(colorsAsHex[i], out colors[i]);
}
gck = new GradientColorKey[] {
new GradientColorKey(colors[0], 0.2f),
new GradientColorKey(colors[1], 0.309f),
new GradientColorKey(colors[2], 0.5f),
new GradientColorKey(colors[3], 0.7f),
new GradientColorKey(colors[4], 0.81f),
new GradientColorKey(colors[5], 1.0f)
};
gradient.alphaKeys = gak;
gradient.colorKeys = gck;
presetContainer.fogOver = gradient;
// set star gradient
gradient = new Gradient();
gak = new GradientAlphaKey[] {
new GradientAlphaKey(255.0f/255.0f, 0.0f),
new GradientAlphaKey(255.0f/255.0f, 0.19f),
new GradientAlphaKey(0.0f/255.0f, 0.245f),
new GradientAlphaKey(0.0f/255.0f, 0.75f),
new GradientAlphaKey(255.0f/255.0f, 0.8f),
new GradientAlphaKey(255.0f/255.0f, 1.0f)
};
colorsAsHex = new string[] { "#FFFFFF", "#FFFFFF" };
colors = new Color[colorsAsHex.Length];
for (int i = 0; i < colors.Length; i++)
{
UnityEngine.ColorUtility.TryParseHtmlString(colorsAsHex[i], out colors[i]);
}
gck = new GradientColorKey[] {
new GradientColorKey(colors[0], 0.0f),
new GradientColorKey(colors[1], 1.0f)
};
gradient.alphaKeys = gak;
gradient.colorKeys = gck;
presetContainer.starGradient = gradient;
// set cloud noise base
gradient = new Gradient();
gak = new GradientAlphaKey[] {
new GradientAlphaKey(0.0f/255.0f, 0.45f),
new GradientAlphaKey(217.0f/255.0f, 0.75f),
new GradientAlphaKey(255.0f/255.0f, 1.0f)
};
colorsAsHex = new string[] { "#000000", "#989898", "#FFFFFF" };
colors = new Color[colorsAsHex.Length];
for (int i = 0; i < colors.Length; i++)
{
UnityEngine.ColorUtility.TryParseHtmlString(colorsAsHex[i], out colors[i]);
}
gck = new GradientColorKey[] {
new GradientColorKey(colors[0], 0.0f),
new GradientColorKey(colors[1], 0.45f),
new GradientColorKey(colors[2], 1.0f)
};
gradient.alphaKeys = gak;
gradient.colorKeys = gck;
presetContainer.cloudNoiseBase = gradient;
// set cloud noise over
gradient = new Gradient();
gak = new GradientAlphaKey[] {
new GradientAlphaKey(207.0f/255.0f, 0.0f),
new GradientAlphaKey(255.0f/255.0f, 1.0f)
};
colorsAsHex = new string[] { "#7C7C7C", "#FFFFFF" };
colors = new Color[colorsAsHex.Length];
for (int i = 0; i < colors.Length; i++)
{
UnityEngine.ColorUtility.TryParseHtmlString(colorsAsHex[i], out colors[i]);
}
gck = new GradientColorKey[] {
new GradientColorKey(colors[0], 0.0f),
new GradientColorKey(colors[1], 1.0f)
};
gradient.alphaKeys = gak;
gradient.colorKeys = gck;
presetContainer.cloudNoiseOver = gradient;
// set sky tint
string colorAsHex = "#80808000";
Color color;
UnityEngine.ColorUtility.TryParseHtmlString(colorAsHex, out color);
presetContainer.skyTint = color;
// set masser color
colorAsHex = "#AF4B4BFF";
UnityEngine.ColorUtility.TryParseHtmlString(colorAsHex, out color);
presetContainer.MasserColor = color;
// set secunda color
colorAsHex = "#C3C3C3FF";
UnityEngine.ColorUtility.TryParseHtmlString(colorAsHex, out color);
presetContainer.SecundaColor = color;
// set atmosphere offset
presetContainer.atmsphrOffset = 1;
// set atmosphere base curve
presetContainer.atmosphereBase = new AnimationCurve();
presetContainer.atmosphereBase.preWrapMode = WrapMode.Clamp;
presetContainer.atmosphereBase.postWrapMode = WrapMode.Clamp;
presetContainer.atmosphereBase.keys = new Keyframe[] { new Keyframe(0.0f, 0.9f), new Keyframe(0.3f, 0.1f), new Keyframe(0.65f, 0.1f), new Keyframe(1.0f, 1.0f) };
// set atmosphere over curve
presetContainer.atmosphereOver = new AnimationCurve();
presetContainer.atmosphereOver.preWrapMode = WrapMode.Loop;
presetContainer.atmosphereOver.postWrapMode = WrapMode.Loop;
presetContainer.atmosphereOver.keys = new Keyframe[] { new Keyframe(0.0f, -0.33f), new Keyframe(1.0f, -0.33f) };
// set moon alpha base curve
presetContainer.moonAlphaBase = new AnimationCurve();
presetContainer.moonAlphaBase.preWrapMode = WrapMode.Clamp;
presetContainer.moonAlphaBase.postWrapMode = WrapMode.Clamp;
presetContainer.moonAlphaBase.keys = new Keyframe[] { new Keyframe(0.0f, 0.3f), new Keyframe(0.28f, 0.0f), new Keyframe(0.8f, 0.1f), new Keyframe(1.0f, 0.3f) };
presetContainer.moonAlphaBase.SmoothTangents(1, 1.0f);
presetContainer.moonAlphaBase.SmoothTangents(2, 1.0f);
// set moon alpha over curve
presetContainer.moonAlphaOver = new AnimationCurve();
presetContainer.moonAlphaOver.preWrapMode = WrapMode.Loop;
presetContainer.moonAlphaOver.postWrapMode = WrapMode.Loop;
presetContainer.moonAlphaOver.keys = new Keyframe[] { new Keyframe(0.0f, 0.045f), new Keyframe(0.29f, 0.0f), new Keyframe(1.0f, 0.045f) };
presetContainer.moonAlphaOver.SmoothTangents(1, 1.0f);
}
}
}
| |
/// Refly License
///
/// Copyright (c) 2004 Jonathan de Halleux, http://www.dotnetwiki.org
///
/// This software is provided 'as-is', without any express or implied warranty.
/// In no event will the authors be held liable for any damages arising from
/// the use of this software.
///
/// Permission is granted to anyone to use this software for any purpose,
/// including commercial applications, and to alter it and redistribute it
/// freely, subject to the following restrictions:
///
/// 1. The origin of this software must not be misrepresented;
/// you must not claim that you wrote the original software.
/// If you use this software in a product, an acknowledgment in the product
/// documentation would be appreciated but is not required.
///
/// 2. Altered source versions must be plainly marked as such,
/// and must not be misrepresented as being the original software.
///
///3. This notice may not be removed or altered from any source distribution.
using System;
using System.Reflection;
using System.CodeDom;
using System.Collections.Specialized;
namespace Refly.CodeDom
{
using Refly.CodeDom.Collections;
using Refly.CodeDom.Expressions;
using Refly.CodeDom.Statements;
/// <summary>
/// A class declaration
/// </summary>
public class ClassDeclaration : Declaration
{
private NamespaceDeclaration ns;
private ITypeDeclaration parent = null;
private ClassOutputType outputType = ClassOutputType.Class;
#if WHIDBEY
private TypeParameterDeclarationCollection typeParameters = new TypeParameterDeclarationCollection();
#endif
private TypeDeclarationCollection interfaces = new TypeDeclarationCollection();
private StringConstantDeclaration constants = new StringConstantDeclaration();
private StringFieldDeclarationDictionary fields = new StringFieldDeclarationDictionary();
private EventDeclarationCollection events = new EventDeclarationCollection();
private PropertyDeclarationCollection properties = new PropertyDeclarationCollection();
private MethodDeclarationCollection methods = new MethodDeclarationCollection();
private DelegateDeclarationCollection delegates = new DelegateDeclarationCollection();
private ConstructorDeclarationCollection constructors = new ConstructorDeclarationCollection();
private IndexerDeclarationCollection indexers = new IndexerDeclarationCollection();
private StringClassDeclarationDictionary nestedClasses = new StringClassDeclarationDictionary();
private StringSet imports = new StringSet();
private TypeAttributes attributes = TypeAttributes.Public;
internal ClassDeclaration(string name, NamespaceDeclaration ns)
:base(name,ns.Conformer)
{
this.ns = ns;
}
/// <summary>
/// Gets or sets the output type.
/// </summary>
/// <value>
/// A <see cref="ClassOutputType"/> instance.
/// </value>
public ClassOutputType OutputType
{
get
{
return this.outputType;
}
set
{
this.outputType = value;
}
}
public NamespaceDeclaration Namespace
{
get
{
return this.ns;
}
}
#if WHIDBEY
public TypeParameterDeclarationCollection TypeParameters
{
get { return this.typeParameters; }
}
#endif
public override string FullName
{
get
{
return String.Format("{0}.{1}",this.Namespace.FullName,this.Name);
}
}
public ITypeDeclaration Parent
{
get
{
return this.parent;
}
set
{
this.parent = value;
}
}
public new TypeAttributes Attributes
{
get
{
return this.attributes;
}
set
{
this.attributes=value;
}
}
public TypeDeclarationCollection Interfaces
{
get
{
return this.interfaces;
}
}
public StringConstantDeclaration Constants
{
get
{
return this.constants;
}
}
public StringFieldDeclarationDictionary Fields
{
get
{
return this.fields;
}
}
public EventDeclarationCollection Events
{
get
{
return this.events;
}
}
public PropertyDeclarationCollection Properties
{
get
{
return this.properties;
}
}
public MethodDeclarationCollection Methods
{
get
{
return this.methods;
}
}
public DelegateDeclarationCollection Delegates {
get {
return this.delegates;
}
}
public StringClassDeclarationDictionary NestedClasses
{
get
{
return this.nestedClasses;
}
}
public IndexerDeclarationCollection Indexers
{
get
{
return this.indexers;
}
}
public StringSet Imports
{
get
{
return this.imports;
}
}
public string InterfaceName
{
get
{
return String.Format("I{0}",Name);
}
}
public ConstantDeclaration AddConstant(Type type, string name,SnippetExpression expression)
{
if (type==null)
throw new ArgumentNullException("type");
if (name==null)
throw new ArgumentNullException("name");
if (expression==null)
throw new ArgumentNullException("expression");
if (this.constants.Contains(name))
throw new ArgumentException("field already existing in class");
ConstantDeclaration c = new ConstantDeclaration(this.Conformer.ToCamel(name),this,type,expression);
this.constants.Add(c);
return c;
}
public FieldDeclaration AddField(ITypeDeclaration type, string name)
{
if (type==null)
throw new ArgumentNullException("type");
if (name==null)
throw new ArgumentNullException("name");
if (this.fields.Contains(name))
throw new ArgumentException("field already existing in class");
FieldDeclaration f = new FieldDeclaration(this.Conformer.ToCamel(name),this,type);
this.fields.Add(f);
return f;
}
public FieldDeclaration AddField(Type type, string name)
{
return AddField(new TypeTypeDeclaration(type),name);
}
public FieldDeclaration AddField(String type, string name)
{
return AddField(new StringTypeDeclaration(type),name);
}
public EventDeclaration AddEvent(ITypeDeclaration type, string name)
{
if (type==null)
throw new ArgumentNullException("type");
if (name==null)
throw new ArgumentNullException("name");
EventDeclaration e = new EventDeclaration(this.Conformer.ToCapitalized(name),this,type);
this.events.Add(e);
return e;
}
public EventDeclaration AddEvent(Type type, string name)
{
return AddEvent(new TypeTypeDeclaration(type),name);
}
public EventDeclaration AddEvent(string type, string name)
{
return AddEvent(new StringTypeDeclaration(type),name);
}
public ClassDeclaration AddClass(string name)
{
ClassDeclaration c = new ClassDeclaration(this.Conformer.ToCapitalized(name),this.Namespace);
this.nestedClasses.Add(c);
return c;
}
public IndexerDeclaration AddIndexer(ITypeDeclaration type)
{
if (type==null)
throw new ArgumentNullException("type");
IndexerDeclaration index = new IndexerDeclaration(
this,
type
);
this.indexers.Add(index);
return index;
}
public IndexerDeclaration AddIndexer(Type type)
{
return AddIndexer(new TypeTypeDeclaration(type));
}
public IndexerDeclaration AddIndexer(string type)
{
return AddIndexer(new StringTypeDeclaration(type));
}
public PropertyDeclaration AddProperty(ITypeDeclaration type, string name)
{
if (type==null)
throw new ArgumentNullException("type");
if (name==null)
throw new ArgumentNullException("name");
PropertyDeclaration p = new PropertyDeclaration(this.Conformer.ToCapitalized(name),this,type);
this.properties.Add(p);
return p;
}
public PropertyDeclaration AddProperty(Type type, string name)
{
return AddProperty(new TypeTypeDeclaration(type),name);
}
public PropertyDeclaration AddProperty(String type, string name)
{
return AddProperty(new StringTypeDeclaration(type),name);
}
public PropertyDeclaration AddProperty(
FieldDeclaration f,
string name,
bool hasGet,
bool hasSet,
bool checkNonNull
)
{
PropertyDeclaration p = this.AddProperty(
f.Type,
name);
if (hasGet)
{
p.Get.Return(Expr.This.Field(f));
}
if (hasSet)
{
if (checkNonNull)
{
ConditionStatement ifnull = Stm.If(Expr.Value.Identity(Expr.Null));
p.Set.Add(ifnull);
ifnull.TrueStatements.Add(
Stm.Throw(typeof(ArgumentNullException))
);
p.SetExceptions.Add(new ThrowedExceptionDeclaration(
typeof(ArgumentNullException),
"value is a null reference"
));
}
p.Set.Add(
Stm.Assign(
Expr.This.Field(f),
Expr.Value
)
);
}
return p;
}
public PropertyDeclaration AddProperty(
FieldDeclaration f,
bool hasGet,
bool hasSet,
bool checkNonNull
) {
return this.AddProperty(f, f.Name, hasGet, hasSet, checkNonNull);
}
public ConstructorDeclaration AddConstructor()
{
ConstructorDeclaration ctr = new ConstructorDeclaration(this);
this.constructors.Add(ctr);
return ctr;
}
public MethodDeclaration AddMethod(string name)
{
if (name==null)
throw new ArgumentNullException("name");
MethodDeclaration m = new MethodDeclaration(name,this);
this.methods.Add(m);
return m;
}
public DelegateDeclaration AddDelegate(string name)
{
if (name==null)
throw new ArgumentNullException("name");
DelegateDeclaration d = new DelegateDeclaration(name,this);
this.delegates.Add(d);
return d;
}
public void ToCodeDom(CodeTypeDeclarationCollection types)
{
if(this.OutputType!=ClassOutputType.Interface)
{
CodeTypeDeclaration c = new CodeTypeDeclaration(this.Name);
c.TypeAttributes = this.Attributes;
types.Add(c);
ToClassCodeDom(c);
}
if (this.OutputType==ClassOutputType.Interface || this.OutputType==ClassOutputType.ClassAndInterface)
{
CodeTypeDeclaration c = new CodeTypeDeclaration(InterfaceName);
types.Add(c);
ToInterfaceCodeDom(c);
}
}
private void ToClassCodeDom(CodeTypeDeclaration c)
{
base.ToCodeDom(c);
// set as class
switch(this.OutputType)
{
case ClassOutputType.Class:
c.IsClass = true;
break;
case ClassOutputType.ClassAndInterface:
c.IsClass = true;
break;
case ClassOutputType.Struct:
c.IsStruct = true;
break;
}
// add parent
if (this.Parent!=null)
c.BaseTypes.Add(this.Parent.TypeReference);
#if WHIDBEY
// adding generic parameters
foreach (TypeParameterDeclaration typeParameter in this.TypeParameters)
c.TypeParameters.Add(typeParameter.ToCodeDom());
#endif
// add interfaces
if (this.OutputType==ClassOutputType.ClassAndInterface)
c.BaseTypes.Add(new CodeTypeReference(InterfaceName));
foreach(ITypeDeclaration itf in this.interfaces)
{
c.BaseTypes.Add(itf.TypeReference);
}
// add methods
foreach(DelegateDeclaration d in this.delegates)
{
c.Members.Add( d.ToCodeDom() );
}
// add constants
foreach(ConstantDeclaration ct in this.constants.Values)
{
c.Members.Add( ct.ToCodeDom() );
}
// add fields
foreach(FieldDeclaration f in this.fields.Values)
{
c.Members.Add( f.ToCodeDom());
}
// add constructors
foreach(ConstructorDeclaration ctr in this.constructors)
{
c.Members.Add( ctr.ToCodeDom() );
}
// add events
foreach(EventDeclaration e in this.events)
{
c.Members.Add( e.ToCodeDom());
}
// add inderxers
foreach(IndexerDeclaration index in this.indexers)
{
c.Members.Add( index.ToCodeDom());
}
// add properties
foreach(PropertyDeclaration p in this.properties)
{
c.Members.Add( p.ToCodeDom());
}
// add methods
foreach(MethodDeclaration m in this.methods)
{
c.Members.Add( m.ToCodeDom() );
}
// add nested classes
foreach(ClassDeclaration nc in this.NestedClasses.Values)
{
CodeTypeDeclaration ctype = new CodeTypeDeclaration(nc.Name);
nc.ToClassCodeDom(ctype);
c.Members.Add(ctype);
}
}
private void ToInterfaceCodeDom(CodeTypeDeclaration c)
{
base.ToCodeDom(c);
// set as class
c.IsInterface = true;
#if WHIDBEY
// adding generic parameters
foreach (TypeParameterDeclaration typeParameter in this.TypeParameters)
c.TypeParameters.Add(typeParameter.ToCodeDom());
#endif
// add interfaces
foreach(ITypeDeclaration itf in this.interfaces)
{
c.BaseTypes.Add(itf.TypeReference);
}
// add events
foreach(EventDeclaration e in this.events)
{
c.Members.Add( e.ToCodeDom());
}
// add inderxers
foreach(IndexerDeclaration index in this.indexers)
{
c.Members.Add( index.ToCodeDom());
}
// add properties
foreach(PropertyDeclaration p in this.properties)
{
c.Members.Add( p.ToCodeDom());
}
// add methods
foreach(MethodDeclaration m in this.methods)
{
c.Members.Add( m.ToCodeDom() );
}
}
}
}
| |
//
// Authors:
// Ben Motmans <[email protected]>
//
// Copyright (c) 2007 Ben Motmans
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using Gtk;
using System;
using System.Text;
using System.Collections.Generic;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using MonoDevelop.Components;
using MonoDevelop.Database.Sql;
using MonoDevelop.Database.Components;
namespace MonoDevelop.Database.Designer
{
[System.ComponentModel.Category("widget")]
[System.ComponentModel.ToolboxItem(true)]
public partial class ForeignKeyConstraintEditorWidget : Gtk.Bin
{
public event EventHandler ContentChanged;
private ISchemaProvider schemaProvider;
private TableSchema table;
private TableSchemaCollection tables;
private ColumnSchemaCollection columns;
private ConstraintSchemaCollection constraints;
TableSchema refTable = null;
private const int colNameIndex = 0;
private const int colReferenceTableIndex = 1;
private const int colIsColumnConstraintIndex = 2;
private const int colColumnsIndex = 3;
private const int colReferenceColumnsIndex = 4;
private const int colDeleteActionIndex = 5;
private const int colUpdateActionIndex = 6;
private const int colObjIndex = 7;
private ListStore store;
private ListStore storeActions;
private ListStore storeTables;
private SchemaActions action;
private ForeignKeyConstraintEditorSettings settings;
//TODO: difference between columns and reference columns + combo events
public ForeignKeyConstraintEditorWidget (ISchemaProvider schemaProvider, SchemaActions action, ForeignKeyConstraintEditorSettings settings)
{
if (schemaProvider == null)
throw new ArgumentNullException ("schemaProvider");
if (settings == null)
throw new ArgumentNullException ("settings");
this.schemaProvider = schemaProvider;
this.action = action;
this.settings = settings;
this.Build();
store = new ListStore (typeof (string), typeof (string), typeof (bool), typeof (string), typeof (string), typeof (string), typeof (string), typeof (object));
listFK.Model = store;
storeActions = new ListStore (typeof (string), typeof (int));
storeTables = new ListStore (typeof (string), typeof(TableSchema));
if (settings.SupportsCascade)
storeActions.AppendValues ("Cascade", (int)ForeignKeyAction.Cascade);
if (settings.SupportsRestrict)
storeActions.AppendValues ("Restrict", (int)ForeignKeyAction.Restrict);
if (settings.SupportsNoAction)
storeActions.AppendValues ("No Action", (int)ForeignKeyAction.NoAction);
if (settings.SupportsSetNull)
storeActions.AppendValues ("Set Null", (int)ForeignKeyAction.SetNull);
if (settings.SupportsSetDefault)
storeActions.AppendValues ("Set Default", (int)ForeignKeyAction.SetDefault);
TreeViewColumn colName = new TreeViewColumn ();
TreeViewColumn colRefTable = new TreeViewColumn ();
TreeViewColumn colIsColumnConstraint = new TreeViewColumn ();
TreeViewColumn colDeleteAction = new TreeViewColumn ();
TreeViewColumn colUpdateAction = new TreeViewColumn ();
colName.Title = AddinCatalog.GetString ("Name");
colRefTable.Title = AddinCatalog.GetString ("Reference Table");
colIsColumnConstraint.Title = AddinCatalog.GetString ("Column Constraint");
colDeleteAction.Title = AddinCatalog.GetString ("Delete Action");
colUpdateAction.Title = AddinCatalog.GetString ("Update Action");
colRefTable.MinWidth = 120;
CellRendererText nameRenderer = new CellRendererText ();
CellRendererCombo refTableRenderer = new CellRendererCombo ();
CellRendererToggle isColumnConstraintRenderer = new CellRendererToggle ();
CellRendererCombo deleteActionRenderer = new CellRendererCombo ();
CellRendererCombo updateActionRenderer = new CellRendererCombo ();
nameRenderer.Editable = true;
nameRenderer.Edited += new EditedHandler (NameEdited);
refTableRenderer.Model = storeTables;
refTableRenderer.TextColumn = 0;
refTableRenderer.Editable = true;
refTableRenderer.Edited += new EditedHandler (RefTableEdited);
deleteActionRenderer.Model = storeActions;
deleteActionRenderer.TextColumn = 0;
deleteActionRenderer.Editable = true;
deleteActionRenderer.Edited += new EditedHandler (DeleteActionEdited);
updateActionRenderer.Model = storeActions;
updateActionRenderer.TextColumn = 0;
updateActionRenderer.Editable = true;
updateActionRenderer.Edited += new EditedHandler (UpdateActionEdited);
colName.PackStart (nameRenderer, true);
colRefTable.PackStart (refTableRenderer, true);
colIsColumnConstraint.PackStart (isColumnConstraintRenderer, true);
colDeleteAction.PackStart (deleteActionRenderer, true);
colUpdateAction.PackStart (updateActionRenderer, true);
colName.AddAttribute (nameRenderer, "text", colNameIndex);
colRefTable.AddAttribute (refTableRenderer, "text", colReferenceTableIndex);
colIsColumnConstraint.AddAttribute (isColumnConstraintRenderer, "active", colIsColumnConstraintIndex);
colDeleteAction.AddAttribute (deleteActionRenderer, "text", colDeleteActionIndex);
colUpdateAction.AddAttribute (updateActionRenderer, "text", colUpdateActionIndex);
colIsColumnConstraint.Visible = false;
listFK.AppendColumn (colName);
listFK.AppendColumn (colRefTable);
listFK.AppendColumn (colIsColumnConstraint);
listFK.AppendColumn (colDeleteAction);
listFK.AppendColumn (colUpdateAction);
columnSelecter.ColumnToggled += new EventHandler (ColumnToggled);
referenceColumnSelecter.ColumnToggled += new EventHandler (ReferenceColumnToggled);
listFK.Selection.Changed += new EventHandler (SelectionChanged);
ShowAll ();
}
public void Initialize (TableSchemaCollection tables, TableSchema table, ColumnSchemaCollection columns, ConstraintSchemaCollection constraints)
{
if (columns == null)
throw new ArgumentNullException ("columns");
if (table == null)
throw new ArgumentNullException ("table");
if (constraints == null)
throw new ArgumentNullException ("constraints");
if (tables == null)
throw new ArgumentNullException ("tables");
this.table = table;
this.tables = tables;
this.columns = columns;
this.constraints = constraints;
columnSelecter.Initialize (columns);
foreach (TableSchema tbl in tables)
if (tbl.Name != table.Name)
storeTables.AppendValues (tbl.Name, tbl);
}
protected virtual void AddClicked (object sender, EventArgs e)
{
ForeignKeyConstraintSchema fk = schemaProvider.CreateForeignKeyConstraintSchema (string.Concat (table.Name,
"_",
"fk_new"));
int index = 1;
while (constraints.Contains (fk.Name))
fk.Name = string.Concat (table.Name, "_", "fk_new", (index++).ToString ());
constraints.Add (fk);
AddConstraint (fk);
EmitContentChanged ();
}
protected virtual void RemoveClicked (object sender, EventArgs e)
{
TreeIter iter;
if (listFK.Selection.GetSelected (out iter)) {
ForeignKeyConstraintSchema fk = store.GetValue (iter, colObjIndex) as ForeignKeyConstraintSchema;
if (MessageService.Confirm (
AddinCatalog.GetString ("Are you sure you want to remove foreign key constraint '{0}'?", fk.Name),
AlertButton.Remove
)) {
store.Remove (ref iter);
constraints.Remove (fk);
EmitContentChanged ();
}
}
}
private void SelectionChanged (object sender, EventArgs args)
{
columnSelecter.DeselectAll ();
referenceColumnSelecter.Clear ();
TreeIter iter;
if (listFK.Selection.GetSelected (out iter)) {
FillReferenceColumnSelector (iter, store.GetValue (iter, colReferenceTableIndex).ToString ());
buttonRemove.Sensitive = true;
columnSelecter.Sensitive = true;
SetSelectionFromIter (iter);
} else {
buttonRemove.Sensitive = false;
columnSelecter.Sensitive = false;
}
}
private void SetSelectionFromIter (TreeIter iter)
{
bool iscolc = (bool)store.GetValue (iter, colIsColumnConstraintIndex);
columnSelecter.SingleCheck = iscolc;
string colstr = store.GetValue (iter, colColumnsIndex) as string;
if (colstr != String.Empty) {
string[] cols = colstr.Split (',');
foreach (string col in cols)
columnSelecter.Select (col);
}
colstr = store.GetValue (iter, colReferenceColumnsIndex) as string;
if (colstr != string.Empty) {
string[] cols = colstr.Split (',');
foreach (string col in cols)
referenceColumnSelecter.Select (col);
}
}
private void RefTableEdited (object sender, EditedArgs args)
{
TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) {
FillReferenceColumnSelector (iter, args.NewText);
}
}
private void FillReferenceColumnSelector (TreeIter iter, string table)
{
if (tables.Contains (table)) {
refTable = tables.Search (table);
if (refTable != null) {
referenceColumnSelecter.Initialize (refTable.Columns);
referenceColumnSelecter.Sensitive = true;
store.SetValue (iter, colReferenceTableIndex, table);
SetSelectionFromIter (iter);
} else {
referenceColumnSelecter.Sensitive = false;
referenceColumnSelecter.Clear ();
}
EmitContentChanged ();
}
}
private void ColumnToggled (object sender, EventArgs args)
{
TreeIter iter;
if (listFK.Selection.GetSelected (out iter)) {
(store.GetValue (iter, colObjIndex) as ForeignKeyConstraintSchema).Columns.Clear ();
foreach (ColumnSchema col in columnSelecter.CheckedColumns)
(store.GetValue (iter, colObjIndex) as ForeignKeyConstraintSchema).Columns.Add (col);
store.SetValue (iter, colColumnsIndex, GetColumnsString (columnSelecter.CheckedColumns));
EmitContentChanged ();
}
}
private void ReferenceColumnToggled (object sender, EventArgs args)
{
TreeIter iter;
if (listFK.Selection.GetSelected (out iter)) {
if (refTable != null) {
(store.GetValue (iter, colObjIndex) as ForeignKeyConstraintSchema).ReferenceTable = refTable;
(store.GetValue (iter, colObjIndex) as ForeignKeyConstraintSchema).ReferenceColumns.Clear ();
foreach (ColumnSchema col in referenceColumnSelecter.CheckedColumns)
(store.GetValue (iter, colObjIndex) as ForeignKeyConstraintSchema).ReferenceColumns.Add (col);
store.SetValue (iter, colReferenceColumnsIndex, GetColumnsString (referenceColumnSelecter.CheckedColumns));
EmitContentChanged ();
}
}
}
private void NameEdited (object sender, EditedArgs args)
{
TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) {
if (!string.IsNullOrEmpty (args.NewText)) {
store.SetValue (iter, colNameIndex, args.NewText);
EmitContentChanged ();
} else {
string oldText = store.GetValue (iter, colNameIndex) as string;
(sender as CellRendererText).Text = oldText;
}
}
}
private void UpdateActionEdited (object sender, EditedArgs args)
{
TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) {
if (IsValidForeignKeyAction (args.NewText)) {
store.SetValue (iter, colUpdateActionIndex, args.NewText);
(store.GetValue (iter, colObjIndex) as ForeignKeyConstraintSchema).UpdateAction =
GetForeignKeyAction (iter, colUpdateActionIndex);
EmitContentChanged ();
} else {
string oldText = store.GetValue (iter, colUpdateActionIndex) as string;
(sender as CellRendererText).Text = oldText;
}
}
}
private void DeleteActionEdited (object sender, EditedArgs args)
{
TreeIter iter;
if (store.GetIterFromString (out iter, args.Path)) {
if (IsValidForeignKeyAction (args.NewText)) {
store.SetValue (iter, colDeleteActionIndex, args.NewText);
(store.GetValue (iter, colObjIndex) as ForeignKeyConstraintSchema).DeleteAction =
GetForeignKeyAction (iter, colDeleteActionIndex);
EmitContentChanged ();
} else {
string oldText = store.GetValue (iter, colDeleteActionIndex) as string;
(sender as CellRendererText).Text = oldText;
}
}
}
private bool IsValidForeignKeyAction (string name)
{
foreach (string item in Enum.GetNames (typeof (ForeignKeyAction))) {
if (item == name.Replace (" ", ""))
return true;
}
return false;
}
private void AddConstraint (ForeignKeyConstraintSchema fk)
{
store.AppendValues (fk.Name, String.Empty, false, String.Empty, String.Empty,
fk.DeleteAction.ToString (), fk.UpdateAction.ToString (), fk
);
}
protected virtual void EmitContentChanged ()
{
if (ContentChanged != null)
ContentChanged (this, EventArgs.Empty);
}
public virtual bool ValidateSchemaObjects (out string msg)
{
TreeIter iter;
if (store.GetIterFirst (out iter)) {
do {
string name = store.GetValue (iter, colNameIndex) as string;
string columns = store.GetValue (iter, colColumnsIndex) as string;
if (String.IsNullOrEmpty (columns)) {
msg = AddinCatalog.GetString ("Unique Key constraint '{0}' must be applied to one or more columns.", name);
return false;
}
} while (store.IterNext (ref iter));
}
msg = null;
return true;
}
public virtual void FillSchemaObjects ()
{
/*
* This code isn't needed anymore, beacause Foreign Key's constraint are added on demand when clicking
* Add Button.
*/
}
private string GetColumnsString (IEnumerable<ColumnSchema> collection)
{
bool first = true;
StringBuilder sb = new StringBuilder ();
foreach (ColumnSchema column in collection) {
if (first)
first = false;
else
sb.Append (',');
sb.Append (column.Name);
}
return sb.ToString ();
}
private ForeignKeyAction GetForeignKeyAction (TreeIter colIter, int colIndex)
{
string name = store.GetValue (colIter, colIndex) as string;
TreeIter iter;
if (storeActions.GetIterFirst (out iter)) {
do {
string actionName = storeActions.GetValue (iter, 0) as string;
if (actionName == name)
return (ForeignKeyAction)storeActions.GetValue (iter, 1);
} while (storeActions.IterNext (ref iter));
}
return ForeignKeyAction.None;
}
}
public class ForeignKeyConstraintEditorSettings
{
private bool supportsCascade = true;
private bool supportsRestrict = true;
private bool supportsNoAction = true;
private bool supportsSetNull = true;
private bool supportsSetDefault = true;
public bool SupportsCascade {
get { return supportsCascade; }
set { supportsCascade = value; }
}
public bool SupportsRestrict {
get { return supportsRestrict; }
set { supportsRestrict = value; }
}
public bool SupportsNoAction {
get { return supportsNoAction; }
set { supportsNoAction = value; }
}
public bool SupportsSetNull {
get { return supportsSetNull; }
set { supportsSetNull = value; }
}
public bool SupportsSetDefault {
get { return supportsSetDefault; }
set { supportsSetDefault = value; }
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: DocFolder
// ObjectType: DocFolder
// CSLAType: EditableChild
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using Csla.Rules;
using Csla.Rules.CommonRules;
using DocStore.Business.Security;
namespace DocStore.Business
{
/// <summary>
/// Folder where this document is archived (editable child object).<br/>
/// This is a generated <see cref="DocFolder"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="DocFolderColl"/> collection.
/// </remarks>
[Serializable]
public partial class DocFolder : BusinessBase<DocFolder>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="FolderID"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> FolderIDProperty = RegisterProperty<int>(p => p.FolderID, "Folder ID");
/// <summary>
/// Gets the Folder ID.
/// </summary>
/// <value>The Folder ID.</value>
public int FolderID
{
get { return GetProperty(FolderIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="FolderRef"/> property.
/// </summary>
public static readonly PropertyInfo<string> FolderRefProperty = RegisterProperty<string>(p => p.FolderRef, "Folder Ref");
/// <summary>
/// Gets the Folder Ref.
/// </summary>
/// <value>The Folder Ref.</value>
public string FolderRef
{
get { return GetProperty(FolderRefProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Year"/> property.
/// </summary>
public static readonly PropertyInfo<int> YearProperty = RegisterProperty<int>(p => p.Year, "Folder Year");
/// <summary>
/// Gets the Folder Year.
/// </summary>
/// <value>The Folder Year.</value>
public int Year
{
get { return GetProperty(YearProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Subject"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubjectProperty = RegisterProperty<string>(p => p.Subject, "Subject");
/// <summary>
/// Gets the Subject.
/// </summary>
/// <value>The Subject.</value>
public string Subject
{
get { return GetProperty(SubjectProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date");
/// <summary>
/// Gets the Create Date.
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return GetProperty(CreateDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CreateUserIDProperty = RegisterProperty<int>(p => p.CreateUserID, "Create User ID");
/// <summary>
/// Gets the Create User ID.
/// </summary>
/// <value>The Create User ID.</value>
public int CreateUserID
{
get { return GetProperty(CreateUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
/// <summary>
/// Gets the Change Date.
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return GetProperty(ChangeDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> ChangeUserIDProperty = RegisterProperty<int>(p => p.ChangeUserID, "Change User ID");
/// <summary>
/// Gets the Change User ID.
/// </summary>
/// <value>The Change User ID.</value>
public int ChangeUserID
{
get { return GetProperty(ChangeUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="RowVersion"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version");
/// <summary>
/// Gets the Row Version.
/// </summary>
/// <value>The Row Version.</value>
public byte[] RowVersion
{
get { return GetProperty(RowVersionProperty); }
}
/// <summary>
/// Gets the Create User Name.
/// </summary>
/// <value>The Create User Name.</value>
public string CreateUserName
{
get
{
var result = string.Empty;
if (Admin.UserNVL.GetUserNVL().ContainsKey(CreateUserID))
result = Admin.UserNVL.GetUserNVL().GetItemByKey(CreateUserID).Value;
return result;
}
}
/// <summary>
/// Gets the Change User Name.
/// </summary>
/// <value>The Change User Name.</value>
public string ChangeUserName
{
get
{
var result = string.Empty;
if (Admin.UserNVL.GetUserNVL().ContainsKey(ChangeUserID))
result = Admin.UserNVL.GetUserNVL().GetItemByKey(ChangeUserID).Value;
return result;
}
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="DocFolder"/> object, based on given parameters.
/// </summary>
/// <param name="folderID">The FolderID of the DocFolder to create.</param>
/// <returns>A reference to the created <see cref="DocFolder"/> object.</returns>
internal static DocFolder NewDocFolder(int folderID)
{
return DataPortal.Create<DocFolder>(folderID);
}
/// <summary>
/// Factory method. Loads a <see cref="DocFolder"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="DocFolder"/> object.</returns>
internal static DocFolder GetDocFolder(SafeDataReader dr)
{
DocFolder obj = new DocFolder();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="DocFolder"/> object, based on given parameters.
/// </summary>
/// <param name="folderID">The FolderID of the DocFolder to create.</param>
/// <param name="callback">The completion callback method.</param>
internal static void NewDocFolder(int folderID, EventHandler<DataPortalResult<DocFolder>> callback)
{
DataPortal.BeginCreate<DocFolder>(folderID, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DocFolder"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public DocFolder()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Object Authorization
/// <summary>
/// Adds the object authorization rules.
/// </summary>
protected static void AddObjectAuthorizationRules()
{
BusinessRules.AddRule(typeof (DocFolder), new IsInRole(AuthorizationActions.CreateObject, "Archivist"));
BusinessRules.AddRule(typeof (DocFolder), new IsInRole(AuthorizationActions.GetObject, "User"));
BusinessRules.AddRule(typeof (DocFolder), new IsInRole(AuthorizationActions.EditObject, "Author"));
BusinessRules.AddRule(typeof (DocFolder), new IsInRole(AuthorizationActions.DeleteObject, "Admin", "Manager"));
AddObjectAuthorizationRulesExtend();
}
/// <summary>
/// Allows the set up of custom object authorization rules.
/// </summary>
static partial void AddObjectAuthorizationRulesExtend();
/// <summary>
/// Checks if the current user can create a new DocFolder object.
/// </summary>
/// <returns><c>true</c> if the user can create a new object; otherwise, <c>false</c>.</returns>
public static bool CanAddObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(DocFolder));
}
/// <summary>
/// Checks if the current user can retrieve DocFolder's properties.
/// </summary>
/// <returns><c>true</c> if the user can read the object; otherwise, <c>false</c>.</returns>
public static bool CanGetObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(DocFolder));
}
/// <summary>
/// Checks if the current user can change DocFolder's properties.
/// </summary>
/// <returns><c>true</c> if the user can update the object; otherwise, <c>false</c>.</returns>
public static bool CanEditObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(DocFolder));
}
/// <summary>
/// Checks if the current user can delete a DocFolder object.
/// </summary>
/// <returns><c>true</c> if the user can delete the object; otherwise, <c>false</c>.</returns>
public static bool CanDeleteObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(DocFolder));
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="DocFolder"/> object properties, based on given criteria.
/// </summary>
/// <param name="folderID">The create criteria.</param>
protected void DataPortal_Create(int folderID)
{
LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now));
LoadProperty(CreateUserIDProperty, UserInformation.UserId);
LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty));
LoadProperty(ChangeUserIDProperty, ReadProperty(CreateUserIDProperty));
LoadProperty(FolderIDProperty, folderID);
var args = new DataPortalHookArgs(folderID);
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="DocFolder"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(FolderIDProperty, dr.GetInt32("FolderID"));
LoadProperty(FolderRefProperty, dr.GetString("FolderRef"));
LoadProperty(YearProperty, dr.GetInt32("Year"));
LoadProperty(SubjectProperty, dr.GetString("Subject"));
LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true));
LoadProperty(CreateUserIDProperty, dr.GetInt32("CreateUserID"));
LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true));
LoadProperty(ChangeUserIDProperty, dr.GetInt32("ChangeUserID"));
LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]);
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="DocFolder"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
private void Child_Insert(Doc parent)
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("AddDocFolderRelation", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocID", parent.DocID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@FolderID", ReadProperty(FolderIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@CreateUserID", ReadProperty(CreateUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="DocFolder"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
private void Child_Update(Doc parent)
{
if (!IsDirty)
return;
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("UpdateDocFolderRelation", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocID", parent.DocID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@FolderID", ReadProperty(FolderIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
}
}
private void SimpleAuditTrail()
{
LoadProperty(ChangeDateProperty, DateTime.Now);
LoadProperty(ChangeUserIDProperty, UserInformation.UserId);
OnPropertyChanged("ChangeUserName");
if (IsNew)
{
LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty));
LoadProperty(CreateUserIDProperty, ReadProperty(ChangeUserIDProperty));
OnPropertyChanged("CreateUserName");
}
}
/// <summary>
/// Self deletes the <see cref="DocFolder"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
private void Child_DeleteSelf(Doc parent)
{
// audit the object, just in case soft delete is used on this object
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("DeleteDocFolderRelation", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@DocID", parent.DocID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@FolderID", ReadProperty(FolderIDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Abp.AspNetCore.App.Controllers;
using Abp.AspNetCore.App.Models;
using Abp.Events.Bus;
using Abp.Events.Bus.Exceptions;
using Abp.UI;
using Abp.Web.Models;
using Microsoft.AspNetCore.Localization;
using Shouldly;
using Xunit;
namespace Abp.AspNetCore.Tests
{
public class SimpleTestControllerTests : AppTestBase
{
[Fact]
public void Should_Resolve_Controller()
{
ServiceProvider.GetService<SimpleTestController>().ShouldNotBeNull();
}
[Fact]
public async Task Should_Return_Content()
{
// Act
var response = await GetResponseAsStringAsync(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.SimpleContent)
)
);
// Assert
response.ShouldBe("Hello world...");
}
[Fact]
public async Task Should_Wrap_Json_By_Default()
{
// Act
var response = await GetResponseAsObjectAsync<AjaxResponse<SimpleViewModel>>(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.SimpleJson)
)
);
//Assert
response.Result.StrValue.ShouldBe("Forty Two");
response.Result.IntValue.ShouldBe(42);
}
[Theory]
[InlineData(true, "This is a user friendly exception message")]
[InlineData(false, "This is an exception message")]
public async Task Should_Wrap_Json_Exception_By_Default(bool userFriendly, string message)
{
//Arrange
var exceptionEventRaised = false;
Resolve<IEventBus>().Register<AbpHandledExceptionData>(data =>
{
exceptionEventRaised = true;
data.Exception.ShouldNotBeNull();
data.Exception.Message.ShouldBe(message);
});
// Act
var response = await GetResponseAsObjectAsync<AjaxResponse<SimpleViewModel>>(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.SimpleJsonException),
new
{
message,
userFriendly
}),
HttpStatusCode.InternalServerError
);
//Assert
response.Error.ShouldNotBeNull();
if (userFriendly)
{
response.Error.Message.ShouldBe(message);
}
else
{
response.Error.Message.ShouldNotBe(message);
}
exceptionEventRaised.ShouldBeTrue();
}
[Fact]
public async Task Should_Not_Wrap_Json_Exception_If_Requested()
{
//Act & Assert
await Assert.ThrowsAsync<UserFriendlyException>(async () =>
{
await GetResponseAsObjectAsync<AjaxResponse<SimpleViewModel>>(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.SimpleJsonExceptionDownWrap)
));
});
}
[Fact]
public async Task Should_Not_Wrap_Json_If_DontWrap_Declared()
{
// Act
var response = await GetResponseAsObjectAsync<SimpleViewModel>(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.SimpleJsonDontWrap)
));
//Assert
response.StrValue.ShouldBe("Forty Two");
response.IntValue.ShouldBe(42);
}
[Fact]
public async Task Should_Wrap_Void_Methods()
{
// Act
var response = await GetResponseAsObjectAsync<AjaxResponse>(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetVoidTest)
));
response.Success.ShouldBeTrue();
response.Result.ShouldBeNull();
}
[Fact]
public async Task Should_Not_Wrap_Void_Methods_If_Requested()
{
// Act
var response = await GetResponseAsStringAsync(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetVoidTestDontWrap)
));
response.ShouldBeNullOrEmpty();
}
[Fact]
public async Task Should_Not_Wrap_ActionResult()
{
// Act
var response = await GetResponseAsStringAsync(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetActionResultTest)
));
//Assert
response.ShouldBe("GetActionResultTest-Result");
}
[Fact]
public async Task Should_Not_Wrap_Async_ActionResult()
{
// Act
var response = await GetResponseAsStringAsync(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetActionResultTestAsync)
));
//Assert
response.ShouldBe("GetActionResultTestAsync-Result");
}
[Fact]
public async Task Should_Wrap_Async_Void_On_Exception()
{
// Act
var response = await GetResponseAsObjectAsync<AjaxResponse>(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetVoidExceptionTestAsync)
), HttpStatusCode.InternalServerError);
response.Error.ShouldNotBeNull();
response.Error.Message.ShouldBe("GetVoidExceptionTestAsync-Exception");
response.Result.ShouldBeNull();
}
[Fact]
public async Task Should_Not_Wrap_Async_ActionResult_On_Exception()
{
// Act
(await Assert.ThrowsAsync<UserFriendlyException>(async () =>
{
await GetResponseAsStringAsync(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetActionResultExceptionTestAsync)
), HttpStatusCode.InternalServerError);
})).Message.ShouldBe("GetActionResultExceptionTestAsync-Exception");
}
[Fact]
public async Task AbpLocalizationHeaderRequestCultureProvider_Test()
{
//Arrange
Client.DefaultRequestHeaders.Add(CookieRequestCultureProvider.DefaultCookieName, "c=it|uic=it");
var culture = await GetResponseAsStringAsync(
GetUrl<SimpleTestController>(
nameof(SimpleTestController.GetCurrentCultureNameTest)
));
culture.ShouldBe("it");
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security;
using System.Web.UI;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace NUnit.Framework.Api
{
/// <summary>
/// FrameworkController provides a facade for use in loading, browsing
/// and running tests without requiring a reference to the NUnit
/// framework. All calls are encapsulated in constructors for
/// this class and its nested classes, which only require the
/// types of the Common Type System as arguments.
///
/// The controller supports four actions: Load, Explore, Count and Run.
/// They are intended to be called by a driver, which should allow for
/// proper sequencing of calls. Load must be called before any of the
/// other actions. The driver may support other actions, such as
/// reload on run, by combining these calls.
/// </summary>
public class FrameworkController : LongLivedMarshalByRefObject
{
private const string LOG_FILE_FORMAT = "InternalTrace.{0}.{1}.log";
// Preloaded test assembly, if passed in constructor
private readonly Assembly _testAssembly;
#region Constructors
/// <summary>
/// Construct a FrameworkController using the default builder and runner.
/// </summary>
/// <param name="assemblyNameOrPath">The AssemblyName or path to the test assembly</param>
/// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
/// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
public FrameworkController(string assemblyNameOrPath, string idPrefix, IDictionary settings)
{
Initialize(assemblyNameOrPath, settings);
this.Builder = new DefaultTestAssemblyBuilder();
this.Runner = new NUnitTestAssemblyRunner(this.Builder);
Test.IdPrefix = idPrefix;
}
/// <summary>
/// Construct a FrameworkController using the default builder and runner.
/// </summary>
/// <param name="assembly">The test assembly</param>
/// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
/// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
public FrameworkController(Assembly assembly, string idPrefix, IDictionary settings)
: this(assembly.FullName, idPrefix, settings)
{
_testAssembly = assembly;
}
/// <summary>
/// Construct a FrameworkController, specifying the types to be used
/// for the runner and builder. This constructor is provided for
/// purposes of development.
/// </summary>
/// <param name="assemblyNameOrPath">The full AssemblyName or the path to the test assembly</param>
/// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
/// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
/// <param name="runnerType">The Type of the test runner</param>
/// <param name="builderType">The Type of the test builder</param>
public FrameworkController(string assemblyNameOrPath, string idPrefix, IDictionary settings, string runnerType, string builderType)
{
Initialize(assemblyNameOrPath, settings);
Builder = (ITestAssemblyBuilder)Reflect.Construct(Type.GetType(builderType));
Runner = (ITestAssemblyRunner)Reflect.Construct(Type.GetType(runnerType), new object[] { Builder });
Test.IdPrefix = idPrefix ?? "";
}
/// <summary>
/// Construct a FrameworkController, specifying the types to be used
/// for the runner and builder. This constructor is provided for
/// purposes of development.
/// </summary>
/// <param name="assembly">The test assembly</param>
/// <param name="idPrefix">A prefix used for all test ids created under this controller.</param>
/// <param name="settings">A Dictionary of settings to use in loading and running the tests</param>
/// <param name="runnerType">The Type of the test runner</param>
/// <param name="builderType">The Type of the test builder</param>
public FrameworkController(Assembly assembly, string idPrefix, IDictionary settings, string runnerType, string builderType)
: this(assembly.FullName, idPrefix, settings, runnerType, builderType)
{
_testAssembly = assembly;
}
// This method invokes members on the 'System.Diagnostics.Process' class and must satisfy the link demand of
// the full-trust 'PermissionSetAttribute' on this class. Callers of this method have no influence on how the
// Process class is used, so we can safely satisfy the link demand with a 'SecuritySafeCriticalAttribute' rather
// than a 'SecurityCriticalAttribute' and allow use by security transparent callers.
[SecuritySafeCritical]
private void Initialize(string assemblyNameOrPath, IDictionary settings)
{
AssemblyNameOrPath = assemblyNameOrPath;
var newSettings = settings as IDictionary<string, object>;
Settings = newSettings ?? settings.Cast<DictionaryEntry>().ToDictionary(de => (string)de.Key, de => de.Value);
if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceLevel))
{
var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)Settings[FrameworkPackageSettings.InternalTraceLevel], true);
if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceWriter))
InternalTrace.Initialize((TextWriter)Settings[FrameworkPackageSettings.InternalTraceWriter], traceLevel);
else
{
var workDirectory = Settings.ContainsKey(FrameworkPackageSettings.WorkDirectory)
? (string)Settings[FrameworkPackageSettings.WorkDirectory]
: Directory.GetCurrentDirectory();
var id = Process.GetCurrentProcess().Id;
var logName = string.Format(LOG_FILE_FORMAT, id, Path.GetFileName(assemblyNameOrPath));
InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel);
}
}
}
#endregion
#region Properties
/// <summary>
/// Gets the ITestAssemblyBuilder used by this controller instance.
/// </summary>
/// <value>The builder.</value>
public ITestAssemblyBuilder Builder { get; }
/// <summary>
/// Gets the ITestAssemblyRunner used by this controller instance.
/// </summary>
/// <value>The runner.</value>
public ITestAssemblyRunner Runner { get; }
/// <summary>
/// Gets the AssemblyName or the path for which this FrameworkController was created
/// </summary>
public string AssemblyNameOrPath { get; private set; }
/// <summary>
/// Gets the Assembly for which this
/// </summary>
public Assembly Assembly { get; private set; }
/// <summary>
/// Gets a dictionary of settings for the FrameworkController
/// </summary>
internal IDictionary<string, object> Settings { get; private set; }
#endregion
#region Public Action methods Used by nunit.driver for running tests
/// <summary>
/// Loads the tests in the assembly
/// </summary>
/// <returns></returns>
public string LoadTests()
{
if (_testAssembly != null)
Runner.Load(_testAssembly, Settings);
else
Runner.Load(AssemblyNameOrPath, Settings);
return Runner.LoadedTest.ToXml(false).OuterXml;
}
/// <summary>
/// Returns info about the tests in an assembly
/// </summary>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <returns>The XML result of exploring the tests</returns>
public string ExploreTests(string filter)
{
TNode result = Runner.ExploreTests(TestFilter.FromXml(filter)).ToXml(true);
return InsertChildElements(result).OuterXml;
}
/// <summary>
/// Runs the tests in an assembly
/// </summary>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <returns>The XML result of the test run</returns>
public string RunTests(string filter)
{
TNode result = Runner.Run(new TestProgressReporter(null), TestFilter.FromXml(filter)).ToXml(true);
return InsertChildElements(result).OuterXml;
}
class ActionCallback : ICallbackEventHandler
{
Action<string> _callback;
public ActionCallback(Action<string> callback)
{
_callback = callback;
}
public string GetCallbackResult()
{
throw new NotImplementedException();
}
public void RaiseCallbackEvent(string report)
{
if (_callback != null)
_callback.Invoke(report);
}
}
/// <summary>
/// Runs the tests in an assembly synchronously reporting back the test results through the callback
/// or through the return value
/// </summary>
/// <param name="callback">The callback that receives the test results</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <returns>The XML result of the test run</returns>
public string RunTests(Action<string> callback, string filter)
{
var handler = new ActionCallback(callback);
TNode result = Runner.Run(new TestProgressReporter(handler), TestFilter.FromXml(filter)).ToXml(true);
return InsertChildElements(result).OuterXml;
}
/// <summary>
/// Runs the tests in an assembly asynchronously reporting back the test results through the callback
/// </summary>
/// <param name="callback">The callback that receives the test results</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
private void RunAsync(Action<string> callback, string filter)
{
var handler = new ActionCallback(callback);
Runner.RunAsync(new TestProgressReporter(handler), TestFilter.FromXml(filter));
}
/// <summary>
/// Stops the test run
/// </summary>
/// <param name="force">True to force the stop, false for a cooperative stop</param>
public void StopRun(bool force)
{
Runner.StopRun(force);
}
/// <summary>
/// Counts the number of test cases in the loaded TestSuite
/// </summary>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <returns>The number of tests</returns>
public int CountTests(string filter)
{
return Runner.CountTestCases(TestFilter.FromXml(filter));
}
#endregion
#region Private Action Methods Used by Nested Classes
private void LoadTests(ICallbackEventHandler handler)
{
handler.RaiseCallbackEvent(LoadTests());
}
private void ExploreTests(ICallbackEventHandler handler, string filter)
{
handler.RaiseCallbackEvent(ExploreTests(filter));
}
private void RunTests(ICallbackEventHandler handler, string filter)
{
TNode result = Runner.Run(new TestProgressReporter(handler), TestFilter.FromXml(filter)).ToXml(true);
// Insert elements as first child in reverse order
if (Settings != null) // Some platforms don't have settings
InsertSettingsElement(result, Settings);
InsertEnvironmentElement(result);
handler.RaiseCallbackEvent(result.OuterXml);
}
private void RunAsync(ICallbackEventHandler handler, string filter)
{
Runner.RunAsync(new TestProgressReporter(handler), TestFilter.FromXml(filter));
}
private void StopRun(ICallbackEventHandler handler, bool force)
{
StopRun(force);
}
private void CountTests(ICallbackEventHandler handler, string filter)
{
handler.RaiseCallbackEvent(CountTests(filter).ToString());
}
/// <summary>
/// Inserts the environment and settings elements
/// </summary>
/// <param name="targetNode">Target node</param>
/// <returns>The updated target node</returns>
private TNode InsertChildElements(TNode targetNode)
{
// Insert elements as first child in reverse order
if (Settings != null) // Some platforms don't have settings
InsertSettingsElement(targetNode, Settings);
InsertEnvironmentElement(targetNode);
return targetNode;
}
/// <summary>
/// Inserts environment element
/// </summary>
/// <param name="targetNode">Target node</param>
/// <returns>The new node</returns>
public static TNode InsertEnvironmentElement(TNode targetNode)
{
TNode env = new TNode("environment");
targetNode.ChildNodes.Insert(0, env);
env.AddAttribute("framework-version", typeof(FrameworkController).GetTypeInfo().Assembly.GetName().Version.ToString());
env.AddAttribute("clr-version", Environment.Version.ToString());
#if NETSTANDARD2_0
env.AddAttribute("os-version", System.Runtime.InteropServices.RuntimeInformation.OSDescription);
#else
env.AddAttribute("os-version", OSPlatform.CurrentPlatform.ToString());
#endif
env.AddAttribute("platform", Environment.OSVersion.Platform.ToString());
env.AddAttribute("cwd", Directory.GetCurrentDirectory());
env.AddAttribute("machine-name", Environment.MachineName);
env.AddAttribute("user", Environment.UserName);
env.AddAttribute("user-domain", Environment.UserDomainName);
env.AddAttribute("culture", CultureInfo.CurrentCulture.ToString());
env.AddAttribute("uiculture", CultureInfo.CurrentUICulture.ToString());
env.AddAttribute("os-architecture", GetProcessorArchitecture());
return env;
}
private static string GetProcessorArchitecture()
{
return IntPtr.Size == 8 ? "x64" : "x86";
}
/// <summary>
/// Inserts settings element
/// </summary>
/// <param name="targetNode">Target node</param>
/// <param name="settings">Settings dictionary</param>
/// <returns>The new node</returns>
public static TNode InsertSettingsElement(TNode targetNode, IDictionary<string, object> settings)
{
TNode settingsNode = new TNode("settings");
targetNode.ChildNodes.Insert(0, settingsNode);
foreach (string key in settings.Keys)
AddSetting(settingsNode, key, settings[key]);
// Add default values for display
if (!settings.ContainsKey(FrameworkPackageSettings.NumberOfTestWorkers))
AddSetting(settingsNode, FrameworkPackageSettings.NumberOfTestWorkers, NUnitTestAssemblyRunner.DefaultLevelOfParallelism);
return settingsNode;
}
private static void AddSetting(TNode settingsNode, string name, object value)
{
TNode setting = new TNode("setting");
setting.AddAttribute("name", name);
if (value != null)
{
var dict = value as IDictionary;
if (dict != null)
{
AddDictionaryEntries(setting, dict);
AddBackwardsCompatibleDictionaryEntries(setting, dict);
}
else
{
setting.AddAttribute("value", value.ToString());
}
}
else
{
setting.AddAttribute("value", null);
}
settingsNode.ChildNodes.Add(setting);
}
private static void AddBackwardsCompatibleDictionaryEntries(TNode settingsNode, IDictionary entries)
{
var pairs = new List<string>(entries.Count);
foreach (var key in entries.Keys)
{
pairs.Add($"[{key}, {entries[key]}]");
}
settingsNode.AddAttribute("value", string.Join(", ", pairs.ToArray()));
}
private static void AddDictionaryEntries(TNode settingNode, IDictionary entries)
{
foreach(var key in entries.Keys)
{
var value = entries[key];
var entryNode = new TNode("item");
entryNode.AddAttribute("key", key.ToString());
entryNode.AddAttribute("value", value?.ToString() ?? "");
settingNode.ChildNodes.Add(entryNode);
}
}
#endregion
#region Nested Action Classes
#region TestContollerAction
/// <summary>
/// FrameworkControllerAction is the base class for all actions
/// performed against a FrameworkController.
/// </summary>
public abstract class FrameworkControllerAction : LongLivedMarshalByRefObject
{
}
#endregion
#region LoadTestsAction
/// <summary>
/// LoadTestsAction loads a test into the FrameworkController
/// </summary>
public class LoadTestsAction : FrameworkControllerAction
{
/// <summary>
/// LoadTestsAction loads the tests in an assembly.
/// </summary>
/// <param name="controller">The controller.</param>
/// <param name="handler">The callback handler.</param>
public LoadTestsAction(FrameworkController controller, object handler)
{
controller.LoadTests((ICallbackEventHandler)handler);
}
}
#endregion
#region ExploreTestsAction
/// <summary>
/// ExploreTestsAction returns info about the tests in an assembly
/// </summary>
public class ExploreTestsAction : FrameworkControllerAction
{
/// <summary>
/// Initializes a new instance of the <see cref="ExploreTestsAction"/> class.
/// </summary>
/// <param name="controller">The controller for which this action is being performed.</param>
/// <param name="filter">Filter used to control which tests are included (NYI)</param>
/// <param name="handler">The callback handler.</param>
public ExploreTestsAction(FrameworkController controller, string filter, object handler)
{
controller.ExploreTests((ICallbackEventHandler)handler, filter);
}
}
#endregion
#region CountTestsAction
/// <summary>
/// CountTestsAction counts the number of test cases in the loaded TestSuite
/// held by the FrameworkController.
/// </summary>
public class CountTestsAction : FrameworkControllerAction
{
/// <summary>
/// Construct a CountsTestAction and perform the count of test cases.
/// </summary>
/// <param name="controller">A FrameworkController holding the TestSuite whose cases are to be counted</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <param name="handler">A callback handler used to report results</param>
public CountTestsAction(FrameworkController controller, string filter, object handler)
{
controller.CountTests((ICallbackEventHandler)handler, filter);
}
}
#endregion
#region RunTestsAction
/// <summary>
/// RunTestsAction runs the loaded TestSuite held by the FrameworkController.
/// </summary>
public class RunTestsAction : FrameworkControllerAction
{
/// <summary>
/// Construct a RunTestsAction and run all tests in the loaded TestSuite.
/// </summary>
/// <param name="controller">A FrameworkController holding the TestSuite to run</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <param name="handler">A callback handler used to report results</param>
public RunTestsAction(FrameworkController controller, string filter, object handler)
{
controller.RunTests((ICallbackEventHandler)handler, filter);
}
}
#endregion
#region RunAsyncAction
/// <summary>
/// RunAsyncAction initiates an asynchronous test run, returning immediately
/// </summary>
public class RunAsyncAction : FrameworkControllerAction
{
/// <summary>
/// Construct a RunAsyncAction and run all tests in the loaded TestSuite.
/// </summary>
/// <param name="controller">A FrameworkController holding the TestSuite to run</param>
/// <param name="filter">A string containing the XML representation of the filter to use</param>
/// <param name="handler">A callback handler used to report results</param>
public RunAsyncAction(FrameworkController controller, string filter, object handler)
{
controller.RunAsync((ICallbackEventHandler)handler, filter);
}
}
#endregion
#region StopRunAction
/// <summary>
/// StopRunAction stops an ongoing run.
/// </summary>
public class StopRunAction : FrameworkControllerAction
{
/// <summary>
/// Construct a StopRunAction and stop any ongoing run. If no
/// run is in process, no error is raised.
/// </summary>
/// <param name="controller">The FrameworkController for which a run is to be stopped.</param>
/// <param name="force">True the stop should be forced, false for a cooperative stop.</param>
/// <param name="handler">>A callback handler used to report results</param>
/// <remarks>A forced stop will cause threads and processes to be killed as needed.</remarks>
public StopRunAction(FrameworkController controller, bool force, object handler)
{
controller.StopRun((ICallbackEventHandler)handler, force);
}
}
#endregion
#endregion
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dlp.V2.Tests
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Api.Gax.ResourceNames;
using apis = Google.Cloud.Dlp.V2;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Moq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
/// <summary>Generated unit tests</summary>
public class GeneratedDlpServiceClientTest
{
[Fact]
public void InspectContent()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
InspectContentRequest request = new InspectContentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
InspectContentResponse expectedResponse = new InspectContentResponse();
mockGrpcClient.Setup(x => x.InspectContent(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
InspectContentResponse response = client.InspectContent(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task InspectContentAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
InspectContentRequest request = new InspectContentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
InspectContentResponse expectedResponse = new InspectContentResponse();
mockGrpcClient.Setup(x => x.InspectContentAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<InspectContentResponse>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
InspectContentResponse response = await client.InspectContentAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void RedactImage()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
RedactImageRequest request = new RedactImageRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
RedactImageResponse expectedResponse = new RedactImageResponse
{
RedactedImage = ByteString.CopyFromUtf8("28"),
ExtractedText = "extractedText998260012",
};
mockGrpcClient.Setup(x => x.RedactImage(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
RedactImageResponse response = client.RedactImage(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task RedactImageAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
RedactImageRequest request = new RedactImageRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
RedactImageResponse expectedResponse = new RedactImageResponse
{
RedactedImage = ByteString.CopyFromUtf8("28"),
ExtractedText = "extractedText998260012",
};
mockGrpcClient.Setup(x => x.RedactImageAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<RedactImageResponse>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
RedactImageResponse response = await client.RedactImageAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeidentifyContent()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
DeidentifyContentRequest request = new DeidentifyContentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
DeidentifyContentResponse expectedResponse = new DeidentifyContentResponse();
mockGrpcClient.Setup(x => x.DeidentifyContent(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
DeidentifyContentResponse response = client.DeidentifyContent(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeidentifyContentAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
DeidentifyContentRequest request = new DeidentifyContentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
DeidentifyContentResponse expectedResponse = new DeidentifyContentResponse();
mockGrpcClient.Setup(x => x.DeidentifyContentAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<DeidentifyContentResponse>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
DeidentifyContentResponse response = await client.DeidentifyContentAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void ReidentifyContent()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
ReidentifyContentRequest request = new ReidentifyContentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
ReidentifyContentResponse expectedResponse = new ReidentifyContentResponse();
mockGrpcClient.Setup(x => x.ReidentifyContent(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
ReidentifyContentResponse response = client.ReidentifyContent(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task ReidentifyContentAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
ReidentifyContentRequest request = new ReidentifyContentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
ReidentifyContentResponse expectedResponse = new ReidentifyContentResponse();
mockGrpcClient.Setup(x => x.ReidentifyContentAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<ReidentifyContentResponse>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
ReidentifyContentResponse response = await client.ReidentifyContentAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void ListInfoTypes()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
ListInfoTypesRequest request = new ListInfoTypesRequest();
ListInfoTypesResponse expectedResponse = new ListInfoTypesResponse();
mockGrpcClient.Setup(x => x.ListInfoTypes(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
ListInfoTypesResponse response = client.ListInfoTypes(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task ListInfoTypesAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
ListInfoTypesRequest request = new ListInfoTypesRequest();
ListInfoTypesResponse expectedResponse = new ListInfoTypesResponse();
mockGrpcClient.Setup(x => x.ListInfoTypesAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<ListInfoTypesResponse>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
ListInfoTypesResponse response = await client.ListInfoTypesAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateInspectTemplate()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
CreateInspectTemplateRequest request = new CreateInspectTemplateRequest
{
ParentAsOrganizationName = new OrganizationName("[ORGANIZATION]"),
};
InspectTemplate expectedResponse = new InspectTemplate
{
Name = "name3373707",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.CreateInspectTemplate(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
InspectTemplate response = client.CreateInspectTemplate(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateInspectTemplateAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
CreateInspectTemplateRequest request = new CreateInspectTemplateRequest
{
ParentAsOrganizationName = new OrganizationName("[ORGANIZATION]"),
};
InspectTemplate expectedResponse = new InspectTemplate
{
Name = "name3373707",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.CreateInspectTemplateAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<InspectTemplate>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
InspectTemplate response = await client.CreateInspectTemplateAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void UpdateInspectTemplate()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
UpdateInspectTemplateRequest request = new UpdateInspectTemplateRequest
{
InspectTemplateNameOneof = InspectTemplateNameOneof.From(new OrganizationInspectTemplateName("[ORGANIZATION]", "[INSPECT_TEMPLATE]")),
};
InspectTemplate expectedResponse = new InspectTemplate
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.UpdateInspectTemplate(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
InspectTemplate response = client.UpdateInspectTemplate(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task UpdateInspectTemplateAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
UpdateInspectTemplateRequest request = new UpdateInspectTemplateRequest
{
InspectTemplateNameOneof = InspectTemplateNameOneof.From(new OrganizationInspectTemplateName("[ORGANIZATION]", "[INSPECT_TEMPLATE]")),
};
InspectTemplate expectedResponse = new InspectTemplate
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.UpdateInspectTemplateAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<InspectTemplate>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
InspectTemplate response = await client.UpdateInspectTemplateAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetInspectTemplate()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
GetInspectTemplateRequest request = new GetInspectTemplateRequest();
InspectTemplate expectedResponse = new InspectTemplate
{
Name = "name3373707",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.GetInspectTemplate(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
InspectTemplate response = client.GetInspectTemplate(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetInspectTemplateAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
GetInspectTemplateRequest request = new GetInspectTemplateRequest();
InspectTemplate expectedResponse = new InspectTemplate
{
Name = "name3373707",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.GetInspectTemplateAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<InspectTemplate>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
InspectTemplate response = await client.GetInspectTemplateAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteInspectTemplate()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
DeleteInspectTemplateRequest request = new DeleteInspectTemplateRequest
{
InspectTemplateNameOneof = InspectTemplateNameOneof.From(new OrganizationInspectTemplateName("[ORGANIZATION]", "[INSPECT_TEMPLATE]")),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteInspectTemplate(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteInspectTemplate(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteInspectTemplateAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
DeleteInspectTemplateRequest request = new DeleteInspectTemplateRequest
{
InspectTemplateNameOneof = InspectTemplateNameOneof.From(new OrganizationInspectTemplateName("[ORGANIZATION]", "[INSPECT_TEMPLATE]")),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteInspectTemplateAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteInspectTemplateAsync(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateDeidentifyTemplate()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
CreateDeidentifyTemplateRequest request = new CreateDeidentifyTemplateRequest
{
ParentAsOrganizationName = new OrganizationName("[ORGANIZATION]"),
};
DeidentifyTemplate expectedResponse = new DeidentifyTemplate
{
Name = "name3373707",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.CreateDeidentifyTemplate(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
DeidentifyTemplate response = client.CreateDeidentifyTemplate(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateDeidentifyTemplateAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
CreateDeidentifyTemplateRequest request = new CreateDeidentifyTemplateRequest
{
ParentAsOrganizationName = new OrganizationName("[ORGANIZATION]"),
};
DeidentifyTemplate expectedResponse = new DeidentifyTemplate
{
Name = "name3373707",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.CreateDeidentifyTemplateAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<DeidentifyTemplate>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
DeidentifyTemplate response = await client.CreateDeidentifyTemplateAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void UpdateDeidentifyTemplate()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
UpdateDeidentifyTemplateRequest request = new UpdateDeidentifyTemplateRequest
{
DeidentifyTemplateNameOneof = DeidentifyTemplateNameOneof.From(new OrganizationDeidentifyTemplateName("[ORGANIZATION]", "[DEIDENTIFY_TEMPLATE]")),
};
DeidentifyTemplate expectedResponse = new DeidentifyTemplate
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.UpdateDeidentifyTemplate(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
DeidentifyTemplate response = client.UpdateDeidentifyTemplate(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task UpdateDeidentifyTemplateAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
UpdateDeidentifyTemplateRequest request = new UpdateDeidentifyTemplateRequest
{
DeidentifyTemplateNameOneof = DeidentifyTemplateNameOneof.From(new OrganizationDeidentifyTemplateName("[ORGANIZATION]", "[DEIDENTIFY_TEMPLATE]")),
};
DeidentifyTemplate expectedResponse = new DeidentifyTemplate
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.UpdateDeidentifyTemplateAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<DeidentifyTemplate>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
DeidentifyTemplate response = await client.UpdateDeidentifyTemplateAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetDeidentifyTemplate()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
GetDeidentifyTemplateRequest request = new GetDeidentifyTemplateRequest
{
DeidentifyTemplateNameOneof = DeidentifyTemplateNameOneof.From(new OrganizationDeidentifyTemplateName("[ORGANIZATION]", "[DEIDENTIFY_TEMPLATE]")),
};
DeidentifyTemplate expectedResponse = new DeidentifyTemplate
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.GetDeidentifyTemplate(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
DeidentifyTemplate response = client.GetDeidentifyTemplate(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetDeidentifyTemplateAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
GetDeidentifyTemplateRequest request = new GetDeidentifyTemplateRequest
{
DeidentifyTemplateNameOneof = DeidentifyTemplateNameOneof.From(new OrganizationDeidentifyTemplateName("[ORGANIZATION]", "[DEIDENTIFY_TEMPLATE]")),
};
DeidentifyTemplate expectedResponse = new DeidentifyTemplate
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.GetDeidentifyTemplateAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<DeidentifyTemplate>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
DeidentifyTemplate response = await client.GetDeidentifyTemplateAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteDeidentifyTemplate()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
DeleteDeidentifyTemplateRequest request = new DeleteDeidentifyTemplateRequest
{
DeidentifyTemplateNameOneof = DeidentifyTemplateNameOneof.From(new OrganizationDeidentifyTemplateName("[ORGANIZATION]", "[DEIDENTIFY_TEMPLATE]")),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteDeidentifyTemplate(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteDeidentifyTemplate(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteDeidentifyTemplateAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
DeleteDeidentifyTemplateRequest request = new DeleteDeidentifyTemplateRequest
{
DeidentifyTemplateNameOneof = DeidentifyTemplateNameOneof.From(new OrganizationDeidentifyTemplateName("[ORGANIZATION]", "[DEIDENTIFY_TEMPLATE]")),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteDeidentifyTemplateAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteDeidentifyTemplateAsync(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateDlpJob()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
CreateDlpJobRequest request = new CreateDlpJobRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
DlpJob expectedResponse = new DlpJob
{
Name = "name3373707",
JobTriggerName = "jobTriggerName1819490804",
};
mockGrpcClient.Setup(x => x.CreateDlpJob(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
DlpJob response = client.CreateDlpJob(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateDlpJobAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
CreateDlpJobRequest request = new CreateDlpJobRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
DlpJob expectedResponse = new DlpJob
{
Name = "name3373707",
JobTriggerName = "jobTriggerName1819490804",
};
mockGrpcClient.Setup(x => x.CreateDlpJobAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<DlpJob>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
DlpJob response = await client.CreateDlpJobAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetDlpJob()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
GetDlpJobRequest request = new GetDlpJobRequest
{
DlpJobName = new DlpJobName("[PROJECT]", "[DLP_JOB]"),
};
DlpJob expectedResponse = new DlpJob
{
Name = "name2-1052831874",
JobTriggerName = "jobTriggerName1819490804",
};
mockGrpcClient.Setup(x => x.GetDlpJob(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
DlpJob response = client.GetDlpJob(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetDlpJobAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
GetDlpJobRequest request = new GetDlpJobRequest
{
DlpJobName = new DlpJobName("[PROJECT]", "[DLP_JOB]"),
};
DlpJob expectedResponse = new DlpJob
{
Name = "name2-1052831874",
JobTriggerName = "jobTriggerName1819490804",
};
mockGrpcClient.Setup(x => x.GetDlpJobAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<DlpJob>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
DlpJob response = await client.GetDlpJobAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteDlpJob()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
DeleteDlpJobRequest request = new DeleteDlpJobRequest
{
DlpJobName = new DlpJobName("[PROJECT]", "[DLP_JOB]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteDlpJob(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteDlpJob(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteDlpJobAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
DeleteDlpJobRequest request = new DeleteDlpJobRequest
{
DlpJobName = new DlpJobName("[PROJECT]", "[DLP_JOB]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteDlpJobAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteDlpJobAsync(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CancelDlpJob()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
CancelDlpJobRequest request = new CancelDlpJobRequest
{
DlpJobName = new DlpJobName("[PROJECT]", "[DLP_JOB]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.CancelDlpJob(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
client.CancelDlpJob(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CancelDlpJobAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
CancelDlpJobRequest request = new CancelDlpJobRequest
{
DlpJobName = new DlpJobName("[PROJECT]", "[DLP_JOB]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.CancelDlpJobAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
await client.CancelDlpJobAsync(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetJobTrigger()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
GetJobTriggerRequest request = new GetJobTriggerRequest
{
ProjectJobTriggerName = new ProjectJobTriggerName("[PROJECT]", "[JOB_TRIGGER]"),
};
JobTrigger expectedResponse = new JobTrigger
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.GetJobTrigger(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
JobTrigger response = client.GetJobTrigger(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetJobTriggerAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
GetJobTriggerRequest request = new GetJobTriggerRequest
{
ProjectJobTriggerName = new ProjectJobTriggerName("[PROJECT]", "[JOB_TRIGGER]"),
};
JobTrigger expectedResponse = new JobTrigger
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.GetJobTriggerAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<JobTrigger>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
JobTrigger response = await client.GetJobTriggerAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteJobTrigger()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
DeleteJobTriggerRequest request = new DeleteJobTriggerRequest
{
ProjectJobTriggerName = new ProjectJobTriggerName("[PROJECT]", "[JOB_TRIGGER]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteJobTrigger(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteJobTrigger(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteJobTriggerAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
DeleteJobTriggerRequest request = new DeleteJobTriggerRequest
{
ProjectJobTriggerName = new ProjectJobTriggerName("[PROJECT]", "[JOB_TRIGGER]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteJobTriggerAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteJobTriggerAsync(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public void UpdateJobTrigger()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
UpdateJobTriggerRequest request = new UpdateJobTriggerRequest
{
ProjectJobTriggerName = new ProjectJobTriggerName("[PROJECT]", "[JOB_TRIGGER]"),
};
JobTrigger expectedResponse = new JobTrigger
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.UpdateJobTrigger(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
JobTrigger response = client.UpdateJobTrigger(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task UpdateJobTriggerAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
UpdateJobTriggerRequest request = new UpdateJobTriggerRequest
{
ProjectJobTriggerName = new ProjectJobTriggerName("[PROJECT]", "[JOB_TRIGGER]"),
};
JobTrigger expectedResponse = new JobTrigger
{
Name = "name2-1052831874",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.UpdateJobTriggerAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<JobTrigger>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
JobTrigger response = await client.UpdateJobTriggerAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateJobTrigger()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
CreateJobTriggerRequest request = new CreateJobTriggerRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
JobTrigger expectedResponse = new JobTrigger
{
Name = "name3373707",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.CreateJobTrigger(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
JobTrigger response = client.CreateJobTrigger(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateJobTriggerAsync()
{
Mock<DlpService.DlpServiceClient> mockGrpcClient = new Mock<DlpService.DlpServiceClient>(MockBehavior.Strict);
CreateJobTriggerRequest request = new CreateJobTriggerRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
JobTrigger expectedResponse = new JobTrigger
{
Name = "name3373707",
DisplayName = "displayName1615086568",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.CreateJobTriggerAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<JobTrigger>(Task.FromResult(expectedResponse), null, null, null, null));
DlpServiceClient client = new DlpServiceClientImpl(mockGrpcClient.Object, null);
JobTrigger response = await client.CreateJobTriggerAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/********************************************************************++
Description:
Windows Vista and later support non-traditional UI fallback ie., a
user on an Arabic machine can choose either French or English(US) as
UI fallback language.
CLR does not support this (non-traditional) fallback mechanism. So
the static methods in this class calculate appropriate UI Culture
natively. ConsoleHot uses this API to set correct Thread UICulture.
Dependent on:
GetThreadPreferredUILanguages
SetThreadPreferredUILanguages
These methods are available on Windows Vista and later.
--********************************************************************/
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using Dbg = System.Management.Automation.Diagnostics;
using WORD = System.UInt16;
namespace Microsoft.PowerShell
{
/// <summary>
/// Custom culture.
/// </summary>
internal class VistaCultureInfo : CultureInfo
{
private string[] _fallbacks;
// Cache the immediate parent and immediate fallback
private VistaCultureInfo _parentCI = null;
private object _syncObject = new object();
/// <summary>
/// Constructs a CultureInfo that keeps track of fallbacks.
/// </summary>
/// <param name="name">Name of the culture to construct.</param>
/// <param name="fallbacks">
/// ordered,null-delimited list of fallbacks
/// </param>
public VistaCultureInfo(string name,
string[] fallbacks)
: base(name)
{
_fallbacks = fallbacks;
}
/// <summary>
/// Returns Parent culture for the current CultureInfo.
/// If Parent.Name is null or empty, then chooses the immediate fallback
/// If it is not empty, otherwise just returns Parent.
/// </summary>
public override CultureInfo Parent
{
get
{
// First traverse the parent hierarchy as established by CLR.
// This is required because there is difference in the parent hierarchy
// between CLR and Windows for Chinese. Ex: Native windows has
// zh-CN->zh-Hans->neutral whereas CLR has zh-CN->zh-CHS->zh-Hans->neutral
if ((base.Parent != null) && (!string.IsNullOrEmpty(base.Parent.Name)))
{
return ImmediateParent;
}
// Check whether we have any fallback specified
// MUI_MERGE_SYSTEM_FALLBACK | MUI_MERGE_USER_FALLBACK
// returns fallback cultures (specified by the user)
// and also adds neutral culture where appropriate.
// Ex: ja-jp ja en-us en
while ((_fallbacks != null) && (_fallbacks.Length > 0))
{
string fallback = _fallbacks[0];
string[] fallbacksForParent = null;
if (_fallbacks.Length > 1)
{
fallbacksForParent = new string[_fallbacks.Length - 1];
Array.Copy(_fallbacks, 1, fallbacksForParent, 0, _fallbacks.Length - 1);
}
try
{
return new VistaCultureInfo(fallback, fallbacksForParent);
}
// if there is any exception constructing the culture..catch..and go to
// the next culture in the list.
catch (ArgumentException)
{
_fallbacks = fallbacksForParent;
}
}
// no fallbacks..just return base parent
return base.Parent;
}
}
/// <summary>
/// This is called to create the parent culture (as defined by CLR)
/// of the current culture.
/// </summary>
private VistaCultureInfo ImmediateParent
{
get
{
if (_parentCI == null)
{
lock (_syncObject)
{
if (_parentCI == null)
{
string parentCulture = base.Parent.Name;
// remove the parentCulture from the m_fallbacks list.
// ie., remove duplicates from the parent hierarchy.
string[] fallbacksForTheParent = null;
if (_fallbacks != null)
{
fallbacksForTheParent = new string[_fallbacks.Length];
int currentIndex = 0;
foreach (string culture in _fallbacks)
{
if (!parentCulture.Equals(culture, StringComparison.OrdinalIgnoreCase))
{
fallbacksForTheParent[currentIndex] = culture;
currentIndex++;
}
}
// There is atleast 1 duplicate in m_fallbacks which was not added to
// fallbacksForTheParent array. Resize the array to take care of this.
if (_fallbacks.Length != currentIndex)
{
Array.Resize<string>(ref fallbacksForTheParent, currentIndex);
}
}
_parentCI = new VistaCultureInfo(parentCulture, fallbacksForTheParent);
}
}
}
return _parentCI;
}
}
/// <summary>
/// Clones the custom CultureInfo retaining the fallbacks.
/// </summary>
/// <returns>Cloned custom CultureInfo.</returns>
public override object Clone()
{
return new VistaCultureInfo(base.Name, _fallbacks);
}
}
/// <summary>
/// Static wrappers to get User chosen UICulture (for Vista and later)
/// </summary>
internal static class NativeCultureResolver
{
private static CultureInfo s_uiCulture = null;
private static CultureInfo s_culture = null;
private static object s_syncObject = new object();
/// <summary>
/// Gets the UICulture to be used by console host.
/// </summary>
internal static CultureInfo UICulture
{
get
{
if (s_uiCulture == null)
{
lock (s_syncObject)
{
if (s_uiCulture == null)
{
s_uiCulture = GetUICulture();
}
}
}
return (CultureInfo)s_uiCulture.Clone();
}
}
internal static CultureInfo Culture
{
get
{
if (s_culture == null)
{
lock (s_syncObject)
{
if (s_culture == null)
{
s_culture = GetCulture();
}
}
}
return s_culture;
}
}
internal static CultureInfo GetUICulture()
{
return GetUICulture(true);
}
internal static CultureInfo GetCulture()
{
return GetCulture(true);
}
internal static CultureInfo GetUICulture(bool filterOutNonConsoleCultures)
{
if (!IsVistaAndLater())
{
s_uiCulture = EmulateDownLevel();
return s_uiCulture;
}
// We are running on Vista
string langBuffer = GetUserPreferredUILangs(filterOutNonConsoleCultures);
if (!string.IsNullOrEmpty(langBuffer))
{
try
{
string[] fallbacks = langBuffer.Split(new char[] { '\0' },
StringSplitOptions.RemoveEmptyEntries);
string fallback = fallbacks[0];
string[] fallbacksForParent = null;
if (fallbacks.Length > 1)
{
fallbacksForParent = new string[fallbacks.Length - 1];
Array.Copy(fallbacks, 1, fallbacksForParent, 0, fallbacks.Length - 1);
}
s_uiCulture = new VistaCultureInfo(fallback, fallbacksForParent);
return s_uiCulture;
}
catch (ArgumentException)
{
}
}
s_uiCulture = EmulateDownLevel();
return s_uiCulture;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("GoldMan", "#pw17903:UseOfLCID", Justification = "In XP and below GetUserDefaultLocaleName is not available")]
internal static CultureInfo GetCulture(bool filterOutNonConsoleCultures)
{
CultureInfo returnValue;
try
{
if (!IsVistaAndLater())
{
int lcid = GetUserDefaultLCID();
returnValue = new CultureInfo(lcid);
}
else
{
// Vista and above
StringBuilder name = new StringBuilder(16);
if (0 == GetUserDefaultLocaleName(name, 16))
{
// ther is an error retrieving the culture,
// just use the current thread's culture
returnValue = CultureInfo.CurrentCulture;
}
else
{
returnValue = new CultureInfo(name.ToString().Trim());
}
}
if (filterOutNonConsoleCultures)
{
// filter out languages that console cannot display..
// Sometimes GetConsoleFallbackUICulture returns neutral cultures
// like "en" on "ar-SA". However neutral culture cannot be
// assigned as CurrentCulture. CreateSpecificCulture fixes
// this problem.
returnValue = CultureInfo.CreateSpecificCulture(
returnValue.GetConsoleFallbackUICulture().Name);
}
}
catch (ArgumentException)
{
// if there is any exception retrieving the
// culture, just use the current thread's culture.
returnValue = CultureInfo.CurrentCulture;
}
return returnValue;
}
[DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)]
internal static extern WORD GetUserDefaultUILanguage();
/// <summary>
/// Constructs CultureInfo object without considering any Vista and later
/// custom culture fallback logic.
/// </summary>
/// <returns>A CultureInfo object.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("GoldMan", "#pw17903:UseOfLCID", Justification = "This is only called In XP and below where GetUserDefaultLocaleName is not available, or as a fallback when GetThreadPreferredUILanguages fails")]
private static CultureInfo EmulateDownLevel()
{
// GetConsoleFallbackUICulture is not required.
// This is retained in order not to break existing code.
ushort langId = NativeCultureResolver.GetUserDefaultUILanguage();
CultureInfo ci = new CultureInfo((int)langId);
return ci.GetConsoleFallbackUICulture();
}
/// <summary>
/// Checks if the current operating system is Vista or later.
/// </summary>
/// <returns>
/// true, if vista and above
/// false, otherwise.
/// </returns>
private static bool IsVistaAndLater()
{
// The version number is obtained from MSDN
// 4 - Windows NT 4.0, Windows Me, Windows 98, or Windows 95.
// 5 - Windows Server 2003 R2, Windows Server 2003, Windows XP, or Windows 2000.
// 6 - Windows Vista or Windows Server "Longhorn".
if (Environment.OSVersion.Version.Major >= 6)
{
return true;
}
return false;
}
/// <summary>
/// This method is called on vista and above.
/// Using GetThreadPreferredUILanguages this method gets
/// the UI languages a user has chosen.
/// </summary>
/// <returns>
/// List of ThreadPreferredUILanguages.
/// </returns>
/// <remarks>
/// This method will work only on Vista and later.
/// </remarks>
private static string GetUserPreferredUILangs(bool filterOutNonConsoleCultures)
{
long numberLangs = 0;
int bufferSize = 0;
string returnval = string.Empty;
if (filterOutNonConsoleCultures)
{
// Filter out languages that do not support console.
// The third parameter should be null otherwise this API will not
// set Console CodePage filter.
// The MSDN documentation does not call this out explicitly. Opened
// Bug 950 (Windows Developer Content) to track this.
if (!SetThreadPreferredUILanguages(s_MUI_CONSOLE_FILTER, null, IntPtr.Zero))
{
return returnval;
}
}
// calculate buffer size required
// MUI_MERGE_SYSTEM_FALLBACK | MUI_MERGE_USER_FALLBACK
// returns fallback cultures (specified by the user)
// and also adds neutral culture where appropriate.
// Ex: ja-jp ja en-us en
if (!GetThreadPreferredUILanguages(
s_MUI_LANGUAGE_NAME | s_MUI_MERGE_SYSTEM_FALLBACK | s_MUI_MERGE_USER_FALLBACK,
out numberLangs,
null,
out bufferSize))
{
return returnval;
}
// calculate space required to store output.
// StringBuilder will not work for this case as CLR
// does not copy the entire string if there are delimiter ('\0')
// in the middle of a string.
byte[] langBufferPtr = new byte[bufferSize * 2];
// Now get the actual value
if (!GetThreadPreferredUILanguages(
s_MUI_LANGUAGE_NAME | s_MUI_MERGE_SYSTEM_FALLBACK | s_MUI_MERGE_USER_FALLBACK,
out numberLangs,
langBufferPtr, // Pointer to a buffer in which this function retrieves an ordered, null-delimited list.
out bufferSize))
{
return returnval;
}
try
{
string langBuffer = Encoding.Unicode.GetString(langBufferPtr);
returnval = langBuffer.Trim().ToLowerInvariant();
return returnval;
}
catch (ArgumentNullException)
{
}
catch (System.Text.DecoderFallbackException)
{
}
return returnval;
}
#region Dll Import data
/// <summary>
/// Returns the locale identifier for the user default locale.
/// </summary>
/// <returns></returns>
/// <remarks>
/// This function can return data from custom locales. Locales are not
/// guaranteed to be the same from computer to computer or between runs
/// of an application. If your application must persist or transmit data,
/// see Using Persistent Locale Data.
/// Applications that are intended to run only on Windows Vista and later
/// should use GetUserDefaultLocaleName in preference to this function.
/// GetUserDefaultLocaleName provides good support for supplemental locales.
/// However, GetUserDefaultLocaleName is not supported for versions of Windows
/// prior to Windows Vista.
/// </remarks>
[DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)]
private static extern int GetUserDefaultLCID();
/// <summary>
/// Retrieves the user default locale name.
/// </summary>
/// <param name="lpLocaleName"></param>
/// <param name="cchLocaleName"></param>
/// <returns>
/// Returns the size of the buffer containing the locale name, including
/// the terminating null character, if successful. The function returns 0
/// if it does not succeed. To get extended error information, the application
/// can call GetLastError. Possible returns from GetLastError
/// include ERR_INSUFFICIENT_BUFFER.
/// </returns>
/// <remarks>
/// </remarks>
[DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)]
private static extern int GetUserDefaultLocaleName(
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder lpLocaleName,
int cchLocaleName);
[DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)]
private static extern bool SetThreadPreferredUILanguages(int dwFlags,
StringBuilder pwszLanguagesBuffer,
IntPtr pulNumLanguages);
[DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)]
private static extern bool GetThreadPreferredUILanguages(int dwFlags,
out long pulNumLanguages,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)]
byte[] pwszLanguagesBuffer,
out int pcchLanguagesBuffer);
[DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)]
internal static extern Int16 SetThreadUILanguage(Int16 langId);
// private static int MUI_LANGUAGE_ID = 0x4;
private static int s_MUI_LANGUAGE_NAME = 0x8;
private static int s_MUI_CONSOLE_FILTER = 0x100;
private static int s_MUI_MERGE_USER_FALLBACK = 0x20;
private static int s_MUI_MERGE_SYSTEM_FALLBACK = 0x10;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Xunit;
namespace System.IO.Tests
{
public class BinaryWriterTests
{
protected virtual Stream CreateStream()
{
return new MemoryStream();
}
[Fact]
public void BinaryWriter_CtorAndWriteTests1()
{
// [] Smoke test to ensure that we can write with the constructed writer
using (Stream mstr = CreateStream())
using (BinaryWriter dw2 = new BinaryWriter(mstr))
using (BinaryReader dr2 = new BinaryReader(mstr))
{
dw2.Write(true);
dw2.Flush();
mstr.Position = 0;
Assert.True(dr2.ReadBoolean());
}
}
[Fact]
public void BinaryWriter_CtorAndWriteTests1_Negative()
{
// [] Should throw ArgumentNullException for null argument
Assert.Throws<ArgumentNullException>(() => new BinaryWriter(null));
// [] Can't construct a BinaryWriter on a readonly stream
using (Stream memStream = new MemoryStream(new byte[10], false))
{
Assert.Throws<ArgumentException>(() => new BinaryWriter(memStream));
}
// [] Can't construct a BinaryWriter with a closed stream
{
Stream memStream = CreateStream();
memStream.Dispose();
Assert.Throws<ArgumentException>(() => new BinaryWriter(memStream));
}
}
[Theory]
[MemberData("EncodingAndEncodingStrings")]
public void BinaryWriter_EncodingCtorAndWriteTests(Encoding encoding, string testString)
{
using (Stream memStream = CreateStream())
using (BinaryWriter writer = new BinaryWriter(memStream, encoding))
using (BinaryReader reader = new BinaryReader(memStream, encoding))
{
writer.Write(testString);
writer.Flush();
memStream.Position = 0;
Assert.Equal(testString, reader.ReadString());
}
}
public static IEnumerable<object[]> EncodingAndEncodingStrings
{
get
{
yield return new object[] { Encoding.UTF8, "This is UTF8\u00FF" };
yield return new object[] { Encoding.BigEndianUnicode, "This is BigEndianUnicode\u00FF" };
yield return new object[] { Encoding.Unicode, "This is Unicode\u00FF" };
}
}
[Fact]
public void BinaryWriter_EncodingCtorAndWriteTests_Negative()
{
// [] Check for ArgumentNullException on null stream
Assert.Throws<ArgumentNullException>(() => new BinaryReader((Stream)null, Encoding.UTF8));
// [] Check for ArgumentNullException on null encoding
Assert.Throws<ArgumentNullException>(() => new BinaryReader(CreateStream(), null));
}
[Fact]
public void BinaryWriter_SeekTests()
{
int[] iArrLargeValues = new int[] { 10000, 100000, int.MaxValue / 200, int.MaxValue / 1000, short.MaxValue, int.MaxValue, int.MaxValue - 1, int.MaxValue / 2, int.MaxValue / 10, int.MaxValue / 100 };
BinaryWriter dw2 = null;
MemoryStream mstr = null;
byte[] bArr = null;
StringBuilder sb = new StringBuilder();
Int64 lReturn = 0;
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("Hello, this is my string".ToCharArray());
for (int iLoop = 0; iLoop < iArrLargeValues.Length; iLoop++)
{
lReturn = dw2.Seek(iArrLargeValues[iLoop], SeekOrigin.Begin);
Assert.Equal(iArrLargeValues[iLoop], lReturn);
}
dw2.Dispose();
mstr.Dispose();
// [] Seek from start of stream
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(0, SeekOrigin.Begin);
Assert.Equal(0, lReturn);
dw2.Write("lki".ToCharArray());
dw2.Flush();
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("lki3456789", sb.ToString());
dw2.Dispose();
mstr.Dispose();
// [] Seek into stream from start
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(3, SeekOrigin.Begin);
Assert.Equal(3, lReturn);
dw2.Write("lk".ToCharArray());
dw2.Flush();
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("012lk56789", sb.ToString());
dw2.Dispose();
mstr.Dispose();
// [] Seek from end of stream
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(-3, SeekOrigin.End);
Assert.Equal(7, lReturn);
dw2.Write("ll".ToCharArray());
dw2.Flush();
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("0123456ll9", sb.ToString());
dw2.Dispose();
mstr.Dispose();
// [] Seeking from current position
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
mstr.Position = 2;
lReturn = dw2.Seek(2, SeekOrigin.Current);
Assert.Equal(4, lReturn);
dw2.Write("ll".ToCharArray());
dw2.Flush();
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("0123ll6789", sb.ToString());
dw2.Dispose();
mstr.Dispose();
// [] Seeking past the end from middle
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(4, SeekOrigin.End); //This wont throw any exception now.
Assert.Equal(14, mstr.Position);
dw2.Dispose();
mstr.Dispose();
// [] Seek past the end from beginning
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(11, SeekOrigin.Begin); //This wont throw any exception now.
Assert.Equal(11, mstr.Position);
dw2.Dispose();
mstr.Dispose();
// [] Seek to the end
mstr = new MemoryStream();
dw2 = new BinaryWriter(mstr);
dw2.Write("0123456789".ToCharArray());
lReturn = dw2.Seek(10, SeekOrigin.Begin);
Assert.Equal(10, lReturn);
dw2.Write("ll".ToCharArray());
bArr = mstr.ToArray();
sb = new StringBuilder();
for (int i = 0; i < bArr.Length; i++)
sb.Append((char)bArr[i]);
Assert.Equal("0123456789ll", sb.ToString());
dw2.Dispose();
mstr.Dispose();
}
[Theory]
[InlineData(-1)]
[InlineData(-2)]
[InlineData(-10000)]
[InlineData(int.MinValue)]
public void BinaryWriter_SeekTests_NegativeOffset(int invalidValue)
{
// [] IOException if offset is negative
using (Stream memStream = CreateStream())
using (BinaryWriter writer = new BinaryWriter(memStream))
{
writer.Write("Hello, this is my string".ToCharArray());
Assert.Throws<IOException>(() => writer.Seek(invalidValue, SeekOrigin.Begin));
}
}
[Fact]
public void BinaryWriter_SeekTests_InvalidSeekOrigin()
{
// [] ArgumentException for invalid seekOrigin
using (Stream memStream = CreateStream())
using (BinaryWriter writer = new BinaryWriter(memStream))
{
writer.Write("012345789".ToCharArray());
Assert.Throws<ArgumentException>(() =>
{
writer.Seek(3, ~SeekOrigin.Begin);
});
}
}
[Fact]
public void BinaryWriter_BaseStreamTests()
{
// [] Get the base stream for MemoryStream
using (Stream ms2 = CreateStream())
using (BinaryWriter sr2 = new BinaryWriter(ms2))
{
Assert.Same(ms2, sr2.BaseStream);
}
}
[Fact]
public virtual void BinaryWriter_FlushTests()
{
// [] Check that flush updates the underlying stream
using (Stream memstr2 = CreateStream())
using (BinaryWriter bw2 = new BinaryWriter(memstr2))
{
string str = "HelloWorld";
int expectedLength = str.Length + 1; // 1 for 7-bit encoded length
bw2.Write(str);
Assert.Equal(expectedLength, memstr2.Length);
bw2.Flush();
Assert.Equal(expectedLength, memstr2.Length);
}
// [] Flushing a closed writer may throw an exception depending on the underlying stream
using (Stream memstr2 = CreateStream())
{
BinaryWriter bw2 = new BinaryWriter(memstr2);
bw2.Dispose();
bw2.Flush();
}
}
[Fact]
public void BinaryWriter_DisposeTests()
{
// Disposing multiple times should not throw an exception
using (Stream memStream = CreateStream())
using (BinaryWriter binaryWriter = new BinaryWriter(memStream))
{
binaryWriter.Dispose();
binaryWriter.Dispose();
binaryWriter.Dispose();
}
}
[Fact]
public void BinaryWriter_DisposeTests_Negative()
{
using (Stream memStream = CreateStream())
{
BinaryWriter binaryWriter = new BinaryWriter(memStream);
binaryWriter.Dispose();
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Seek(1, SeekOrigin.Begin));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new byte[2], 0, 2));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new char[2], 0, 2));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(true));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((byte)4));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new byte[] { 1, 2 }));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write('a'));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(new char[] { 'a', 'b' }));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(5.3));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((short)3));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write(33));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((Int64)42));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((sbyte)4));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write("Hello There"));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((float)4.3));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((UInt16)3));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((uint)4));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write((ulong)5));
Assert.Throws<ObjectDisposedException>(() => binaryWriter.Write("Bah"));
}
}
}
}
| |
using System;
using System.Net.Sockets;
using Google.ProtocolBuffers;
using Rhino.DistributedHashTable.Exceptions;
using Rhino.DistributedHashTable.Internal;
using Rhino.DistributedHashTable.Parameters;
using Rhino.DistributedHashTable.Protocol;
using Rhino.DistributedHashTable.Remote;
using Rhino.DistributedHashTable.Util;
using Rhino.PersistentHashTable;
using NodeEndpoint = Rhino.DistributedHashTable.Internal.NodeEndpoint;
using Value = Rhino.PersistentHashTable.Value;
using System.Linq;
using ReplicationType=Rhino.DistributedHashTable.Internal.ReplicationType;
namespace Rhino.DistributedHashTable.Client
{
/// <summary>
/// Thread Safety - This is NOT a thread safe connection
/// Exception Safety - After an exception is thrown, it should be disposed and not used afterward
/// Connection Pooling - It is expected that this will be part of a connection pool
/// </summary>
public class DistributedHashTableStorageClient :
IDistributedHashTableStorage,
IDistributedHashTableNodeReplication,
IDistributedHashTableRemoteNode
{
private readonly NodeEndpoint endpoint;
protected readonly TcpClient Client;
private readonly NetworkStream stream;
private readonly MessageStreamWriter<StorageMessageUnion> writer;
public DistributedHashTableStorageClient(NodeEndpoint endpoint)
{
this.endpoint = endpoint;
Client = new TcpClient(endpoint.Sync.Host, endpoint.Sync.Port);
stream = Client.GetStream();
writer = new MessageStreamWriter<StorageMessageUnion>(stream);
}
public NodeEndpoint Endpoint
{
get { return endpoint; }
}
public virtual void Dispose()
{
stream.Dispose();
Client.Close();
}
public PutResult[] Put(int topologyVersion,
params ExtendedPutRequest[] valuesToAdd)
{
writer.Write(new StorageMessageUnion.Builder
{
Type = StorageMessageType.PutRequests,
TopologyVersion = topologyVersion,
PutRequestsList =
{
valuesToAdd.Select(x => x.GetPutRequest())
}
}.Build());
writer.Flush();
stream.Flush();
var union = ReadReply(StorageMessageType.PutResponses);
return union.PutResponsesList.Select(x => new PutResult
{
ConflictExists = x.ConflictExists,
Version = new PersistentHashTable.ValueVersion
{
InstanceId = new Guid(x.Version.InstanceId.ToByteArray()),
Number = x.Version.Number
}
}).ToArray();
}
private StorageMessageUnion ReadReply(StorageMessageType responses)
{
var iterator = MessageStreamIterator<StorageMessageUnion>.FromStreamProvider(() => new UndisposableStream(stream));
var union = iterator.First();
if(union.Type==StorageMessageType.TopologyChangedError)
throw new TopologyVersionDoesNotMatchException();
if(union.Type==StorageMessageType.SeeOtherError)
{
throw new SeeOtherException
{
Endpoint = union.SeeOtherError.Other.GetNodeEndpoint()
};
}
if (union.Type == StorageMessageType.StorageErrorResult)
throw new RemoteNodeException(union.Exception.Message);
if (union.Type != responses)
throw new UnexpectedReplyException("Got reply " + union.Type + " but expected " + responses);
return union;
}
public bool[] Remove(int topologyVersion,
params ExtendedRemoveRequest[] valuesToRemove)
{
writer.Write(new StorageMessageUnion.Builder
{
Type = StorageMessageType.RemoveRequests,
TopologyVersion = topologyVersion,
RemoveRequestsList =
{
valuesToRemove.Select(x=>x.GetRemoveRequest())
}
}.Build());
writer.Flush();
stream.Flush();
var union = ReadReply(StorageMessageType.RemoveResponses);
return union.RemoveResponesList.Select(x => x.WasRemoved).ToArray();
}
public Value[][] Get(int topologyVersion,
params ExtendedGetRequest[] valuesToGet)
{
writer.Write(new StorageMessageUnion.Builder
{
Type = StorageMessageType.GetRequests,
TopologyVersion = topologyVersion,
GetRequestsList =
{
valuesToGet.Select(x => CreateGetRequest(x))
}
}.Build());
writer.Flush();
stream.Flush();
var union = ReadReply(StorageMessageType.GetResponses);
return union.GetResponsesList.Select(x =>
x.ValuesList.Select(y=> new Value
{
Data = y.Data.ToByteArray(),
ExpiresAt = y.ExpiresAtAsDouble != null ? DateTime.FromOADate(y.ExpiresAtAsDouble.Value) : (DateTime?)null,
Key = y.Key,
ParentVersions = y.ParentVersionsList.Select(z => new PersistentHashTable.ValueVersion
{
InstanceId = new Guid(z.InstanceId.ToByteArray()),
Number = z.Number
}).ToArray(),
ReadOnly = y.ReadOnly,
Sha256Hash = y.Sha256Hash.ToByteArray(),
Tag = y.Tag,
Timestamp = DateTime.FromOADate(y.TimeStampAsDouble),
Version = new PersistentHashTable.ValueVersion
{
InstanceId = new Guid(y.Version.InstanceId.ToByteArray()),
Number = y.Version.Number
}
}).ToArray()
).ToArray();
}
private static GetRequestMessage CreateGetRequest(ExtendedGetRequest x)
{
return new GetRequestMessage.Builder
{
Key = x.Key,
Segment = x.Segment,
}.Build();
}
public IDistributedHashTableNodeReplication Replication
{
get { return this; }
}
public ReplicationResult ReplicateNextPage(NodeEndpoint replicationEndpoint,
ReplicationType type,
int segment)
{
writer.Write(new StorageMessageUnion.Builder
{
Type = StorageMessageType.ReplicateNextPageRequest,
ReplicateNextPageRequest = new ReplicateNextPageRequestMessage.Builder
{
ReplicationEndpoint = replicationEndpoint.GetNodeEndpoint(),
Segment = segment,
Type = type == ReplicationType.Backup? Protocol.ReplicationType.Backup : Protocol.ReplicationType.Ownership
}.Build()
}.Build());
writer.Flush();
stream.Flush();
var union = ReadReply(StorageMessageType.ReplicateNextPageResponse);
return new ReplicationResult
{
Done = union.ReplicateNextPageResponse.Done,
PutRequests = union.ReplicateNextPageResponse.PutRequestsList.Select(
x => x.GetPutRequest()
).ToArray(),
RemoveRequests = union.ReplicateNextPageResponse.RemoveRequestsList.Select(
x => x.GetRemoveRequest()
).ToArray()
};
}
public int[] AssignAllEmptySegments(NodeEndpoint replicationEndpoint,
ReplicationType type, int[] segments)
{
writer.Write(new StorageMessageUnion.Builder
{
Type = StorageMessageType.AssignAllEmptySegmentsRequest,
AssignAllEmptySegmentsRequest = new AssignAllEmptySegmentsRequestMessage.Builder
{
ReplicationEndpoint = replicationEndpoint.GetNodeEndpoint(),
Type = type == ReplicationType.Backup? Protocol.ReplicationType.Backup : Protocol.ReplicationType.Ownership,
SegmentsList = { segments }
}.Build()
}.Build());
writer.Flush();
stream.Flush();
var union = ReadReply(StorageMessageType.AssignAllEmptySegmentsResponse);
return union.AssignAllEmptySegmentsResponse.AssignedSegmentsList.ToArray();
}
public void UpdateTopology()
{
writer.Write(new StorageMessageUnion.Builder
{
Type = StorageMessageType.UpdateTopology,
}.Build());
writer.Flush();
stream.Flush();
ReadReply(StorageMessageType.TopologyUpdated);
}
}
}
| |
// 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 Newtonsoft.Json;
using System;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Sensus.Shared.Probes.User.Scripts
{
/// <summary>
/// Represents a condition under which a scripted probe is run.
/// </summary>
public class Trigger
{
private object _conditionValue;
private Type _conditionValueEnumType;
public Probe Probe { get; set; }
public string DatumPropertyName { get; set; }
[JsonIgnore]
public PropertyInfo DatumProperty => Probe.DatumType.GetProperty(DatumPropertyName);
public TriggerValueCondition Condition { get; set; }
public object ConditionValue
{
get { return _conditionValue; }
set
{
_conditionValue = value;
// convert to enumerated type if we have the string type name
if (_conditionValueEnumType != null)
{
_conditionValue = Enum.ToObject(_conditionValueEnumType, _conditionValue);
}
}
}
/// <summary>
/// This is a workaround for an odd behavior of JSON.NET, which serializes enumerations as integers. We happen to be deserializing them as objects
/// into ConditionValue, which means they are stored as integers after deserialization. Integers are not comparable with the enumerated values
/// that come off the probes, so we need to jump through some hoops during deserization (i.e., below and above). Below, gettings and setting the
/// value works off of the enumerated type that should be used for the ConditionValue above. When either the below or above are set, they check
/// for the existence of the other and convert the number returned by JSON.NET to its appropriate enumerated type.
/// </summary>
public string ConditionValueEnumType
{
get { return _conditionValue is Enum ? _conditionValue.GetType().FullName : null; }
set
{
if (value != null)
{
_conditionValueEnumType = Assembly.GetExecutingAssembly().GetType(value);
// convert to enumerated type if we have the integer value
if (_conditionValue != null)
{
_conditionValue = Enum.ToObject(_conditionValueEnumType, _conditionValue);
}
}
}
}
public bool Change { get; set; }
public bool FireRepeatedly { get; set; }
public bool FireValueConditionMetOnPreviousCall { get; set; }
public string RegularExpressionText { get; set; }
public TimeSpan StartTime { get; set; }
public TimeSpan EndTime { get; set; }
private Trigger()
{
Reset();
}
public Trigger(Probe probe, PropertyInfo datumProperty, TriggerValueCondition condition, object conditionValue, bool change, bool fireRepeatedly, bool useRegularExpressions, TimeSpan startTime, TimeSpan endTime) : this()
{
if (probe == null) throw new Exception("Trigger is missing Probe selection.");
if (datumProperty == null) throw new Exception("Trigger is missing Property selection.");
if (conditionValue == null) throw new Exception("Trigger is missing Value selection.");
if (endTime <= startTime) throw new Exception("Trigger Start Time must precede End Time.");
Probe = probe;
DatumPropertyName = datumProperty.Name;
Condition = condition;
_conditionValue = conditionValue;
Change = change;
FireRepeatedly = fireRepeatedly;
StartTime = startTime;
EndTime = endTime;
if (useRegularExpressions)
{
RegularExpressionText = _conditionValue.ToString();
}
}
public void Reset()
{
FireValueConditionMetOnPreviousCall = false;
}
public bool FireFor(object value)
{
try
{
var fireValueConditionMet = FireValueConditionMet(value);
var fireRepeatConditionMet = FireRepeatConditionMet();
var fireWindowConditionMet = FireWindowConditionMet();
FireValueConditionMetOnPreviousCall = fireValueConditionMet;
return fireValueConditionMet && fireRepeatConditionMet && fireWindowConditionMet;
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log(ex.Message, LoggingLevel.Normal, GetType());
return false;
}
}
public override string ToString()
{
return $"{Probe.DisplayName} ({DatumPropertyName} {Condition} {_conditionValue})";
}
public override bool Equals(object obj)
{
var trigger = obj as Trigger;
return trigger != null && Probe == trigger.Probe && DatumPropertyName == trigger.DatumPropertyName && Condition == trigger.Condition && ConditionValue == trigger.ConditionValue && Change == trigger.Change;
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
#region Private Methods
private bool FireValueConditionMet(object value)
{
if (RegularExpressionText == null)
{
try
{
var compareTo = ((IComparable)value).CompareTo(_conditionValue);
if (Condition == TriggerValueCondition.Equal) return compareTo == 0;
if (Condition == TriggerValueCondition.GreaterThan) return compareTo > 0;
if (Condition == TriggerValueCondition.GreaterThanOrEqual) return compareTo >= 0;
if (Condition == TriggerValueCondition.LessThan) return compareTo < 0;
if (Condition == TriggerValueCondition.LessThanOrEqual) return compareTo <= 0;
throw new Exception($"Trigger failed recognize Condition: {Condition}");
}
catch (Exception ex)
{
throw new Exception($"Trigger failed to compare values: {ex.Message}", ex);
}
}
else
{
try
{
return Regex.IsMatch(value.ToString(), RegularExpressionText);
}
catch (Exception ex)
{
throw new Exception($"Trigger failed to run Regex.Match: {ex.Message}", ex);
}
}
}
private bool FireRepeatConditionMet()
{
return FireRepeatedly || !FireValueConditionMetOnPreviousCall;
}
private bool FireWindowConditionMet()
{
return StartTime <= DateTime.Now.TimeOfDay && DateTime.Now.TimeOfDay <= EndTime;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using DbMigrations.Client.Infrastructure;
using DbMigrations.Client.Model;
using DbMigrations.Client.Resources;
namespace DbMigrations.Client.Application
{
public class MigrationManager : IMigrationManager
{
private Logger Logger { get; }
private readonly IScriptFileRepository _scriptFileRepository;
private readonly IDatabase _database;
public MigrationManager(
IScriptFileRepository scriptFileRepository,
IDatabase database,
Logger logger)
{
_scriptFileRepository = scriptFileRepository;
_database = database;
Logger = logger;
}
public bool MigrateSchema(bool whatif, bool syncOnly = false, bool reInit = false)
{
if (reInit)
{
_database.ClearAll();
}
if (!whatif)
_database.EnsureMigrationsTable();
var migrations = GetMigrations();
if (!migrations.Any())
{
Logger.InfoLine("Database is consistent; no migrations to execute.");
return true;
}
var ok = ApplyMigrations(whatif, syncOnly, migrations);
if (!ok)
{
foreach (var migration in migrations)
{
Logger.InfoLine(migration.ToString());
if (migration.IsConsistent)
continue;
if (!migration.HasChangedOnDisk)
continue;
WriteDiffs(migration);
}
Logger.Line();
return false;
}
return true;
}
private void WriteDiffs(MigrationScript migration)
{
var diffs = Diff.Compute(migration.Migration.Content, migration.Script.Content);
foreach (var diff in diffs)
{
switch (diff.Operation)
{
case Operation.Equal:
Logger.Info(diff.Text);
break;
case Operation.Delete:
Logger.Write(ConsoleColor.Red, "(" + diff.Text + ")");
break;
case Operation.Insert:
Logger.Write(ConsoleColor.Green, diff.Text);
break;
}
}
}
private List<MigrationScript> GetMigrations()
{
var migrations = _database.GetMigrations();
var scripts = _scriptFileRepository.GetScripts(ScriptKind.Migration);
var migrationScripts = ZipWithScripts(migrations, scripts).ToList();
return migrationScripts;
}
/// <summary>
/// Zip db migrations with scripts on disk
/// </summary>
private static IEnumerable<MigrationScript> ZipWithScripts(IEnumerable<Migration> left, IEnumerable<Script> right)
{
if (left == null) throw new ArgumentNullException(nameof(left));
if (right == null) throw new ArgumentNullException(nameof(right));
var result = left.FullOuterJoin(right, m => m.ScriptName, s => s.ScriptName)
.OrderBy(j => j.Key)
.Select(x => new MigrationScript(x.Key, x.Left, x.Right))
.ToList();
result.ConnectMigrations();
return result;
}
private bool ApplyMigrations(bool whatif, bool syncOnly, IList<MigrationScript> migrations)
{
var maxFileNameLength = migrations.Select(s => s.Name.Length).Max();
foreach (var migration in migrations)
{
bool result = true;
Logger.Info($"[{migration.Script?.Collection}] ");
if (migration.IsConsistent)
{
Logger.Info($"{migration.Name} was already applied.");
}
else if (migration.IsNewMigration)
{
if (!whatif)
result = Apply(migration.Script, syncOnly, maxFileNameLength + 4);
}
else
{
Logger.Error($"ERROR: {migration}".PadRight(maxFileNameLength + 4));
result = false;
}
Logger.Line();
if (!result)
return false;
}
return true;
}
private bool Apply(Script script, bool syncOnly, int padding)
{
try
{
var migrationRecord = new Migration(script.ScriptName, script.Checksum, DateTime.UtcNow, script.Content);
if (!syncOnly)
{
Logger.Info($"{script.ScriptName} - applying... ".PadRight(padding));
_database.ApplyMigration(migrationRecord);
}
else
{
Logger.Info($"{script.ScriptName} - inserting... ".PadRight(padding));
_database.Insert(migrationRecord);
}
Logger.Ok();
}
catch (Exception e)
{
Logger.Error("ERROR: " + e.Message);
return false;
}
return true;
}
public bool HasScripts(ScriptKind kind)
{
var scripts = _scriptFileRepository.GetScripts(kind);
return scripts.Any();
}
public bool ExecuteScripts(bool whatif, ScriptKind kind)
{
var scripts = _scriptFileRepository.GetScripts(kind);
var maxFolderNameLength = scripts.Select(s => s.Collection.Length).DefaultIfEmpty().Max();
var maxFileNameLength = scripts.Select(s => s.ScriptName.Length).DefaultIfEmpty().Max();
foreach (var script in scripts)
{
Logger.Info($"[{script.Collection}".PadRight(maxFolderNameLength + 1) + "] ");
Logger.Info((script.ScriptName + "... ").PadRight(maxFileNameLength + 4));
try
{
if (!whatif)
{
_database.RunInTransaction(script.Content);
Logger.Ok();
}
}
catch (Exception e)
{
Logger.ErrorLine("ERROR: " + e.Message);
return false;
}
Console.WriteLine();
}
return true;
}
}
public static class Ex
{
public static void ConnectMigrations(this IList<MigrationScript> result)
{
foreach (var item in result.Zip(result.Skip(1), (l, r) => new {item = l, next = r}))
{
item.item.Next = item.next;
}
}
}
}
| |
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 ParkingRampSimulatorServices.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;
}
}
}
| |
/*
* 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.IO;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Tools;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
{
public class CSCodeGenerator : ICodeConverter
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SYMBOL m_astRoot = null;
private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> m_positionMap;
private int m_indentWidth = 4; // for indentation
private int m_braceCount; // for indentation
private int m_CSharpLine; // the current line of generated C# code
private int m_CSharpCol; // the current column of generated C# code
private List<string> m_warnings = new List<string>();
private IScriptModuleComms m_comms = null;
private bool m_insertCoopTerminationChecks;
private static string m_coopTerminationCheck = "opensim_reserved_CheckForCoopTermination();";
/// <summary>
/// Keep a record of the previous node when we do the parsing.
/// </summary>
/// <remarks>
/// We do this here because the parser generated by CSTools does not retain a reference to its parent node.
/// The previous node is required so we can correctly insert co-op termination checks when required.
/// </remarks>
// private SYMBOL m_previousNode;
/// <summary>
/// Creates an 'empty' CSCodeGenerator instance.
/// </summary>
public CSCodeGenerator()
{
m_comms = null;
ResetCounters();
}
public CSCodeGenerator(IScriptModuleComms comms, bool insertCoopTerminationChecks)
{
m_comms = comms;
m_insertCoopTerminationChecks = insertCoopTerminationChecks;
ResetCounters();
}
/// <summary>
/// Get the mapping between LSL and C# line/column number.
/// </summary>
/// <returns>Dictionary\<KeyValuePair\<int, int\>, KeyValuePair\<int, int\>\>.</returns>
public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> PositionMap
{
get { return m_positionMap; }
}
/// <summary>
/// Get the mapping between LSL and C# line/column number.
/// </summary>
/// <returns>SYMBOL pointing to root of the abstract syntax tree.</returns>
public SYMBOL ASTRoot
{
get { return m_astRoot; }
}
/// <summary>
/// Resets various counters and metadata.
/// </summary>
private void ResetCounters()
{
m_braceCount = 0;
m_CSharpLine = 0;
m_CSharpCol = 1;
m_positionMap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
m_astRoot = null;
}
/// <summary>
/// Generate the code from the AST we have.
/// </summary>
/// <param name="script">The LSL source as a string.</param>
/// <returns>String containing the generated C# code.</returns>
public string Convert(string script)
{
// m_log.DebugFormat("[CS CODE GENERATOR]: Converting to C#\n{0}", script);
m_warnings.Clear();
ResetCounters();
Parser p = new LSLSyntax(new yyLSLSyntax(), new ErrorHandler(true));
LSL2CSCodeTransformer codeTransformer;
try
{
codeTransformer = new LSL2CSCodeTransformer(p.Parse(script));
}
catch (CSToolsException e)
{
string message;
// LL start numbering lines at 0 - geeks!
// Also need to subtract one line we prepend!
//
string emessage = e.Message;
string slinfo = e.slInfo.ToString();
// Remove wrong line number info
//
if (emessage.StartsWith(slinfo+": "))
emessage = emessage.Substring(slinfo.Length+2);
message = String.Format("({0},{1}) {2}",
e.slInfo.lineNumber - 1,
e.slInfo.charPosition - 1, emessage);
throw new Exception(message);
}
m_astRoot = codeTransformer.Transform();
string retstr = String.Empty;
// standard preamble
//retstr = GenerateLine("using OpenSim.Region.ScriptEngine.Common;");
//retstr += GenerateLine("using System.Collections.Generic;");
//retstr += GenerateLine("");
//retstr += GenerateLine("namespace SecondLife");
//retstr += GenerateLine("{");
m_braceCount++;
//retstr += GenerateIndentedLine("public class Script : OpenSim.Region.ScriptEngine.Common");
//retstr += GenerateIndentedLine("{");
m_braceCount++;
// line number
m_CSharpLine += 9;
// here's the payload
retstr += GenerateLine();
foreach (SYMBOL s in m_astRoot.kids)
retstr += GenerateNode(m_astRoot, s);
// close braces!
m_braceCount--;
//retstr += GenerateIndentedLine("}");
m_braceCount--;
//retstr += GenerateLine("}");
// Removes all carriage return characters which may be generated in Windows platform. Is there
// cleaner way of doing this?
retstr = retstr.Replace("\r", "");
return retstr;
}
/// <summary>
/// Get the set of warnings generated during compilation.
/// </summary>
/// <returns></returns>
public string[] GetWarnings()
{
return m_warnings.ToArray();
}
private void AddWarning(string warning)
{
if (!m_warnings.Contains(warning))
{
m_warnings.Add(warning);
}
}
/// <summary>
/// Recursively called to generate each type of node. Will generate this
/// node, then all it's children.
/// </summary>
/// <param name="previousSymbol">The parent node.</param>
/// <param name="s">The current node to generate code for.</param>
/// <returns>String containing C# code for SYMBOL s.</returns>
private string GenerateNode(SYMBOL previousSymbol, SYMBOL s)
{
string retstr = String.Empty;
// make sure to put type lower in the inheritance hierarchy first
// ie: since IdentArgument and ExpressionArgument inherit from
// Argument, put IdentArgument and ExpressionArgument before Argument
if (s is GlobalFunctionDefinition)
retstr += GenerateGlobalFunctionDefinition((GlobalFunctionDefinition) s);
else if (s is GlobalVariableDeclaration)
retstr += GenerateGlobalVariableDeclaration((GlobalVariableDeclaration) s);
else if (s is State)
retstr += GenerateState((State) s);
else if (s is CompoundStatement)
retstr += GenerateCompoundStatement(previousSymbol, (CompoundStatement) s);
else if (s is Declaration)
retstr += GenerateDeclaration((Declaration) s);
else if (s is Statement)
retstr += GenerateStatement(previousSymbol, (Statement) s);
else if (s is ReturnStatement)
retstr += GenerateReturnStatement((ReturnStatement) s);
else if (s is JumpLabel)
retstr += GenerateJumpLabel((JumpLabel) s);
else if (s is JumpStatement)
retstr += GenerateJumpStatement((JumpStatement) s);
else if (s is StateChange)
retstr += GenerateStateChange((StateChange) s);
else if (s is IfStatement)
retstr += GenerateIfStatement((IfStatement) s);
else if (s is WhileStatement)
retstr += GenerateWhileStatement((WhileStatement) s);
else if (s is DoWhileStatement)
retstr += GenerateDoWhileStatement((DoWhileStatement) s);
else if (s is ForLoop)
retstr += GenerateForLoop((ForLoop) s);
else if (s is ArgumentList)
retstr += GenerateArgumentList((ArgumentList) s);
else if (s is Assignment)
retstr += GenerateAssignment((Assignment) s);
else if (s is BinaryExpression)
retstr += GenerateBinaryExpression((BinaryExpression) s);
else if (s is ParenthesisExpression)
retstr += GenerateParenthesisExpression((ParenthesisExpression) s);
else if (s is UnaryExpression)
retstr += GenerateUnaryExpression((UnaryExpression) s);
else if (s is IncrementDecrementExpression)
retstr += GenerateIncrementDecrementExpression((IncrementDecrementExpression) s);
else if (s is TypecastExpression)
retstr += GenerateTypecastExpression((TypecastExpression) s);
else if (s is FunctionCall)
retstr += GenerateFunctionCall((FunctionCall) s);
else if (s is VectorConstant)
retstr += GenerateVectorConstant((VectorConstant) s);
else if (s is RotationConstant)
retstr += GenerateRotationConstant((RotationConstant) s);
else if (s is ListConstant)
retstr += GenerateListConstant((ListConstant) s);
else if (s is Constant)
retstr += GenerateConstant((Constant) s);
else if (s is IdentDotExpression)
retstr += Generate(CheckName(((IdentDotExpression) s).Name) + "." + ((IdentDotExpression) s).Member, s);
else if (s is IdentExpression)
retstr += GenerateIdentifier(((IdentExpression) s).Name, s);
else if (s is IDENT)
retstr += Generate(CheckName(((TOKEN) s).yytext), s);
else
{
foreach (SYMBOL kid in s.kids)
retstr += GenerateNode(s, kid);
}
return retstr;
}
/// <summary>
/// Generates the code for a GlobalFunctionDefinition node.
/// </summary>
/// <param name="gf">The GlobalFunctionDefinition node.</param>
/// <returns>String containing C# code for GlobalFunctionDefinition gf.</returns>
private string GenerateGlobalFunctionDefinition(GlobalFunctionDefinition gf)
{
string retstr = String.Empty;
// we need to separate the argument declaration list from other kids
List<SYMBOL> argumentDeclarationListKids = new List<SYMBOL>();
List<SYMBOL> remainingKids = new List<SYMBOL>();
foreach (SYMBOL kid in gf.kids)
if (kid is ArgumentDeclarationList)
argumentDeclarationListKids.Add(kid);
else
remainingKids.Add(kid);
retstr += GenerateIndented(String.Format("{0} {1}(", gf.ReturnType, CheckName(gf.Name)), gf);
// print the state arguments, if any
foreach (SYMBOL kid in argumentDeclarationListKids)
retstr += GenerateArgumentDeclarationList((ArgumentDeclarationList) kid);
retstr += GenerateLine(")");
foreach (SYMBOL kid in remainingKids)
retstr += GenerateNode(gf, kid);
return retstr;
}
/// <summary>
/// Generates the code for a GlobalVariableDeclaration node.
/// </summary>
/// <param name="gv">The GlobalVariableDeclaration node.</param>
/// <returns>String containing C# code for GlobalVariableDeclaration gv.</returns>
private string GenerateGlobalVariableDeclaration(GlobalVariableDeclaration gv)
{
string retstr = String.Empty;
foreach (SYMBOL s in gv.kids)
{
retstr += Indent();
retstr += GenerateNode(gv, s);
retstr += GenerateLine(";");
}
return retstr;
}
/// <summary>
/// Generates the code for a State node.
/// </summary>
/// <param name="s">The State node.</param>
/// <returns>String containing C# code for State s.</returns>
private string GenerateState(State s)
{
string retstr = String.Empty;
foreach (SYMBOL kid in s.kids)
if (kid is StateEvent)
retstr += GenerateStateEvent((StateEvent) kid, s.Name);
return retstr;
}
/// <summary>
/// Generates the code for a StateEvent node.
/// </summary>
/// <param name="se">The StateEvent node.</param>
/// <param name="parentStateName">The name of the parent state.</param>
/// <returns>String containing C# code for StateEvent se.</returns>
private string GenerateStateEvent(StateEvent se, string parentStateName)
{
string retstr = String.Empty;
// we need to separate the argument declaration list from other kids
List<SYMBOL> argumentDeclarationListKids = new List<SYMBOL>();
List<SYMBOL> remainingKids = new List<SYMBOL>();
foreach (SYMBOL kid in se.kids)
if (kid is ArgumentDeclarationList)
argumentDeclarationListKids.Add(kid);
else
remainingKids.Add(kid);
// "state" (function) declaration
retstr += GenerateIndented(String.Format("public void {0}_event_{1}(", parentStateName, se.Name), se);
// print the state arguments, if any
foreach (SYMBOL kid in argumentDeclarationListKids)
retstr += GenerateArgumentDeclarationList((ArgumentDeclarationList) kid);
retstr += GenerateLine(")");
foreach (SYMBOL kid in remainingKids)
retstr += GenerateNode(se, kid);
return retstr;
}
/// <summary>
/// Generates the code for an ArgumentDeclarationList node.
/// </summary>
/// <param name="adl">The ArgumentDeclarationList node.</param>
/// <returns>String containing C# code for ArgumentDeclarationList adl.</returns>
private string GenerateArgumentDeclarationList(ArgumentDeclarationList adl)
{
string retstr = String.Empty;
int comma = adl.kids.Count - 1; // tells us whether to print a comma
foreach (Declaration d in adl.kids)
{
retstr += Generate(String.Format("{0} {1}", d.Datatype, CheckName(d.Id)), d);
if (0 < comma--)
retstr += Generate(", ");
}
return retstr;
}
/// <summary>
/// Generates the code for an ArgumentList node.
/// </summary>
/// <param name="al">The ArgumentList node.</param>
/// <returns>String containing C# code for ArgumentList al.</returns>
private string GenerateArgumentList(ArgumentList al)
{
string retstr = String.Empty;
int comma = al.kids.Count - 1; // tells us whether to print a comma
foreach (SYMBOL s in al.kids)
{
retstr += GenerateNode(al, s);
if (0 < comma--)
retstr += Generate(", ");
}
return retstr;
}
/// <summary>
/// Generates the code for a CompoundStatement node.
/// </summary>
/// <param name="cs">The CompoundStatement node.</param>
/// <returns>String containing C# code for CompoundStatement cs.</returns>
private string GenerateCompoundStatement(SYMBOL previousSymbol, CompoundStatement cs)
{
string retstr = String.Empty;
// opening brace
retstr += GenerateIndentedLine("{");
m_braceCount++;
if (m_insertCoopTerminationChecks)
{
// We have to check in event functions as well because the user can manually call these.
if (previousSymbol is GlobalFunctionDefinition
|| previousSymbol is WhileStatement
|| previousSymbol is DoWhileStatement
|| previousSymbol is ForLoop
|| previousSymbol is StateEvent)
retstr += GenerateIndentedLine(m_coopTerminationCheck);
}
foreach (SYMBOL kid in cs.kids)
retstr += GenerateNode(cs, kid);
// closing brace
m_braceCount--;
retstr += GenerateIndentedLine("}");
return retstr;
}
/// <summary>
/// Generates the code for a Declaration node.
/// </summary>
/// <param name="d">The Declaration node.</param>
/// <returns>String containing C# code for Declaration d.</returns>
private string GenerateDeclaration(Declaration d)
{
return Generate(String.Format("{0} {1}", d.Datatype, CheckName(d.Id)), d);
}
/// <summary>
/// Generates the code for a Statement node.
/// </summary>
/// <param name="s">The Statement node.</param>
/// <returns>String containing C# code for Statement s.</returns>
private string GenerateStatement(SYMBOL previousSymbol, Statement s)
{
string retstr = String.Empty;
bool printSemicolon = true;
bool transformToBlock = false;
if (m_insertCoopTerminationChecks)
{
// A non-braced single line do while structure cannot contain multiple statements.
// So to insert the termination check we change this to a braced control structure instead.
if (previousSymbol is WhileStatement
|| previousSymbol is DoWhileStatement
|| previousSymbol is ForLoop)
{
transformToBlock = true;
// FIXME: This will be wrongly indented because the previous for/while/dowhile will have already indented.
retstr += GenerateIndentedLine("{");
retstr += GenerateIndentedLine(m_coopTerminationCheck);
}
}
retstr += Indent();
if (0 < s.kids.Count)
{
// Jump label prints its own colon, we don't need a semicolon.
printSemicolon = !(s.kids.Top is JumpLabel);
// If we encounter a lone Ident, we skip it, since that's a C#
// (MONO) error.
if (!(s.kids.Top is IdentExpression && 1 == s.kids.Count))
foreach (SYMBOL kid in s.kids)
retstr += GenerateNode(s, kid);
}
if (printSemicolon)
retstr += GenerateLine(";");
if (transformToBlock)
{
// FIXME: This will be wrongly indented because the for/while/dowhile is currently handling the unindent
retstr += GenerateIndentedLine("}");
}
return retstr;
}
/// <summary>
/// Generates the code for an Assignment node.
/// </summary>
/// <param name="a">The Assignment node.</param>
/// <returns>String containing C# code for Assignment a.</returns>
private string GenerateAssignment(Assignment a)
{
string retstr = String.Empty;
List<string> identifiers = new List<string>();
checkForMultipleAssignments(identifiers, a);
retstr += GenerateNode(a, (SYMBOL) a.kids.Pop());
retstr += Generate(String.Format(" {0} ", a.AssignmentType), a);
foreach (SYMBOL kid in a.kids)
retstr += GenerateNode(a, kid);
return retstr;
}
// This code checks for LSL of the following forms, and generates a
// warning if it finds them.
//
// list l = [ "foo" ];
// l = (l=[]) + l + ["bar"];
// (produces l=["foo","bar"] in SL but l=["bar"] in OS)
//
// integer i;
// integer j;
// i = (j = 3) + (j = 4) + (j = 5);
// (produces j=3 in SL but j=5 in OS)
//
// Without this check, that code passes compilation, but does not do what
// the end user expects, because LSL in SL evaluates right to left instead
// of left to right.
//
// The theory here is that producing an error and alerting the end user that
// something needs to change is better than silently generating incorrect code.
private void checkForMultipleAssignments(List<string> identifiers, SYMBOL s)
{
if (s is Assignment)
{
Assignment a = (Assignment)s;
string newident = null;
if (a.kids[0] is Declaration)
{
newident = ((Declaration)a.kids[0]).Id;
}
else if (a.kids[0] is IDENT)
{
newident = ((IDENT)a.kids[0]).yytext;
}
else if (a.kids[0] is IdentDotExpression)
{
newident = ((IdentDotExpression)a.kids[0]).Name; // +"." + ((IdentDotExpression)a.kids[0]).Member;
}
else
{
AddWarning(String.Format("Multiple assignments checker internal error '{0}' at line {1} column {2}.", a.kids[0].GetType(), ((SYMBOL)a.kids[0]).Line - 1, ((SYMBOL)a.kids[0]).Position));
}
if (identifiers.Contains(newident))
{
AddWarning(String.Format("Multiple assignments to '{0}' at line {1} column {2}; results may differ between LSL and OSSL.", newident, ((SYMBOL)a.kids[0]).Line - 1, ((SYMBOL)a.kids[0]).Position));
}
identifiers.Add(newident);
}
int index;
for (index = 0; index < s.kids.Count; index++)
{
checkForMultipleAssignments(identifiers, (SYMBOL) s.kids[index]);
}
}
/// <summary>
/// Generates the code for a ReturnStatement node.
/// </summary>
/// <param name="rs">The ReturnStatement node.</param>
/// <returns>String containing C# code for ReturnStatement rs.</returns>
private string GenerateReturnStatement(ReturnStatement rs)
{
string retstr = String.Empty;
retstr += Generate("return ", rs);
foreach (SYMBOL kid in rs.kids)
retstr += GenerateNode(rs, kid);
return retstr;
}
/// <summary>
/// Generates the code for a JumpLabel node.
/// </summary>
/// <param name="jl">The JumpLabel node.</param>
/// <returns>String containing C# code for JumpLabel jl.</returns>
private string GenerateJumpLabel(JumpLabel jl)
{
string labelStatement;
if (m_insertCoopTerminationChecks)
labelStatement = m_coopTerminationCheck;
else
labelStatement = "NoOp();";
return GenerateLine(String.Format("{0}: {1}", CheckName(jl.LabelName), labelStatement), jl);
}
/// <summary>
/// Generates the code for a JumpStatement node.
/// </summary>
/// <param name="js">The JumpStatement node.</param>
/// <returns>String containing C# code for JumpStatement js.</returns>
private string GenerateJumpStatement(JumpStatement js)
{
return Generate(String.Format("goto {0}", CheckName(js.TargetName)), js);
}
/// <summary>
/// Generates the code for an IfStatement node.
/// </summary>
/// <param name="ifs">The IfStatement node.</param>
/// <returns>String containing C# code for IfStatement ifs.</returns>
private string GenerateIfStatement(IfStatement ifs)
{
string retstr = String.Empty;
retstr += GenerateIndented("if (", ifs);
retstr += GenerateNode(ifs, (SYMBOL) ifs.kids.Pop());
retstr += GenerateLine(")");
// CompoundStatement handles indentation itself but we need to do it
// otherwise.
bool indentHere = ifs.kids.Top is Statement;
if (indentHere) m_braceCount++;
retstr += GenerateNode(ifs, (SYMBOL) ifs.kids.Pop());
if (indentHere) m_braceCount--;
if (0 < ifs.kids.Count) // do it again for an else
{
retstr += GenerateIndentedLine("else", ifs);
indentHere = ifs.kids.Top is Statement;
if (indentHere) m_braceCount++;
retstr += GenerateNode(ifs, (SYMBOL) ifs.kids.Pop());
if (indentHere) m_braceCount--;
}
return retstr;
}
/// <summary>
/// Generates the code for a StateChange node.
/// </summary>
/// <param name="sc">The StateChange node.</param>
/// <returns>String containing C# code for StateChange sc.</returns>
private string GenerateStateChange(StateChange sc)
{
return Generate(String.Format("state(\"{0}\")", sc.NewState), sc);
}
/// <summary>
/// Generates the code for a WhileStatement node.
/// </summary>
/// <param name="ws">The WhileStatement node.</param>
/// <returns>String containing C# code for WhileStatement ws.</returns>
private string GenerateWhileStatement(WhileStatement ws)
{
string retstr = String.Empty;
retstr += GenerateIndented("while (", ws);
retstr += GenerateNode(ws, (SYMBOL) ws.kids.Pop());
retstr += GenerateLine(")");
// CompoundStatement handles indentation itself but we need to do it
// otherwise.
bool indentHere = ws.kids.Top is Statement;
if (indentHere) m_braceCount++;
retstr += GenerateNode(ws, (SYMBOL) ws.kids.Pop());
if (indentHere) m_braceCount--;
return retstr;
}
/// <summary>
/// Generates the code for a DoWhileStatement node.
/// </summary>
/// <param name="dws">The DoWhileStatement node.</param>
/// <returns>String containing C# code for DoWhileStatement dws.</returns>
private string GenerateDoWhileStatement(DoWhileStatement dws)
{
string retstr = String.Empty;
retstr += GenerateIndentedLine("do", dws);
// CompoundStatement handles indentation itself but we need to do it
// otherwise.
bool indentHere = dws.kids.Top is Statement;
if (indentHere) m_braceCount++;
retstr += GenerateNode(dws, (SYMBOL) dws.kids.Pop());
if (indentHere) m_braceCount--;
retstr += GenerateIndented("while (", dws);
retstr += GenerateNode(dws, (SYMBOL) dws.kids.Pop());
retstr += GenerateLine(");");
return retstr;
}
/// <summary>
/// Generates the code for a ForLoop node.
/// </summary>
/// <param name="fl">The ForLoop node.</param>
/// <returns>String containing C# code for ForLoop fl.</returns>
private string GenerateForLoop(ForLoop fl)
{
string retstr = String.Empty;
retstr += GenerateIndented("for (", fl);
// It's possible that we don't have an assignment, in which case
// the child will be null and we only print the semicolon.
// for (x = 0; x < 10; x++)
// ^^^^^
ForLoopStatement s = (ForLoopStatement) fl.kids.Pop();
if (null != s)
{
retstr += GenerateForLoopStatement(s);
}
retstr += Generate("; ");
// for (x = 0; x < 10; x++)
// ^^^^^^
retstr += GenerateNode(fl, (SYMBOL) fl.kids.Pop());
retstr += Generate("; ");
// for (x = 0; x < 10; x++)
// ^^^
retstr += GenerateForLoopStatement((ForLoopStatement) fl.kids.Pop());
retstr += GenerateLine(")");
// CompoundStatement handles indentation itself but we need to do it
// otherwise.
bool indentHere = fl.kids.Top is Statement;
if (indentHere) m_braceCount++;
retstr += GenerateNode(fl, (SYMBOL) fl.kids.Pop());
if (indentHere) m_braceCount--;
return retstr;
}
/// <summary>
/// Generates the code for a ForLoopStatement node.
/// </summary>
/// <param name="fls">The ForLoopStatement node.</param>
/// <returns>String containing C# code for ForLoopStatement fls.</returns>
private string GenerateForLoopStatement(ForLoopStatement fls)
{
string retstr = String.Empty;
int comma = fls.kids.Count - 1; // tells us whether to print a comma
// It's possible that all we have is an empty Ident, for example:
//
// for (x; x < 10; x++) { ... }
//
// Which is illegal in C# (MONO). We'll skip it.
if (fls.kids.Top is IdentExpression && 1 == fls.kids.Count)
return retstr;
for (int i = 0; i < fls.kids.Count; i++)
{
SYMBOL s = (SYMBOL)fls.kids[i];
// Statements surrounded by parentheses in for loops
//
// e.g. for ((i = 0), (j = 7); (i < 10); (++i))
//
// are legal in LSL but not in C# so we need to discard the parentheses
//
// The following, however, does not appear to be legal in LLS
//
// for ((i = 0, j = 7); (i < 10); (++i))
//
// As of Friday 20th November 2009, the Linden Lab simulators appear simply never to compile or run this
// script but with no debug or warnings at all! Therefore, we won't deal with this yet (which looks
// like it would be considerably more complicated to handle).
while (s is ParenthesisExpression)
s = (SYMBOL)s.kids.Pop();
retstr += GenerateNode(fls, s);
if (0 < comma--)
retstr += Generate(", ");
}
return retstr;
}
/// <summary>
/// Generates the code for a BinaryExpression node.
/// </summary>
/// <param name="be">The BinaryExpression node.</param>
/// <returns>String containing C# code for BinaryExpression be.</returns>
private string GenerateBinaryExpression(BinaryExpression be)
{
string retstr = String.Empty;
if (be.ExpressionSymbol.Equals("&&") || be.ExpressionSymbol.Equals("||"))
{
// special case handling for logical and/or, see Mantis 3174
retstr += "((bool)(";
retstr += GenerateNode(be, (SYMBOL)be.kids.Pop());
retstr += "))";
retstr += Generate(String.Format(" {0} ", be.ExpressionSymbol.Substring(0,1)), be);
retstr += "((bool)(";
foreach (SYMBOL kid in be.kids)
retstr += GenerateNode(be, kid);
retstr += "))";
}
else
{
retstr += GenerateNode(be, (SYMBOL)be.kids.Pop());
retstr += Generate(String.Format(" {0} ", be.ExpressionSymbol), be);
foreach (SYMBOL kid in be.kids)
retstr += GenerateNode(be, kid);
}
return retstr;
}
/// <summary>
/// Generates the code for a UnaryExpression node.
/// </summary>
/// <param name="ue">The UnaryExpression node.</param>
/// <returns>String containing C# code for UnaryExpression ue.</returns>
private string GenerateUnaryExpression(UnaryExpression ue)
{
string retstr = String.Empty;
retstr += Generate(ue.UnarySymbol, ue);
retstr += GenerateNode(ue, (SYMBOL) ue.kids.Pop());
return retstr;
}
/// <summary>
/// Generates the code for a ParenthesisExpression node.
/// </summary>
/// <param name="pe">The ParenthesisExpression node.</param>
/// <returns>String containing C# code for ParenthesisExpression pe.</returns>
private string GenerateParenthesisExpression(ParenthesisExpression pe)
{
string retstr = String.Empty;
retstr += Generate("(");
foreach (SYMBOL kid in pe.kids)
retstr += GenerateNode(pe, kid);
retstr += Generate(")");
return retstr;
}
/// <summary>
/// Generates the code for a IncrementDecrementExpression node.
/// </summary>
/// <param name="ide">The IncrementDecrementExpression node.</param>
/// <returns>String containing C# code for IncrementDecrementExpression ide.</returns>
private string GenerateIncrementDecrementExpression(IncrementDecrementExpression ide)
{
string retstr = String.Empty;
if (0 < ide.kids.Count)
{
IdentDotExpression dot = (IdentDotExpression) ide.kids.Top;
retstr += Generate(String.Format("{0}", ide.PostOperation ? CheckName(dot.Name) + "." + dot.Member + ide.Operation : ide.Operation + CheckName(dot.Name) + "." + dot.Member), ide);
}
else
retstr += Generate(String.Format("{0}", ide.PostOperation ? CheckName(ide.Name) + ide.Operation : ide.Operation + CheckName(ide.Name)), ide);
return retstr;
}
/// <summary>
/// Generates the code for a TypecastExpression node.
/// </summary>
/// <param name="te">The TypecastExpression node.</param>
/// <returns>String containing C# code for TypecastExpression te.</returns>
private string GenerateTypecastExpression(TypecastExpression te)
{
string retstr = String.Empty;
// we wrap all typecasted statements in parentheses
retstr += Generate(String.Format("({0}) (", te.TypecastType), te);
retstr += GenerateNode(te, (SYMBOL) te.kids.Pop());
retstr += Generate(")");
return retstr;
}
/// <summary>
/// Generates the code for an identifier
/// </summary>
/// <param name="id">The symbol name</param>
/// <param name="s">The Symbol node.</param>
/// <returns>String containing C# code for identifier reference.</returns>
private string GenerateIdentifier(string id, SYMBOL s)
{
if (m_comms != null)
{
object value = m_comms.LookupModConstant(id);
if (value != null)
{
string retval = null;
if (value is int)
retval = String.Format("new LSL_Types.LSLInteger({0})",((int)value).ToString());
else if (value is float)
retval = String.Format("new LSL_Types.LSLFloat({0})",((float)value).ToString());
else if (value is string)
retval = String.Format("new LSL_Types.LSLString(\"{0}\")",((string)value));
else if (value is OpenMetaverse.UUID)
retval = String.Format("new LSL_Types.key(\"{0}\")",((OpenMetaverse.UUID)value).ToString());
else if (value is OpenMetaverse.Vector3)
retval = String.Format("new LSL_Types.Vector3(\"{0}\")",((OpenMetaverse.Vector3)value).ToString());
else if (value is OpenMetaverse.Quaternion)
retval = String.Format("new LSL_Types.Quaternion(\"{0}\")",((OpenMetaverse.Quaternion)value).ToString());
else retval = id;
return Generate(retval, s);
}
}
return Generate(CheckName(id), s);
}
/// <summary>
/// Generates the code for a FunctionCall node.
/// </summary>
/// <param name="fc">The FunctionCall node.</param>
/// <returns>String containing C# code for FunctionCall fc.</returns>
private string GenerateFunctionCall(FunctionCall fc)
{
string retstr = String.Empty;
string modinvoke = null;
if (m_comms != null)
modinvoke = m_comms.LookupModInvocation(fc.Id);
if (modinvoke != null)
{
if (fc.kids[0] is ArgumentList)
{
if ((fc.kids[0] as ArgumentList).kids.Count == 0)
retstr += Generate(String.Format("{0}(\"{1}\"",modinvoke,fc.Id), fc);
else
retstr += Generate(String.Format("{0}(\"{1}\",",modinvoke,fc.Id), fc);
}
}
else
{
retstr += Generate(String.Format("{0}(", CheckName(fc.Id)), fc);
}
foreach (SYMBOL kid in fc.kids)
retstr += GenerateNode(fc, kid);
retstr += Generate(")");
return retstr;
}
/// <summary>
/// Generates the code for a Constant node.
/// </summary>
/// <param name="c">The Constant node.</param>
/// <returns>String containing C# code for Constant c.</returns>
private string GenerateConstant(Constant c)
{
string retstr = String.Empty;
// Supprt LSL's weird acceptance of floats with no trailing digits
// after the period. Turn float x = 10.; into float x = 10.0;
if ("LSL_Types.LSLFloat" == c.Type)
{
int dotIndex = c.Value.IndexOf('.') + 1;
if (0 < dotIndex && (dotIndex == c.Value.Length || !Char.IsDigit(c.Value[dotIndex])))
c.Value = c.Value.Insert(dotIndex, "0");
c.Value = "new LSL_Types.LSLFloat("+c.Value+")";
}
else if ("LSL_Types.LSLInteger" == c.Type)
{
c.Value = "new LSL_Types.LSLInteger("+c.Value+")";
}
else if ("LSL_Types.LSLString" == c.Type)
{
c.Value = "new LSL_Types.LSLString(\""+c.Value+"\")";
}
retstr += Generate(c.Value, c);
return retstr;
}
/// <summary>
/// Generates the code for a VectorConstant node.
/// </summary>
/// <param name="vc">The VectorConstant node.</param>
/// <returns>String containing C# code for VectorConstant vc.</returns>
private string GenerateVectorConstant(VectorConstant vc)
{
string retstr = String.Empty;
retstr += Generate(String.Format("new {0}(", vc.Type), vc);
retstr += GenerateNode(vc, (SYMBOL) vc.kids.Pop());
retstr += Generate(", ");
retstr += GenerateNode(vc, (SYMBOL) vc.kids.Pop());
retstr += Generate(", ");
retstr += GenerateNode(vc, (SYMBOL) vc.kids.Pop());
retstr += Generate(")");
return retstr;
}
/// <summary>
/// Generates the code for a RotationConstant node.
/// </summary>
/// <param name="rc">The RotationConstant node.</param>
/// <returns>String containing C# code for RotationConstant rc.</returns>
private string GenerateRotationConstant(RotationConstant rc)
{
string retstr = String.Empty;
retstr += Generate(String.Format("new {0}(", rc.Type), rc);
retstr += GenerateNode(rc, (SYMBOL) rc.kids.Pop());
retstr += Generate(", ");
retstr += GenerateNode(rc, (SYMBOL) rc.kids.Pop());
retstr += Generate(", ");
retstr += GenerateNode(rc, (SYMBOL) rc.kids.Pop());
retstr += Generate(", ");
retstr += GenerateNode(rc, (SYMBOL) rc.kids.Pop());
retstr += Generate(")");
return retstr;
}
/// <summary>
/// Generates the code for a ListConstant node.
/// </summary>
/// <param name="lc">The ListConstant node.</param>
/// <returns>String containing C# code for ListConstant lc.</returns>
private string GenerateListConstant(ListConstant lc)
{
string retstr = String.Empty;
retstr += Generate(String.Format("new {0}(", lc.Type), lc);
foreach (SYMBOL kid in lc.kids)
retstr += GenerateNode(lc, kid);
retstr += Generate(")");
return retstr;
}
/// <summary>
/// Prints a newline.
/// </summary>
/// <returns>A newline.</returns>
private string GenerateLine()
{
return GenerateLine("");
}
/// <summary>
/// Prints text, followed by a newline.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <returns>String s followed by newline.</returns>
private string GenerateLine(string s)
{
return GenerateLine(s, null);
}
/// <summary>
/// Prints text, followed by a newline.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <param name="sym">Symbol being generated to extract original line
/// number and column from.</param>
/// <returns>String s followed by newline.</returns>
private string GenerateLine(string s, SYMBOL sym)
{
string retstr = Generate(s, sym) + "\n";
m_CSharpLine++;
m_CSharpCol = 1;
return retstr;
}
/// <summary>
/// Prints text.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <returns>String s.</returns>
private string Generate(string s)
{
return Generate(s, null);
}
/// <summary>
/// Prints text.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <param name="sym">Symbol being generated to extract original line
/// number and column from.</param>
/// <returns>String s.</returns>
private string Generate(string s, SYMBOL sym)
{
if (null != sym)
m_positionMap.Add(new KeyValuePair<int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair<int, int>(sym.Line, sym.Position));
m_CSharpCol += s.Length;
return s;
}
/// <summary>
/// Prints text correctly indented, followed by a newline.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <returns>Properly indented string s followed by newline.</returns>
private string GenerateIndentedLine(string s)
{
return GenerateIndentedLine(s, null);
}
/// <summary>
/// Prints text correctly indented, followed by a newline.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <param name="sym">Symbol being generated to extract original line
/// number and column from.</param>
/// <returns>Properly indented string s followed by newline.</returns>
private string GenerateIndentedLine(string s, SYMBOL sym)
{
string retstr = GenerateIndented(s, sym) + "\n";
m_CSharpLine++;
m_CSharpCol = 1;
return retstr;
}
/// <summary>
/// Prints text correctly indented.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <returns>Properly indented string s.</returns>
//private string GenerateIndented(string s)
//{
// return GenerateIndented(s, null);
//}
// THIS FUNCTION IS COMMENTED OUT TO SUPPRESS WARNINGS
/// <summary>
/// Prints text correctly indented.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <param name="sym">Symbol being generated to extract original line
/// number and column from.</param>
/// <returns>Properly indented string s.</returns>
private string GenerateIndented(string s, SYMBOL sym)
{
string retstr = Indent() + s;
if (null != sym)
m_positionMap.Add(new KeyValuePair<int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair<int, int>(sym.Line, sym.Position));
m_CSharpCol += s.Length;
return retstr;
}
/// <summary>
/// Prints correct indentation.
/// </summary>
/// <returns>Indentation based on brace count.</returns>
private string Indent()
{
string retstr = String.Empty;
for (int i = 0; i < m_braceCount; i++)
for (int j = 0; j < m_indentWidth; j++)
{
retstr += " ";
m_CSharpCol++;
}
return retstr;
}
/// <summary>
/// Returns the passed name with an underscore prepended if that name is a reserved word in C#
/// and not resevered in LSL otherwise it just returns the passed name.
///
/// This makes no attempt to cache the results to minimise future lookups. For a non trivial
/// scripts the number of unique identifiers could easily grow to the size of the reserved word
/// list so maintaining a list or dictionary and doing the lookup there firstwould probably not
/// give any real speed advantage.
///
/// I believe there is a class Microsoft.CSharp.CSharpCodeProvider that has a function
/// CreateValidIdentifier(str) that will return either the value of str if it is not a C#
/// key word or "_"+str if it is. But availability under Mono?
/// </summary>
private string CheckName(string s)
{
if (CSReservedWords.IsReservedWord(s))
return "@" + s;
else
return s;
}
}
}
| |
/*
* This file is part of the OpenKinect Project. http://www.openkinect.org
*
* Copyright (c) 2010 individual OpenKinect contributors. See the CONTRIB file
* for details.
*
* This code is licensed to you under the terms of the Apache License, version
* 2.0, or, at your option, the terms of the GNU General Public License,
* version 2.0. See the APACHE20 and GPL2 files for the text of the licenses,
* or the following URLs:
* http://www.apache.org/licenses/LICENSE-2.0
* http://www.gnu.org/licenses/gpl-2.0.txt
*
* If you redistribute this file in source form, modified or unmodified, you
* may:
* 1) Leave this header intact and distribute it under the same terms,
* accompanying it with the APACHE20 and GPL20 files, or
* 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or
* 3) Delete the GPL v2 clause and accompany it with the APACHE20 file
* In all cases you must keep the copyright notice intact and include a copy
* of the CONTRIB file.
*
* Binary distributions must follow the binary distribution requirements of
* either License.
*/
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace freenect
{
/// <summary>
/// Kinect device. This wraps functionality associated with the entire Kinect
/// device into a happy little bundle.
/// </summary>
///
///
public class Kinect
{
/// <summary>
/// Gets or sets the logging level for the Kinect library. This controls
/// how much debugging information is sent to the logging callback
/// </summary>
public static LoggingLevel LogLevel
{
get
{
return Kinect.logLevel;
}
set
{
Kinect.SetLogLevel(value);
}
}
/// <summary>
/// Raised when a log item is received from the low level Kinect library.
/// </summary>
public static event LogEventHandler Log = delegate { };
/// <summary>
/// Gets the device ID for this Kinect device
/// </summary>
public int DeviceID
{
get;
private set;
}
/// <summary>
/// Gets whether the connection to the device is open
/// </summary>
public bool IsOpen
{
get;
private set;
}
/// <summary>
/// Gets the LED on this Kinect device
/// </summary>
public LED LED
{
get;
private set;
}
/// <summary>
/// Gets the Motor instance for this Kinect device
/// </summary>
public Motor Motor
{
get;
private set;
}
/// <summary>
/// Gets the accelerometer for this Kinect device
/// </summary>
public Accelerometer Accelerometer
{
get;
private set;
}
/// <summary>
/// Gets the RGB camera for this Kinect device
/// </summary>
public VideoCamera VideoCamera
{
get;
private set;
}
/// <summary>
/// Gets the depth camera for this Kinect device
/// </summary>
public DepthCamera DepthCamera
{
get;
private set;
}
/// <summary>
/// Gets or sets the name for this Kinect Device.
/// </summary>
/// <remarks>
/// This means nothing at all to the actual library, but can be useful for
/// debugging/presentation reasons. The default value is "Device {Kinect.DeviceID}"
/// without the curly braces. For example, "Device 0" or "Device 1".
/// But you can make it whatever the hell you want.
/// </remarks>
public string Name
{
get;
set;
}
/// <summary>
/// Current logging level for the kinect session (for all devices)
/// </summary>
private static LoggingLevel logLevel;
/// <summary>
/// Pointer to native device object
/// </summary>
internal IntPtr devicePointer = IntPtr.Zero;
/// <summary>
/// Cached device state that can be used after a call to Kinect.UpdateStatus
/// This can be used to save some USB or P/Invoke calls.
/// </summary>
internal FreenectTiltState cachedDeviceState;
/// <summary>
/// Constructor
/// </summary>
/// <param name="id">
/// ID of the Kinect Device. This is a value in the range [0, Kinect.DeviceCount - 1]
/// </param>
public Kinect(int id)
{
// Make sure id is under DeviceCount
if(id >= Kinect.DeviceCount)
{
throw new ArgumentOutOfRangeException("The device ID has to be in the range [0, Kinect.DeviceCount - 1]");
}
// Store device ID for later
this.DeviceID = id;
}
/// <value>
/// Gets number of Kinect devices connected
/// </value>
public static int DeviceCount
{
get
{
return Kinect.GetDeviceCount();
}
}
/// <summary>
/// Opens up the connection to this Kinect device
/// </summary>
public void Open()
{
int result = KinectNative.freenect_open_device(KinectNative.Context, ref this.devicePointer, this.DeviceID);
if(result != 0)
{
throw new Exception("Could not open connection to Kinect Device (ID=" + this.DeviceID + "). Error Code = " + result);
}
// Create child instances
this.LED = new LED(this);
this.Motor = new Motor(this);
this.Accelerometer = new Accelerometer(this);
this.VideoCamera = new VideoCamera(this);
this.DepthCamera = new DepthCamera(this);
//Register the device
KinectNative.RegisterDevice(this.devicePointer, this);
// Open now
this.IsOpen = true;
}
/// <summary>
/// Closes the connection to this Kinect device
/// </summary>
public void Close()
{
// Stop Cameras
if(this.VideoCamera.IsRunning)
{
this.VideoCamera.Stop();
}
if(this.DepthCamera.IsRunning)
{
this.DepthCamera.Stop();
}
// Close device
int result = KinectNative.freenect_close_device(this.devicePointer);
if(result != 0)
{
throw new Exception("Could not close connection to Kinect Device (ID=" + this.DeviceID + "). Error Code = " + result);
}
// Dispose of child instances
this.LED = null;
this.Motor = null;
this.Accelerometer = null;
this.VideoCamera = null;
this.DepthCamera = null;
// Unegister the device
KinectNative.UnregisterDevice(this.devicePointer);
// Not open anymore
this.IsOpen = false;
}
/// <summary>
/// Gets updated device status from the Kinect. This updates any properties in the
/// child devices (Motor, LED, etc.)
/// </summary>
public void UpdateStatus()
{
// Ask for new device status
KinectNative.freenect_update_tilt_state(this.devicePointer);
// Get updated device status
IntPtr ptr = KinectNative.freenect_get_tilt_state(this.devicePointer);
this.cachedDeviceState = (FreenectTiltState)Marshal.PtrToStructure(ptr, typeof(FreenectTiltState));
}
/// <summary>
/// Makes the base library handle any pending USB events. Either this, or UpdateStatus
/// should be called repeatedly.
/// </summary>
public static void ProcessEvents()
{
KinectNative.freenect_process_events(KinectNative.Context);
}
/// <summary>
/// Shuts down the Kinect.NET library and closes any open devices.
/// </summary>
public static void Shutdown()
{
KinectNative.ShutdownContext();
}
/// <summary>
/// Gets the number of Kinect devices connected
/// </summary>
/// <remarks>
/// This is just a support function for the Kinect.DeviceCount property
/// </remarks>
/// <returns>
/// Number of Kinect devices connected.
/// </returns>
private static int GetDeviceCount()
{
// Now we can just return w/e native method puts out
return KinectNative.freenect_num_devices(KinectNative.Context);
}
/// <summary>
/// Sets the logging level for the Kinect session. Support function for Kinect.LogLevel property.
/// </summary>
/// <param name="level">
/// A <see cref="LogLevel"/>
/// </param>
private static void SetLogLevel(LoggingLevel level)
{
KinectNative.freenect_set_log_level(KinectNative.Context, level);
Kinect.logLevel = level;
}
/// <summary>
/// Logging callback.
/// </summary>
/// <param name="device">
/// A <see cref="IntPtr"/>
/// </param>
/// <param name="logLevel">
/// A <see cref="Kinect.LogLevelOptions"/>
/// </param>
/// <param name="message">
/// A <see cref="System.String"/>
/// </param>
internal static void LogCallback(IntPtr device, LoggingLevel logLevel, string message)
{
Kinect realDevice = KinectNative.GetDevice(device);
Kinect.Log(null, new LogEventArgs(realDevice, logLevel, message));
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.PythonTools.Intellisense;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
namespace Microsoft.PythonTools {
using AP = AnalysisProtocol;
struct CachedClassification {
public ITrackingSpan Span;
public string Classification;
public CachedClassification(ITrackingSpan span, string classification) {
Span = span;
Classification = classification;
}
}
/// <summary>
/// Provides classification based upon the AST and analysis.
/// </summary>
internal class PythonAnalysisClassifier : IClassifier {
private AP.AnalysisClassification[] _spanCache;
private readonly object _spanCacheLock = new object();
private readonly PythonAnalysisClassifierProvider _provider;
private readonly ITextBuffer _buffer;
private LocationTracker _spanTranslator;
internal PythonAnalysisClassifier(PythonAnalysisClassifierProvider provider, ITextBuffer buffer) {
buffer.ContentTypeChanged += BufferContentTypeChanged;
_provider = provider;
_buffer = buffer;
_buffer.RegisterForNewAnalysis(OnNewAnalysis);
}
private async void OnNewAnalysis(AnalysisEntry entry) {
if (!_provider._colorNames) {
bool raise = false;
lock (_spanCacheLock) {
if (_spanCache != null) {
_spanCache = null;
raise = true;
}
}
if (raise) {
OnNewClassifications(_buffer.CurrentSnapshot);
}
return;
}
var classifications = await entry.Analyzer.GetAnalysisClassificationsAsync(
entry,
_buffer,
_provider._colorNamesWithAnalysis
);
if (classifications != null) {
Debug.WriteLine("Received {0} classifications", classifications.Data.classifications.Length);
// sort the spans by starting position so we can use binary search when handing them out
Array.Sort(
classifications.Data.classifications,
(x, y) => x.start - y.start
);
lock (_spanCacheLock) {
_spanCache = classifications.Data.classifications;
_spanTranslator = classifications.GetTracker(classifications.Data.version);
}
if (_spanTranslator != null) {
OnNewClassifications(_buffer.CurrentSnapshot);
}
}
}
private void OnNewClassifications(ITextSnapshot snapshot) {
var changed = ClassificationChanged;
if (changed != null) {
changed(this, new ClassificationChangedEventArgs(new SnapshotSpan(snapshot, 0, snapshot.Length)));
}
}
public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged;
class IndexComparer : IComparer {
public static readonly IndexComparer Instance = new IndexComparer();
public int Compare(object x, object y) {
int xValue = GetStart(x), yValue = GetStart(y);
return xValue - yValue;
}
private static int GetStart(object value) {
int indexValue;
AP.AnalysisClassification xClass = value as AP.AnalysisClassification;
if (xClass != null) {
indexValue = xClass.start;
} else {
indexValue = (int)value;
}
return indexValue;
}
}
public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span) {
var classifications = new List<ClassificationSpan>();
var snapshot = span.Snapshot;
AP.AnalysisClassification[] spans;
LocationTracker spanTranslator;
lock (_spanCacheLock) {
spans = _spanCache;
spanTranslator = _spanTranslator;
}
if (span.Length <= 0 || span.Snapshot.IsReplBufferWithCommand() || spans == null || spanTranslator == null) {
return classifications;
}
// find where in the spans we should start scanning from (they're sorted by
// starting position in the old buffer)
var start = spanTranslator.TranslateBack(span.Start);
var end = spanTranslator.TranslateBack(span.End);
var startIndex = Array.BinarySearch(spans, start, IndexComparer.Instance);
if (startIndex < 0) {
startIndex = ~startIndex - 1;
if (startIndex < 0) {
startIndex = 0;
}
}
for (int i = startIndex; i < spans.Length; i++) {
if (spans[i].start > end) {
// we're past the span our caller is interested in, stop scanning...
break;
}
var classification = spans[i];
var cs = spanTranslator.TranslateForward(new Span(classification.start, classification.length));
string typeName = ToVsClassificationName(classification);
IClassificationType classificationType;
if (typeName != null &&
_provider.CategoryMap.TryGetValue(typeName, out classificationType)) {
classifications.Add(
new ClassificationSpan(
new SnapshotSpan(snapshot, cs),
classificationType
)
);
}
}
return classifications;
}
private static string ToVsClassificationName(AP.AnalysisClassification classification) {
string typeName = null;
switch (classification.type) {
case "keyword": typeName = PredefinedClassificationTypeNames.Keyword; break;
case "class": typeName = PythonPredefinedClassificationTypeNames.Class; break;
case "function": typeName = PythonPredefinedClassificationTypeNames.Function; break;
case "module": typeName = PythonPredefinedClassificationTypeNames.Module; break;
case "parameter": typeName = PythonPredefinedClassificationTypeNames.Parameter; break;
}
return typeName;
}
public PythonAnalysisClassifierProvider Provider {
get {
return _provider;
}
}
#region Private Members
private void BufferContentTypeChanged(object sender, ContentTypeChangedEventArgs e) {
_spanCache = null;
_buffer.ContentTypeChanged -= BufferContentTypeChanged;
_buffer.Properties.RemoveProperty(typeof(PythonAnalysisClassifier));
_buffer.UnregisterForNewAnalysis(OnNewAnalysis);
}
#endregion
}
internal static partial class ClassifierExtensions {
public static PythonAnalysisClassifier GetPythonAnalysisClassifier(this ITextBuffer buffer) {
PythonAnalysisClassifier res;
if (buffer.Properties.TryGetProperty(typeof(PythonAnalysisClassifier), out res)) {
return res;
}
return null;
}
}
}
| |
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using Vexe.Runtime.Helpers;
/// <summary>
/// Serializable by Unity's serialization system - Extracted from System.Collections.Generic (not a wrapper)
/// </summary>
[Serializable, DebuggerDisplay("Count = {Count}")]
public class SerializableDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary
{
[SerializeField]
int[] _Buckets;
[SerializeField]
int[] _HashCodes;
[SerializeField]
int[] _Next;
[SerializeField]
int _Count;
[SerializeField]
int _Version;
[SerializeField]
int _FreeList;
[SerializeField]
int _FreeCount;
[SerializeField]
TKey[] _Keys;
[SerializeField]
TValue[] _Values;
readonly IEqualityComparer<TKey> _Comparer;
public Dictionary<TKey, TValue> AsDictionary
{
get { return new Dictionary<TKey, TValue>(this); }
}
public int Count
{
get { return _Count - _FreeCount; }
}
public TValue this[TKey key]
{
get
{
int index = FindIndex(key);
if (index >= 0)
return _Values[index];
ErrorHelper.KeyNotFound(key.ToString());
return default(TValue);
}
set { Insert(key, value, false); }
}
public SerializableDictionary() : this(0, null)
{
}
public SerializableDictionary(int capacity) : this(capacity, null)
{
}
public SerializableDictionary(IEqualityComparer<TKey> comparer) : this(0, comparer)
{
}
public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException("capacity");
Initialize(capacity);
_Comparer = (comparer ?? EqualityComparer<TKey>.Default);
}
public SerializableDictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null)
{
}
public SerializableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
: this((dictionary != null) ? dictionary.Count : 0, comparer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
foreach (KeyValuePair<TKey, TValue> current in dictionary)
Add(current.Key, current.Value);
}
public bool ContainsValue(TValue value)
{
if (value == null)
{
for (int i = 0; i < _Count; i++)
{
if (_HashCodes[i] >= 0 && _Values[i] == null)
return true;
}
}
else
{
var defaultComparer = EqualityComparer<TValue>.Default;
for (int i = 0; i < _Count; i++)
{
if (_HashCodes[i] >= 0 && defaultComparer.Equals(_Values[i], value))
return true;
}
}
return false;
}
public bool ContainsKey(TKey key)
{
return FindIndex(key) >= 0;
}
public void Clear()
{
if (_Count <= 0)
return;
for (int i = 0; i < _Buckets.Length; i++)
_Buckets[i] = -1;
Array.Clear(_Keys, 0, _Count);
Array.Clear(_Values, 0, _Count);
Array.Clear(_HashCodes, 0, _Count);
Array.Clear(_Next, 0, _Count);
_FreeList = -1;
_Count = 0;
_FreeCount = 0;
_Version++;
}
public void Add(TKey key, TValue value)
{
Insert(key, value, true);
}
private void Resize(int newSize, bool forceNewHashCodes)
{
int[] bucketsCopy = new int[newSize];
for (int i = 0; i < bucketsCopy.Length; i++)
bucketsCopy[i] = -1;
var keysCopy = new TKey[newSize];
var valuesCopy = new TValue[newSize];
var hashCodesCopy = new int[newSize];
var nextCopy = new int[newSize];
Array.Copy(_Values, 0, valuesCopy, 0, _Count);
Array.Copy(_Keys, 0, keysCopy, 0, _Count);
Array.Copy(_HashCodes, 0, hashCodesCopy, 0, _Count);
Array.Copy(_Next, 0, nextCopy, 0, _Count);
if (forceNewHashCodes)
{
for (int i = 0; i < _Count; i++)
{
if (hashCodesCopy[i] != -1)
hashCodesCopy[i] = (_Comparer.GetHashCode(keysCopy[i]) & 2147483647);
}
}
for (int i = 0; i < _Count; i++)
{
int index = hashCodesCopy[i] % newSize;
nextCopy[i] = bucketsCopy[index];
bucketsCopy[index] = i;
}
_Buckets = bucketsCopy;
_Keys = keysCopy;
_Values = valuesCopy;
_HashCodes = hashCodesCopy;
_Next = nextCopy;
}
private void Resize()
{
Resize(PrimeHelper.ExpandPrime(_Count), false);
}
public bool Remove(TKey key)
{
if (key == null)
throw new ArgumentNullException("key");
int hash = _Comparer.GetHashCode(key) & 2147483647;
int index = hash % _Buckets.Length;
int num = -1;
for (int i = _Buckets[index]; i >= 0; i = _Next[i])
{
if (_HashCodes[i] == hash && _Comparer.Equals(_Keys[i], key))
{
if (num < 0)
_Buckets[index] = _Next[i];
else
_Next[num] = _Next[i];
_HashCodes[i] = -1;
_Next[i] = _FreeList;
_Keys[i] = default(TKey);
_Values[i] = default(TValue);
_FreeList = i;
_FreeCount++;
_Version++;
return true;
}
num = i;
}
return false;
}
private void Insert(TKey key, TValue value, bool add)
{
if (key == null)
throw new ArgumentNullException("key");
if (_Buckets == null)
Initialize(0);
int hash = _Comparer.GetHashCode(key) & 2147483647;
int index = hash % _Buckets.Length;
int num1 = 0;
for (int i = _Buckets[index]; i >= 0; i = _Next[i])
{
if (_HashCodes[i] == hash && _Comparer.Equals(_Keys[i], key))
{
if (add)
throw new ArgumentException("Key already exists: " + key);
_Values[i] = value;
_Version++;
return;
}
num1++;
}
int num2;
if (_FreeCount > 0)
{
num2 = _FreeList;
_FreeList = _Next[num2];
_FreeCount--;
}
else
{
if (_Count == _Keys.Length)
{
Resize();
index = hash % _Buckets.Length;
}
num2 = _Count;
_Count++;
}
_HashCodes[num2] = hash;
_Next[num2] = _Buckets[index];
_Keys[num2] = key;
_Values[num2] = value;
_Buckets[index] = num2;
_Version++;
//if (num3 > 100 && HashHelpers.IsWellKnownEqualityComparer(comparer))
//{
// comparer = (IEqualityComparer<TKey>)HashHelpers.GetRandomizedEqualityComparer(comparer);
// Resize(entries.Length, true);
//}
}
private void Initialize(int capacity)
{
int prime = PrimeHelper.GetPrime(capacity);
_Buckets = new int[prime];
for (int i = 0; i < _Buckets.Length; i++)
_Buckets[i] = -1;
_Keys = new TKey[prime];
_Values = new TValue[prime];
_HashCodes = new int[prime];
_Next = new int[prime];
_FreeList = -1;
}
private int FindIndex(TKey key)
{
if (key == null)
throw new ArgumentNullException("key");
if (_Buckets != null)
{
int hash = _Comparer.GetHashCode(key) & 2147483647;
for (int i = _Buckets[hash % _Buckets.Length]; i >= 0; i = _Next[i])
{
if (_HashCodes[i] == hash && _Comparer.Equals(_Keys[i], key))
return i;
}
}
return -1;
}
public bool TryGetValue(TKey key, out TValue value)
{
int index = FindIndex(key);
if (index >= 0)
{
value = _Values[index];
return true;
}
value = default(TValue);
return false;
}
public TValue ValueOrDefault(TKey key)
{
return ValueOrDefault(key, default(TValue));
}
public TValue ValueOrDefault(TKey key, TValue defaultValue)
{
//return this[key, defaultValue];
int index = FindIndex(key);
if (index >= 0)
return _Values[index];
return defaultValue;
}
private static class PrimeHelper
{
public static readonly int[] Primes = new int[]
{
3,
7,
11,
17,
23,
29,
37,
47,
59,
71,
89,
107,
131,
163,
197,
239,
293,
353,
431,
521,
631,
761,
919,
1103,
1327,
1597,
1931,
2333,
2801,
3371,
4049,
4861,
5839,
7013,
8419,
10103,
12143,
14591,
17519,
21023,
25229,
30293,
36353,
43627,
52361,
62851,
75431,
90523,
108631,
130363,
156437,
187751,
225307,
270371,
324449,
389357,
467237,
560689,
672827,
807403,
968897,
1162687,
1395263,
1674319,
2009191,
2411033,
2893249,
3471899,
4166287,
4999559,
5999471,
7199369
};
public static bool IsPrime(int candidate)
{
if ((candidate & 1) != 0)
{
int num = (int)Math.Sqrt((double)candidate);
for (int i = 3; i <= num; i += 2)
{
if (candidate % i == 0)
{
return false;
}
}
return true;
}
return candidate == 2;
}
public static int GetPrime(int min)
{
if (min < 0)
throw new ArgumentException("min < 0");
for (int i = 0; i < PrimeHelper.Primes.Length; i++)
{
int prime = PrimeHelper.Primes[i];
if (prime >= min)
return prime;
}
for (int i = min | 1; i < 2147483647; i += 2)
{
if (PrimeHelper.IsPrime(i) && (i - 1) % 101 != 0)
return i;
}
return min;
}
public static int ExpandPrime(int oldSize)
{
int num = 2 * oldSize;
if (num > 2146435069 && 2146435069 > oldSize)
{
return 2146435069;
}
return PrimeHelper.GetPrime(num);
}
}
public ICollection<TKey> Keys
{
get { return _Keys.Take(Count).ToArray(); }
}
public ICollection<TValue> Values
{
get { return _Values.Take(Count).ToArray(); }
}
public void Add(KeyValuePair<TKey, TValue> item)
{
Add(item.Key, item.Value);
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
int index = FindIndex(item.Key);
return index >= 0 &&
EqualityComparer<TValue>.Default.Equals(_Values[index], item.Value);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
if (index < 0 || index > array.Length)
throw new ArgumentOutOfRangeException(string.Format("index = {0} array.Length = {1}", index, array.Length));
if (array.Length - index < Count)
throw new ArgumentException(string.Format("The number of elements in the dictionary ({0}) is greater than the available space from index to the end of the destination array {1}.", Count, array.Length));
for (int i = 0; i < _Count; i++)
{
if (_HashCodes[i] >= 0)
array[index++] = new KeyValuePair<TKey, TValue>(_Keys[i], _Values[i]);
}
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return Remove(item.Key);
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator
{
private readonly SerializableDictionary<TKey, TValue> _Dictionary;
private int _Version;
private int _Index;
private KeyValuePair<TKey, TValue> _Current;
public KeyValuePair<TKey, TValue> Current
{
get { return _Current; }
}
internal Enumerator(SerializableDictionary<TKey, TValue> dictionary)
{
_Dictionary = dictionary;
_Version = dictionary._Version;
_Current = default(KeyValuePair<TKey, TValue>);
_Index = 0;
}
public bool MoveNext()
{
if (_Version != _Dictionary._Version)
throw new InvalidOperationException(string.Format("Enumerator version {0} != Dictionary version {1}", _Version, _Dictionary._Version));
while (_Index < _Dictionary._Count)
{
if (_Dictionary._HashCodes[_Index] >= 0)
{
_Current = new KeyValuePair<TKey, TValue>(_Dictionary._Keys[_Index], _Dictionary._Values[_Index]);
_Index++;
return true;
}
_Index++;
}
_Index = _Dictionary._Count + 1;
_Current = default(KeyValuePair<TKey, TValue>);
return false;
}
void IEnumerator.Reset()
{
if (_Version != _Dictionary._Version)
throw new InvalidOperationException(string.Format("Enumerator version {0} != Dictionary version {1}", _Version, _Dictionary._Version));
_Index = 0;
_Current = default(KeyValuePair<TKey, TValue>);
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
}
public DictionaryEntry Entry
{
get { return new DictionaryEntry(Key, Value); }
}
public object Key
{
get { return Current.Key; }
}
public object Value
{
get { return Current.Value; }
}
}
// IDictionary
#region
public void Add(object key, object value)
{
Add((TKey)key, (TValue)value);
}
public bool Contains(object key)
{
return ContainsKey((TKey)key);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return GetEnumerator();
}
public bool IsFixedSize
{
get { return false; }
}
ICollection IDictionary.Keys
{
get { return _Keys.Take(Count).ToArray(); }
}
ICollection IDictionary.Values
{
get { return _Values.Take(Count).ToArray(); }
}
public void Remove(object key)
{
Remove((TKey)key);
}
public object this[object key]
{
get { return this[(TKey)key]; }
set { this[(TKey)key] = (TValue)value; }
}
public void CopyTo(Array array, int index)
{
CopyTo((KeyValuePair<TKey, TValue>[])array, index);
}
public bool IsSynchronized
{
get { throw new NotImplementedException(); }
}
public object SyncRoot
{
get { throw new NotImplementedException(); }
}
#endregion
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
using System.Runtime.InteropServices;
// ERROR: Not supported in C#: OptionDeclaration
using VB = Microsoft.VisualBasic;
namespace _4PosBackOffice.NET
{
internal partial class frmSelCompChk : System.Windows.Forms.Form
{
[DllImport("ODBCCP32.DLL", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
// Registry API functions
private static extern int SQLConfigDataSource(int hwndParent, int fRequest, string lpszDriver, string lpszAttributes);
// Add data source
const short ODBC_ADD_DSN = 1;
// Delete data source
const short ODBC_REMOVE_DSN = 3;
private struct STARTUPINFO
{
public int cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public int dwX;
public int dwY;
public int dwXSize;
public int dwYSize;
public int dwXCountChars;
public int dwYCountChars;
public int dwFillAttribute;
public int dwFlags;
public short wShowWindow;
public short cbReserved2;
public int lpReserved2;
public int hStdInput;
public int hStdOutput;
public int hStdError;
}
private struct PROCESS_INFORMATION
{
public int hProcess;
public int hThread;
public int dwProcessID;
public int dwThreadID;
}
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int WaitForSingleObject(int hHandle, int dwMilliseconds);
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
//UPGRADE_WARNING: Structure PROCESS_INFORMATION may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"'
//UPGRADE_WARNING: Structure STARTUPINFO may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"'
private static extern int CreateProcessA(string lpApplicationName, string lpCommandLine, int lpProcessAttributes, int lpThreadAttributes, int bInheritHandles, int dwCreationFlags, int lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation);
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int CloseHandle(int hObject);
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int GetExitCodeProcess(int hProcess, ref int lpExitCode);
private const int NORMAL_PRIORITY_CLASS = 0x20;
private const short INFINITE = -1;
ADODB.Connection cnnDBmaster;
ADODB.Connection cnnDBWaitron;
string gMasterPath;
string gSecurityCode;
string gSecKey;
List<Label> Label1 = new List<Label>();
bool loadDBStr;
private void loadLanguage()
{
//frmSelCompChk = No Code [4POS Company Loader...]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmSelCompChk.Caption = rsLang("LanguageLayoutLnk_Description"): frmSelCompChk.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmSelCompChk.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private object ExecCmd(ref string cmdline)
{
int ret = 0;
PROCESS_INFORMATION proc = default(PROCESS_INFORMATION);
STARTUPINFO start = default(STARTUPINFO);
// Initialize the STARTUPINFO structure:
start.cb = Strings.Len(start);
// Start the shelled application:
ret = CreateProcessA(Constants.vbNullString, cmdline, 0, 0, 1, NORMAL_PRIORITY_CLASS, 0, Constants.vbNullString, ref start, ref proc);
// Wait for the shelled application to finish:
ret = WaitForSingleObject(proc.hProcess, INFINITE);
GetExitCodeProcess(proc.hProcess, ref ret);
CloseHandle(proc.hThread);
CloseHandle(proc.hProcess);
//UPGRADE_WARNING: Couldn't resolve default property of object ExecCmd. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
return ret;
}
private bool AddDSN(string strDSN, string strDescription, ref string strDB, ref bool delete = false)
{
bool functionReturnValue = false;
//------------------------------------
//Usage:
// AddDSN "MyDSN", "This is a test", "C:\test\myDB.mdb"
//------------------------------------
// ERROR: Not supported in C#: OnErrorStatement
//Set the Driver Name
string strDriver = null;
string strFolder = null;
strFolder = strDB;
while (!(Strings.Right(strFolder, 1) == "\\")) {
strFolder = Strings.Left(strFolder, Strings.Len(strFolder) - 1);
}
strDriver = "Microsoft Access Driver (*.mdb)";
//Build the attributes - Attributes must be Null separated
string strAttributes = null;
strAttributes = strAttributes + "DESCRIPTION=" + strDescription + Strings.Chr(0);
strAttributes = strAttributes + "DSN=" + strDSN + Strings.Chr(0);
//strAttributes = strAttributes & "DATABASE=" & strDB & Chr(0)
strAttributes = strAttributes + "DBQ=" + strDB + Strings.Chr(0);
strAttributes = strAttributes + "systemDB=" + strFolder + "Secured.mdw" + Strings.Chr(0);
strAttributes = strAttributes + "UID=liquid" + Strings.Chr(0);
strAttributes = strAttributes + "PWD=lqd" + Strings.Chr(0);
//Create DSN
functionReturnValue = SQLConfigDataSource(0, ODBC_REMOVE_DSN, strDriver, strAttributes);
if (delete) {
} else {
functionReturnValue = SQLConfigDataSource(0, ODBC_ADD_DSN, strDriver, strAttributes);
}
return functionReturnValue;
Hell:
//AddDSN = True
functionReturnValue = false;
Interaction.MsgBox(Err().Description);
return functionReturnValue;
}
public ADODB.Recordset getRSMaster(ref object sql)
{
ADODB.Recordset functionReturnValue = default(ADODB.Recordset);
functionReturnValue = new ADODB.Recordset();
functionReturnValue.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
functionReturnValue.Open(sql, cnnDBmaster, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic);
return functionReturnValue;
}
private object getMasterDB()
{
object functionReturnValue = null;
// ERROR: Not supported in C#: OnErrorStatement
//UPGRADE_WARNING: Couldn't resolve default property of object getMasterDB. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
functionReturnValue = true;
cnnDBmaster = new ADODB.Connection();
cnnDBmaster.Open("4posMaster");
//gMasterPath = Split(Split(cnnDBmaster.ConnectionString, ";DBQ=")(1), ";")(0)
//gMasterPath = Split(LCase(gMasterPath), "4posmaster.mdb")(0) '
//win 7
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
Scripting.TextStream textstream = default(Scripting.TextStream);
string lString = null;
if (Win7Ver() == true) {
//If fso.FileExists("C:\4POS\4POSWinPath.txt") Then
// Set textstream = fso.OpenTextFile("C:\4POS\4POSWinPath.txt", ForReading, True)
// lString = textstream.ReadAll
// serverPath = lString '& "pricing.mdb"
//Else
// serverPath = "C:\4POSServer\" '"pricing.mdb"
//End If
gMasterPath = "c:\\4posmaster\\";
//UPGRADE_WARNING: Couldn't resolve default property of object getMasterDB. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
functionReturnValue = true;
return functionReturnValue;
}
//win 7
gMasterPath = Strings.Split(Strings.Split(cnnDBmaster.ConnectionString, ";DBQ=")[1], ";")[0];
gMasterPath = Strings.Split(Strings.LCase(gMasterPath), "4posmaster.mdb")[0];
return functionReturnValue;
openConnection_Error:
//
//UPGRADE_WARNING: Couldn't resolve default property of object getMasterDB. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
functionReturnValue = false;
return functionReturnValue;
}
public bool openConnectionWaitron()
{
bool functionReturnValue = false;
// ERROR: Not supported in C#: OnErrorStatement
bool createDayend = false;
string strDBPath = null;
createDayend = false;
functionReturnValue = true;
cnnDBWaitron = new ADODB.Connection();
strDBPath = modRecordSet.serverPath + "Waitron.mdb";
var _with1 = cnnDBWaitron;
_with1.Provider = "Microsoft.ACE.OLEDB.12.0";
_with1.Properties("Jet OLEDB:System Database").Value = modRecordSet.serverPath + "Secured.mdw";
_with1.Open(strDBPath, "liquid", "lqd");
return functionReturnValue;
openConnection_Error:
functionReturnValue = false;
return functionReturnValue;
}
public void closeConnectionWaitron()
{
cnnDBWaitron.Close();
//UPGRADE_NOTE: Object cnnDBWaitron may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
cnnDBWaitron = null;
}
public ADODB.Recordset getRSwaitron(ref string sql)
{
ADODB.Recordset functionReturnValue = default(ADODB.Recordset);
functionReturnValue = new ADODB.Recordset();
functionReturnValue.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
functionReturnValue.Open(sql, cnnDBWaitron, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic);
return functionReturnValue;
}
private void cmdBuild_Click(System.Object eventSender, System.EventArgs eventArgs)
{
short x = 0;
string TMPgMasterPath = null;
ADODB.Recordset rs = default(ADODB.Recordset);
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
string lDir = null;
if (Interaction.MsgBox("A data instruction will prepare a download for each store of the latest stock and pricing data." + Constants.vbCrLf + Constants.vbCrLf + "Are you sure you wish to continue?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Prepare Download") == MsgBoxResult.Yes) {
//UPGRADE_WARNING: Couldn't resolve default property of object TMPgMasterPath. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
TMPgMasterPath = gMasterPath;
gMasterPath = "c:\\4POSServer\\";
if (fso.FolderExists(gMasterPath + "Data\\")) {
} else {
fso.CreateFolder(gMasterPath + "Data\\");
}
//UPGRADE_WARNING: Dir has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
lDir = FileSystem.Dir(gMasterPath + "data\\*.*");
while (!(string.IsNullOrEmpty(lDir))) {
fso.DeleteFile(gMasterPath + "data\\" + lDir, true);
//UPGRADE_WARNING: Dir has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
lDir = FileSystem.Dir();
}
this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
System.Windows.Forms.Application.DoEvents();
rs = getRSMaster(ref "SELECT 1 as MasterID, #" + DateAndTime.Today + "# as Master_DateReplica");
rs.save(gMasterPath + "Data\\Master.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM Catalogue");
rs.save(gMasterPath + "Data\\catalogue.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM PriceSet");
rs.save(gMasterPath + "Data\\PriceSet.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM Channel ORDER BY ChannelID");
rs.save(gMasterPath + "Data\\channel.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM Deposit ORDER BY DepositID");
rs.save(gMasterPath + "Data\\Deposit.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM PackSize ORDER BY PackSizeID");
rs.save(gMasterPath + "Data\\PackSize.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM Person ORDER BY PersonID");
rs.save(gMasterPath + "Data\\Person.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM PersonChannelLnk");
rs.save(gMasterPath + "Data\\PersonChannelLnk.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM PriceChannelLnk");
rs.save(gMasterPath + "Data\\PriceChannelLnk.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM PricingGroup ORDER BY PricingGroupID");
rs.save(gMasterPath + "Data\\PricingGroup.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM PricingGroupChannelLnk");
rs.save(gMasterPath + "Data\\PricingGroupChannelLnk.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM PropChannelLnk");
rs.save(gMasterPath + "Data\\PropChannelLnk.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM [Set] ORDER BY SetID");
rs.save(gMasterPath + "Data\\Set.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM SetItem");
rs.save(gMasterPath + "Data\\SetItem.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM Shrink ORDER BY ShrinkID");
rs.save(gMasterPath + "Data\\Shrink.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM ShrinkItem");
rs.save(gMasterPath + "Data\\ShrinkItem.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM StockGroup ORDER BY StockGroupID");
rs.save(gMasterPath + "Data\\StockGroup.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM StockItem ORDER BY StockItemID");
rs.save(gMasterPath + "Data\\stockitem.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM Supplier ORDER BY SupplierID");
rs.save(gMasterPath + "Data\\Supplier.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM SupplierDepositLnk");
rs.save(gMasterPath + "Data\\SupplierDepositLnk.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM Promotion");
rs.save(gMasterPath + "Data\\Promotion.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM PromotionItem");
rs.save(gMasterPath + "Data\\PromotionItem.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM StockBreak");
rs.save(gMasterPath + "Data\\StockBreak.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM RecipeStockItemLnk");
rs.save(gMasterPath + "Data\\RecipeStockItemLnk.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM CashTransaction");
rs.save(gMasterPath + "Data\\CashTransaction.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM Increment");
rs.save(gMasterPath + "Data\\Increment.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM IncrementStockItemLnk");
rs.save(gMasterPath + "Data\\IncrementStockItemLnk.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM IncrementQuantity");
rs.save(gMasterPath + "Data\\IncrementQuantity.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM Message");
rs.save(gMasterPath + "Data\\Message.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM MessageItem");
rs.save(gMasterPath + "Data\\MessageItem.rs", ADODB.PersistFormatEnum.adPersistADTG);
rs = modRecordSet.getRS(ref "SELECT * FROM StockItemMessageLnk");
rs.save(gMasterPath + "Data\\StockItemMessageLnk.rs", ADODB.PersistFormatEnum.adPersistADTG);
openConnectionWaitron();
rs = getRSwaitron(ref "SELECT * FROM POSMenu");
rs.save(gMasterPath + "Data\\POSMenu.rs", ADODB.PersistFormatEnum.adPersistADTG);
ExecCmd(ref gMasterPath + "wzzip.exe " + gMasterPath + "Data\\data.zip " + gMasterPath + "Data\\*.*");
if (fso.FileExists(gMasterPath + "Data.zip"))
fso.DeleteFile(gMasterPath + "Data.zip", true);
fso.CopyFile(gMasterPath + "Data\\data.zip", gMasterPath + "Data.zip", true);
rs = getRSMaster(ref "SELECT locationCompany_1.locationCompanyID, locationCompany.locationCompany_Email FROM locationCompany INNER JOIN (locationCompany AS locationCompany_1 INNER JOIN location ON locationCompany_1.locationCompany_LocationID = location.locationID) ON locationCompany.locationCompany_LocationID = location.locationID WHERE (((locationCompany_1.locationCompanyID)=" + lblCompany.Tag + "));");
// ERROR: Not supported in C#: OnErrorStatement
//MAPISession1.SignOn()
//MAPIMessages1.SessionID = MAPISession1.SessionID
//MAPIMessages1.Compose()
x = -1;
// ERROR: Not supported in C#: OnErrorStatement
while (!(rs.EOF)) {
if (!string.IsNullOrEmpty(rs.Fields("locationCompany_Email").Value)) {
//UPGRADE_WARNING: Couldn't resolve default property of object x. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
x = x + 1;
//UPGRADE_WARNING: Couldn't resolve default property of object x. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//MAPIMessages1.RecipIndex = x
//MAPIMessages1.RecipDisplayName = rs.Fields("locationCompany_Email").Value
//MAPIMessages1.ResolveName()
}
rs.moveNext();
}
rs = getRSMaster(ref "SELECT locationAudit.locationAuditID, locationAudit.locationAudit_Email FROM locationCompany INNER JOIN locationAudit ON locationCompany.locationCompany_LocationID = locationAudit.locationAudit_LocationID WHERE (((locationCompany.locationCompanyID)=" + lblCompany.Tag + "));");
while (!(rs.EOF)) {
x = x + 1;
//MAPIMessages1.RecipIndex = x
//MAPIMessages1.RecipDisplayName = rs.Fields("locationAudit_Email").Value
//MAPIMessages1.ResolveName()
rs.moveNext();
}
//MAPIMessages1.MsgSubject = "4POS Data"
//MAPIMessages1.MsgNoteText = "4POS Pricing update as at " & Format(Now, "ddd, dd-mmm-yyyy hh:nn")
//MAPIMessages1.AttachmentType = MSMAPI.AttachTypeConstants.mapData
//MAPIMessages1.AttachmentName = "data.zip"
//MAPIMessages1.AttachmentPathName = gMasterPath & "data.zip"
//MAPIMessages1.Send()
//MAPISession1.SignOff()
gMasterPath = TMPgMasterPath;
}
this.Cursor = System.Windows.Forms.Cursors.Default;
}
private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.Close();
}
private void cmdCompany_Click(System.Object eventSender, System.EventArgs eventArgs)
{
cnnDBmaster.Execute("UPDATE locationCompany SET locationCompany.locationCompany_Name = '" + Strings.Replace(txtCompany.Text, "'", "''") + "' WHERE (((locationCompany.locationCompanyID)=" + lblCompany.Tag + "));");
loadCompanies();
lvLocation.FocusedItem = lvLocation.Items["k" + lblCompany.Tag];
lblCompany.Text = lvLocation.FocusedItem.Text + " - " + lvLocation.FocusedItem.SubItems[1].Text;
}
private void cmdDatabase_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.CDmasterOpen.Title = "Select the path to " + lvLocation.FocusedItem.SubItems[1].Text + " application database ...";
CDmasterOpen.Filter = "Application Data Base|pricing.mdb";
CDmasterOpen.FileName = "";
this.CDmasterOpen.ShowDialog();
if (string.IsNullOrEmpty(CDmasterOpen.FileName)) {
} else {
lblCompany.Tag = Strings.Mid(lvLocation.FocusedItem.Name, 2);
cnnDBmaster.Execute("UPDATE locationCompany SET locationCompany.locationCompany_Path = '" + Strings.Replace(CDmasterOpen.FileName, "'", "''") + "' WHERE (((locationCompany.locationCompanyID)=" + Strings.Mid(lvLocation.FocusedItem.Name, 2) + "));");
loadCompanies();
lvLocation.FocusedItem = lvLocation.Items["k" + lblCompany.Tag];
lvLocation_DoubleClick(lvLocation, new System.EventArgs());
cmdCompany_Click(cmdCompany, new System.EventArgs());
}
}
private void cmdOK_Click(System.Object eventSender, System.EventArgs eventArgs)
{
ADODB.Recordset rs = default(ADODB.Recordset);
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
bool createDayend = false;
// ERROR: Not supported in C#: OnErrorStatement
rs = modRecordSet.getRS(ref "SELECT * FROM Person WHERE (Person_UserID = '" + Strings.Replace(this.txtUserName.Text, "'", "''") + "') AND (Person_Password = '" + Strings.Replace(this.txtPassword.Text, "'", "''") + "')");
if (rs.BOF | rs.EOF) {
Interaction.MsgBox("Invalid User Name or Password, try again!", MsgBoxStyle.Exclamation, "Login");
txtPassword.Focus();
} else {
if (Convert.ToInt32(rs.Fields("Person_SecurityBit").Value + "0")) {
this.Close();
My.MyProject.Forms.frmMenu.lblUser.Text = rs.Fields("Person_FirstName").Value + " " + rs.Fields("Person_LastName").Value;
My.MyProject.Forms.frmMenu.lblUser.Tag = rs.Fields("PersonID").Value;
My.MyProject.Forms.frmMenu.gBit = rs.Fields("Person_SecurityBit").Value;
My.MyProject.Forms.frmMenu.loadMenu("stock");
if (fso.FileExists(modRecordSet.serverPath + "report" + My.MyProject.Forms.frmMenu.lblUser.Tag + ".mdb")) {
} else {
fso.CopyFile(modRecordSet.serverPath + "templateReport.mdb", modRecordSet.serverPath + "report" + My.MyProject.Forms.frmMenu.lblUser.Tag + ".mdb");
createDayend = true;
}
if (modReport.openConnectionReport()) {
} else {
Interaction.MsgBox("Unable to locate the Report Database!" + Constants.vbCrLf + Constants.vbCrLf + "The Update Controller wil terminate.", MsgBoxStyle.Critical, "SERVER ERROR");
System.Environment.Exit(0);
}
if (createDayend) {
modReport.cnnDBreport.Execute("DELETE * FROM Report");
modReport.cnnDBreport.Execute("INSERT INTO Report ( ReportID, Report_DayEndStartID, Report_DayEndEndID, Report_Heading ) SELECT 1 AS reportKey, Max(aDayEnd.DayEndID) AS MaxOfDayEndID, Max(aDayEnd.DayEndID) AS MaxOfDayEndID1, 'From ' & Format(Max([aDayEnd].[DayEnd_Date]),'ddd dd mmm yyyy') & ' to ' & Format(Max([aDayEnd].[DayEnd_Date]),'ddd dd mmm yyyy') & ' covering a dayend range of 1 days' AS theHeading FROM aDayEnd;");
My.MyProject.Forms.frmUpdateDayEnd.ShowDialog();
}
rs = modReport.getRSreport(ref "SELECT DayEnd.DayEnd_Date AS fromDate, DayEnd_1.DayEnd_Date AS toDate FROM (Report INNER JOIN DayEnd ON Report.Report_DayEndStartID = DayEnd.DayEndID) INNER JOIN DayEnd AS DayEnd_1 ON Report.Report_DayEndEndID = DayEnd_1.DayEndID;");
if (rs.RecordCount) {
My.MyProject.Forms.frmMenu._DTPicker1_0.Format = DateTimePickerFormat.Custom;
My.MyProject.Forms.frmMenu._DTPicker1_0.CustomFormat = string.Format("{0} {1} {2}", Strings.Format(rs.Fields("fromDate").Value, "yyyy"), Strings.Format(rs.Fields("fromDate").Value, "m"), Strings.Format(rs.Fields("fromDate").Value, "d"));
My.MyProject.Forms.frmMenu._DTPicker1_1.Format = DateTimePickerFormat.Custom;
My.MyProject.Forms.frmMenu._DTPicker1_1.CustomFormat = string.Format("{0} {1} {2}", Strings.Format(rs.Fields("toDate").Value, "yyyy"), Strings.Format(rs.Fields("toDate").Value, "m"), Strings.Format(rs.Fields("toDate").Value, "d"));
}
My.MyProject.Forms.frmMenu.setDayEndRange();
My.MyProject.Forms.frmMenu.lblDayEndCurrent.Text = My.MyProject.Forms.frmMenu.lblDayEnd.Text;
} else {
Interaction.MsgBox("You do not have the correct permissions to access the 4POS Office Application, try again!", MsgBoxStyle.Exclamation, "Login");
this.txtUserName.Focus();
System.Windows.Forms.SendKeys.Send("{Home}+{End}");
}
}
}
private void BuildRegistrationKey()
{
short x = 0;
string lCode = null;
string leCode = null;
gSecurityCode = Strings.UCase(txtCompany.Text) + "XDFHWPGMIJ";
gSecurityCode = Strings.Replace(gSecurityCode, " ", "");
gSecurityCode = Strings.Replace(gSecurityCode, "'", "");
gSecurityCode = Strings.Replace(gSecurityCode, "\"", "");
gSecurityCode = Strings.Replace(gSecurityCode, ",", "");
for (x = 1; x <= 10; x++) {
gSecurityCode = Strings.Left(gSecurityCode, x) + Strings.Replace(Strings.Mid(gSecurityCode, x + 1), Strings.Mid(gSecurityCode, x, 1), "");
}
gSecurityCode = Strings.Left(gSecurityCode, 10);
lCode = getSerialNumber();
leCode = "";
// ERROR: Not supported in C#: OnErrorStatement
for (x = 1; x <= Strings.Len(lCode); x++) {
leCode = leCode + Strings.Mid(gSecurityCode, Convert.ToDouble(Strings.Mid(lCode, x, 1)) + 1, 1);
}
// ERROR: Not supported in C#: OnErrorStatement
lblCode.Text = leCode;
}
private void Command1_Click()
{
if (checkSecurity()) {
this.frmRegister.Visible = false;
} else {
this.frmRegister.Visible = true;
BuildRegistrationKey();
}
}
private void cmdRegistration_Click(System.Object eventSender, System.EventArgs eventArgs)
{
string lCode = null;
string lPassword = null;
int x = 0;
ADODB.Recordset rs = default(ADODB.Recordset);
string lNewString = null;
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
const string securtyStringReply = "9487203516";
if (Interaction.MsgBox("By Clicking 'Yes' you confirm that your company name is correct and you understand the licensing agreement." + Constants.vbCrLf + Constants.vbCrLf + "Do you wish to continue?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "REGISTRATION") == MsgBoxResult.Yes) {
if (Strings.Len(gSecKey) == 12) {
lNewString = "";
for (x = 0; x <= Strings.Len(txtKey.Text); x++) {
if (Information.IsNumeric(Strings.Mid(txtKey.Text, x, 1))) {
lNewString = lNewString + Strings.InStr(securtyStringReply, Strings.Mid(txtKey.Text, x, 1)) - 1;
}
}
cmdCompany_Click(cmdCompany, new System.EventArgs());
return;
} else {
lNewString = "";
for (x = 1; x <= Strings.Len(txtKey.Text); x++) {
if (Information.IsNumeric(Strings.Mid(txtKey.Text, x, 1))) {
lNewString = lNewString + Strings.InStr(securtyStringReply, Strings.Mid(txtKey.Text, x, 1)) - 1;
}
}
if (!string.IsNullOrEmpty(lNewString)) {
if (System.Math.Abs(Convert.ToDouble(lNewString)) == System.Math.Abs(Convert.ToDouble(getSerialNumber()))) {
lPassword = "pospospospos";
lCode = getSerialNumber();
if (!string.IsNullOrEmpty(lCode)) {
lCode = Encrypt(lCode, lPassword);
cmdCompany_Click(cmdCompany, new System.EventArgs());
modRecordSet.cnnDB.Execute("UPDATE Company SET Company.Company_Code = '" + Strings.Replace(lCode, "'", "''") + "';");
frmRegister.Visible = false;
}
return;
}
}
}
}
Interaction.MsgBox("The 'Activation key' is invalid!", MsgBoxStyle.Exclamation, "4POS REGISTRATION");
}
private void frmSelCompChk_Load(System.Object eventSender, System.EventArgs eventArgs)
{
Label1.AddRange(new Label[] {
_Label1_0,
_Label1_1,
_Label1_2,
_Label1_3,
_Label1_4
});
//Dim iret As Long
//Dim lHandle As Long
//Dim rs As Recordset
//Dim fso As New FileSystemObject
//Dim lFile As String
//If getMasterDB() Then
// loadCompanies
//Else
// MsgBox "System could not find Master Database." & vbCrLf & vbCrLf & "Please restart this application", vbInformation, "Company Select"
// Unload Me
//End If
}
//Private Sub Label3_Click()
// Dim rs As Recordset
// Set rs = getRS("SELECT * FROM aTransactionItem")
// If rs.RecordCount = 0 Then
// rs.save gMasterPath & "Data\aTransactionItem.rs", adPersistADTG
// End If
//End Sub
public bool loadDB(ref string[] arrComp)
{
bool functionReturnValue = false;
bool loadData = false;
bool loading = false;
string gHeading = null;
string gFieldName = null;
int gFieldID = 0;
string gField = null;
string lName = null;
int iret = 0;
int lHandle = 0;
ADODB.Recordset rs = default(ADODB.Recordset);
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
string lFile = null;
//Dim rs As ADODB.Recordset
string lSQL = null;
int x = 0;
string lID = null;
gField = lName;
rs = modRecordSet.getRS(ref "SELECT * From ftConstruct WHERE (ftConstruct_Name = '" + Strings.Replace(lName, "'", "''") + "')");
gFieldID = rs.Fields("ftConstruct_FieldID").Value;
gFieldName = rs.Fields("ftConstruct_FieldName").Value;
gHeading = rs.Fields("ftConstruct_DisplayName").Value;
lSQL = rs.Fields("ftConstruct_SQL").Value;
rs.Close();
rs = modRecordSet.getRS(ref lSQL);
//Display the list of Titles in the DataCombo
loading = true;
loadData = false;
loadDBStr = false;
if (getMasterDB()) {
loadCompanies();
this.ShowDialog();
functionReturnValue = loadDBStr;
//If Me.lvLocation.SelectedItem.SubItems(2) = "" Then
//Else
// loadDB = Me.lvLocation.SelectedItem.SubItems(2)
// Unload Me
//End If
} else {
Interaction.MsgBox("System could not find Master Database." + Constants.vbCrLf + Constants.vbCrLf + "Please restart this application", MsgBoxStyle.Information, "Company Select");
functionReturnValue = false;
this.Close();
}
return functionReturnValue;
}
private void lvLocation_DoubleClick(System.Object eventSender, System.EventArgs eventArgs)
{
short x = 0;
ADODB.Recordset rs = default(ADODB.Recordset);
System.Windows.Forms.ListViewItem lListitem = null;
string lPath = null;
ADODB.Connection cn = default(ADODB.Connection);
cn = modRecordSet.openSComp(ref this.lvLocation.FocusedItem.SubItems[2].Text);
if (cn == null) {
} else {
loadDBStr = Convert.ToBoolean(this.lvLocation.FocusedItem.SubItems[2].Text);
//Exit Sub
this.Close();
return;
}
lblCompany.Text = "...";
lblCompany.Tag = "";
lblPath.Text = "...";
lblDir.Text = "...";
for (x = 0; x <= Label1.Count; x++) {
Label1[x].Enabled = false;
}
this.txtUserName.Enabled = false;
txtPassword.Enabled = false;
this.cmdOK.Enabled = false;
cmdCompany.Enabled = false;
cmdBuild.Enabled = false;
cmdDatabase.Enabled = false;
this.CDmasterOpen.Title = "Select the path to " + lvLocation.FocusedItem.SubItems[1].Text + " application database ...";
CDmasterOpen.Filter = "Application Data Base|pricing.mdb";
CDmasterOpen.FileName = "";
this.CDmasterOpen.ShowDialog();
if (string.IsNullOrEmpty(CDmasterOpen.FileName)) {
} else {
lblCompany.Tag = Strings.Mid(lvLocation.FocusedItem.Name, 2);
cnnDBmaster.Execute("UPDATE locationCompany SET locationCompany.locationCompany_Path = '" + Strings.Replace(CDmasterOpen.FileName, "'", "''") + "' WHERE (((locationCompany.locationCompanyID)=" + Strings.Mid(lvLocation.FocusedItem.Name, 2) + "));");
loadCompanies();
lvLocation.FocusedItem = lvLocation.Items["k" + lblCompany.Tag];
//lvLocation_DblClick
}
}
private void loadCompanies()
{
string locationCompany_Name = null;
int locationCompanyID = 0;
int x = 0;
ADODB.Recordset rs = new ADODB.Recordset();
System.Windows.Forms.ListViewItem lListitem = null;
rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
if (openConnection()) {
}
rs.Open("SELECT locationCompany.locationCompanyID, location.location_Name, locationCompany.locationCompany_Name, locationCompany.locationCompany_Path FROM location INNER JOIN locationCompany ON location.locationID = locationCompany.locationCompany_LocationID ORDER BY location.location_Name, locationCompany.locationCompany_Name;", cnnDBmaster, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic);
//Me.lvLocation.ListItems.Clear
if (rs.RecordCount) {
x = -1;
object[,] gArray = new object[rs.RecordCount, 3];
while (!(rs.EOF)) {
x = x + 1;
gArray[x, 0] = rs.Fields(locationCompanyID).Value;
gArray[x, 1] = rs.Fields(locationCompany_Name).Value + "";
gArray[x, 2] = 0;
rs.moveNext();
}
rs.Close();
//Do Until rs.EOF
// Set lListitem = lvLocation.ListItems.Add(, "k" & rs("locationCompanyID"), rs("locationCompany_Name"), , 2)
// lListitem.SubItems(1) = rs("location_Name") & ""
// lListitem.SubItems(2) = rs("locationCompany_Path") & ""
// If LCase(rs("locationCompany_Path") & "") = LCase(serverPath & "pricing.mdb") Then
// lListitem.Selected = True
// 'lvLocation_DblClick
// End If
// rs.moveNext
//Loop
}
}
private void txtCompany_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
txtCompany.SelectionStart = 0;
txtCompany.SelectionLength = 9999;
}
private void txtCompany_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
if (!string.IsNullOrEmpty(Strings.Trim(txtCompany.Text))) {
modRecordSet.cnnDB.Execute("UPDATE Company SET Company_Name = '" + Strings.Replace(txtCompany.Text, "'", "''") + "'");
}
BuildRegistrationKey();
}
private void txtKey_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
txtKey.SelectionStart = 0;
txtKey.SelectionLength = 9999;
}
private void txtPassword_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
txtPassword.SelectionStart = 0;
txtPassword.SelectionLength = 9999;
}
private void txtPassword_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 13) {
KeyAscii = 0;
cmdOK_Click(cmdOK, new System.EventArgs());
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtUserName_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
txtUserName.SelectionStart = 0;
txtUserName.SelectionLength = 9999;
}
private void txtUserName_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (KeyAscii == 13) {
KeyAscii = 0;
txtPassword.Focus();
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private string getSerialNumber()
{
string functionReturnValue = null;
Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
Scripting.Folder fsoFolder = default(Scripting.Folder);
Scripting.Drive fsoDrive = default(Scripting.Drive);
functionReturnValue = "";
if (fso.FolderExists(modRecordSet.serverPath)) {
fsoFolder = fso.GetFolder(modRecordSet.serverPath);
functionReturnValue = Convert.ToString(fsoFolder.Drive.SerialNumber);
}
return functionReturnValue;
}
private string Encrypt(string secret, string PassWord)
{
int l = 0;
short x = 0;
string Char_Renamed = null;
l = Strings.Len(PassWord);
for (x = 1; x <= Strings.Len(secret); x++) {
Char_Renamed = Convert.ToString(Strings.Asc(Strings.Mid(PassWord, (x % l) - l * Convert.ToInt16((x % l) == 0), 1)));
Strings.Mid(secret, x, 1) = Strings.Chr(Strings.Asc(Strings.Mid(secret, x, 1)) ^ Char_Renamed);
}
return secret;
}
public bool checkSecurity()
{
bool functionReturnValue = false;
string lCode = null;
string leCode = null;
string lPassword = null;
ADODB.Recordset rs = default(ADODB.Recordset);
short x = 0;
functionReturnValue = false;
rs = modRecordSet.getRS(ref "SELECT * From Company");
if (rs.RecordCount) {
gSecKey = rs.Fields("Company_Code").Value + "";
if (Information.IsNumeric(rs.Fields("Company_Code").Value)) {
if (Strings.Len(rs.Fields("Company_Code").Value) == 13) {
functionReturnValue = true;
return functionReturnValue;
}
}
lPassword = "pospospospos";
lCode = getSerialNumber();
if (lCode == "0" & Strings.LCase(Strings.Left(modRecordSet.serverPath, 3)) != "c:\\" & !string.IsNullOrEmpty(rs.Fields("Company_Code").Value)) {
functionReturnValue = true;
} else {
leCode = Encrypt(lCode, lPassword);
for (x = 1; x <= Strings.Len(leCode); x++) {
if (Strings.Asc(Strings.Mid(leCode, x, 1)) < 33) {
leCode = Strings.Left(leCode, x - 1) + Strings.Chr(33) + Strings.Mid(leCode, x + 1);
}
}
if (rs.Fields("Company_Code").Value == leCode) {
//If IsNull(rs("Company_TerminateDate")) Then
functionReturnValue = true;
return functionReturnValue;
//Else
// If Date > rs("Company_TerminateDate") Then
// cnnDB.Execute "UPDATE Company SET Company.Company_Code = '';"
// checkSecurity = False
// End If
//End If
} else {
txtCompany.Text = rs.Fields("Company_Name").Value;
txtCompany.SelectionStart = 0;
txtCompany.SelectionLength = 999;
}
}
} else {
Interaction.MsgBox("Unable to locate the '4POS Application Suite' database.", MsgBoxStyle.Critical, "4POS");
System.Environment.Exit(0);
}
return functionReturnValue;
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using FeedBuilder.Properties;
namespace FeedBuilder
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
#region " Private constants/variables"
private const string DialogFilter = "Feed configuration files (*.config)|*.config|All files (*.*)|*.*";
private const string DefaultFileName = "FeedBuilder.config";
private OpenFileDialog _openDialog;
#endregion
private ArgumentsParser _argParser;
#region " Properties"
public string FileName { get; set; }
public bool ShowGui { get; set; }
#endregion
#region " Loading/Initialization/Lifetime"
private void frmMain_Load(Object sender, EventArgs e)
{
Visible = false;
InitializeFormSettings();
string[] args = Environment.GetCommandLineArgs();
// The first arg is the path to ourself
//If args.Count >= 2 Then
// If File.Exists(args(1)) Then
// Dim p As New FeedBuilderSettingsProvider()
// p.LoadFrom(args(1))
// Me.FileName = args(1)
// End If
//End If
// The first arg is the path to ourself
_argParser = new ArgumentsParser(args);
if (!_argParser.HasArgs)
{
FreeConsole();
return;
}
FileName = _argParser.FileName;
if (!string.IsNullOrEmpty(FileName))
{
if (File.Exists(FileName))
{
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.LoadFrom(FileName);
InitializeFormSettings();
}
else
{
_argParser.ShowGui = true;
_argParser.Build = false;
UpdateTitle();
}
}
if (_argParser.ShowGui) Show();
if (_argParser.Build) Build();
if (!_argParser.ShowGui) Close();
}
private void InitializeFormSettings()
{
if (string.IsNullOrEmpty(Settings.Default.OutputFolder))
{
txtOutputFolder.Text = string.Empty;
}
else
{
string path = GetFullDirectoryPath(Settings.Default.OutputFolder);
txtOutputFolder.Text = Directory.Exists(path) ? Settings.Default.OutputFolder : string.Empty;
}
txtFeedXML.Text = string.IsNullOrEmpty(Settings.Default.FeedXML) ? string.Empty : Settings.Default.FeedXML;
txtBaseURL.Text = string.IsNullOrEmpty(Settings.Default.BaseURL) ? string.Empty : Settings.Default.BaseURL;
chkVersion.Checked = Settings.Default.CompareVersion;
chkSize.Checked = Settings.Default.CompareSize;
chkDate.Checked = Settings.Default.CompareDate;
chkHash.Checked = Settings.Default.CompareHash;
chkIgnoreSymbols.Checked = Settings.Default.IgnoreDebugSymbols;
chkIgnoreVsHost.Checked = Settings.Default.IgnoreVsHosting;
chkCopyFiles.Checked = Settings.Default.CopyFiles;
chkCleanUp.Checked = Settings.Default.CleanUp;
txtAddExtension.Text = Settings.Default.AddExtension;
if (Settings.Default.IgnoreFiles == null) Settings.Default.IgnoreFiles = new StringCollection();
ReadFiles();
UpdateTitle();
}
private void UpdateTitle()
{
if (string.IsNullOrEmpty(FileName)) Text = "Feed Builder";
else Text = "Feed Builder - " + FileName;
}
private void SaveFormSettings()
{
if (!string.IsNullOrEmpty(txtOutputFolder.Text.Trim()) && Directory.Exists(txtOutputFolder.Text.Trim())) Settings.Default.OutputFolder = txtOutputFolder.Text.Trim();
// ReSharper disable AssignNullToNotNullAttribute
if (!string.IsNullOrEmpty(txtFeedXML.Text.Trim()) && Directory.Exists(Path.GetDirectoryName(txtFeedXML.Text.Trim()))) Settings.Default.FeedXML = txtFeedXML.Text.Trim();
// ReSharper restore AssignNullToNotNullAttribute
if (!string.IsNullOrEmpty(txtBaseURL.Text.Trim())) Settings.Default.BaseURL = txtBaseURL.Text.Trim();
if (!string.IsNullOrEmpty(txtAddExtension.Text.Trim())) Settings.Default.AddExtension = txtAddExtension.Text.Trim();
Settings.Default.CompareVersion = chkVersion.Checked;
Settings.Default.CompareSize = chkSize.Checked;
Settings.Default.CompareDate = chkDate.Checked;
Settings.Default.CompareHash = chkHash.Checked;
Settings.Default.IgnoreDebugSymbols = chkIgnoreSymbols.Checked;
Settings.Default.IgnoreVsHosting = chkIgnoreVsHost.Checked;
Settings.Default.CopyFiles = chkCopyFiles.Checked;
Settings.Default.CleanUp = chkCleanUp.Checked;
if (Settings.Default.IgnoreFiles == null) Settings.Default.IgnoreFiles = new StringCollection();
Settings.Default.IgnoreFiles.Clear();
foreach (ListViewItem thisItem in lstFiles.Items)
{
if (!thisItem.Checked) Settings.Default.IgnoreFiles.Add(thisItem.Text);
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
SaveFormSettings();
Settings.Default.Save();
}
#endregion
#region " Commands Events"
private void cmdBuild_Click(Object sender, EventArgs e)
{
Build();
}
private void btnOpenOutputs_Click(object sender, EventArgs e)
{
OpenOutputsFolder();
}
private void btnNew_Click(Object sender, EventArgs e)
{
Settings.Default.Reset();
InitializeFormSettings();
}
private void btnOpen_Click(Object sender, EventArgs e)
{
OpenFileDialog dlg;
if (_openDialog == null)
{
dlg = new OpenFileDialog
{
CheckFileExists = true,
FileName = string.IsNullOrEmpty(FileName) ? DefaultFileName : FileName
};
_openDialog = dlg;
}
else dlg = _openDialog;
dlg.Filter = DialogFilter;
if (dlg.ShowDialog() != DialogResult.OK) return;
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.LoadFrom(dlg.FileName);
FileName = dlg.FileName;
InitializeFormSettings();
}
private void btnSave_Click(Object sender, EventArgs e)
{
Save(false);
}
private void btnSaveAs_Click(Object sender, EventArgs e)
{
Save(true);
}
private void btnRefresh_Click(Object sender, EventArgs e)
{
ReadFiles();
}
#endregion
#region " Options Events"
private void cmdOutputFolder_Click(Object sender, EventArgs e)
{
fbdOutputFolder.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (fbdOutputFolder.ShowDialog(this) != DialogResult.OK) return;
txtOutputFolder.Text = fbdOutputFolder.SelectedPath;
ReadFiles();
}
private void cmdFeedXML_Click(Object sender, EventArgs e)
{
sfdFeedXML.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (sfdFeedXML.ShowDialog(this) == DialogResult.OK) txtFeedXML.Text = sfdFeedXML.FileName;
}
private void chkIgnoreSymbols_CheckedChanged(object sender, EventArgs e)
{
ReadFiles();
}
private void chkCopyFiles_CheckedChanged(Object sender, EventArgs e)
{
chkCleanUp.Enabled = chkCopyFiles.Checked;
if (!chkCopyFiles.Checked) chkCleanUp.Checked = false;
}
#endregion
#region " Helper Methods "
private void Build()
{
AttachConsole(ATTACH_PARENT_PROCESS);
Console.WriteLine("Building NAppUpdater feed '{0}'", txtBaseURL.Text.Trim());
if (string.IsNullOrEmpty(txtFeedXML.Text))
{
const string msg = "The feed file location needs to be defined.\n" + "The outputs cannot be generated without this.";
if (_argParser.ShowGui) MessageBox.Show(msg);
Console.WriteLine(msg);
return;
}
// If the target folder doesn't exist, create a path to it
string dest = txtFeedXML.Text.Trim();
var destDir = Directory.GetParent(GetFullDirectoryPath(Path.GetDirectoryName(dest)));
if (!Directory.Exists(destDir.FullName)) Directory.CreateDirectory(destDir.FullName);
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(dec);
XmlElement feed = doc.CreateElement("Feed");
if (!string.IsNullOrEmpty(txtBaseURL.Text.Trim())) feed.SetAttribute("BaseUrl", txtBaseURL.Text.Trim());
doc.AppendChild(feed);
XmlElement tasks = doc.CreateElement("Tasks");
Console.WriteLine("Processing feed items");
int itemsCopied = 0;
int itemsCleaned = 0;
int itemsSkipped = 0;
int itemsFailed = 0;
int itemsMissingConditions = 0;
foreach (ListViewItem thisItem in lstFiles.Items)
{
string destFile = "";
string filename = "";
try
{
filename = thisItem.Text;
destFile = Path.Combine(destDir.FullName, filename);
}
catch { }
if (destFile == "" || filename == "")
{
string msg = string.Format("The file could not be pathed:\nFolder:'{0}'\nFile:{1}", destDir.FullName, filename);
if (_argParser.ShowGui) MessageBox.Show(msg);
Console.WriteLine(msg);
continue;
}
if (thisItem.Checked)
{
var fileInfoEx = (FileInfoEx)thisItem.Tag;
XmlElement task = doc.CreateElement("FileUpdateTask");
task.SetAttribute("localPath", fileInfoEx.RelativeName);
// generate FileUpdateTask metadata items
task.SetAttribute("lastModified", fileInfoEx.FileInfo.LastWriteTime.ToFileTime().ToString(CultureInfo.InvariantCulture));
if (!string.IsNullOrEmpty(txtAddExtension.Text))
{
task.SetAttribute("updateTo", AddExtensionToPath(fileInfoEx.RelativeName, txtAddExtension.Text));
}
task.SetAttribute("fileSize", fileInfoEx.FileInfo.Length.ToString(CultureInfo.InvariantCulture));
if (!string.IsNullOrEmpty(fileInfoEx.FileVersion)) task.SetAttribute("version", fileInfoEx.FileVersion);
XmlElement conds = doc.CreateElement("Conditions");
XmlElement cond;
//File Exists
cond = doc.CreateElement("FileExistsCondition");
cond.SetAttribute("type", "or-not");
conds.AppendChild(cond);
//Version
if (chkVersion.Checked && !string.IsNullOrEmpty(fileInfoEx.FileVersion))
{
cond = doc.CreateElement("FileVersionCondition");
cond.SetAttribute("type", "or");
cond.SetAttribute("what", "below");
cond.SetAttribute("version", fileInfoEx.FileVersion);
conds.AppendChild(cond);
}
//Size
if (chkSize.Checked)
{
cond = doc.CreateElement("FileSizeCondition");
cond.SetAttribute("type", "or-not");
cond.SetAttribute("what", "is");
cond.SetAttribute("size", fileInfoEx.FileInfo.Length.ToString(CultureInfo.InvariantCulture));
conds.AppendChild(cond);
}
//Date
if (chkDate.Checked)
{
cond = doc.CreateElement("FileDateCondition");
cond.SetAttribute("type", "or");
cond.SetAttribute("what", "older");
// local timestamp, not UTC
cond.SetAttribute("timestamp", fileInfoEx.FileInfo.LastWriteTime.ToFileTime().ToString(CultureInfo.InvariantCulture));
conds.AppendChild(cond);
}
//Hash
if (chkHash.Checked)
{
cond = doc.CreateElement("FileChecksumCondition");
cond.SetAttribute("type", "or-not");
cond.SetAttribute("checksumType", "sha256");
cond.SetAttribute("checksum", fileInfoEx.Hash);
conds.AppendChild(cond);
}
if (conds.ChildNodes.Count == 0) itemsMissingConditions++;
task.AppendChild(conds);
tasks.AppendChild(task);
if (chkCopyFiles.Checked)
{
if (CopyFile(fileInfoEx.FileInfo.FullName, destFile)) itemsCopied++;
else itemsFailed++;
}
}
else
{
try
{
if (chkCleanUp.Checked & File.Exists(destFile))
{
File.Delete(destFile);
itemsCleaned += 1;
}
else itemsSkipped += 1;
}
catch (IOException)
{
itemsFailed += 1;
}
}
}
feed.AppendChild(tasks);
string xmlDest = Path.Combine(destDir.FullName, Path.GetFileName(dest));
doc.Save(xmlDest);
// open the outputs folder if we're running from the GUI or
// we have an explicit command line option to do so
if (!_argParser.HasArgs || _argParser.OpenOutputsFolder) OpenOutputsFolder();
Console.WriteLine("Done building feed.");
if (itemsCopied > 0) Console.WriteLine("{0,5} items copied", itemsCopied);
if (itemsCleaned > 0) Console.WriteLine("{0,5} items cleaned", itemsCleaned);
if (itemsSkipped > 0) Console.WriteLine("{0,5} items skipped", itemsSkipped);
if (itemsFailed > 0) Console.WriteLine("{0,5} items failed", itemsFailed);
if (itemsMissingConditions > 0) Console.WriteLine("{0,5} items without any conditions", itemsMissingConditions);
}
private bool CopyFile(string sourceFile, string destFile)
{
// If the target folder doesn't exist, create the path to it
var fi = new FileInfo(destFile);
var d = Directory.GetParent(fi.FullName);
if (!Directory.Exists(d.FullName)) CreateDirectoryPath(d.FullName);
if (!string.IsNullOrEmpty(txtAddExtension.Text))
{
destFile = AddExtensionToPath(destFile, txtAddExtension.Text);
}
// Copy with delayed retry
int retries = 3;
while (retries > 0)
{
try
{
if (File.Exists(destFile)) File.Delete(destFile);
File.Copy(sourceFile, destFile);
retries = 0; // success
return true;
}
catch (IOException)
{
// Failed... let's try sleeping a bit (slow disk maybe)
if (retries-- > 0) Thread.Sleep(200);
}
catch (UnauthorizedAccessException)
{
// same handling as IOException
if (retries-- > 0) Thread.Sleep(200);
}
}
return false;
}
private void CreateDirectoryPath(string directoryPath)
{
// Create the folder/path if it doesn't exist, with delayed retry
int retries = 3;
while (retries > 0 && !Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
if (retries-- < 3) Thread.Sleep(200);
}
}
private void OpenOutputsFolder()
{
string path = txtOutputFolder.Text.Trim();
if (string.IsNullOrEmpty(path))
{
return;
}
string dir = GetFullDirectoryPath(path);
CreateDirectoryPath(dir);
Process process = new Process
{
StartInfo =
{
UseShellExecute = true,
FileName = dir
}
};
process.Start();
}
private int GetImageIndex(string ext)
{
switch (ext.Trim('.'))
{
case "bmp":
return 1;
case "dll":
return 2;
case "doc":
case "docx":
return 3;
case "exe":
return 4;
case "htm":
case "html":
return 5;
case "jpg":
case "jpeg":
return 6;
case "pdf":
return 7;
case "png":
return 8;
case "txt":
return 9;
case "wav":
case "mp3":
return 10;
case "wmv":
return 11;
case "xls":
case "xlsx":
return 12;
case "zip":
return 13;
default:
return 0;
}
}
private void ReadFiles()
{
string outputDir = GetFullDirectoryPath(txtOutputFolder.Text.Trim());
if (string.IsNullOrEmpty(outputDir) || !Directory.Exists(outputDir))
{
return;
}
outputDir = GetFullDirectoryPath(outputDir);
lstFiles.BeginUpdate();
lstFiles.Items.Clear();
FileSystemEnumerator enumerator = new FileSystemEnumerator(outputDir, "*.*", true);
foreach (FileInfo fi in enumerator.Matches())
{
string filePath = fi.FullName;
if ((IsIgnorable(filePath)))
{
continue;
}
FileInfoEx fileInfo = new FileInfoEx(filePath, outputDir.Length);
ListViewItem item = new ListViewItem(fileInfo.RelativeName, GetImageIndex(fileInfo.FileInfo.Extension));
item.SubItems.Add(fileInfo.FileVersion);
item.SubItems.Add(fileInfo.FileInfo.Length.ToString(CultureInfo.InvariantCulture));
item.SubItems.Add(fileInfo.FileInfo.LastWriteTime.ToString(CultureInfo.InvariantCulture));
item.SubItems.Add(fileInfo.Hash);
item.Checked = (!Settings.Default.IgnoreFiles.Contains(fileInfo.RelativeName));
item.Tag = fileInfo;
lstFiles.Items.Add(item);
}
lstFiles.EndUpdate();
}
private string GetFullDirectoryPath(string path)
{
string absolutePath = path;
if (!Path.IsPathRooted(absolutePath))
{
absolutePath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), path);
}
if (!absolutePath.EndsWith("\\"))
{
absolutePath += "\\";
}
return Path.GetFullPath(absolutePath);
}
private bool IsIgnorable(string filename)
{
string ext = Path.GetExtension(filename);
if ((chkIgnoreSymbols.Checked && ext == ".pdb")) return true;
return (chkIgnoreVsHost.Checked && filename.ToLower().Contains("vshost.exe"));
}
private string AddExtensionToPath(string filePath, string extension)
{
string sanitizedExtension = (extension.Trim().StartsWith(".") ? String.Empty : ".") + extension.Trim();
return filePath + sanitizedExtension;
}
private void Save(bool forceDialog)
{
SaveFormSettings();
if (forceDialog || string.IsNullOrEmpty(FileName))
{
SaveFileDialog dlg = new SaveFileDialog
{
Filter = DialogFilter,
FileName = DefaultFileName
};
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.OK)
{
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.SaveAs(dlg.FileName);
FileName = dlg.FileName;
}
}
else
{
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.SaveAs(FileName);
}
UpdateTitle();
}
#endregion
private void frmMain_DragEnter(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files.Length == 0) return;
e.Effect = files[0].EndsWith(".config") ? DragDropEffects.Move : DragDropEffects.None;
}
private void frmMain_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files.Length == 0) return;
try
{
string fileName = files[0];
FeedBuilderSettingsProvider p = new FeedBuilderSettingsProvider();
p.LoadFrom(fileName);
FileName = fileName;
InitializeFormSettings();
}
catch (Exception ex)
{
MessageBox.Show("The file could not be opened: \n" + ex.Message);
}
}
private static readonly int ATTACH_PARENT_PROCESS = -1;
[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll")]
private static extern bool FreeConsole();
}
}
| |
//
// KinoIsoline - Isoline effect
//
// Copyright (C) 2015 Keijiro Takahashi
//
// 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 UnityEngine;
namespace Kino
{
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Kino Image Effects/Isoline")]
public class Isoline : MonoBehaviour
{
#region Public Properties
// Line color
[SerializeField, ColorUsage(true, true, 0, 8, 0.125f, 3)]
Color _lineColor = Color.white;
public Color lineColor {
get { return _lineColor; }
set { _lineColor = value; }
}
// Luminance blending ratio
[SerializeField, Range(0, 1)]
float _luminanceBlending = 1;
public float luminanceBlending {
get { return _luminanceBlending; }
set { _luminanceBlending = value; }
}
// Depth fall-off
[SerializeField]
float _fallOffDepth = 40;
public float fallOffDepth {
get { return _fallOffDepth; }
set { _fallOffDepth = value; }
}
// Background color
[SerializeField]
Color _backgroundColor = Color.black;
public Color backgroundColor {
get { return _backgroundColor; }
set { _backgroundColor = value; }
}
// Slicing axis
[SerializeField]
Vector3 _axis = Vector3.one * 0.577f;
public Vector3 axis {
get { return _axis; }
set { _axis = value; }
}
// Contour interval
[SerializeField]
float _interval = 0.25f;
public float interval {
get { return _interval; }
set { _interval = value; }
}
// Offset
[SerializeField]
Vector3 _offset;
public Vector3 offset {
get { return _offset; }
set { _offset = value; }
}
// Distortion frequency
[SerializeField]
float _distortionFrequency = 1;
public float distortionFrequency {
get { return _distortionFrequency; }
set { _distortionFrequency = value; }
}
// Distortion amount
[SerializeField]
float _distortionAmount = 0;
public float distortionAmount {
get { return _distortionAmount; }
set { _distortionAmount = value; }
}
// Modulation mode
public enum ModulationMode {
None, Frac, Sin, Noise
}
[SerializeField]
ModulationMode _modulationMode = ModulationMode.None;
public ModulationMode modulationMode {
get { return _modulationMode; }
set { _modulationMode = value; }
}
// Modulation axis
[SerializeField]
Vector3 _modulationAxis = Vector3.forward;
public Vector3 modulationAxis {
get { return _modulationAxis; }
set { _modulationAxis = value; }
}
// Modulation frequency
[SerializeField]
float _modulationFrequency = 0.2f;
public float modulationFrequency {
get { return _modulationFrequency; }
set { _modulationFrequency = value; }
}
// Modulation speed
[SerializeField]
float _modulationSpeed = 1;
public float modulationSpeed {
get { return _modulationSpeed; }
set { _modulationSpeed = value; }
}
// Modulation exponent
[SerializeField, Range(1, 50)]
float _modulationExponent = 24;
public float modulationExponent {
get { return _modulationExponent; }
set { _modulationExponent = value; }
}
#endregion
#region Private Properties
[SerializeField]
Shader _shader;
Material _material;
float _modulationTime;
#endregion
#region MonoBehaviour Functions
void OnEnable()
{
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
}
void Update()
{
_modulationTime += Time.deltaTime * _modulationSpeed;
}
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (_material == null) {
_material = new Material(_shader);
_material.hideFlags = HideFlags.DontSave;
}
var matrix = GetComponent<Camera>().cameraToWorldMatrix;
_material.SetMatrix("_InverseView", matrix);
_material.SetColor("_Color", _lineColor);
_material.SetFloat("_FallOffDepth", _fallOffDepth);
_material.SetFloat("_Blend", _luminanceBlending);
_material.SetColor("_BgColor", _backgroundColor);
_material.SetVector("_Axis", _axis.normalized);
_material.SetFloat("_Density", 1.0f / _interval);
_material.SetVector("_Offset", _offset);
_material.SetFloat("_DistFreq", _distortionFrequency);
_material.SetFloat("_DistAmp", _distortionAmount);
if (_distortionAmount > 0)
_material.EnableKeyword("DISTORTION");
else
_material.DisableKeyword("DISTORTION");
_material.DisableKeyword("MODULATION_FRAC");
_material.DisableKeyword("MODULATION_SIN");
_material.DisableKeyword("MODULATION_NOISE");
if (_modulationMode == ModulationMode.Frac)
_material.EnableKeyword("MODULATION_FRAC");
else if (_modulationMode == ModulationMode.Sin)
_material.EnableKeyword("MODULATION_SIN");
else if (_modulationMode == ModulationMode.Noise)
_material.EnableKeyword("MODULATION_NOISE");
var modFreq = _modulationFrequency;
if (_modulationMode == ModulationMode.Sin)
modFreq *= Mathf.PI * 2;
_material.SetVector("_ModAxis", _modulationAxis.normalized);
_material.SetFloat("_ModFreq", modFreq);
_material.SetFloat("_ModTime", _modulationTime);
_material.SetFloat("_ModExp", _modulationExponent);
Graphics.Blit(source, destination, _material);
}
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
namespace DevExpress {
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public class DXWindowBase : ContentControl {
public static DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(object), typeof(DXWindowBase),
new PropertyMetadata((d, e) => ((DXWindowBase)d).PropertyChangedTitle()));
public static DependencyProperty LeftProperty =
DependencyProperty.Register("Left", typeof(double), typeof(DXWindowBase),
new PropertyMetadata((d, e) => ((DXWindowBase)d).PropertyChangedLeft()));
public static DependencyProperty TopProperty =
DependencyProperty.Register("Top", typeof(double), typeof(DXWindowBase),
new PropertyMetadata((d, e) => ((DXWindowBase)d).PropertyChangedTop()));
public static DependencyProperty CloseOnEscapeProperty =
DependencyProperty.Register("CloseOnEscape", typeof(bool), typeof(DXWindowBase),
new PropertyMetadata(true, (d, e) => ((DXWindowBase)d).PropertyChangedCloseOnEscape()));
public bool IsModal { get; protected set; }
public bool IsVisible { get { return Popup != null; } }
public virtual bool KeepPosition { get; set; }
public object Title {
get { return GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public double Left {
get { return (double)GetValue(LeftProperty); }
set { SetValue(LeftProperty, value); }
}
public double Top {
get { return (double)GetValue(TopProperty); }
set { SetValue(TopProperty, value); }
}
public bool CloseOnEscape {
get { return (bool)GetValue(CloseOnEscapeProperty); }
set { SetValue(CloseOnEscapeProperty, value); }
}
public event CancelEventHandler Closing;
public event EventHandler Closed;
public event EventHandler Opened;
public event EventHandler Activated;
protected internal Popup Popup { get; private set; }
Control prevFocusedControl;
static Point previousPosition = new Point();
CancelEventArgs closingEventArgs;
public DXWindowBase() {
this.Visibility = Visibility.Collapsed;
WindowManager.Default.Register(this);
}
public static void HideAllWindows() {
WindowManager.Default.HideAllWindows();
}
public virtual void Show() {
Show(new Popup());
}
public virtual void Show(Popup popup) {
if(IsVisible) return;
ApplyTemplate();
if(Parent is Panel)
(Parent as Panel).Children.Remove(this);
this.Visibility = Visibility.Visible;
prevFocusedControl = FocusManager.GetFocusedElement() as Control;
if(prevFocusedControl != null) popup.FlowDirection = prevFocusedControl.FlowDirection;
Popup = popup;
popup.Child = this;
popup.HorizontalOffset = Left;
popup.VerticalOffset = Top;
popup.IsOpen = true;
WindowManager.Default.SetWindowActive(this);
RaiseActivated();
OnOpened();
}
public virtual void ShowDialog() {
if(IsVisible) return;
IsModal = true;
ShowVeil();
Show();
}
public virtual void Close() {
Hide();
}
public virtual void Hide() {
if(!IsVisible) return;
if(closingEventArgs == null || !closingEventArgs.Cancel)
OnClosing();
}
public void Activate() {
if(IsModal || WindowManager.Default.ActiveWindow == null || !WindowManager.Default.ActiveWindow.IsAlive || WindowManager.Default.ActiveWindow.Target == this || Popup == null)
return;
WindowManager.Default.SetWindowActive(this);
Popup.IsOpen = false;
Popup.IsOpen = true;
RaiseActivated();
}
public override void OnApplyTemplate() {
base.OnApplyTemplate();
GotFocus += OnGotFocus;
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) {
base.OnMouseLeftButtonDown(e);
Activate();
}
protected override void OnKeyDown(KeyEventArgs e) {
base.OnKeyDown(e);
if(!e.Handled && e.Key == Key.Escape && CloseOnEscape)
OnClosing();
}
void OnGotFocus(object sender, RoutedEventArgs e) {
WindowManager.Default.SetWindowActive(this);
RaiseActivated();
}
protected internal virtual void SetActive(bool isActive) {
}
protected virtual void OnOpened() {
UpdateWindowPos();
RaiseOpened();
}
protected virtual void OnClosed() {
if(KeepPosition)
previousPosition = new Point(Left, Top);
RaiseClosed();
Left = 0;
Top = 0;
}
protected virtual bool OnClosing() {
bool isClosing = RaiseClosing();
if(isClosing == true)
CloseCore();
closingEventArgs = new CancelEventArgs();
return isClosing;
}
protected virtual void CloseCore() {
if(Popup == null)
return;
Popup.IsOpen = false;
Popup.Child = null;
Popup = null;
HideVeil();
OnClosed();
IsModal = false;
if(prevFocusedControl != null) {
prevFocusedControl.Focus();
prevFocusedControl = null;
}
}
protected virtual void ShowVeil() {
}
protected virtual void HideVeil() {
}
protected void UpdateWindowPos() {
if(KeepPosition && previousPosition != new Point()) {
Left = previousPosition.X;
Top = previousPosition.Y;
}
if(Left == 0 && Top == 0) {
UpdateLayout();
Size res = DesiredSize;
Size appSize = GetHostSize();
Left = Math.Floor((appSize.Width - res.Width) / 2);
if(FlowDirection == FlowDirection.RightToLeft) Left = Left + res.Width;
Top = Math.Floor((appSize.Height - res.Height) / 2);
if(Top < 0) Top = 0;
if(Left < 0) Left = 0;
}
}
Size GetHostSize() {
return new Size(
Application.Current.Host.Content.ActualWidth / Application.Current.Host.Content.ZoomFactor,
Application.Current.Host.Content.ActualHeight / Application.Current.Host.Content.ZoomFactor);
}
protected virtual void PropertyChangedTitle() { }
protected virtual void PropertyChangedLeft() {
if(IsVisible)
Popup.HorizontalOffset = Left;
}
protected virtual void PropertyChangedTop() {
if(IsVisible)
Popup.VerticalOffset = Top;
}
protected virtual void PropertyChangedCloseOnEscape() { }
protected virtual bool RaiseClosing() {
closingEventArgs = new CancelEventArgs();
OnClosing(closingEventArgs);
return !closingEventArgs.Cancel;
}
protected virtual void OnClosing(CancelEventArgs e) {
if(Closing != null)
Closing(this, closingEventArgs);
}
protected virtual void RaiseClosed() {
if(Closed != null)
Closed(this, EventArgs.Empty);
}
protected virtual void RaiseActivated() {
if(Activated != null)
Activated(this, EventArgs.Empty);
}
protected virtual void RaiseOpened() {
if(Opened != null)
Opened(this, EventArgs.Empty);
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Xml;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.Collections.Specialized;
using System.Threading;
using System.Net;
namespace Oranikle.Report.Engine
{
///<summary>
/// Represents an image. Source of image can from database, external or embedded.
///</summary>
[Serializable]
public class Image : ReportItem
{
ImageSourceEnum _ImageSource; // Identifies the source of the image:
Expression _Value; // See Source. Expected datatype is string or
// binary, depending on Source. If the Value is
// null, no image is displayed.
Expression _MIMEType; // (string) An expression, the value of which is the
// MIMEType for the image.
// Valid values are: image/bmp, image/jpeg,
// image/gif, image/png, image/x-png
// Required if Source = Database. Ignored otherwise.
ImageSizingEnum _Sizing; // Defines the behavior if the image does not fit within the specified size.
bool _ConstantImage; // true if Image is a constant at runtime
public Image(ReportDefn r, ReportLink p, XmlNode xNode):base(r,p,xNode)
{
_ImageSource=ImageSourceEnum.Unknown;
_Value=null;
_MIMEType=null;
_Sizing=ImageSizingEnum.AutoSize;
_ConstantImage = false;
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "Source":
_ImageSource = Oranikle.Report.Engine.ImageSource.GetStyle(xNodeLoop.InnerText);
break;
case "Value":
_Value = new Expression(r, this, xNodeLoop, ExpressionType.Variant);
break;
case "MIMEType":
_MIMEType = new Expression(r, this, xNodeLoop, ExpressionType.String);
break;
case "Sizing":
_Sizing = ImageSizing.GetStyle(xNodeLoop.InnerText, OwnerReport.rl);
break;
default:
if (ReportItemElement(xNodeLoop)) // try at ReportItem level
break;
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown Image element " + xNodeLoop.Name + " ignored.");
break;
}
}
if (_ImageSource==ImageSourceEnum.Unknown)
OwnerReport.rl.LogError(8, "Image requires a Source element.");
if (_Value == null)
OwnerReport.rl.LogError(8, "Image requires the Value element.");
}
// Handle parsing of function in final pass
override public void FinalPass()
{
base.FinalPass();
_Value.FinalPass();
if (_MIMEType != null)
_MIMEType.FinalPass();
_ConstantImage = this.IsConstant();
return;
}
// Returns true if the image and style remain constant at runtime
bool IsConstant()
{
if (_Value.IsConstant())
{
if (_MIMEType == null || _MIMEType.IsConstant())
{
// if (this.Style == null || this.Style.ConstantStyle)
// return true;
return true; // ok if style changes
}
}
return false;
}
override public void Run(IPresent ip, Row row)
{
base.Run(ip, row);
string mtype=null;
Stream strm=null;
try
{
strm = GetImageStream(ip.Report(), row, out mtype);
ip.Image(this, row, mtype, strm);
}
catch
{
// image failed to load; continue processing
}
finally
{
if (strm != null)
strm.Close();
}
return;
}
override public void RunPage(Pages pgs, Row row)
{
Report r = pgs.Report;
bool bHidden = IsHidden(r, row);
WorkClass wc = GetWC(r);
string mtype=null;
Stream strm=null;
System.Drawing.Image im=null;
SetPagePositionBegin(pgs);
if (bHidden)
{
PageImage pi = new PageImage(ImageFormat.Jpeg, null, 0, 0);
this.SetPagePositionAndStyle(r, pi, row);
SetPagePositionEnd(pgs, pi.Y + pi.H);
return;
}
if (wc.PgImage != null)
{ // have we already generated this one
// reuse most of the work; only position will likely change
PageImage pi = new PageImage(wc.PgImage.ImgFormat, wc.PgImage.ImageData, wc.PgImage.SamplesW, wc.PgImage.SamplesH);
pi.Name = wc.PgImage.Name; // this is name it will be shared under
pi.Sizing = this._Sizing;
this.SetPagePositionAndStyle(r, pi, row);
pgs.CurrentPage.AddObject(pi);
SetPagePositionEnd(pgs, pi.Y + pi.H);
return;
}
try
{
strm = GetImageStream(r, row, out mtype);
if (strm == null)
{
r.rl.LogError(4, string.Format("Unable to load image {0}.", this.Name.Nm));
return;
}
im = System.Drawing.Image.FromStream(strm);
int height = im.Height;
int width = im.Width;
MemoryStream ostrm = new MemoryStream();
// 140208AJM Better JPEG Encoding
ImageFormat imf;
// if (mtype.ToLower() == "image/jpeg") //TODO: how do we get png to work
// imf = ImageFormat.Jpeg;
// else
imf = ImageFormat.Jpeg;
System.Drawing.Imaging.ImageCodecInfo[] info;
info = ImageCodecInfo.GetImageEncoders();
EncoderParameters encoderParameters;
encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, ImageQualityManager.EmbeddedImageQuality);
System.Drawing.Imaging.ImageCodecInfo codec = null;
for (int i = 0; i < info.Length; i++)
{
if (info[i].FormatDescription == "JPEG")
{
codec = info[i];
break;
}
}
im.Save(ostrm, codec, encoderParameters);
// im.Save(ostrm, imf, encoderParameters);
//END 140208AJM
byte[] ba = ostrm.ToArray();
ostrm.Close();
PageImage pi = new PageImage(imf, ba, width, height);
pi.Sizing = this._Sizing;
this.SetPagePositionAndStyle(r, pi, row);
pgs.CurrentPage.AddObject(pi);
if (_ConstantImage)
{
wc.PgImage = pi;
// create unique name; PDF generation uses this to optimize the saving of the image only once
pi.Name = "pi" + Interlocked.Increment(ref Parser.Counter).ToString(); // create unique name
}
SetPagePositionEnd(pgs, pi.Y + pi.H);
}
catch (Exception e)
{
// image failed to load, continue processing
r.rl.LogError(4, "Image load failed. " + e.Message);
}
finally
{
if (strm != null)
strm.Close();
if (im != null)
im.Dispose();
}
return;
}
Stream GetImageStream(Report rpt, Row row, out string mtype)
{
mtype=null;
Stream strm=null;
try
{
switch (this.ImageSource)
{
case ImageSourceEnum.Database:
if (_MIMEType == null)
return null;
mtype = _MIMEType.EvaluateString(rpt, row);
object o = _Value.Evaluate(rpt, row);
strm = new MemoryStream((byte[]) o);
break;
case ImageSourceEnum.Embedded:
string name = _Value.EvaluateString(rpt, row);
EmbeddedImage ei = (EmbeddedImage) OwnerReport.LUEmbeddedImages[name];
mtype = ei.MIMEType;
byte[] ba = Convert.FromBase64String(ei.ImageData);
strm = new MemoryStream(ba);
break;
case ImageSourceEnum.External:
string fname = _Value.EvaluateString(rpt, row);
mtype = GetMimeType(fname);
if (fname.StartsWith("http:") ||
fname.StartsWith("file:") ||
fname.StartsWith("https:"))
{
WebRequest wreq = WebRequest.Create(fname);
WebResponse wres = wreq.GetResponse();
strm = wres.GetResponseStream();
}
else
strm = new FileStream(fname, System.IO.FileMode.Open, FileAccess.Read);
break;
default:
return null;
}
}
catch (Exception e)
{
if (strm != null)
{
strm.Close();
strm = null;
}
rpt.rl.LogError(4, string.Format("Unable to load image. {0}", e.Message));
}
return strm;
}
public ImageSourceEnum ImageSource
{
get { return _ImageSource; }
set { _ImageSource = value; }
}
public Expression Value
{
get { return _Value; }
set { _Value = value; }
}
public Expression MIMEType
{
get { return _MIMEType; }
set { _MIMEType = value; }
}
public ImageSizingEnum Sizing
{
get { return _Sizing; }
set { _Sizing = value; }
}
public bool ConstantImage
{
get { return _ConstantImage; }
}
static public string GetMimeType(string file)
{
String fileExt;
int startPos = file.LastIndexOf(".") + 1;
fileExt = file.Substring(startPos).ToLower();
switch (fileExt)
{
case "bmp":
return "image/bmp";
case "jpeg":
case "jpe":
case "jpg":
case "jfif":
return "image/jpeg";
case "gif":
return "image/gif";
case "png":
return "image/png";
case "tif":
case "tiff":
return "image/tiff";
default:
return null;
}
}
private WorkClass GetWC(Report rpt)
{
WorkClass wc = rpt.Cache.Get(this, "wc") as WorkClass;
if (wc == null)
{
wc = new WorkClass();
rpt.Cache.Add(this, "wc", wc);
}
return wc;
}
private void RemoveImageWC(Report rpt)
{
rpt.Cache.Remove(this, "wc");
}
class WorkClass
{
public PageImage PgImage; // When ConstantImage is true this will save the PageImage for reuse
public WorkClass()
{
PgImage=null;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Search.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Search.Fluent.Models;
using Microsoft.Azure.Management.Search.Fluent.SearchService.Definition;
using Microsoft.Rest;
internal partial class SearchServicesImpl
{
/// <summary>
/// Begins a definition for a new resource.
/// This is the beginning of the builder pattern used to create top level resources
/// in Azure. The final method completing the definition and starting the actual resource creation
/// process in Azure is Creatable.create().
/// Note that the Creatable.create() method is
/// only available at the stage of the resource definition that has the minimum set of input
/// parameters specified. If you do not see Creatable.create() among the available methods, it
/// means you have not yet specified all the required input settings. Input settings generally begin
/// with the word "with", for example: <code>.withNewResourceGroup()</code> and return the next stage
/// of the resource definition, as an interface in the "fluent interface" style.
/// </summary>
/// <param name="name">The name of the new resource.</param>
/// <return>The first stage of the new resource definition.</return>
SearchService.Definition.IBlank Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsCreating<SearchService.Definition.IBlank>.Define(string name)
{
return this.Define(name);
}
/// <summary>
/// Lists resources of the specified type in the specified resource group.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group to list the resources from.</param>
/// <return>The list of resources.</return>
System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.Search.Fluent.ISearchService> Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsListingByResourceGroup<Microsoft.Azure.Management.Search.Fluent.ISearchService>.ListByResourceGroup(string resourceGroupName)
{
return this.ListByResourceGroup(resourceGroupName);
}
/// <summary>
/// Checks if Search service name is valid and is not in use asynchronously.
/// </summary>
/// <param name="name">The Search service name to check.</param>
/// <return>A representation of the deferred computation of this call, returning whether the name is available or other info if not.</return>
async Task<Microsoft.Azure.Management.Search.Fluent.ICheckNameAvailabilityResult> Microsoft.Azure.Management.Search.Fluent.ISearchServices.CheckNameAvailabilityAsync(string name, CancellationToken cancellationToken)
{
return await this.CheckNameAvailabilityAsync(name, cancellationToken);
}
/// <summary>
/// Returns the list of query API keys for the given Azure Search service.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group within the current subscription. You can obtain this value from the Azure Resource Manager API or the portal.</param>
/// <param name="searchServiceName">The name of the Azure Search service associated with the specified resource group.</param>
/// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws>
/// <return>A representation of the future computation of this call.</return>
async Task<IEnumerable<Microsoft.Azure.Management.Search.Fluent.IQueryKey>> Microsoft.Azure.Management.Search.Fluent.ISearchServices.ListQueryKeysAsync(string resourceGroupName, string searchServiceName, CancellationToken cancellationToken)
{
return await this.ListQueryKeysAsync(resourceGroupName, searchServiceName, cancellationToken);
}
/// <summary>
/// Gets the primary and secondary admin API keys for the specified Azure Search service.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group within the current subscription; you can obtain this value from the Azure Resource Manager API or the portal.</param>
/// <param name="searchServiceName">The name of the Azure Search service associated with the specified resource group.</param>
/// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws>
/// <throws>CloudException thrown if the request is rejected by server.</throws>
/// <throws>RuntimeException all other wrapped checked exceptions if the request fails to be sent.</throws>
/// <return>The AdminKeys object if successful.</return>
Microsoft.Azure.Management.Search.Fluent.IAdminKeys Microsoft.Azure.Management.Search.Fluent.ISearchServices.GetAdminKeys(string resourceGroupName, string searchServiceName)
{
return this.GetAdminKeys(resourceGroupName, searchServiceName);
}
/// <summary>
/// Checks if the specified Search service name is valid and available.
/// </summary>
/// <param name="name">The Search service name to check.</param>
/// <return>Whether the name is available and other info if not.</return>
Microsoft.Azure.Management.Search.Fluent.ICheckNameAvailabilityResult Microsoft.Azure.Management.Search.Fluent.ISearchServices.CheckNameAvailability(string name)
{
return this.CheckNameAvailability(name);
}
/// <summary>
/// Returns the list of query API keys for the given Azure Search service.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group within the current subscription; you can obtain this value from the Azure Resource Manager API or the portal.</param>
/// <param name="searchServiceName">The name of the Azure Search service associated with the specified resource group.</param>
/// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws>
/// <throws>CloudException thrown if the request is rejected by server.</throws>
/// <throws>RuntimeException all other wrapped checked exceptions if the request fails to be sent.</throws>
/// <return>The List<QueryKey> object if successful.</return>
System.Collections.Generic.IReadOnlyList<Microsoft.Azure.Management.Search.Fluent.IQueryKey> Microsoft.Azure.Management.Search.Fluent.ISearchServices.ListQueryKeys(string resourceGroupName, string searchServiceName)
{
return this.ListQueryKeys(resourceGroupName, searchServiceName);
}
/// <summary>
/// Regenerates either the primary or secondary admin API key. You can only regenerate one key at a time.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group within the current subscription. You can obtain this value from the Azure Resource Manager API or the portal.</param>
/// <param name="searchServiceName">The name of the Azure Search service associated with the specified resource group.</param>
/// <param name="name">The name of the new query API key.</param>
/// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws>
/// <return>A representation of the future computation of this call.</return>
async Task<Microsoft.Azure.Management.Search.Fluent.IQueryKey> Microsoft.Azure.Management.Search.Fluent.ISearchServices.CreateQueryKeyAsync(string resourceGroupName, string searchServiceName, string name, CancellationToken cancellationToken)
{
return await this.CreateQueryKeyAsync(resourceGroupName, searchServiceName, name, cancellationToken);
}
/// <summary>
/// Deletes the specified query key. Unlike admin keys, query keys are not regenerated. The process for
/// regenerating a query key is to delete and then recreate it.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group within the current subscription. You can obtain this value from the Azure Resource Manager API or the portal.</param>
/// <param name="searchServiceName">The name of the Azure Search service associated with the specified resource group.</param>
/// <param name="key">The query key to be deleted. Query keys are identified by value, not by name.</param>
/// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws>
/// <throws>CloudException thrown if the request is rejected by server.</throws>
/// <throws>RuntimeException all other wrapped checked exceptions if the request fails to be sent.</throws>
void Microsoft.Azure.Management.Search.Fluent.ISearchServices.DeleteQueryKey(string resourceGroupName, string searchServiceName, string key)
{
this.DeleteQueryKey(resourceGroupName, searchServiceName, key);
}
/// <summary>
/// Gets the primary and secondary admin API keys for the specified Azure Search service.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group within the current subscription; you can obtain this value from the Azure Resource Manager API or the portal.</param>
/// <param name="searchServiceName">The name of the Azure Search service associated with the specified resource group.</param>
/// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws>
/// <return>A representation of the future computation of this call.</return>
async Task<Microsoft.Azure.Management.Search.Fluent.IAdminKeys> Microsoft.Azure.Management.Search.Fluent.ISearchServices.GetAdminKeysAsync(string resourceGroupName, string searchServiceName, CancellationToken cancellationToken)
{
return await this.GetAdminKeysAsync(resourceGroupName, searchServiceName, cancellationToken);
}
/// <summary>
/// Regenerates either the primary or secondary admin API key. You can only regenerate one key at a time.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group within the current subscription. You can obtain this value from the Azure Resource Manager API or the portal.</param>
/// <param name="searchServiceName">The name of the Azure Search service associated with the specified resource group.</param>
/// <param name="keyKind">
/// Specifies which key to regenerate. Valid values include 'primary' and 'secondary'.
/// Possible values include: 'primary', 'secondary'.
/// </param>
/// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws>
/// <return>The observable to the AdminKeyResultInner object.</return>
async Task<Microsoft.Azure.Management.Search.Fluent.IAdminKeys> Microsoft.Azure.Management.Search.Fluent.ISearchServices.RegenerateAdminKeysAsync(string resourceGroupName, string searchServiceName, AdminKeyKind keyKind, CancellationToken cancellationToken)
{
return await this.RegenerateAdminKeysAsync(resourceGroupName, searchServiceName, keyKind, cancellationToken);
}
/// <summary>
/// Regenerates either the primary or secondary admin API key. You can only regenerate one key at a time.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group within the current subscription. You can obtain this value from the Azure Resource Manager API or the portal.</param>
/// <param name="searchServiceName">The name of the Azure Search service associated with the specified resource group.</param>
/// <param name="name">The name of the new query API key.</param>
/// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws>
/// <throws>CloudException thrown if the request is rejected by server.</throws>
/// <throws>RuntimeException all other wrapped checked exceptions if the request fails to be sent.</throws>
/// <return>The QueryKey object if successful.</return>
Microsoft.Azure.Management.Search.Fluent.IQueryKey Microsoft.Azure.Management.Search.Fluent.ISearchServices.CreateQueryKey(string resourceGroupName, string searchServiceName, string name)
{
return this.CreateQueryKey(resourceGroupName, searchServiceName, name);
}
/// <summary>
/// Deletes the specified query key. Unlike admin keys, query keys are not regenerated. The process for
/// regenerating a query key is to delete and then recreate it.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group within the current subscription. You can obtain this value from the Azure Resource Manager API or the portal.</param>
/// <param name="searchServiceName">The name of the Azure Search service associated with the specified resource group.</param>
/// <param name="key">The query key to be deleted. Query keys are identified by value, not by name.</param>
/// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws>
/// <return>A representation of the future computation of this call.</return>
async Task Microsoft.Azure.Management.Search.Fluent.ISearchServices.DeleteQueryKeyAsync(string resourceGroupName, string searchServiceName, string key, CancellationToken cancellationToken)
{
await this.DeleteQueryKeyAsync(resourceGroupName, searchServiceName, key, cancellationToken);
}
/// <summary>
/// Regenerates either the primary or secondary admin API key. You can only regenerate one key at a time.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group within the current subscription. You can obtain this value from the Azure Resource Manager API or the portal.</param>
/// <param name="searchServiceName">The name of the Azure Search service associated with the specified resource group.</param>
/// <param name="keyKind">
/// Specifies which key to regenerate. Valid values include 'primary' and 'secondary'.
/// Possible values include: 'primary', 'secondary'.
/// </param>
/// <throws>IllegalArgumentException thrown if parameters fail the validation.</throws>
/// <throws>CloudException thrown if the request is rejected by server.</throws>
/// <throws>RuntimeException all other wrapped checked exceptions if the request fails to be sent.</throws>
/// <return>The AdminKeys object if successful.</return>
Microsoft.Azure.Management.Search.Fluent.IAdminKeys Microsoft.Azure.Management.Search.Fluent.ISearchServices.RegenerateAdminKeys(string resourceGroupName, string searchServiceName, AdminKeyKind keyKind)
{
return this.RegenerateAdminKeys(resourceGroupName, searchServiceName, keyKind);
}
/// <summary>
/// Lists all the resources of the specified type in the currently selected subscription.
/// </summary>
/// <return>List of resources.</return>
async Task<Microsoft.Azure.Management.ResourceManager.Fluent.Core.IPagedCollection<ISearchService>> Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsListing<Microsoft.Azure.Management.Search.Fluent.ISearchService>.ListAsync(bool loadAllPages, CancellationToken cancellationToken)
{
return await this.ListAsync(loadAllPages, cancellationToken);
}
/// <summary>
/// Lists all the resources of the specified type in the currently selected subscription.
/// </summary>
/// <return>List of resources.</return>
System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.Search.Fluent.ISearchService> Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsListing<Microsoft.Azure.Management.Search.Fluent.ISearchService>.List()
{
return this.List();
}
}
}
| |
using System;
#if HasITuple
using System.Runtime.CompilerServices;
#endif
namespace Prometheus.Client
{
public static class GaugeExtensions
{
public static void Inc(this IGauge gauge, double increment, DateTimeOffset timestamp)
{
gauge.Inc(increment, timestamp.ToUnixTimeMilliseconds());
}
public static void IncTo(this IGauge gauge, double value, DateTimeOffset timestamp)
{
gauge.IncTo(value, timestamp.ToUnixTimeMilliseconds());
}
public static void Inc(this IMetricFamily<IGauge> metricFamily, double increment = 1)
{
metricFamily.Unlabelled.Inc(increment);
}
public static void Inc(this IMetricFamily<IGauge> metricFamily, double increment, long timestamp)
{
metricFamily.Unlabelled.Inc(increment, timestamp);
}
public static void Inc(this IMetricFamily<IGauge> metricFamily, double increment, DateTimeOffset timestamp)
{
metricFamily.Unlabelled.Inc(increment, timestamp.ToUnixTimeMilliseconds());
}
public static void IncTo(this IMetricFamily<IGauge> metricFamily, double value)
{
metricFamily.Unlabelled.IncTo(value);
}
public static void IncTo(this IMetricFamily<IGauge> metricFamily, double value, long timestamp)
{
metricFamily.Unlabelled.IncTo(value, timestamp);
}
public static void IncTo(this IMetricFamily<IGauge> metricFamily, double value, DateTimeOffset timestamp)
{
metricFamily.Unlabelled.IncTo(value, timestamp.ToUnixTimeMilliseconds());
}
public static void Dec(this IGauge gauge, double decrement, DateTimeOffset timestamp)
{
gauge.Dec(decrement, timestamp.ToUnixTimeMilliseconds());
}
public static void DecTo(this IGauge gauge, double value, DateTimeOffset timestamp)
{
gauge.DecTo(value, timestamp.ToUnixTimeMilliseconds());
}
public static void Dec(this IMetricFamily<IGauge> metricFamily, double decrement = 1)
{
metricFamily.Unlabelled.Dec(decrement);
}
public static void Dec(this IMetricFamily<IGauge> metricFamily, double decrement, long timestamp)
{
metricFamily.Unlabelled.Dec(decrement, timestamp);
}
public static void Dec(this IMetricFamily<IGauge> metricFamily, double decrement, DateTimeOffset timestamp)
{
metricFamily.Unlabelled.Dec(decrement, timestamp);
}
public static void DecTo(this IMetricFamily<IGauge> metricFamily, double value)
{
metricFamily.Unlabelled.DecTo(value);
}
public static void DecTo(this IMetricFamily<IGauge> metricFamily, double value, long timestamp)
{
metricFamily.Unlabelled.DecTo(value, timestamp);
}
public static void DecTo(this IMetricFamily<IGauge> metricFamily, double value, DateTimeOffset timestamp)
{
metricFamily.Unlabelled.DecTo(value, timestamp);
}
public static void Set(this IGauge gauge, double val, DateTimeOffset timestamp)
{
gauge.Set(val, timestamp.ToUnixTimeMilliseconds());
}
public static void Set(this IMetricFamily<IGauge> metricFamily, double value)
{
metricFamily.Unlabelled.Set(value);
}
public static void Set(this IMetricFamily<IGauge> metricFamily, double value, long timestamp)
{
metricFamily.Unlabelled.Set(value, timestamp);
}
public static void Set(this IMetricFamily<IGauge> metricFamily, double value, DateTimeOffset timestamp)
{
metricFamily.Unlabelled.Set(value, timestamp);
}
public static void Inc<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double increment = 1)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.Inc(increment);
}
public static void Inc<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double increment, long timestamp)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.Inc(increment, timestamp);
}
public static void Inc<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double increment, DateTimeOffset timestamp)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.Inc(increment, timestamp);
}
public static void IncTo<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double value)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.IncTo(value);
}
public static void IncTo<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double value, long timestamp)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.IncTo(value, timestamp);
}
public static void IncTo<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double value, DateTimeOffset timestamp)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.IncTo(value, timestamp);
}
public static void Dec<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double decrement = 1)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.Dec(decrement);
}
public static void Dec<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double decrement, long timestamp)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.Dec(decrement, timestamp);
}
public static void Dec<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double decrement, DateTimeOffset timestamp)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.Dec(decrement, timestamp);
}
public static void DecTo<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double value)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.DecTo(value);
}
public static void DecTo<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double value, long timestamp)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.DecTo(value, timestamp);
}
public static void DecTo<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double value, DateTimeOffset timestamp)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.DecTo(value, timestamp);
}
public static void Set<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double value)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.Set(value);
}
public static void Set<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double value, long timestamp)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.Set(value, timestamp);
}
public static void Set<TLabels>(this IMetricFamily<IGauge, TLabels> metricFamily, double value, DateTimeOffset timestamp)
#if HasITuple
where TLabels : struct, ITuple, IEquatable<TLabels>
#else
where TLabels : struct, IEquatable<TLabels>
#endif
{
metricFamily.Unlabelled.Set(value, timestamp);
}
public static IMetricFamily<IGauge, ValueTuple<string>> CreateGauge(this IMetricFactory factory, string name, string help, string labelName, bool includeTimestamp = false)
{
return factory.CreateGauge(name, help, ValueTuple.Create(labelName), includeTimestamp);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.IO
{
/// <summary>Provides an implementation of FileSystem for Unix systems.</summary>
internal sealed partial class UnixFileSystem : FileSystem
{
public override int MaxPath { get { return Interop.libc.MaxPath; } }
public override int MaxDirectoryPath { get { return Interop.libc.MaxPath; } }
public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent);
}
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
// Note: we could consider using sendfile here, but it isn't part of the POSIX spec, and
// has varying degrees of support on different systems.
// The destination path may just be a directory into which the file should be copied.
// If it is, append the filename from the source onto the destination directory
if (DirectoryExists(destFullPath))
{
destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));
}
// Copy the contents of the file from the source to the destination, creating the destination in the process
const int bufferSize = FileStream.DefaultBufferSize;
const bool useAsync = false;
using (Stream src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync))
using (Stream dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))
{
src.CopyTo(dst);
}
// Now copy over relevant read/write/execute permissions from the source to the destination
Interop.Sys.FileStatus status;
while (Interop.CheckIo(Interop.Sys.Stat(sourceFullPath, out status), sourceFullPath)) ;
int newMode = status.Mode & (int)Interop.Sys.Permissions.Mask;
while (Interop.CheckIo(Interop.Sys.ChMod(destFullPath, newMode), destFullPath)) ;
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
// The desired behavior for Move(source, dest) is to not overwrite the destination file
// if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,
// link/unlink are used instead. Note that the Unix FileSystemWatcher will treat a Move
// as a Creation and Deletion instead of a Rename and thus differ from Windows.
while (Interop.Sys.Link(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EINTR) // interrupted; try again
{
continue;
}
else if (errorInfo.Error == Interop.Error.EXDEV) // rename fails across devices / mount points
{
CopyFile(sourceFullPath, destFullPath, overwrite: false);
break;
}
else if (errorInfo.Error == Interop.Error.ENOENT && !Directory.Exists(Path.GetDirectoryName(destFullPath))) // The parent directory of destFile can't be found
{
// Windows distinguishes between whether the directory or the file isn't found,
// and throws a different exception in these cases. We attempt to approximate that
// here; there is a race condition here, where something could change between
// when the error occurs and our checks, but it's the best we can do, and the
// worst case in such a race condition (which could occur if the file system is
// being manipulated concurrently with these checks) is that we throw a
// FileNotFoundException instead of DirectoryNotFoundexception.
throw Interop.GetExceptionForIoErrno(errorInfo, destFullPath, isDirectory: true);
}
else
{
throw Interop.GetExceptionForIoErrno(errorInfo);
}
}
DeleteFile(sourceFullPath);
}
public override void DeleteFile(string fullPath)
{
while (Interop.Sys.Unlink(fullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EINTR) // interrupted; try again
{
continue;
}
else if (errorInfo.Error == Interop.Error.ENOENT) // already doesn't exist; nop
{
break;
}
else
{
if (errorInfo.Error == Interop.Error.EISDIR)
errorInfo = Interop.Error.EACCES.Info();
throw Interop.GetExceptionForIoErrno(errorInfo, fullPath);
}
}
}
public override void CreateDirectory(string fullPath)
{
// NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))
{
length--;
}
// For paths that are only // or ///
if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
{
throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
}
// We can save a bunch of work if the directory we want to create already exists.
if (DirectoryExists(fullPath))
{
return;
}
// Attempt to figure out which directories don't exist, and only create the ones we need.
bool somepathexists = false;
Stack<string> stackDir = new Stack<string>();
int lengthRoot = PathInternal.GetRootLength(fullPath);
if (length > lengthRoot)
{
int i = length - 1;
while (i >= lengthRoot && !somepathexists)
{
string dir = fullPath.Substring(0, i + 1);
if (!DirectoryExists(dir)) // Create only the ones missing
{
stackDir.Push(dir);
}
else
{
somepathexists = true;
}
while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
{
i--;
}
i--;
}
}
int count = stackDir.Count;
if (count == 0 && !somepathexists)
{
string root = Directory.InternalGetDirectoryRoot(fullPath);
if (!DirectoryExists(root))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
return;
}
// Create all the directories
int result = 0;
Interop.ErrorInfo firstError = default(Interop.ErrorInfo);
string errorString = fullPath;
while (stackDir.Count > 0)
{
string name = stackDir.Pop();
if (name.Length >= MaxDirectoryPath)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
Interop.ErrorInfo errorInfo = default(Interop.ErrorInfo);
while ((result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.S_IRWXU)) < 0 && (errorInfo = Interop.Sys.GetLastErrorInfo()).Error == Interop.Error.EINTR) ;
if (result < 0 && firstError.Error == 0)
{
// While we tried to avoid creating directories that don't
// exist above, there are a few cases that can fail, e.g.
// a race condition where another process or thread creates
// the directory first, or there's a file at the location.
if (errorInfo.Error != Interop.Error.EEXIST)
{
firstError = errorInfo;
}
else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))
{
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
firstError = errorInfo;
errorString = name;
}
}
}
// Only throw an exception if creating the exact directory we wanted failed to work correctly.
if (result < 0 && firstError.Error != 0)
{
throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
}
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
while (Interop.Sys.Rename(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EINTR: // interrupted; try again
continue;
case Interop.Error.EACCES: // match Win32 exception
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno);
default:
throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true);
}
}
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
if (!DirectoryExists(fullPath))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
RemoveDirectoryInternal(fullPath, recursive, throwOnTopLevelDirectoryNotFound: true);
}
private void RemoveDirectoryInternal(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
Exception firstException = null;
if (recursive)
{
try
{
foreach (string item in EnumeratePaths(fullPath, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
{
if (!ShouldIgnoreDirectory(Path.GetFileName(item)))
{
try
{
if (DirectoryExists(item))
{
RemoveDirectoryInternal(item, recursive, throwOnTopLevelDirectoryNotFound: false);
}
else
{
DeleteFile(item);
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
}
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
if (firstException != null)
{
throw firstException;
}
}
while (Interop.Sys.RmDir(fullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EINTR: // interrupted; try again
continue;
case Interop.Error.EACCES:
case Interop.Error.EPERM:
case Interop.Error.EROFS:
case Interop.Error.EISDIR:
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); // match Win32 exception
case Interop.Error.ENOENT:
if (!throwOnTopLevelDirectoryNotFound)
{
return;
}
goto default;
default:
throw Interop.GetExceptionForIoErrno(errorInfo, fullPath, isDirectory: true);
}
}
}
public override bool DirectoryExists(string fullPath)
{
Interop.ErrorInfo ignored;
return DirectoryExists(fullPath, out ignored);
}
private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo)
{
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo);
}
public override bool FileExists(string fullPath)
{
Interop.ErrorInfo ignored;
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFREG, out ignored);
}
private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo)
{
Interop.Sys.FileStatus fileinfo;
while (true)
{
errorInfo = default(Interop.ErrorInfo);
int result = Interop.Sys.Stat(fullPath, out fileinfo);
if (result < 0)
{
errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EINTR)
{
continue;
}
return false;
}
return (fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == fileType;
}
}
public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p);
}
public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
switch (searchTarget)
{
case SearchTarget.Files:
return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new FileInfo(path, null));
case SearchTarget.Directories:
return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new DirectoryInfo(path, null));
default:
return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ?
(FileSystemInfo)new DirectoryInfo(path, null) :
(FileSystemInfo)new FileInfo(path, null));
}
}
private sealed class FileSystemEnumerable<T> : IEnumerable<T>
{
private readonly PathPair _initialDirectory;
private readonly string _searchPattern;
private readonly SearchOption _searchOption;
private readonly bool _includeFiles;
private readonly bool _includeDirectories;
private readonly Func<string, bool, T> _translateResult;
private IEnumerator<T> _firstEnumerator;
internal FileSystemEnumerable(
string userPath, string searchPattern,
SearchOption searchOption, SearchTarget searchTarget,
Func<string, bool, T> translateResult)
{
// Basic validation of the input path
if (userPath == null)
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrWhiteSpace(userPath))
{
throw new ArgumentException(SR.Argument_EmptyPath, "path");
}
// Validate and normalize the search pattern. If after doing so it's empty,
// matching Win32 behavior we can skip all additional validation and effectively
// return an empty enumerable.
searchPattern = NormalizeSearchPattern(searchPattern);
if (searchPattern.Length > 0)
{
PathHelpers.CheckSearchPattern(searchPattern);
PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern);
// If the search pattern contains any paths, make sure we factor those into
// the user path, and then trim them off.
int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (lastSlash >= 0)
{
if (lastSlash >= 1)
{
userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash));
}
searchPattern = searchPattern.Substring(lastSlash + 1);
}
string fullPath = Path.GetFullPath(userPath);
// Store everything for the enumerator
_initialDirectory = new PathPair(userPath, fullPath);
_searchPattern = searchPattern;
_searchOption = searchOption;
_includeFiles = (searchTarget & SearchTarget.Files) != 0;
_includeDirectories = (searchTarget & SearchTarget.Directories) != 0;
_translateResult = translateResult;
}
// Open the first enumerator so that any errors are propagated synchronously.
_firstEnumerator = Enumerate();
}
public IEnumerator<T> GetEnumerator()
{
return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private IEnumerator<T> Enumerate()
{
return Enumerate(
_initialDirectory.FullPath != null ?
OpenDirectory(_initialDirectory.FullPath) :
null);
}
private IEnumerator<T> Enumerate(Microsoft.Win32.SafeHandles.SafeDirectoryHandle dirHandle)
{
if (dirHandle == null)
{
// Empty search
yield break;
}
Debug.Assert(!dirHandle.IsInvalid);
Debug.Assert(!dirHandle.IsClosed);
// Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories
// Lazily-initialized only if we find subdirectories that will be explored.
Stack<PathPair> toExplore = null;
PathPair dirPath = _initialDirectory;
while (dirHandle != null)
{
try
{
// Read each entry from the enumerator
Interop.Sys.DirectoryEntry dirent;
while (Interop.Sys.ReadDir(dirHandle, out dirent) == 0)
{
// Get from the dir entry whether the entry is a file or directory.
// We classify everything as a file unless we know it to be a directory.
bool isDir;
if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR)
{
// We know it's a directory.
isDir = true;
}
else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN)
{
// It's a symlink or unknown: stat to it to see if we can resolve it to a directory.
// If we can't (e.g.symlink to a file, broken symlink, etc.), we'll just treat it as a file.
Interop.ErrorInfo errnoIgnored;
isDir = DirectoryExists(Path.Combine(dirPath.FullPath, dirent.InodeName), out errnoIgnored);
}
else
{
// Otherwise, treat it as a file. This includes regular files, FIFOs, etc.
isDir = false;
}
// Yield the result if the user has asked for it. In the case of directories,
// always explore it by pushing it onto the stack, regardless of whether
// we're returning directories.
if (isDir)
{
if (!ShouldIgnoreDirectory(dirent.InodeName))
{
string userPath = null;
if (_searchOption == SearchOption.AllDirectories)
{
if (toExplore == null)
{
toExplore = new Stack<PathPair>();
}
userPath = Path.Combine(dirPath.UserPath, dirent.InodeName);
toExplore.Push(new PathPair(userPath, Path.Combine(dirPath.FullPath, dirent.InodeName)));
}
if (_includeDirectories &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(userPath ?? Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/true);
}
}
}
else if (_includeFiles &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/false);
}
}
}
finally
{
// Close the directory enumerator
dirHandle.Dispose();
dirHandle = null;
}
if (toExplore != null && toExplore.Count > 0)
{
// Open the next directory.
dirPath = toExplore.Pop();
dirHandle = OpenDirectory(dirPath.FullPath);
}
}
}
private static string NormalizeSearchPattern(string searchPattern)
{
if (searchPattern == "." || searchPattern == "*.*")
{
searchPattern = "*";
}
else if (PathHelpers.EndsInDirectorySeparator(searchPattern))
{
searchPattern += "*";
}
return searchPattern;
}
private static Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDirectory(string fullPath)
{
Microsoft.Win32.SafeHandles.SafeDirectoryHandle handle = Interop.Sys.OpenDir(fullPath);
if (handle.IsInvalid)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true);
}
return handle;
}
}
/// <summary>Determines whether the specified directory name should be ignored.</summary>
/// <param name="name">The name to evaluate.</param>
/// <returns>true if the name is "." or ".."; otherwise, false.</returns>
private static bool ShouldIgnoreDirectory(string name)
{
return name == "." || name == "..";
}
public override string GetCurrentDirectory()
{
return Interop.libc.getcwd();
}
public override void SetCurrentDirectory(string fullPath)
{
while (Interop.CheckIo(Interop.Sys.ChDir(fullPath), fullPath)) ;
}
public override FileAttributes GetAttributes(string fullPath)
{
return new FileInfo(fullPath, null).Attributes;
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
new FileInfo(fullPath, null).Attributes = attributes;
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
return new FileInfo(fullPath, null).CreationTime;
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.CreationTime = time;
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
return new FileInfo(fullPath, null).LastAccessTime;
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastAccessTime = time;
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
return new FileInfo(fullPath, null).LastWriteTime;
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastWriteTime = time;
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/devtools/clouderrorreporting/v1beta1/report_errors_service.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.ErrorReporting.V1Beta1 {
/// <summary>Holder for reflection information generated from google/devtools/clouderrorreporting/v1beta1/report_errors_service.proto</summary>
public static partial class ReportErrorsServiceReflection {
#region Descriptor
/// <summary>File descriptor for google/devtools/clouderrorreporting/v1beta1/report_errors_service.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ReportErrorsServiceReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ckdnb29nbGUvZGV2dG9vbHMvY2xvdWRlcnJvcnJlcG9ydGluZy92MWJldGEx",
"L3JlcG9ydF9lcnJvcnNfc2VydmljZS5wcm90bxIrZ29vZ2xlLmRldnRvb2xz",
"LmNsb3VkZXJyb3JyZXBvcnRpbmcudjFiZXRhMRocZ29vZ2xlL2FwaS9hbm5v",
"dGF0aW9ucy5wcm90bxo4Z29vZ2xlL2RldnRvb2xzL2Nsb3VkZXJyb3JyZXBv",
"cnRpbmcvdjFiZXRhMS9jb21tb24ucHJvdG8aH2dvb2dsZS9wcm90b2J1Zi90",
"aW1lc3RhbXAucHJvdG8ifwoXUmVwb3J0RXJyb3JFdmVudFJlcXVlc3QSFAoM",
"cHJvamVjdF9uYW1lGAEgASgJEk4KBWV2ZW50GAIgASgLMj8uZ29vZ2xlLmRl",
"dnRvb2xzLmNsb3VkZXJyb3JyZXBvcnRpbmcudjFiZXRhMS5SZXBvcnRlZEVy",
"cm9yRXZlbnQiGgoYUmVwb3J0RXJyb3JFdmVudFJlc3BvbnNlIvcBChJSZXBv",
"cnRlZEVycm9yRXZlbnQSLgoKZXZlbnRfdGltZRgBIAEoCzIaLmdvb2dsZS5w",
"cm90b2J1Zi5UaW1lc3RhbXASVAoPc2VydmljZV9jb250ZXh0GAIgASgLMjsu",
"Z29vZ2xlLmRldnRvb2xzLmNsb3VkZXJyb3JyZXBvcnRpbmcudjFiZXRhMS5T",
"ZXJ2aWNlQ29udGV4dBIPCgdtZXNzYWdlGAMgASgJEkoKB2NvbnRleHQYBCAB",
"KAsyOS5nb29nbGUuZGV2dG9vbHMuY2xvdWRlcnJvcnJlcG9ydGluZy52MWJl",
"dGExLkVycm9yQ29udGV4dDL4AQoTUmVwb3J0RXJyb3JzU2VydmljZRLgAQoQ",
"UmVwb3J0RXJyb3JFdmVudBJELmdvb2dsZS5kZXZ0b29scy5jbG91ZGVycm9y",
"cmVwb3J0aW5nLnYxYmV0YTEuUmVwb3J0RXJyb3JFdmVudFJlcXVlc3QaRS5n",
"b29nbGUuZGV2dG9vbHMuY2xvdWRlcnJvcnJlcG9ydGluZy52MWJldGExLlJl",
"cG9ydEVycm9yRXZlbnRSZXNwb25zZSI/gtPkkwI5IjAvdjFiZXRhMS97cHJv",
"amVjdF9uYW1lPXByb2plY3RzLyp9L2V2ZW50czpyZXBvcnQ6BWV2ZW50QvkB",
"Ci9jb20uZ29vZ2xlLmRldnRvb2xzLmNsb3VkZXJyb3JyZXBvcnRpbmcudjFi",
"ZXRhMUIYUmVwb3J0RXJyb3JzU2VydmljZVByb3RvUAFaXmdvb2dsZS5nb2xh",
"bmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvZGV2dG9vbHMvY2xvdWRlcnJv",
"cnJlcG9ydGluZy92MWJldGExO2Nsb3VkZXJyb3JyZXBvcnRpbmeqAiNHb29n",
"bGUuQ2xvdWQuRXJyb3JSZXBvcnRpbmcuVjFCZXRhMcoCI0dvb2dsZVxDbG91",
"ZFxFcnJvclJlcG9ydGluZ1xWMWJldGExYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Cloud.ErrorReporting.V1Beta1.CommonReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ErrorReporting.V1Beta1.ReportErrorEventRequest), global::Google.Cloud.ErrorReporting.V1Beta1.ReportErrorEventRequest.Parser, new[]{ "ProjectName", "Event" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ErrorReporting.V1Beta1.ReportErrorEventResponse), global::Google.Cloud.ErrorReporting.V1Beta1.ReportErrorEventResponse.Parser, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.ErrorReporting.V1Beta1.ReportedErrorEvent), global::Google.Cloud.ErrorReporting.V1Beta1.ReportedErrorEvent.Parser, new[]{ "EventTime", "ServiceContext", "Message", "Context" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A request for reporting an individual error event.
/// </summary>
public sealed partial class ReportErrorEventRequest : pb::IMessage<ReportErrorEventRequest> {
private static readonly pb::MessageParser<ReportErrorEventRequest> _parser = new pb::MessageParser<ReportErrorEventRequest>(() => new ReportErrorEventRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReportErrorEventRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ErrorReporting.V1Beta1.ReportErrorsServiceReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReportErrorEventRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReportErrorEventRequest(ReportErrorEventRequest other) : this() {
projectName_ = other.projectName_;
Event = other.event_ != null ? other.Event.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReportErrorEventRequest Clone() {
return new ReportErrorEventRequest(this);
}
/// <summary>Field number for the "project_name" field.</summary>
public const int ProjectNameFieldNumber = 1;
private string projectName_ = "";
/// <summary>
/// [Required] The resource name of the Google Cloud Platform project. Written
/// as `projects/` plus the
/// [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840).
/// Example: `projects/my-project-123`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectName {
get { return projectName_; }
set {
projectName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "event" field.</summary>
public const int EventFieldNumber = 2;
private global::Google.Cloud.ErrorReporting.V1Beta1.ReportedErrorEvent event_;
/// <summary>
/// [Required] The error event to be reported.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.ErrorReporting.V1Beta1.ReportedErrorEvent Event {
get { return event_; }
set {
event_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReportErrorEventRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReportErrorEventRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ProjectName != other.ProjectName) return false;
if (!object.Equals(Event, other.Event)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ProjectName.Length != 0) hash ^= ProjectName.GetHashCode();
if (event_ != null) hash ^= Event.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 (ProjectName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ProjectName);
}
if (event_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Event);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ProjectName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectName);
}
if (event_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Event);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReportErrorEventRequest other) {
if (other == null) {
return;
}
if (other.ProjectName.Length != 0) {
ProjectName = other.ProjectName;
}
if (other.event_ != null) {
if (event_ == null) {
event_ = new global::Google.Cloud.ErrorReporting.V1Beta1.ReportedErrorEvent();
}
Event.MergeFrom(other.Event);
}
}
[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: {
ProjectName = input.ReadString();
break;
}
case 18: {
if (event_ == null) {
event_ = new global::Google.Cloud.ErrorReporting.V1Beta1.ReportedErrorEvent();
}
input.ReadMessage(event_);
break;
}
}
}
}
}
/// <summary>
/// Response for reporting an individual error event.
/// Data may be added to this message in the future.
/// </summary>
public sealed partial class ReportErrorEventResponse : pb::IMessage<ReportErrorEventResponse> {
private static readonly pb::MessageParser<ReportErrorEventResponse> _parser = new pb::MessageParser<ReportErrorEventResponse>(() => new ReportErrorEventResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReportErrorEventResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ErrorReporting.V1Beta1.ReportErrorsServiceReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReportErrorEventResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReportErrorEventResponse(ReportErrorEventResponse other) : this() {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReportErrorEventResponse Clone() {
return new ReportErrorEventResponse(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReportErrorEventResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReportErrorEventResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
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) {
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReportErrorEventResponse other) {
if (other == null) {
return;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
/// <summary>
/// An error event which is reported to the Error Reporting system.
/// </summary>
public sealed partial class ReportedErrorEvent : pb::IMessage<ReportedErrorEvent> {
private static readonly pb::MessageParser<ReportedErrorEvent> _parser = new pb::MessageParser<ReportedErrorEvent>(() => new ReportedErrorEvent());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReportedErrorEvent> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.ErrorReporting.V1Beta1.ReportErrorsServiceReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReportedErrorEvent() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReportedErrorEvent(ReportedErrorEvent other) : this() {
EventTime = other.eventTime_ != null ? other.EventTime.Clone() : null;
ServiceContext = other.serviceContext_ != null ? other.ServiceContext.Clone() : null;
message_ = other.message_;
Context = other.context_ != null ? other.Context.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReportedErrorEvent Clone() {
return new ReportedErrorEvent(this);
}
/// <summary>Field number for the "event_time" field.</summary>
public const int EventTimeFieldNumber = 1;
private global::Google.Protobuf.WellKnownTypes.Timestamp eventTime_;
/// <summary>
/// [Optional] Time when the event occurred.
/// If not provided, the time when the event was received by the
/// Error Reporting system will be used.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp EventTime {
get { return eventTime_; }
set {
eventTime_ = value;
}
}
/// <summary>Field number for the "service_context" field.</summary>
public const int ServiceContextFieldNumber = 2;
private global::Google.Cloud.ErrorReporting.V1Beta1.ServiceContext serviceContext_;
/// <summary>
/// [Required] The service context in which this error has occurred.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.ErrorReporting.V1Beta1.ServiceContext ServiceContext {
get { return serviceContext_; }
set {
serviceContext_ = value;
}
}
/// <summary>Field number for the "message" field.</summary>
public const int MessageFieldNumber = 3;
private string message_ = "";
/// <summary>
/// [Required] A message describing the error. The message can contain an
/// exception stack in one of the supported programming languages and formats.
/// In that case, the message is parsed and detailed exception information
/// is returned when retrieving the error event again.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Message {
get { return message_; }
set {
message_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "context" field.</summary>
public const int ContextFieldNumber = 4;
private global::Google.Cloud.ErrorReporting.V1Beta1.ErrorContext context_;
/// <summary>
/// [Optional] A description of the context in which the error occurred.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.ErrorReporting.V1Beta1.ErrorContext Context {
get { return context_; }
set {
context_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReportedErrorEvent);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReportedErrorEvent other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(EventTime, other.EventTime)) return false;
if (!object.Equals(ServiceContext, other.ServiceContext)) return false;
if (Message != other.Message) return false;
if (!object.Equals(Context, other.Context)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (eventTime_ != null) hash ^= EventTime.GetHashCode();
if (serviceContext_ != null) hash ^= ServiceContext.GetHashCode();
if (Message.Length != 0) hash ^= Message.GetHashCode();
if (context_ != null) hash ^= Context.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 (eventTime_ != null) {
output.WriteRawTag(10);
output.WriteMessage(EventTime);
}
if (serviceContext_ != null) {
output.WriteRawTag(18);
output.WriteMessage(ServiceContext);
}
if (Message.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Message);
}
if (context_ != null) {
output.WriteRawTag(34);
output.WriteMessage(Context);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (eventTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EventTime);
}
if (serviceContext_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ServiceContext);
}
if (Message.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Message);
}
if (context_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Context);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReportedErrorEvent other) {
if (other == null) {
return;
}
if (other.eventTime_ != null) {
if (eventTime_ == null) {
eventTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
EventTime.MergeFrom(other.EventTime);
}
if (other.serviceContext_ != null) {
if (serviceContext_ == null) {
serviceContext_ = new global::Google.Cloud.ErrorReporting.V1Beta1.ServiceContext();
}
ServiceContext.MergeFrom(other.ServiceContext);
}
if (other.Message.Length != 0) {
Message = other.Message;
}
if (other.context_ != null) {
if (context_ == null) {
context_ = new global::Google.Cloud.ErrorReporting.V1Beta1.ErrorContext();
}
Context.MergeFrom(other.Context);
}
}
[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 (eventTime_ == null) {
eventTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(eventTime_);
break;
}
case 18: {
if (serviceContext_ == null) {
serviceContext_ = new global::Google.Cloud.ErrorReporting.V1Beta1.ServiceContext();
}
input.ReadMessage(serviceContext_);
break;
}
case 26: {
Message = input.ReadString();
break;
}
case 34: {
if (context_ == null) {
context_ = new global::Google.Cloud.ErrorReporting.V1Beta1.ErrorContext();
}
input.ReadMessage(context_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
//---------------------------------------------------------------------------
//
// <copyright file="LinearKeyFrames.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This class is used as part of a ByteKeyFrameCollection in
/// conjunction with a KeyFrameByteAnimation to animate a
/// Byte property value along a set of key frames.
///
/// This ByteKeyFrame interpolates the between the Byte Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearByteKeyFrame : ByteKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearByteKeyFrame.
/// </summary>
public LinearByteKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearByteKeyFrame.
/// </summary>
public LinearByteKeyFrame(Byte value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearByteKeyFrame.
/// </summary>
public LinearByteKeyFrame(Byte value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearByteKeyFrame();
}
#endregion
#region ByteKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Byte InterpolateValueCore(Byte baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateByte(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a ColorKeyFrameCollection in
/// conjunction with a KeyFrameColorAnimation to animate a
/// Color property value along a set of key frames.
///
/// This ColorKeyFrame interpolates the between the Color Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearColorKeyFrame : ColorKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearColorKeyFrame.
/// </summary>
public LinearColorKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearColorKeyFrame.
/// </summary>
public LinearColorKeyFrame(Color value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearColorKeyFrame.
/// </summary>
public LinearColorKeyFrame(Color value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearColorKeyFrame();
}
#endregion
#region ColorKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Color InterpolateValueCore(Color baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateColor(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a DecimalKeyFrameCollection in
/// conjunction with a KeyFrameDecimalAnimation to animate a
/// Decimal property value along a set of key frames.
///
/// This DecimalKeyFrame interpolates the between the Decimal Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearDecimalKeyFrame : DecimalKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearDecimalKeyFrame.
/// </summary>
public LinearDecimalKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearDecimalKeyFrame.
/// </summary>
public LinearDecimalKeyFrame(Decimal value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearDecimalKeyFrame.
/// </summary>
public LinearDecimalKeyFrame(Decimal value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearDecimalKeyFrame();
}
#endregion
#region DecimalKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Decimal InterpolateValueCore(Decimal baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateDecimal(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a DoubleKeyFrameCollection in
/// conjunction with a KeyFrameDoubleAnimation to animate a
/// Double property value along a set of key frames.
///
/// This DoubleKeyFrame interpolates the between the Double Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearDoubleKeyFrame : DoubleKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearDoubleKeyFrame.
/// </summary>
public LinearDoubleKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearDoubleKeyFrame.
/// </summary>
public LinearDoubleKeyFrame(Double value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearDoubleKeyFrame.
/// </summary>
public LinearDoubleKeyFrame(Double value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearDoubleKeyFrame();
}
#endregion
#region DoubleKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Double InterpolateValueCore(Double baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateDouble(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a Int16KeyFrameCollection in
/// conjunction with a KeyFrameInt16Animation to animate a
/// Int16 property value along a set of key frames.
///
/// This Int16KeyFrame interpolates the between the Int16 Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearInt16KeyFrame : Int16KeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearInt16KeyFrame.
/// </summary>
public LinearInt16KeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearInt16KeyFrame.
/// </summary>
public LinearInt16KeyFrame(Int16 value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearInt16KeyFrame.
/// </summary>
public LinearInt16KeyFrame(Int16 value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearInt16KeyFrame();
}
#endregion
#region Int16KeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Int16 InterpolateValueCore(Int16 baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateInt16(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a Int32KeyFrameCollection in
/// conjunction with a KeyFrameInt32Animation to animate a
/// Int32 property value along a set of key frames.
///
/// This Int32KeyFrame interpolates the between the Int32 Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearInt32KeyFrame : Int32KeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearInt32KeyFrame.
/// </summary>
public LinearInt32KeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearInt32KeyFrame.
/// </summary>
public LinearInt32KeyFrame(Int32 value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearInt32KeyFrame.
/// </summary>
public LinearInt32KeyFrame(Int32 value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearInt32KeyFrame();
}
#endregion
#region Int32KeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Int32 InterpolateValueCore(Int32 baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateInt32(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a Int64KeyFrameCollection in
/// conjunction with a KeyFrameInt64Animation to animate a
/// Int64 property value along a set of key frames.
///
/// This Int64KeyFrame interpolates the between the Int64 Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearInt64KeyFrame : Int64KeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearInt64KeyFrame.
/// </summary>
public LinearInt64KeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearInt64KeyFrame.
/// </summary>
public LinearInt64KeyFrame(Int64 value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearInt64KeyFrame.
/// </summary>
public LinearInt64KeyFrame(Int64 value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearInt64KeyFrame();
}
#endregion
#region Int64KeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Int64 InterpolateValueCore(Int64 baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateInt64(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a PointKeyFrameCollection in
/// conjunction with a KeyFramePointAnimation to animate a
/// Point property value along a set of key frames.
///
/// This PointKeyFrame interpolates the between the Point Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearPointKeyFrame : PointKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearPointKeyFrame.
/// </summary>
public LinearPointKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearPointKeyFrame.
/// </summary>
public LinearPointKeyFrame(Point value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearPointKeyFrame.
/// </summary>
public LinearPointKeyFrame(Point value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearPointKeyFrame();
}
#endregion
#region PointKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Point InterpolateValueCore(Point baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolatePoint(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a Point3DKeyFrameCollection in
/// conjunction with a KeyFramePoint3DAnimation to animate a
/// Point3D property value along a set of key frames.
///
/// This Point3DKeyFrame interpolates the between the Point3D Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearPoint3DKeyFrame : Point3DKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearPoint3DKeyFrame.
/// </summary>
public LinearPoint3DKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearPoint3DKeyFrame.
/// </summary>
public LinearPoint3DKeyFrame(Point3D value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearPoint3DKeyFrame.
/// </summary>
public LinearPoint3DKeyFrame(Point3D value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearPoint3DKeyFrame();
}
#endregion
#region Point3DKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Point3D InterpolateValueCore(Point3D baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolatePoint3D(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a QuaternionKeyFrameCollection in
/// conjunction with a KeyFrameQuaternionAnimation to animate a
/// Quaternion property value along a set of key frames.
///
/// This QuaternionKeyFrame interpolates the between the Quaternion Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearQuaternionKeyFrame : QuaternionKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearQuaternionKeyFrame.
/// </summary>
public LinearQuaternionKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearQuaternionKeyFrame.
/// </summary>
public LinearQuaternionKeyFrame(Quaternion value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearQuaternionKeyFrame.
/// </summary>
public LinearQuaternionKeyFrame(Quaternion value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearQuaternionKeyFrame();
}
#endregion
#region QuaternionKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Quaternion InterpolateValueCore(Quaternion baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateQuaternion(baseValue, Value, keyFrameProgress, UseShortestPath);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a Rotation3DKeyFrameCollection in
/// conjunction with a KeyFrameRotation3DAnimation to animate a
/// Rotation3D property value along a set of key frames.
///
/// This Rotation3DKeyFrame interpolates the between the Rotation3D Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearRotation3DKeyFrame : Rotation3DKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearRotation3DKeyFrame.
/// </summary>
public LinearRotation3DKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearRotation3DKeyFrame.
/// </summary>
public LinearRotation3DKeyFrame(Rotation3D value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearRotation3DKeyFrame.
/// </summary>
public LinearRotation3DKeyFrame(Rotation3D value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearRotation3DKeyFrame();
}
#endregion
#region Rotation3DKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Rotation3D InterpolateValueCore(Rotation3D baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateRotation3D(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a RectKeyFrameCollection in
/// conjunction with a KeyFrameRectAnimation to animate a
/// Rect property value along a set of key frames.
///
/// This RectKeyFrame interpolates the between the Rect Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearRectKeyFrame : RectKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearRectKeyFrame.
/// </summary>
public LinearRectKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearRectKeyFrame.
/// </summary>
public LinearRectKeyFrame(Rect value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearRectKeyFrame.
/// </summary>
public LinearRectKeyFrame(Rect value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearRectKeyFrame();
}
#endregion
#region RectKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Rect InterpolateValueCore(Rect baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateRect(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a SingleKeyFrameCollection in
/// conjunction with a KeyFrameSingleAnimation to animate a
/// Single property value along a set of key frames.
///
/// This SingleKeyFrame interpolates the between the Single Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearSingleKeyFrame : SingleKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearSingleKeyFrame.
/// </summary>
public LinearSingleKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearSingleKeyFrame.
/// </summary>
public LinearSingleKeyFrame(Single value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearSingleKeyFrame.
/// </summary>
public LinearSingleKeyFrame(Single value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearSingleKeyFrame();
}
#endregion
#region SingleKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Single InterpolateValueCore(Single baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateSingle(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a SizeKeyFrameCollection in
/// conjunction with a KeyFrameSizeAnimation to animate a
/// Size property value along a set of key frames.
///
/// This SizeKeyFrame interpolates the between the Size Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearSizeKeyFrame : SizeKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearSizeKeyFrame.
/// </summary>
public LinearSizeKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearSizeKeyFrame.
/// </summary>
public LinearSizeKeyFrame(Size value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearSizeKeyFrame.
/// </summary>
public LinearSizeKeyFrame(Size value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearSizeKeyFrame();
}
#endregion
#region SizeKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Size InterpolateValueCore(Size baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateSize(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a VectorKeyFrameCollection in
/// conjunction with a KeyFrameVectorAnimation to animate a
/// Vector property value along a set of key frames.
///
/// This VectorKeyFrame interpolates the between the Vector Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearVectorKeyFrame : VectorKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearVectorKeyFrame.
/// </summary>
public LinearVectorKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearVectorKeyFrame.
/// </summary>
public LinearVectorKeyFrame(Vector value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearVectorKeyFrame.
/// </summary>
public LinearVectorKeyFrame(Vector value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearVectorKeyFrame();
}
#endregion
#region VectorKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Vector InterpolateValueCore(Vector baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateVector(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a Vector3DKeyFrameCollection in
/// conjunction with a KeyFrameVector3DAnimation to animate a
/// Vector3D property value along a set of key frames.
///
/// This Vector3DKeyFrame interpolates the between the Vector3D Value of
/// the previous key frame and its own Value linearly to produce its output value.
/// </summary>
public partial class LinearVector3DKeyFrame : Vector3DKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new LinearVector3DKeyFrame.
/// </summary>
public LinearVector3DKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new LinearVector3DKeyFrame.
/// </summary>
public LinearVector3DKeyFrame(Vector3D value)
: base(value)
{
}
/// <summary>
/// Creates a new LinearVector3DKeyFrame.
/// </summary>
public LinearVector3DKeyFrame(Vector3D value, KeyTime keyTime)
: base(value, keyTime)
{
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new LinearVector3DKeyFrame();
}
#endregion
#region Vector3DKeyFrame
/// <summary>
/// Implemented to linearly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Vector3D InterpolateValueCore(Vector3D baseValue, double keyFrameProgress)
{
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateVector3D(baseValue, Value, keyFrameProgress);
}
}
#endregion
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using NodaTime.Globalization;
using NodaTime.Properties;
using NodaTime.Text.Patterns;
using NodaTime.Utility;
using JetBrains.Annotations;
namespace NodaTime.Text
{
internal sealed class OffsetPatternParser : IPatternParser<Offset>
{
private static readonly Dictionary<char, CharacterHandler<Offset, OffsetParseBucket>> PatternCharacterHandlers =
new Dictionary<char, CharacterHandler<Offset, OffsetParseBucket>>
{
{ '%', SteppedPatternBuilder<Offset, OffsetParseBucket>.HandlePercent },
{ '\'', SteppedPatternBuilder<Offset, OffsetParseBucket>.HandleQuote },
{ '\"', SteppedPatternBuilder<Offset, OffsetParseBucket>.HandleQuote },
{ '\\', SteppedPatternBuilder<Offset, OffsetParseBucket>.HandleBackslash },
{ ':', (pattern, builder) => builder.AddLiteral(builder.FormatInfo.TimeSeparator, ParseResult<Offset>.TimeSeparatorMismatch) },
{ 'h', (pattern, builder) => { throw new InvalidPatternException(Messages.Parse_Hour12PatternNotSupported, typeof(Offset)); } },
{ 'H', SteppedPatternBuilder<Offset, OffsetParseBucket>.HandlePaddedField
(2, PatternFields.Hours24, 0, 23, GetPositiveHours, (bucket, value) => bucket.Hours = value) },
{ 'm', SteppedPatternBuilder<Offset, OffsetParseBucket>.HandlePaddedField
(2, PatternFields.Minutes, 0, 59, GetPositiveMinutes, (bucket, value) => bucket.Minutes = value) },
{ 's', SteppedPatternBuilder<Offset, OffsetParseBucket>.HandlePaddedField
(2, PatternFields.Seconds, 0, 59, GetPositiveSeconds, (bucket, value) => bucket.Seconds = value) },
{ '+', HandlePlus },
{ '-', HandleMinus },
{ 'Z', (ignored1, ignored2) => { throw new InvalidPatternException(Messages.Parse_ZPrefixNotAtStartOfPattern); } }
};
// These are used to compute the individual (always-positive) components of an offset.
// For example, an offset of "three and a half hours behind UTC" would have a "positive hours" value
// of 3, and a "positive minutes" value of 30. The sign is computed elsewhere.
private static int GetPositiveHours(Offset offset) => Math.Abs(offset.Milliseconds) / NodaConstants.MillisecondsPerHour;
private static int GetPositiveMinutes(Offset offset) => (Math.Abs(offset.Milliseconds) % NodaConstants.MillisecondsPerHour) / NodaConstants.MillisecondsPerMinute;
private static int GetPositiveSeconds(Offset offset) => (Math.Abs(offset.Milliseconds) % NodaConstants.MillisecondsPerMinute) / NodaConstants.MillisecondsPerSecond;
// Note: public to implement the interface. It does no harm, and it's simpler than using explicit
// interface implementation.
public IPattern<Offset> ParsePattern(string patternText, NodaFormatInfo formatInfo) => ParsePartialPattern(patternText, formatInfo);
private IPartialPattern<Offset> ParsePartialPattern(string patternText, NodaFormatInfo formatInfo)
{
// Nullity check is performed in OffsetPattern.
if (patternText.Length == 0)
{
throw new InvalidPatternException(Messages.Parse_FormatStringEmpty);
}
if (patternText.Length == 1)
{
switch (patternText)
{
case "g":
return CreateGeneralPattern(formatInfo);
case "G":
return new ZPrefixPattern(CreateGeneralPattern(formatInfo));
case "l":
patternText = formatInfo.OffsetPatternLong;
break;
case "m":
patternText = formatInfo.OffsetPatternMedium;
break;
case "s":
patternText = formatInfo.OffsetPatternShort;
break;
default:
throw new InvalidPatternException(Messages.Parse_UnknownStandardFormat, patternText, typeof(Offset));
}
}
// This is the only way we'd normally end up in custom parsing land for Z on its own.
if (patternText == "%Z")
{
throw new InvalidPatternException(Messages.Parse_EmptyZPrefixedOffsetPattern);
}
// Handle Z-prefix by stripping it, parsing the rest as a normal pattern, then building a special pattern
// which decides whether or not to delegate.
bool zPrefix = patternText.StartsWith("Z");
var patternBuilder = new SteppedPatternBuilder<Offset, OffsetParseBucket>(formatInfo, () => new OffsetParseBucket());
patternBuilder.ParseCustomPattern(zPrefix ? patternText.Substring(1) : patternText, PatternCharacterHandlers);
// No need to validate field combinations here, but we do need to do something a bit special
// for Z-handling.
IPartialPattern<Offset> pattern = patternBuilder.Build(Offset.FromHoursAndMinutes(5, 30));
return zPrefix ? new ZPrefixPattern(pattern) : pattern;
}
#region Standard patterns
private IPartialPattern<Offset> CreateGeneralPattern(NodaFormatInfo formatInfo)
{
var patterns = new List<IPartialPattern<Offset>>();
foreach (char c in "lms")
{
patterns.Add(ParsePartialPattern(c.ToString(), formatInfo));
}
Func<Offset, IPartialPattern<Offset>> formatter = value => PickGeneralFormatter(value, patterns);
return new CompositePattern<Offset>(patterns, formatter);
}
private static IPartialPattern<Offset> PickGeneralFormatter(Offset value, List<IPartialPattern<Offset>> patterns)
{
// Note: this relies on the order in ExpandStandardFormatPattern
int index;
// Work out the least significant non-zero part.
int absoluteSeconds = Math.Abs(value.Seconds);
if (absoluteSeconds % NodaConstants.SecondsPerMinute != 0)
{
index = 0;
}
else if ((absoluteSeconds % NodaConstants.SecondsPerHour) / NodaConstants.SecondsPerMinute != 0)
{
index = 1;
}
else
{
index = 2;
}
return patterns[index];
}
#endregion
/// <summary>
/// Pattern which optionally delegates to another, but both parses and formats Offset.Zero as "Z".
/// </summary>
private sealed class ZPrefixPattern : IPartialPattern<Offset>
{
private readonly IPartialPattern<Offset> fullPattern;
internal ZPrefixPattern(IPartialPattern<Offset> fullPattern)
{
this.fullPattern = fullPattern;
}
public ParseResult<Offset> Parse(string text) => text == "Z" ? ParseResult<Offset>.ForValue(Offset.Zero) : fullPattern.Parse(text);
public string Format(Offset value) => value == Offset.Zero ? "Z" : fullPattern.Format(value);
public ParseResult<Offset> ParsePartial(ValueCursor cursor)
{
if (cursor.Current == 'Z')
{
cursor.MoveNext();
return ParseResult<Offset>.ForValue(Offset.Zero);
}
return fullPattern.ParsePartial(cursor);
}
public StringBuilder AppendFormat(Offset value, [NotNull] StringBuilder builder)
{
Preconditions.CheckNotNull(builder, nameof(builder));
return value == Offset.Zero ? builder.Append("Z") : fullPattern.AppendFormat(value, builder);
}
}
#region Character handlers
private static void HandlePlus(PatternCursor pattern, SteppedPatternBuilder<Offset, OffsetParseBucket> builder)
{
builder.AddField(PatternFields.Sign, pattern.Current);
builder.AddRequiredSign((bucket, positive) => bucket.IsNegative = !positive, offset => offset.Milliseconds >= 0);
}
private static void HandleMinus(PatternCursor pattern, SteppedPatternBuilder<Offset, OffsetParseBucket> builder)
{
builder.AddField(PatternFields.Sign, pattern.Current);
builder.AddNegativeOnlySign((bucket, positive) => bucket.IsNegative = !positive, offset => offset.Milliseconds >= 0);
}
#endregion
/// <summary>
/// Provides a container for the interim parsed pieces of an <see cref="Offset" /> value.
/// </summary>
[DebuggerStepThrough]
private sealed class OffsetParseBucket : ParseBucket<Offset>
{
/// <summary>
/// The hours in the range [0, 23].
/// </summary>
internal int Hours;
/// <summary>
/// The minutes in the range [0, 59].
/// </summary>
internal int Minutes;
/// <summary>
/// The seconds in the range [0, 59].
/// </summary>
internal int Seconds;
/// <summary>
/// Gets a value indicating whether this instance is negative.
/// </summary>
/// <value>
/// <c>true</c> if this instance is negative; otherwise, <c>false</c>.
/// </value>
public bool IsNegative;
/// <summary>
/// Calculates the value from the parsed pieces.
/// </summary>
internal override ParseResult<Offset> CalculateValue(PatternFields usedFields, string text)
{
int seconds = Hours * NodaConstants.SecondsPerHour +
Minutes * NodaConstants.SecondsPerMinute +
Seconds;
if (IsNegative)
{
seconds = -seconds;
}
return ParseResult<Offset>.ForValue(Offset.FromSeconds(seconds));
}
}
}
}
| |
using System.Collections.Concurrent;
using Signum.Utilities.Reflection;
using Signum.Engine.Linq;
using System.Data;
using Signum.Entities.Reflection;
using Signum.Entities.Internal;
using Signum.Engine.Connection;
using Microsoft.Data.SqlClient;
namespace Signum.Engine.Cache;
public abstract class CachedTableBase
{
public abstract ITable Table { get; }
public abstract IColumn? ParentColumn { get; set; }
internal List<CachedTableBase>? subTables;
public List<CachedTableBase>? SubTables { get { return subTables; } }
protected SqlPreCommandSimple query = null!;
internal ICacheLogicController controller;
internal CachedTableConstructor Constructor = null!;
internal CachedTableBase(ICacheLogicController controller)
{
this.controller = controller;
}
protected void OnChange(object sender, SqlNotificationEventArgs args)
{
try
{
if (args.Info == SqlNotificationInfo.Invalid &&
args.Source == SqlNotificationSource.Statement &&
args.Type == SqlNotificationType.Subscribe)
throw new InvalidOperationException("Invalid query for SqlDependency") { Data = { { "query", query.PlainSql() } } };
if (args.Info == SqlNotificationInfo.PreviousFire)
throw new InvalidOperationException("The same transaction that loaded the data is invalidating it! Table: {0} SubTables: {1} ".
FormatWith(Table, subTables?.Select(e=>e.Table).ToString(","))) { Data = { { "query", query.PlainSql() } } };
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine("Change {0}".FormatWith(GetType().TypeName()));
Reset();
Interlocked.Increment(ref invalidations);
controller.OnChange(this, args);
}
catch (Exception e)
{
e.LogException();
}
}
public void ResetAll(bool forceReset)
{
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine("ResetAll {0}".FormatWith(GetType().TypeName()));
Reset();
if (forceReset)
{
invalidations = 0;
hits = 0;
loads = 0;
sumLoadTime = 0;
}
else
{
Interlocked.Increment(ref invalidations);
}
if (subTables != null)
foreach (var st in subTables)
st.ResetAll(forceReset);
}
public abstract void SchemaCompleted();
internal void LoadAll()
{
Load();
if (subTables != null)
foreach (var st in subTables)
st.LoadAll();
}
protected abstract void Load();
protected abstract void Reset();
public abstract Type Type { get; }
public abstract int? Count { get; }
int invalidations;
public int Invalidations { get { return invalidations; } }
protected int hits;
public int Hits { get { return hits; } }
int loads;
public int Loads { get { return loads; } }
long sumLoadTime;
public TimeSpan SumLoadTime
{
get { return TimeSpan.FromMilliseconds(sumLoadTime / PerfCounter.FrequencyMilliseconds); }
}
protected IDisposable MeasureLoad()
{
long start = PerfCounter.Ticks;
return new Disposable(() =>
{
sumLoadTime += (PerfCounter.Ticks - start);
Interlocked.Increment(ref loads);
});
}
internal static readonly MethodInfo ToStringMethod = ReflectionTools.GetMethodInfo((object o) => o.ToString());
internal abstract bool Contains(PrimaryKey primaryKey);
}
class CachedTable<T> : CachedTableBase where T : Entity
{
Table table;
ResetLazy<Dictionary<PrimaryKey, object>> rows;
public Dictionary<PrimaryKey, object> GetRows()
{
return rows.Value;
}
Func<FieldReader, object> rowReader;
Action<object, IRetriever, T> completer;
Expression<Action<object, IRetriever, T>> completerExpression;
Func<object, PrimaryKey> idGetter;
Expression<Func<PrimaryKey, string>> toStrGetterExpression = null!;
Func<PrimaryKey, string> toStrGetter = null!;
public override IColumn? ParentColumn { get; set; }
SemiCachedController<T>? semiCachedController;
public CachedTable(ICacheLogicController controller, AliasGenerator? aliasGenerator, string? lastPartialJoin, string? remainingJoins)
: base(controller)
{
this.table = Schema.Current.Table(typeof(T));
CachedTableConstructor ctr = this.Constructor = new CachedTableConstructor(this, aliasGenerator);
var isPostgres = Schema.Current.Settings.IsPostgres;
//Query
using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true }))
{
string select = "SELECT\r\n{0}\r\nFROM {1} {2}\r\n".FormatWith(
Table.Columns.Values.ToString(c => ctr.currentAlias + "." + c.Name.SqlEscape(isPostgres), ",\r\n"),
table.Name.ToString(),
ctr.currentAlias!.ToString());
ctr.remainingJoins = lastPartialJoin == null ? null : lastPartialJoin + ctr.currentAlias + ".Id\r\n" + remainingJoins;
if (ctr.remainingJoins != null)
select += ctr.remainingJoins;
query = new SqlPreCommandSimple(select);
}
//Reader
{
rowReader = ctr.GetRowReader();
}
//Completer
{
ParameterExpression me = Expression.Parameter(typeof(T), "me");
var block = ctr.MaterializeEntity(me, table);
completerExpression = Expression.Lambda<Action<object, IRetriever, T>>(block, CachedTableConstructor.originObject, CachedTableConstructor.retriever, me);
completer = completerExpression.Compile();
idGetter = ctr.GetPrimaryKeyGetter((IColumn)table.PrimaryKey);
}
rows = new ResetLazy<Dictionary<PrimaryKey, object>>(() =>
{
return SqlServerRetry.Retry(() =>
{
CacheLogic.AssertSqlDependencyStarted();
Table table = Connector.Current.Schema.Table(typeof(T));
Dictionary<PrimaryKey, object> result = new Dictionary<PrimaryKey, object>();
using (MeasureLoad())
using (Connector.Override(Connector.Current.ForDatabase(table.Name.Schema?.Database)))
using (var tr = Transaction.ForceNew(IsolationLevel.ReadCommitted))
{
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine("Load {0}".FormatWith(GetType().TypeName()));
Connector.Current.ExecuteDataReaderOptionalDependency(query, OnChange, fr =>
{
object obj = rowReader(fr);
result[idGetter(obj)] = obj; //Could be repeated joins
});
tr.Commit();
}
return result;
});
}, mode: LazyThreadSafetyMode.ExecutionAndPublication);
if(!CacheLogic.WithSqlDependency && lastPartialJoin.HasText()) //Is semi
{
semiCachedController = new SemiCachedController<T>(this);
}
}
public override void SchemaCompleted()
{
toStrGetterExpression = ToStringExpressionVisitor.GetToString<T>(this.Constructor, s => s.ToString());
toStrGetter = toStrGetterExpression.Compile();
if (this.subTables != null)
foreach (var item in this.subTables)
item.SchemaCompleted();
}
protected override void Reset()
{
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine((rows.IsValueCreated ? "RESET {0}" : "Reset {0}").FormatWith(GetType().TypeName()));
rows.Reset();
if (this.BackReferenceDictionaries != null)
{
foreach (var item in this.BackReferenceDictionaries.Values)
{
item.Reset();
}
}
}
protected override void Load()
{
rows.Load();
}
public string GetToString(PrimaryKey id)
{
return toStrGetter(id);
}
public object GetRow(PrimaryKey id)
{
Interlocked.Increment(ref hits);
var origin = this.GetRows().TryGetC(id);
if (origin == null)
throw new EntityNotFoundException(typeof(T), id);
return origin;
}
public string? TryGetToString(PrimaryKey id)
{
Interlocked.Increment(ref hits);
var origin = this.GetRows().TryGetC(id);
if (origin == null)
return null;
return toStrGetter(id);
}
public void Complete(T entity, IRetriever retriever)
{
Interlocked.Increment(ref hits);
var origin = this.GetRows().TryGetC(entity.Id);
if (origin == null)
throw new EntityNotFoundException(typeof(T), entity.Id);
completer(origin, retriever, entity);
var additional = Schema.Current.GetAdditionalBindings(typeof(T));
if(additional != null)
{
foreach (var ab in additional)
ab.SetInMemory(entity, retriever);
}
}
internal IEnumerable<PrimaryKey> GetAllIds()
{
Interlocked.Increment(ref hits);
return this.GetRows().Keys;
}
public override int? Count
{
get { return rows.IsValueCreated ? rows.Value.Count : (int?)null; }
}
public override Type Type
{
get { return typeof(T); }
}
public override ITable Table
{
get { return table; }
}
internal override bool Contains(PrimaryKey primaryKey)
{
return this.GetRows().ContainsKey(primaryKey);
}
ConcurrentDictionary<LambdaExpression, ResetLazy<Dictionary<PrimaryKey, List<PrimaryKey>>>> BackReferenceDictionaries =
new ConcurrentDictionary<LambdaExpression, ResetLazy<Dictionary<PrimaryKey, List<PrimaryKey>>>>(ExpressionComparer.GetComparer<LambdaExpression>(false));
internal Dictionary<PrimaryKey, List<PrimaryKey>> GetBackReferenceDictionary<R>(Expression<Func<T, Lite<R>?>> backReference)
where R : Entity
{
var lazy = BackReferenceDictionaries.GetOrAdd(backReference, br =>
{
var column = GetColumn(Reflector.GetMemberList((Expression<Func<T, Lite<R>>>)br));
var idGetter = this.Constructor.GetPrimaryKeyGetter(table.PrimaryKey);
if (column.Nullable.ToBool())
{
var backReferenceGetter = this.Constructor.GetPrimaryKeyNullableGetter(column);
return new ResetLazy<Dictionary<PrimaryKey, List<PrimaryKey>>>(() =>
{
return this.rows.Value.Values
.Where(a => backReferenceGetter(a) != null)
.GroupToDictionary(a => backReferenceGetter(a)!.Value, a => idGetter(a));
}, LazyThreadSafetyMode.ExecutionAndPublication);
}
else
{
var backReferenceGetter = this.Constructor.GetPrimaryKeyGetter(column);
return new ResetLazy<Dictionary<PrimaryKey, List<PrimaryKey>>>(() =>
{
return this.rows.Value.Values
.GroupToDictionary(a => backReferenceGetter(a), a => idGetter(a));
}, LazyThreadSafetyMode.ExecutionAndPublication);
}
});
return lazy.Value;
}
private IColumn GetColumn(MemberInfo[] members)
{
IFieldFinder? current = (Table)this.Table;
Field? field = null;
for (int i = 0; i < members.Length - 1; i++)
{
if (current == null)
throw new InvalidOperationException("{0} does not implement {1}".FormatWith(field, typeof(IFieldFinder).Name));
field = current.GetField(members[i]);
current = field as IFieldFinder;
}
var lastMember = members[members.Length - 1];
if (lastMember is Type t)
return ((FieldImplementedBy)field!).ImplementationColumns.GetOrThrow(t);
else if (current != null)
return (IColumn)current.GetField(lastMember);
else
throw new InvalidOperationException("Unexpected");
}
}
class CachedTableMList<T> : CachedTableBase
{
public override IColumn? ParentColumn { get; set; }
TableMList table;
ResetLazy<Dictionary<PrimaryKey, Dictionary<PrimaryKey, object>>> relationalRows;
static ParameterExpression result = Expression.Parameter(typeof(T));
Func<FieldReader, object> rowReader;
Expression<Func<object, IRetriever, MList<T>.RowIdElement>> activatorExpression;
Func<object, IRetriever, MList<T>.RowIdElement> activator;
Func<object, PrimaryKey> parentIdGetter;
Func<object, PrimaryKey> rowIdGetter;
public CachedTableMList(ICacheLogicController controller, TableMList table, AliasGenerator? aliasGenerator, string lastPartialJoin, string? remainingJoins)
: base(controller)
{
this.table = table;
var isPostgres = Schema.Current.Settings.IsPostgres;
CachedTableConstructor ctr = this.Constructor= new CachedTableConstructor(this, aliasGenerator);
//Query
using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true }))
{
string select = "SELECT\r\n{0}\r\nFROM {1} {2}\r\n".FormatWith(
ctr.table.Columns.Values.ToString(c => ctr.currentAlias + "." + c.Name.SqlEscape(isPostgres), ",\r\n"),
table.Name.ToString(),
ctr.currentAlias!.ToString());
ctr.remainingJoins = lastPartialJoin + ctr.currentAlias + "." + table.BackReference.Name.SqlEscape(isPostgres) + "\r\n" + remainingJoins;
query = new SqlPreCommandSimple(select);
}
//Reader
{
rowReader = ctr.GetRowReader();
}
//Completer
{
List<Expression> instructions = new List<Expression>
{
Expression.Assign(ctr.origin, Expression.Convert(CachedTableConstructor.originObject, ctr.tupleType)),
Expression.Assign(result, ctr.MaterializeField(table.Field))
};
var ci = typeof(MList<T>.RowIdElement).GetConstructor(new []{typeof(T), typeof(PrimaryKey), typeof(int?)})!;
var order = table.Order == null ? Expression.Constant(null, typeof(int?)) :
ctr.GetTupleProperty(table.Order).Nullify();
instructions.Add(Expression.New(ci, result, CachedTableConstructor.NewPrimaryKey(ctr.GetTupleProperty(table.PrimaryKey)), order));
var block = Expression.Block(typeof(MList<T>.RowIdElement), new[] { ctr.origin, result }, instructions);
activatorExpression = Expression.Lambda<Func<object, IRetriever, MList<T>.RowIdElement>>(block, CachedTableConstructor.originObject, CachedTableConstructor.retriever);
activator = activatorExpression.Compile();
parentIdGetter = ctr.GetPrimaryKeyGetter(table.BackReference);
rowIdGetter = ctr.GetPrimaryKeyGetter(table.PrimaryKey);
}
relationalRows = new ResetLazy<Dictionary<PrimaryKey, Dictionary<PrimaryKey, object>>>(() =>
{
return SqlServerRetry.Retry(() =>
{
CacheLogic.AssertSqlDependencyStarted();
Dictionary<PrimaryKey, Dictionary<PrimaryKey, object>> result = new Dictionary<PrimaryKey, Dictionary<PrimaryKey, object>>();
using (MeasureLoad())
using (Connector.Override(Connector.Current.ForDatabase(table.Name.Schema?.Database)))
using (var tr = Transaction.ForceNew(IsolationLevel.ReadCommitted))
{
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine("Load {0}".FormatWith(GetType().TypeName()));
Connector.Current.ExecuteDataReaderOptionalDependency(query, OnChange, fr =>
{
object obj = rowReader(fr);
PrimaryKey parentId = parentIdGetter(obj);
var dic = result.TryGetC(parentId);
if (dic == null)
result[parentId] = dic = new Dictionary<PrimaryKey, object>();
dic[rowIdGetter(obj)] = obj;
});
tr.Commit();
}
return result;
});
}, mode: LazyThreadSafetyMode.ExecutionAndPublication);
}
protected override void Reset()
{
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine((relationalRows.IsValueCreated ? "RESET {0}" : "Reset {0}").FormatWith(GetType().TypeName()));
relationalRows.Reset();
}
protected override void Load()
{
relationalRows.Load();
}
public MList<T> GetMList(PrimaryKey id, IRetriever retriever)
{
Interlocked.Increment(ref hits);
MList<T> result;
var dic = relationalRows.Value.TryGetC(id);
if (dic == null)
result = new MList<T>();
else
{
result = new MList<T>(dic.Count);
var innerList = ((IMListPrivate<T>)result).InnerList;
foreach (var obj in dic.Values)
{
innerList.Add(activator(obj, retriever));
}
((IMListPrivate)result).ExecutePostRetrieving(null!);
}
CachedTableConstructor.resetModifiedAction(retriever, result);
return result;
}
public override int? Count
{
get { return relationalRows.IsValueCreated ? relationalRows.Value.Count : (int?)null; }
}
public override Type Type
{
get { return typeof(MList<T>); }
}
public override ITable Table
{
get { return table; }
}
internal override bool Contains(PrimaryKey primaryKey)
{
throw new InvalidOperationException("CacheMListTable does not implements contains");
}
public override void SchemaCompleted()
{
if (this.subTables != null)
foreach (var item in this.subTables)
item.SchemaCompleted();
}
}
class CachedLiteTable<T> : CachedTableBase where T : Entity
{
public override IColumn? ParentColumn { get; set; }
Table table;
Alias currentAlias;
string lastPartialJoin;
string? remainingJoins;
Func<FieldReader, KeyValuePair<PrimaryKey, string>> rowReader = null!;
ResetLazy<Dictionary<PrimaryKey, string>> toStrings = null!;
SemiCachedController<T>? semiCachedController;
public CachedLiteTable(ICacheLogicController controller, AliasGenerator aliasGenerator, string lastPartialJoin, string? remainingJoins)
: base(controller)
{
this.table = Schema.Current.Table(typeof(T));
this.lastPartialJoin = lastPartialJoin;
this.remainingJoins = remainingJoins;
this.currentAlias = aliasGenerator.NextTableAlias(table.Name.Name);
if (!CacheLogic.WithSqlDependency)
{
semiCachedController = new SemiCachedController<T>(this);
}
}
public override void SchemaCompleted()
{
List<IColumn> columns = new List<IColumn> { table.PrimaryKey };
ParameterExpression reader = Expression.Parameter(typeof(FieldReader));
var expression = ToStringExpressionVisitor.GetToString(table, reader, columns);
var isPostgres = Schema.Current.Settings.IsPostgres;
//Query
using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true }))
{
string select = "SELECT {0}\r\nFROM {1} {2}\r\n".FormatWith(
columns.ToString(c => currentAlias + "." + c.Name.SqlEscape(isPostgres), ", "),
table.Name.ToString(),
currentAlias.ToString());
select += this.lastPartialJoin + currentAlias + "." + table.PrimaryKey.Name.SqlEscape(isPostgres) + "\r\n" + this.remainingJoins;
query = new SqlPreCommandSimple(select);
}
//Reader
{
var kvpConstructor = Expression.New(CachedTableConstructor.ciKVPIntString,
CachedTableConstructor.NewPrimaryKey(FieldReader.GetExpression(reader, 0, this.table.PrimaryKey.Type)),
expression);
rowReader = Expression.Lambda<Func<FieldReader, KeyValuePair<PrimaryKey, string>>>(kvpConstructor, reader).Compile();
}
toStrings = new ResetLazy<Dictionary<PrimaryKey, string>>(() =>
{
return SqlServerRetry.Retry(() =>
{
CacheLogic.AssertSqlDependencyStarted();
Dictionary<PrimaryKey, string> result = new Dictionary<PrimaryKey, string>();
using (MeasureLoad())
using (Connector.Override(Connector.Current.ForDatabase(table.Name.Schema?.Database)))
using (var tr = Transaction.ForceNew(IsolationLevel.ReadCommitted))
{
if (CacheLogic.LogWriter != null)
CacheLogic.LogWriter.WriteLine("Load {0}".FormatWith(GetType().TypeName()));
Connector.Current.ExecuteDataReaderOptionalDependency(query, OnChange, fr =>
{
var kvp = rowReader(fr);
result[kvp.Key] = kvp.Value;
});
tr.Commit();
}
return result;
});
}, mode: LazyThreadSafetyMode.ExecutionAndPublication);
if (this.subTables != null)
foreach (var item in this.subTables)
item.SchemaCompleted();
}
protected override void Reset()
{
if (toStrings == null)
return;
if (CacheLogic.LogWriter != null )
CacheLogic.LogWriter.WriteLine((toStrings.IsValueCreated ? "RESET {0}" : "Reset {0}").FormatWith(GetType().TypeName()));
toStrings.Reset();
}
protected override void Load()
{
if (toStrings == null)
return;
toStrings.Load();
}
public Lite<T> GetLite(PrimaryKey id, IRetriever retriever)
{
Interlocked.Increment(ref hits);
var lite = (LiteImp<T>)Lite.Create<T>(id, toStrings.Value[id]);
return retriever.ModifiablePostRetrieving(lite)!;
}
public override int? Count
{
get { return toStrings.IsValueCreated ? toStrings.Value.Count : (int?)null; }
}
public override Type Type
{
get { return typeof(Lite<T>); }
}
public override ITable Table
{
get { return table; }
}
class ToStringExpressionVisitor : ExpressionVisitor
{
ParameterExpression param;
ParameterExpression reader;
List<IColumn> columns;
Table table;
public ToStringExpressionVisitor(ParameterExpression param, ParameterExpression reader, List<IColumn> columns, Table table)
{
this.param = param;
this.reader = reader;
this.columns = columns;
this.table = table;
}
public static Expression GetToString(Table table, ParameterExpression reader, List<IColumn> columns)
{
LambdaExpression lambda = ExpressionCleaner.GetFieldExpansion(table.Type, CachedTableBase.ToStringMethod)!;
if (lambda == null)
{
columns.Add(table.ToStrColumn!);
return FieldReader.GetExpression(reader, columns.Count - 1, typeof(string));
}
var cleanLambda = (LambdaExpression)ExpressionCleaner.Clean(lambda, ExpressionEvaluator.PartialEval, shortCircuit: false)!;
ToStringExpressionVisitor toStr = new ToStringExpressionVisitor(
cleanLambda.Parameters.SingleEx(),
reader,
columns,
table
);
var result = toStr.Visit(cleanLambda.Body);
return result;
}
protected override Expression VisitUnary(UnaryExpression node)
{
if (node.NodeType == ExpressionType.Convert)
{
var obj = Visit(node.Operand);
return Expression.Convert(obj, node.Type);
}
return base.VisitUnary(node);
}
static MethodInfo miMixin = ReflectionTools.GetMethodInfo((Entity e) => e.Mixin<MixinEntity>()).GetGenericMethodDefinition();
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression == param)
{
var field = table.GetField(node.Member);
var column = GetColumn(field);
columns.Add(column);
return FieldReader.GetExpression(reader, columns.Count - 1, column.Type);
}
if (node.Expression is MethodCallExpression me && me.Method.IsInstantiationOf(miMixin))
{
var type = me.Method.GetGenericArguments()[0];
var mixin = table.Mixins!.GetOrThrow(type);
var field = mixin.GetField(node.Member);
var column = GetColumn(field);
columns.Add(column);
return FieldReader.GetExpression(reader, columns.Count - 1, column.Type);
}
return base.VisitMember(node);
}
private IColumn GetColumn(Field field)
{
if (field is FieldPrimaryKey || field is FieldValue || field is FieldTicks)
return (IColumn)field;
throw new InvalidOperationException("{0} not supported when caching the ToString for a Lite of a transacional entity ({1})".FormatWith(field.GetType().TypeName(), this.table.Type.TypeName()));
}
}
internal override bool Contains(PrimaryKey primaryKey)
{
return this.toStrings.Value.ContainsKey(primaryKey);
}
}
public class SemiCachedController<T> where T : Entity
{
CachedTableBase cachedTable;
public SemiCachedController(CachedTableBase cachedTable)
{
this.cachedTable = cachedTable;
CacheLogic.semiControllers.GetOrCreate(typeof(T)).Add(cachedTable);
var ee = Schema.Current.EntityEvents<T>();
ee.Saving += ident =>
{
if (ident.IsGraphModified && !ident.IsNew)
{
cachedTable.LoadAll();
if (cachedTable.Contains(ident.Id))
DisableAndInvalidate();
}
};
//ee.PreUnsafeDelete += query => DisableAndInvalidate();
ee.PreUnsafeUpdate += (update, entityQuery) => { DisableAndInvalidateMassive(entityQuery); return null; };
ee.PreUnsafeInsert += (query, constructor, entityQuery) =>
{
if (constructor.Body.Type.IsInstantiationOf(typeof(MListElement<,>)))
DisableAndInvalidateMassive(entityQuery);
return constructor;
};
ee.PreUnsafeMListDelete += (mlistQuery, entityQuery) => { DisableAndInvalidateMassive(entityQuery); return null; };
ee.PreBulkInsert += inMListTable =>
{
if (inMListTable)
DisableAndInvalidateMassive(null);
};
}
public int? MassiveInvalidationCheckLimit = 500;
void DisableAndInvalidateMassive(IQueryable<T>? elements)
{
var asssumeAsInvalidation = CacheLogic.assumeMassiveChangesAsInvalidations.Value?.TryGetS(typeof(T));
if (asssumeAsInvalidation == false)
{
}
else if(asssumeAsInvalidation == true)
{
DisableAndInvalidate();
}
else if (asssumeAsInvalidation == null) //Default
{
if (MassiveInvalidationCheckLimit != null && elements != null)
{
var ids = elements.Select(a => a.Id).Distinct().Take(MassiveInvalidationCheckLimit.Value).ToList();
if (ids.Count == MassiveInvalidationCheckLimit.Value)
throw new InvalidOperationException($"MassiveInvalidationCheckLimit reached when trying to determine if the massive operation will affect the semi-cached instances of {typeof(T).TypeName()}.");
cachedTable.LoadAll();
if (ids.Any(cachedTable.Contains))
DisableAndInvalidate();
else
return;
}
else
{
throw new InvalidOperationException($"Impossible to determine if the massive operation will affect the semi-cached instances of {typeof(T).TypeName()}. Execute CacheLogic.AssumeMassiveChangesAsInvalidations to desanbiguate.");
}
}
}
void DisableAndInvalidate()
{
CacheLogic.DisableAllConnectedTypesInTransaction(this.cachedTable.controller.Type);
Transaction.PostRealCommit -= Transaction_PostRealCommit;
Transaction.PostRealCommit += Transaction_PostRealCommit;
}
void Transaction_PostRealCommit(Dictionary<string, object> obj)
{
cachedTable.ResetAll(forceReset: false);
CacheLogic.NotifyInvalidateAllConnectedTypes(this.cachedTable.controller.Type);
}
}
| |
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
using IOFile = System.IO.File;
namespace Carbon.IO
{
/// <summary>
/// Provides access to NTFS junction points in .Net.
/// </summary>
/// <remarks>Written by Jeff Brown. Taken from http://www.codeproject.com/Articles/15633/Manipulating-NTFS-Junction-Points-in-NET </remarks>
public static class JunctionPoint
{
/// <summary>
/// The file or directory is not a reparse point.
/// </summary>
private const int ERROR_NOT_A_REPARSE_POINT = 4390;
/// <summary>
/// Command to set the reparse point data block.
/// </summary>
private const int FSCTL_SET_REPARSE_POINT = 0x000900A4;
/// <summary>
/// Command to get the reparse point data block.
/// </summary>
private const int FSCTL_GET_REPARSE_POINT = 0x000900A8;
/// <summary>
/// Command to delete the reparse point data base.
/// </summary>
private const int FSCTL_DELETE_REPARSE_POINT = 0x000900AC;
/// <summary>
/// Reparse point tag used to identify mount points and junction points.
/// </summary>
private const uint IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003;
/// <summary>
/// Symbolic link tag used to identify symoblic links.
/// </summary>
internal const uint IO_SYMOBOLIC_LINK_TAG = 0xA000000C;
/// <summary>
/// This prefix indicates to NTFS that the path is to be treated as a non-interpreted
/// path in the virtual file system.
/// </summary>
private const string NonInterpretedPathPrefix = @"\??\";
[Flags]
internal enum EFileAccess : uint
{
GenericRead = 0x80000000,
GenericWrite = 0x40000000,
GenericExecute = 0x20000000,
GenericAll = 0x10000000,
}
[Flags]
private enum EFileShare : uint
{
None = 0x00000000,
Read = 0x00000001,
Write = 0x00000002,
Delete = 0x00000004,
}
private enum ECreationDisposition : uint
{
New = 1,
CreateAlways = 2,
OpenExisting = 3,
OpenAlways = 4,
TruncateExisting = 5,
}
[Flags]
private enum EFileAttributes : uint
{
Readonly = 0x00000001,
Hidden = 0x00000002,
System = 0x00000004,
Directory = 0x00000010,
Archive = 0x00000020,
Device = 0x00000040,
Normal = 0x00000080,
Temporary = 0x00000100,
SparseFile = 0x00000200,
ReparsePoint = 0x00000400,
Compressed = 0x00000800,
Offline = 0x00001000,
NotContentIndexed = 0x00002000,
Encrypted = 0x00004000,
Write_Through = 0x80000000,
Overlapped = 0x40000000,
NoBuffering = 0x20000000,
RandomAccess = 0x10000000,
SequentialScan = 0x08000000,
DeleteOnClose = 0x04000000,
BackupSemantics = 0x02000000,
PosixSemantics = 0x01000000,
OpenReparsePoint = 0x00200000,
OpenNoRecall = 0x00100000,
FirstPipeInstance = 0x00080000
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode,
IntPtr InBuffer, int nInBufferSize,
IntPtr OutBuffer, int nOutBufferSize,
out int pBytesReturned, IntPtr lpOverlapped);
/// <summary>
/// Creates a junction point from the specified directory to the specified target directory.
/// </summary>
/// <remarks>
/// Only works on NTFS.
/// </remarks>
/// <param name="junctionPoint">The junction point path</param>
/// <param name="targetDir">The target directory</param>
/// <param name="overwrite">If true overwrites an existing reparse point or empty directory</param>
/// <exception cref="IOException">Thrown when the junction point could not be created or when
/// an existing directory was found and <paramref name="overwrite" /> if false</exception>
public static void Create(string junctionPoint, string targetDir, bool overwrite)
{
targetDir = System.IO.Path.GetFullPath(targetDir);
if (!Directory.Exists(targetDir))
throw new IOException("Target path does not exist or is not a directory.");
if (Directory.Exists(junctionPoint))
{
if (!overwrite)
throw new IOException("Directory already exists and overwrite parameter is false.");
}
else
{
Directory.CreateDirectory(junctionPoint);
}
using (SafeFileHandle handle = ReparsePoint.OpenReparsePoint(junctionPoint, ReparsePoint.EFileAccess.GenericWrite))
{
byte[] targetDirBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + System.IO.Path.GetFullPath(targetDir));
var reparseDataBuffer = new ReparseData
{
ReparseTag = IO_REPARSE_TAG_MOUNT_POINT,
ReparseDataLength = (ushort) (targetDirBytes.Length + 12),
SubstituteNameOffset = 0,
SubstituteNameLength = (ushort) targetDirBytes.Length,
PrintNameOffset = (ushort) (targetDirBytes.Length + 2),
PrintNameLength = 0,
PathBuffer = new byte[0x3ff0]
};
Array.Copy(targetDirBytes, reparseDataBuffer.PathBuffer, targetDirBytes.Length);
int inBufferSize = Marshal.SizeOf(reparseDataBuffer);
IntPtr inBuffer = Marshal.AllocHGlobal(inBufferSize);
try
{
Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);
int bytesReturned;
bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_SET_REPARSE_POINT,
inBuffer, targetDirBytes.Length + 20, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);
if (!result)
ThrowLastWin32Error("Unable to create junction point.");
}
finally
{
Marshal.FreeHGlobal(inBuffer);
}
}
}
/// <summary>
/// Deletes a junction point at the specified source directory along with the directory itself.
/// Does nothing if the junction point does not exist.
/// </summary>
/// <remarks>
/// Only works on NTFS.
/// </remarks>
/// <param name="junctionPoint">The junction point path</param>
public static void Delete(string junctionPoint)
{
if (!Directory.Exists(junctionPoint))
{
if (IOFile.Exists(junctionPoint))
throw new IOException("Path is not a junction point.");
return;
}
using (SafeFileHandle handle = ReparsePoint.OpenReparsePoint(junctionPoint, ReparsePoint.EFileAccess.GenericWrite))
{
var reparseDataBuffer = new ReparseData
{
ReparseTag = IO_REPARSE_TAG_MOUNT_POINT,
ReparseDataLength = 0,
PathBuffer = new byte[0x3ff0]
};
int inBufferSize = Marshal.SizeOf(reparseDataBuffer);
IntPtr inBuffer = Marshal.AllocHGlobal(inBufferSize);
try
{
Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);
int bytesReturned;
bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_DELETE_REPARSE_POINT,
inBuffer, 8, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);
if (!result)
ThrowLastWin32Error("Unable to delete junction point.");
}
finally
{
Marshal.FreeHGlobal(inBuffer);
}
try
{
Directory.Delete(junctionPoint);
}
catch (IOException ex)
{
throw new IOException("Unable to delete junction point.", ex);
}
}
}
/// <summary>
/// Determines whether the specified path exists and refers to a junction point.
/// </summary>
/// <param name="path">The junction point path</param>
/// <returns>True if the specified path represents a junction point</returns>
/// <exception cref="IOException">Thrown if the specified path is invalid
/// or some other error occurs</exception>
public static bool Exists(string path)
{
if (!Directory.Exists(path))
return false;
var target = ReparsePoint.GetTarget(path);
return target != null;
}
/// <summary>
/// Gets the target of the specified junction point.
/// </summary>
/// <remarks>
/// Only works on NTFS.
/// </remarks>
/// <param name="junctionPoint">The junction point path</param>
/// <returns>The target of the junction point</returns>
/// <exception cref="IOException">Thrown when the specified path does not
/// exist, is invalid, is not a junction point, or some other error occurs</exception>
public static string GetTarget(string junctionPoint)
{
return ReparsePoint.GetTarget(junctionPoint);
}
private static void ThrowLastWin32Error(string message)
{
throw new IOException(message, Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Zxcvbn.Matcher;
using System.Text.RegularExpressions;
namespace Zxcvbn
{
/// <summary>
/// <para>Zxcvbn is used to estimate the strength of passwords. </para>
///
/// <para>This implementation is a port of the Zxcvbn JavaScript library by Dan Wheeler:
/// https://github.com/lowe/zxcvbn</para>
///
/// <para>To quickly evaluate a password, use the <see cref="MatchPassword"/> static function.</para>
///
/// <para>To evaluate a number of passwords, create an instance of this object and repeatedly call the <see cref="EvaluatePassword"/> function.
/// Reusing the the Zxcvbn instance will ensure that pattern matchers will only be created once rather than being recreated for each password
/// e=being evaluated.</para>
/// </summary>
public class Zxcvbn
{
private const string BruteforcePattern = "bruteforce";
private IMatcherFactory matcherFactory;
private readonly Translation translation;
/// <summary>
/// Create a new instance of Zxcvbn that uses the default matchers.
/// </summary>
public Zxcvbn(Translation translation = Translation.English)
: this(new DefaultMatcherFactory())
{
this.translation = translation;
}
/// <summary>
/// Create an instance of Zxcvbn that will use the given matcher factory to create matchers to use
/// to find password weakness.
/// </summary>
/// <param name="matcherFactory">The factory used to create the pattern matchers used</param>
/// <param name="translation">The language in which the strings are returned</param>
public Zxcvbn(IMatcherFactory matcherFactory, Translation translation = Translation.English)
{
this.matcherFactory = matcherFactory;
this.translation = translation;
}
/// <summary>
/// <para>Perform the password matching on the given password and user inputs, returing the result structure with information
/// on the lowest entropy match found.</para>
///
/// <para>User data will be treated as another kind of dictionary matching, but can be different for each password being evaluated.</para>para>
/// </summary>
/// <param name="password">Password</param>
/// <param name="userInputs">Optionally, an enumarable of user data</param>
/// <returns>Result for lowest entropy match</returns>
public Result EvaluatePassword(string password, IEnumerable<string> userInputs = null)
{
userInputs = userInputs ?? new string[0];
IEnumerable<Match> matches = new List<Match>();
var timer = System.Diagnostics.Stopwatch.StartNew();
foreach (var matcher in matcherFactory.CreateMatchers(userInputs))
{
matches = matches.Union(matcher.MatchPassword(password));
}
var result = FindMinimumEntropyMatch(password, matches);
timer.Stop();
result.CalcTime = timer.ElapsedMilliseconds;
return result;
}
/// <summary>
/// Returns a new result structure initialised with data for the lowest entropy result of all of the matches passed in, adding brute-force
/// matches where there are no lesser entropy found pattern matches.
/// </summary>
/// <param name="matches">Password being evaluated</param>
/// <param name="password">List of matches found against the password</param>
/// <returns>A result object for the lowest entropy match sequence</returns>
private Result FindMinimumEntropyMatch(string password, IEnumerable<Match> matches)
{
var bruteforce_cardinality = PasswordScoring.PasswordCardinality(password);
// Minimum entropy up to position k in the password
var minimumEntropyToIndex = new double[password.Length];
var bestMatchForIndex = new Match[password.Length];
for (var k = 0; k < password.Length; k++)
{
// Start with bruteforce scenario added to previous sequence to beat
minimumEntropyToIndex[k] = (k == 0 ? 0 : minimumEntropyToIndex[k - 1]) + Math.Log(bruteforce_cardinality, 2);
// All matches that end at the current character, test to see if the entropy is less
foreach (var match in matches.Where(m => m.j == k))
{
var candidate_entropy = (match.i <= 0 ? 0 : minimumEntropyToIndex[match.i - 1]) + match.Entropy;
if (candidate_entropy < minimumEntropyToIndex[k])
{
minimumEntropyToIndex[k] = candidate_entropy;
bestMatchForIndex[k] = match;
}
}
}
// Walk backwards through lowest entropy matches, to build the best password sequence
var matchSequence = new List<Match>();
for (var k = password.Length - 1; k >= 0; k--)
{
if (bestMatchForIndex[k] != null)
{
matchSequence.Add(bestMatchForIndex[k]);
k = bestMatchForIndex[k].i; // Jump back to start of match
}
}
matchSequence.Reverse();
// The match sequence might have gaps, fill in with bruteforce matching
// After this the matches in matchSequence must cover the whole string (i.e. match[k].j == match[k + 1].i - 1)
if (matchSequence.Count == 0)
{
// To make things easy, we'll separate out the case where there are no matches so everything is bruteforced
matchSequence.Add(new Match()
{
i = 0,
j = password.Length,
Token = password,
Cardinality = bruteforce_cardinality,
Pattern = BruteforcePattern,
Entropy = Math.Log(Math.Pow(bruteforce_cardinality, password.Length), 2)
});
}
else
{
// There are matches, so find the gaps and fill them in
var matchSequenceCopy = new List<Match>();
for (var k = 0; k < matchSequence.Count; k++)
{
var m1 = matchSequence[k];
var m2 = (k < matchSequence.Count - 1 ? matchSequence[k + 1] : new Match() { i = password.Length }); // Next match, or a match past the end of the password
matchSequenceCopy.Add(m1);
if (m1.j < m2.i - 1)
{
// Fill in gap
var ns = m1.j + 1;
var ne = m2.i - 1;
matchSequenceCopy.Add(new Match()
{
i = ns,
j = ne,
Token = password.Substring(ns, ne - ns + 1),
Cardinality = bruteforce_cardinality,
Pattern = BruteforcePattern,
Entropy = Math.Log(Math.Pow(bruteforce_cardinality, ne - ns + 1), 2)
});
}
}
matchSequence = matchSequenceCopy;
}
var minEntropy = (password.Length == 0 ? 0 : minimumEntropyToIndex[password.Length - 1]);
var crackTime = PasswordScoring.EntropyToCrackTime(minEntropy);
var result = new Result();
result.Password = password;
result.Entropy = Math.Round(minEntropy, 3);
result.MatchSequence = matchSequence;
result.CrackTime = Math.Round(crackTime, 3);
result.CrackTimeDisplay = Utility.DisplayTime(crackTime, this.translation);
result.Score = PasswordScoring.CrackTimeToScore(crackTime);
//starting feedback
if ((matchSequence == null) || (matchSequence.Count() == 0))
{
result.warning = Warning.Default;
result.suggestions.Clear();
result.suggestions.Add(Suggestion.Default);
}
else
{
//no Feedback if score is good or great
if (result.Score > 2)
{
result.warning = Warning.Empty;
result.suggestions.Clear();
result.suggestions.Add(Suggestion.Empty);
}
else
{
//tie feedback to the longest match for longer sequences
Match longestMatch = GetLongestMatch(matchSequence);
GetMatchFeedback(longestMatch, matchSequence.Count() == 1, result);
result.suggestions.Insert(0,Suggestion.AddAnotherWordOrTwo);
}
}
return result;
}
private Match GetLongestMatch(List<Match> matchSequence)
{
Match longestMatch;
if ((matchSequence != null) && (matchSequence.Count() > 0))
{
longestMatch = matchSequence[0];
foreach (Match match in matchSequence)
{
if (match.Token.Length > longestMatch.Token.Length)
longestMatch = match;
}
}
else
longestMatch = new Match();
return longestMatch;
}
private void GetMatchFeedback(Match match, bool isSoleMatch, Result result)
{
switch (match.Pattern)
{
case "dictionary":
GetDictionaryMatchFeedback((DictionaryMatch)match, isSoleMatch, result);
break;
case "spatial":
SpatialMatch spatialMatch = (SpatialMatch) match;
if (spatialMatch.Turns == 1)
result.warning = Warning.StraightRow;
else
result.warning = Warning.ShortKeyboardPatterns;
result.suggestions.Clear();
result.suggestions.Add(Suggestion.UseLongerKeyboardPattern);
break;
case "repeat":
//todo: add support for repeated sequences longer than 1 char
// if(match.Token.Length == 1)
result.warning = Warning.RepeatsLikeAaaEasy;
// else
// result.warning = Warning.RepeatsLikeAbcSlighterHarder;
result.suggestions.Clear();
result.suggestions.Add(Suggestion.AvoidRepeatedWordsAndChars);
break;
case "sequence":
result.warning = Warning.SequenceAbcEasy;
result.suggestions.Clear();
result.suggestions.Add(Suggestion.AvoidSequences);
break;
//todo: add support for recent_year, however not example exist on https://dl.dropboxusercontent.com/u/209/zxcvbn/test/index.html
case "date":
result.warning = Warning.DatesEasy;
result.suggestions.Clear();
result.suggestions.Add(Suggestion.AvoidDatesYearsAssociatedYou);
break;
}
}
private void GetDictionaryMatchFeedback(DictionaryMatch match, bool isSoleMatch, Result result)
{
if (match.DictionaryName.Equals("passwords"))
{
//todo: add support for reversed words
if (isSoleMatch == true && !(match is L33tDictionaryMatch))
{
if (match.Rank <= 10)
result.warning = Warning.Top10Passwords;
else if (match.Rank <= 100)
result.warning = Warning.Top100Passwords;
else
result.warning = Warning.CommonPasswords;
}
else if (PasswordScoring.CrackTimeToScore(PasswordScoring.EntropyToCrackTime(match.Entropy)) <= 1)
{
result.warning = Warning.SimilarCommonPasswords;
}
}
else if (match.DictionaryName.Equals("english"))
{
if (isSoleMatch == true)
result.warning = Warning.WordEasy;
}
else if (match.DictionaryName.Equals("surnames") ||
match.DictionaryName.Equals("male_names") ||
match.DictionaryName.Equals("female_names"))
{
if (isSoleMatch == true)
result.warning = Warning.NameSurnamesEasy;
else
result.warning = Warning.CommonNameSurnamesEasy;
}
else
{
result.warning = Warning.Empty;
}
string word = match.Token;
if (Regex.IsMatch(word, PasswordScoring.StartUpper))
{
result.suggestions.Add(Suggestion.CapsDontHelp);
}
else if (Regex.IsMatch(word, PasswordScoring.AllUpper) && !word.Equals(word.ToLowerInvariant()))
{
result.suggestions.Add(Suggestion.AllCapsEasy);
}
//todo: add support for reversed words
//if match.reversed and match.token.length >= 4
// suggestions.push "Reversed words aren't much harder to guess"
if (match is L33tDictionaryMatch)
{
result.suggestions.Add(Suggestion.PredictableSubstitutionsEasy);
}
}
/// <summary>
/// <para>A static function to match a password against the default matchers without having to create
/// an instance of Zxcvbn yourself, with supplied user data. </para>
///
/// <para>Supplied user data will be treated as another kind of dictionary matching.</para>
/// </summary>
/// <param name="password">the password to test</param>
/// <param name="userInputs">optionally, the user inputs list</param>
/// <returns>The results of the password evaluation</returns>
public static Result MatchPassword(string password, IEnumerable<string> userInputs = null)
{
var zx = new Zxcvbn(new DefaultMatcherFactory());
return zx.EvaluatePassword(password, userInputs);
}
}
}
| |
#if UNITY_ANDROID || UNITY_IOS
namespace UnityEngine.Advertisements {
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ShowOptionsExtended = Optional.ShowOptionsExtended;
internal class UnityAds : MonoBehaviour {
public static bool isShowing = false;
public static bool isInitialized = false;
public static bool allowPrecache = true;
private static bool initCalled = false;
private static UnityAds sharedInstance;
private static string _rewardItemNameKey = "";
private static string _rewardItemPictureKey = "";
private static bool _resultDelivered = false;
private static System.Action<ShowResult> resultCallback = null;
private static string _versionString = Application.unityVersion + "_" + Advertisement.version;
public static UnityAds SharedInstance {
get {
if(!sharedInstance) {
sharedInstance = (UnityAds)FindObjectOfType(typeof(UnityAds));
}
if(!sharedInstance) {
GameObject singleton = new GameObject() { hideFlags = HideFlags.HideInHierarchy | HideFlags.HideInInspector };
sharedInstance = singleton.AddComponent<UnityAds>();
singleton.name = "UnityAdsPluginBridgeObject";
DontDestroyOnLoad(singleton);
}
return sharedInstance;
}
}
public void Init(string gameId, bool testModeEnabled) {
// Prevent double inits in all situations
if (initCalled) return;
initCalled = true;
try {
if(Application.internetReachability == NetworkReachability.NotReachable) {
Utils.LogError("Internet not reachable, can't initialize ads");
return;
}
#if UNITY_ANDROID
System.Net.IPHostEntry videoAdServer = System.Net.Dns.GetHostEntry("impact.applifier.com");
if(videoAdServer.AddressList.Length == 1) {
// 0x7F000001 equals to 127.0.0.1
if(videoAdServer.AddressList[0].Equals(new System.Net.IPAddress(new byte[] {0x7F, 0x00, 0x00, 0x01}))) {
Utils.LogError("Video ad server resolves to localhost (due to ad blocker?), can't initialize ads");
return;
}
}
#endif
} catch(System.Exception e) {
Utils.LogDebug("Exception during connectivity check: " + e.Message);
}
UnityAdsExternal.init(gameId, testModeEnabled, SharedInstance.gameObject.name, _versionString);
}
public void Awake () {
if(gameObject == SharedInstance.gameObject) {
DontDestroyOnLoad(gameObject);
}
else {
Destroy (gameObject);
}
}
/* Static Methods */
public static bool isSupported () {
return UnityAdsExternal.isSupported();
}
public static string getSDKVersion () {
return UnityAdsExternal.getSDKVersion();
}
public static void setLogLevel(Advertisement.DebugLevel logLevel) {
UnityAdsExternal.setLogLevel(logLevel);
}
public static bool canShowZone (string zone) {
if(!isInitialized || isShowing) return false;
return UnityAdsExternal.canShowZone(zone);
}
public static bool hasMultipleRewardItems () {
return UnityAdsExternal.hasMultipleRewardItems();
}
public static List<string> getRewardItemKeys () {
List<string> retList = new List<string>();
string keys = UnityAdsExternal.getRewardItemKeys();
retList = new List<string>(keys.Split(';'));
return retList;
}
public static string getDefaultRewardItemKey () {
return UnityAdsExternal.getDefaultRewardItemKey();
}
public static string getCurrentRewardItemKey () {
return UnityAdsExternal.getCurrentRewardItemKey();
}
public static bool setRewardItemKey (string rewardItemKey) {
return UnityAdsExternal.setRewardItemKey(rewardItemKey);
}
public static void setDefaultRewardItemAsRewardItem () {
UnityAdsExternal.setDefaultRewardItemAsRewardItem();
}
public static string getRewardItemNameKey () {
if (_rewardItemNameKey == null || _rewardItemNameKey.Length == 0) {
fillRewardItemKeyData();
}
return _rewardItemNameKey;
}
public static string getRewardItemPictureKey () {
if (_rewardItemPictureKey == null || _rewardItemPictureKey.Length == 0) {
fillRewardItemKeyData();
}
return _rewardItemPictureKey;
}
public static Dictionary<string, string> getRewardItemDetailsWithKey (string rewardItemKey) {
Dictionary<string, string> retDict = new Dictionary<string, string>();
string rewardItemDataString = "";
rewardItemDataString = UnityAdsExternal.getRewardItemDetailsWithKey(rewardItemKey);
if (rewardItemDataString != null) {
List<string> splittedData = new List<string>(rewardItemDataString.Split(';'));
Utils.LogDebug("UnityAndroid: getRewardItemDetailsWithKey() rewardItemDataString=" + rewardItemDataString);
if (splittedData.Count == 2) {
retDict.Add(getRewardItemNameKey(), splittedData.ToArray().GetValue(0).ToString());
retDict.Add(getRewardItemPictureKey(), splittedData.ToArray().GetValue(1).ToString());
}
}
return retDict;
}
public void Show(string zoneId = null, ShowOptions options = null) {
string gamerSid = null;
_resultDelivered = false;
if (options != null) {
if (options.resultCallback != null) {
resultCallback = options.resultCallback;
}
// Disable obsolete method warnings for this piece of code because here we need to access legacy ShowOptionsExtended to maintain compability
#pragma warning disable 612, 618
ShowOptionsExtended extendedOptions = options as ShowOptionsExtended;
if(extendedOptions != null && extendedOptions.gamerSid != null && extendedOptions.gamerSid.Length > 0) {
gamerSid = extendedOptions.gamerSid;
} else {
gamerSid = options.gamerSid;
}
#pragma warning restore 612, 618
}
if (!isInitialized || isShowing) {
deliverCallback (ShowResult.Failed);
return;
}
if (gamerSid != null) {
if (!show (zoneId, "", new Dictionary<string,string> {{"sid", gamerSid}})) {
deliverCallback (ShowResult.Failed);
}
} else {
if (!show (zoneId)) {
deliverCallback (ShowResult.Failed);
}
}
}
public static bool show (string zoneId = null) {
return show (zoneId, "", null);
}
public static bool show (string zoneId, string rewardItemKey) {
return show (zoneId, rewardItemKey, null);
}
public static bool show (string zoneId, string rewardItemKey, Dictionary<string, string> options) {
if (!isShowing) {
isShowing = true;
if (SharedInstance) {
string optionsString = parseOptionsDictionary (options);
if (UnityAdsExternal.show (zoneId, rewardItemKey, optionsString)) {
return true;
}
}
}
return false;
}
private static void deliverCallback(ShowResult result) {
isShowing = false;
if (resultCallback != null && !_resultDelivered) {
_resultDelivered = true;
resultCallback(result);
resultCallback = null;
}
}
public static void hide () {
if (isShowing) {
UnityAdsExternal.hide();
}
}
private static void fillRewardItemKeyData () {
string keyData = UnityAdsExternal.getRewardItemDetailsKeys();
if (keyData != null && keyData.Length > 2) {
List<string> splittedKeyData = new List<string>(keyData.Split(';'));
_rewardItemNameKey = splittedKeyData.ToArray().GetValue(0).ToString();
_rewardItemPictureKey = splittedKeyData.ToArray().GetValue(1).ToString();
}
}
private static string parseOptionsDictionary(Dictionary<string, string> options) {
string optionsString = "";
if(options != null) {
bool added = false;
if(options.ContainsKey("noOfferScreen")) {
optionsString += (added ? "," : "") + "noOfferScreen:" + options["noOfferScreen"];
added = true;
}
if(options.ContainsKey("openAnimated")) {
optionsString += (added ? "," : "") + "openAnimated:" + options["openAnimated"];
added = true;
}
if(options.ContainsKey("sid")) {
optionsString += (added ? "," : "") + "sid:" + options["sid"];
added = true;
}
if(options.ContainsKey("muteVideoSounds")) {
optionsString += (added ? "," : "") + "muteVideoSounds:" + options["muteVideoSounds"];
added = true;
}
if(options.ContainsKey("useDeviceOrientationForVideo")) {
optionsString += (added ? "," : "") + "useDeviceOrientationForVideo:" + options["useDeviceOrientationForVideo"];
added = true;
}
}
return optionsString;
}
/* Events */
public void onHide () {
isShowing = false;
deliverCallback(ShowResult.Skipped);
Utils.LogDebug("onHide");
}
public void onShow () {
Utils.LogDebug("onShow");
}
public void onVideoStarted () {
Utils.LogDebug("onVideoStarted");
}
public void onVideoCompleted (string parameters) {
if (parameters != null) {
List<string> splittedParameters = new List<string>(parameters.Split(';'));
string rewardItemKey = splittedParameters.ToArray().GetValue(0).ToString();
bool skipped = splittedParameters.ToArray().GetValue(1).ToString() == "true" ? true : false;
Utils.LogDebug("onVideoCompleted: " + rewardItemKey + " - " + skipped);
if(skipped) {
deliverCallback (ShowResult.Skipped);
} else {
deliverCallback (ShowResult.Finished);
}
}
}
public void onFetchCompleted () {
isInitialized = true;
Utils.LogDebug("onFetchCompleted");
}
public void onFetchFailed () {
Utils.LogDebug("onFetchFailed");
}
}
}
#endif
| |
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using BLToolkit.EditableObjects;
using BLToolkit.Reflection;
namespace BLToolkit.ComponentModel
{
// BVChanges: adding creator
public delegate object ObjectCreatorCallback();
// BVChanges: adding creator
public class BindingListImpl: IBindingListView, ICancelAddNew, INotifyCollectionChanged
{
// BVChanges: adding creator
private ObjectCreatorCallback _creator;
public ObjectCreatorCallback Creator { set { _creator = value; } }
// BVChanges: adding creator
#region Init
public BindingListImpl(IList list, Type itemType)
{
if (list == null) throw new ArgumentNullException("list");
if (itemType == null) throw new ArgumentNullException("itemType");
_list = list;
_itemType = itemType;
AddInternal(_list);
}
// BVChanges:
~BindingListImpl()
{
for (int i = 0; i < _list.Count; i++)
{
if (_list[i] is INotifyPropertyChanged)
((INotifyPropertyChanged)_list[i]).PropertyChanged -=
ItemPropertyChanged;
}
}
// BVChanges:
#endregion
#region Protected Members
private readonly IList _list;
private readonly Type _itemType;
private void ApplySort(IComparer comparer)
{
if (_list is ISortable)
((ISortable)_list).Sort(0, _list.Count, comparer);
else if (_list is ArrayList)
((ArrayList)_list).Sort(0, _list.Count, comparer);
else if (_list is Array)
Array.Sort((Array)_list, comparer);
else
{
object[] items = new object[_list.Count];
_list.CopyTo(items, 0);
Array.Sort(items, comparer);
for (int i = 0; i < _list.Count; i++)
_list[i] = items[i];
}
_isSorted = true;
}
#endregion
#region IBindingList Members
#region Command
private int _newItemIndex = -1;
private INotifyObjectEdit _newObject;
public object AddNew()
{
if (AllowNew == false)
throw new NotSupportedException();
EndNew();
// BVChanges: adding creator
object o = null;
if(_creator != null)
o = _creator();
if (o == null)
o = TypeAccessor.CreateInstanceEx(_itemType);
// BVChanges: adding creator
_newObject = o as INotifyObjectEdit;
if (_newObject != null)
_newObject.ObjectEdit += NewObject_ObjectEdit;
_newItemIndex = _list.Add(o);
// BVChanges: adding creator
if (o is INotifyPropertyChanged)
((INotifyPropertyChanged)o).PropertyChanged +=
ItemPropertyChanged;
// BVChanges: adding creator
OnAddItem(o, _newItemIndex);
Debug.WriteLine(string.Format("AddNew - ({0})", o.GetType().Name));
return o;
}
void NewObject_ObjectEdit(object sender, ObjectEditEventArgs args)
{
if (sender == _newObject)
{
switch (args.EditType)
{
case ObjectEditType.End: EndNew(); break;
case ObjectEditType.Cancel: CancelNew(_newItemIndex); break;
default: return;
}
}
}
public bool AllowNew
{
get { return !_list.IsFixedSize; }
}
public bool AllowEdit
{
get { return !_list.IsReadOnly; }
}
public bool AllowRemove
{
get { return !_list.IsFixedSize; }
}
#endregion
#region Change Notification
private bool _notifyChanges = true;
public bool NotifyChanges
{
get { return _notifyChanges; }
set { _notifyChanges = value; }
}
public bool SupportsChangeNotification
{
get { return true; }
}
public event ListChangedEventHandler ListChanged;
private void FireListChangedEvent(object sender, ListChangedEventArgs e)
{
if (_notifyChanges && ListChanged != null)
ListChanged(sender, e);
}
protected virtual void OnListChanged(EditableListChangedEventArgs e)
{
FireListChangedEvent(this, e);
}
protected void OnListChanged(ListChangedType listChangedType, int index)
{
OnListChanged(new EditableListChangedEventArgs(listChangedType, index));
}
private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (_notifyChanges && sender != null)
{
int indexOfSender = _list.IndexOf(sender);
if (indexOfSender >= 0)
{
MemberAccessor ma = TypeAccessor.GetAccessor(sender.GetType())[e.PropertyName];
if (ma != null)
OnListChanged(new EditableListChangedEventArgs(indexOfSender, ma.PropertyDescriptor));
else
OnListChanged(new EditableListChangedEventArgs(ListChangedType.ItemChanged, indexOfSender));
// Do not fire an event for OnCollectionChanged here.
if (_isSorted && _list.Count > 1)
{
int newIndex = GetItemSortedPosition(indexOfSender, sender);
if (newIndex != indexOfSender)
{
_list.RemoveAt(indexOfSender);
_list.Insert(newIndex, sender);
OnMoveItem(sender, indexOfSender, newIndex);
}
}
}
}
}
#endregion
#region Sorting
public bool SupportsSorting
{
get { return true; }
}
[NonSerialized]
private bool _isSorted;
public bool IsSorted
{
get { return _isSorted; }
}
[NonSerialized]
private PropertyDescriptor _sortProperty;
public PropertyDescriptor SortProperty
{
get { return _sortProperty; }
}
[NonSerialized]
private ListSortDirection _sortDirection;
public ListSortDirection SortDirection
{
get { return _sortDirection; }
}
public void ApplySort(PropertyDescriptor property, ListSortDirection direction)
{
Debug.WriteLine(string.Format("Begin ApplySort(\"{0}\", {1})", property.Name, direction));
_sortProperty = property;
_sortDirection = direction;
_sortDescriptions = null;
ApplySort(GetSortComparer(_sortProperty, _sortDirection));
if (_list.Count > 0)
OnReset();
Debug.WriteLine(string.Format("End ApplySort(\"{0}\", {1})", property.Name, direction));
}
public void RemoveSort()
{
_isSorted = false;
_sortProperty = null;
_sortDescriptions = null;
OnReset();
}
#endregion
#region Searching
public bool SupportsSearching
{
get { return true; }
}
public int Find(PropertyDescriptor property, object key)
{
if (property == null) throw new ArgumentException("property");
if (key != null)
for (int i = 0; i < _list.Count; i++)
if (key.Equals(property.GetValue(_list[i])))
return i;
return -1;
}
#endregion
#region Indexes
public void AddIndex(PropertyDescriptor property)
{
}
public void RemoveIndex(PropertyDescriptor property)
{
}
#endregion
#endregion
#region ICancelAddNew Members
public void CancelNew(int itemIndex)
{
if (itemIndex >= 0 && itemIndex == _newItemIndex)
{
_list.RemoveAt(itemIndex);
OnRemoveItem(_newObject, itemIndex);
EndNew();
}
}
public void EndNew(int itemIndex)
{
if (itemIndex == _newItemIndex)
EndNew();
}
public void EndNew()
{
_newItemIndex = -1;
if (_newObject != null)
_newObject.ObjectEdit -= NewObject_ObjectEdit;
_newObject = null;
}
#endregion
#region IList Members
public int Add(object value)
{
int index;
if (!_isSorted)
index = _list.Add(value);
else
{
index = GetSortedInsertIndex(value);
_list.Insert(index, value);
}
AddInternal(value);
OnAddItem(value, index);
return index;
}
public void Clear()
{
if (_list.Count > 0)
{
RemoveInternal(_list);
_list.Clear();
OnReset();
}
}
public bool Contains(object value)
{
return _list.Contains(value);
}
public int IndexOf(object value)
{
return _list.IndexOf(value);
}
public void Insert(int index, object value)
{
if (_isSorted)
index = GetSortedInsertIndex(value);
_list.Insert(index, value);
AddInternal(value);
OnAddItem(value, index);
}
public bool IsFixedSize
{
get { return _list.IsFixedSize; }
}
public bool IsReadOnly
{
get { return _list.IsReadOnly; }
}
public void Remove(object value)
{
int index = IndexOf(value);
if (index >= 0)
RemoveInternal(value);
_list.Remove(value);
if (index >= 0)
OnRemoveItem(value, index);
}
public void RemoveAt(int index)
{
object value = this[index];
RemoveInternal(value);
_list.RemoveAt(index);
OnRemoveItem(value, index);
}
public object this[int index]
{
get { return _list[index]; }
set
{
object o = _list[index];
if (o != value)
{
RemoveInternal(o);
_list[index] = value;
AddInternal(value);
OnChangeItem(o, value, index);
if (_isSorted)
{
int newIndex = GetItemSortedPosition(index, value);
if (newIndex != index)
{
_list.RemoveAt(index);
_list.Insert(newIndex, value);
}
OnMoveItem(value, index, newIndex);
}
}
}
}
#endregion
#region ICollection Members
public void CopyTo(Array array, int index)
{
_list.CopyTo(array, index);
}
public int Count
{
get { return _list.Count; }
}
public bool IsSynchronized
{
get { return _list.IsSynchronized; }
}
public object SyncRoot
{
get { return _list.SyncRoot; }
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return _list.GetEnumerator();
}
#endregion
#region SortPropertyComparer
class SortPropertyComparer : IComparer
{
readonly PropertyDescriptor _property;
readonly ListSortDirection _direction;
public SortPropertyComparer(PropertyDescriptor property, ListSortDirection direction)
{
_property = property;
_direction = direction;
}
public int Compare(object x, object y)
{
object a = _property.GetValue(x);
object b = _property.GetValue(y);
int n = Comparer.Default.Compare(a, b);
return _direction == ListSortDirection.Ascending? n: -n;
}
}
#endregion
#region IComparer Accessor
public IComparer GetSortComparer()
{
if (_isSorted)
{
if (_sortDescriptions != null)
return GetSortComparer(_sortDescriptions);
return GetSortComparer(_sortProperty, _sortDirection);
}
return null;
}
private IComparer GetSortComparer(PropertyDescriptor sortProperty, ListSortDirection sortDirection)
{
if (_sortSubstitutions.ContainsKey(sortProperty.Name))
sortProperty = ((SortSubstitutionPair)_sortSubstitutions[sortProperty.Name]).Substitute;
return new SortPropertyComparer(sortProperty, sortDirection);
}
private IComparer GetSortComparer(ListSortDescriptionCollection sortDescriptions)
{
bool needSubstitution = false;
if (_sortSubstitutions.Count > 0)
{
foreach (ListSortDescription sortDescription in sortDescriptions)
{
if (_sortSubstitutions.ContainsKey(sortDescription.PropertyDescriptor.Name))
{
needSubstitution = true;
break;
}
}
if (needSubstitution)
{
ListSortDescription[] sorts = new ListSortDescription[sortDescriptions.Count];
sortDescriptions.CopyTo(sorts, 0);
for (int i = 0; i < sorts.Length; i++)
if (_sortSubstitutions.ContainsKey(sorts[i].PropertyDescriptor.Name))
sorts[i] = new ListSortDescription(((SortSubstitutionPair)_sortSubstitutions[sorts[i].PropertyDescriptor.Name]).Substitute,
sorts[i].SortDirection);
sortDescriptions = new ListSortDescriptionCollection(sorts);
}
}
return new SortListPropertyComparer(sortDescriptions);
}
#endregion
#region IBindingListView Members
public bool SupportsAdvancedSorting
{
get { return true; }
}
public void ApplySort(ListSortDescriptionCollection sorts)
{
_sortDescriptions = sorts;
_isSorted = true;
_sortProperty = null;
ApplySort(GetSortComparer(sorts));
if (_list.Count > 0)
OnReset();
}
[NonSerialized]
private ListSortDescriptionCollection _sortDescriptions;
public ListSortDescriptionCollection SortDescriptions
{
get { return _sortDescriptions; }
}
public bool SupportsFiltering
{
get { return false; }
}
public string Filter
{
get { throw new NotImplementedException("The method 'BindingListImpl.get_Filter' is not implemented."); }
set { throw new NotImplementedException("The method 'BindingListImpl.set_Filter' is not implemented."); }
}
public void RemoveFilter()
{
throw new NotImplementedException("The method 'BindingListImpl.RemoveFilter()' is not implemented.");
}
#endregion
#region SortListPropertyComparer
class SortListPropertyComparer : IComparer
{
readonly ListSortDescriptionCollection _sorts;
public SortListPropertyComparer(ListSortDescriptionCollection sorts)
{
_sorts = sorts;
}
public int Compare(object x, object y)
{
for (int i = 0; i < _sorts.Count; i++)
{
PropertyDescriptor property = _sorts[i].PropertyDescriptor;
object a = property.GetValue(x);
object b = property.GetValue(y);
int n = Comparer.Default.Compare(a, b);
if (n != 0)
return _sorts[i].SortDirection == ListSortDirection.Ascending? n: -n;
}
return 0;
}
}
#endregion
#region Sorting enhancement
private readonly Hashtable _sortSubstitutions = new Hashtable();
private class SortSubstitutionPair
{
public SortSubstitutionPair(PropertyDescriptor original, PropertyDescriptor substitute)
{
Original = original;
Substitute = substitute;
}
public readonly PropertyDescriptor Original;
public readonly PropertyDescriptor Substitute;
}
public void CreateSortSubstitution(string originalProperty, string substituteProperty)
{
TypeAccessor typeAccessor = TypeAccessor.GetAccessor(_itemType);
PropertyDescriptor originalDescriptor = typeAccessor.PropertyDescriptors[originalProperty];
PropertyDescriptor substituteDescriptor = typeAccessor.PropertyDescriptors[substituteProperty];
if (originalDescriptor == null) throw new InvalidOperationException("Can not retrieve PropertyDescriptor for original property: " + originalProperty);
if (substituteDescriptor == null) throw new InvalidOperationException("Can not retrieve PropertyDescriptor for substitute property: " + substituteProperty);
_sortSubstitutions[originalProperty] = new SortSubstitutionPair(originalDescriptor, substituteDescriptor);
}
public void RemoveSortSubstitution(string originalProperty)
{
_sortSubstitutions.Remove(originalProperty);
}
#endregion
#region Sort enforcement
public int GetItemSortedPosition(int index, object sender)
{
IComparer comparer = GetSortComparer();
if (comparer == null)
return index;
if ((index > 0 && comparer.Compare(_list[index - 1], sender) > 0) ||
(index < _list.Count - 1 && comparer.Compare(_list[index + 1], sender) < 0))
{
for (int i = 0; i < _list.Count; i++)
{
if (i != index && comparer.Compare(_list[i], sender) > 0)
{
if (i > index)
return i - 1;
return i;
}
}
return _list.Count - 1;
}
return index;
}
public int GetSortedInsertIndex(object value)
{
IComparer comparer = GetSortComparer();
if (comparer == null)
return -1;
for (int i = 0; i < _list.Count; i++)
if (comparer.Compare(_list[i], value) > 0)
return i;
return _list.Count;
}
#endregion
#region Misc/Range Operations
public void Move(int newIndex, int oldIndex)
{
if (oldIndex != newIndex)
{
EndNew();
object o = _list[oldIndex];
_list.RemoveAt(oldIndex);
if (!_isSorted)
_list.Insert(newIndex, o);
else
_list.Insert(newIndex = GetSortedInsertIndex(o), o);
OnMoveItem(o, oldIndex, newIndex);
}
}
public void AddRange(ICollection c)
{
foreach (object o in c)
{
if (!_isSorted)
_list.Add(o);
else
_list.Insert(GetSortedInsertIndex(o), o);
}
AddInternal(c);
OnReset();
}
public void InsertRange(int index, ICollection c)
{
if (c.Count == 0)
return;
foreach (object o in c)
{
if (!_isSorted)
_list.Insert(index++, o);
else
_list.Insert(GetSortedInsertIndex(o), o);
}
AddInternal(c);
OnReset();
}
public void RemoveRange(int index, int count)
{
object[] toRemove = new object[count];
for (int i = index; i < _list.Count && i < index + count; i++)
toRemove[i - index] = _list[i];
RemoveInternal(toRemove);
foreach (object o in toRemove)
_list.Remove(o);
OnReset();
}
public void SetRange(int index, ICollection c)
{
int cCount = c.Count;
if (index < 0 || index >= _list.Count - cCount)
throw new ArgumentOutOfRangeException("index");
bool oldNotifyChanges = _notifyChanges;
_notifyChanges = false;
int i = index;
foreach (object newObject in c)
{
RemoveInternal(_list[i + index]);
_list[i + index] = newObject;
}
AddInternal(c);
if (_isSorted)
ApplySort(GetSortComparer());
_notifyChanges = oldNotifyChanges;
OnReset();
}
#endregion
#region Add/Remove Internal
private void AddInternal(object value)
{
EndNew();
if (value is INotifyPropertyChanged)
((INotifyPropertyChanged)value).PropertyChanged +=
ItemPropertyChanged;
}
private void RemoveInternal(object value)
{
EndNew();
if (value is INotifyPropertyChanged)
((INotifyPropertyChanged)value).PropertyChanged -=
ItemPropertyChanged;
}
private void AddInternal(IEnumerable e)
{
foreach (object o in e)
AddInternal(o);
}
private void RemoveInternal(IEnumerable e)
{
foreach (object o in e)
RemoveInternal(o);
}
private void OnAddItem(object item, int index)
{
OnListChanged(new EditableListChangedEventArgs(ListChangedType.ItemAdded, index));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));
}
private void OnRemoveItem(object item, int index)
{
OnListChanged(new EditableListChangedEventArgs(ListChangedType.ItemDeleted, index));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index));
}
private void OnMoveItem(object item, int oldIndex, int newIndex)
{
OnListChanged(new EditableListChangedEventArgs(newIndex, oldIndex));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, item, newIndex, oldIndex));
}
private void OnChangeItem(object oldValue, object newValue, int index)
{
OnListChanged(new EditableListChangedEventArgs(ListChangedType.ItemChanged, index));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, oldValue, newValue, index));
}
private void OnReset()
{
OnListChanged(new EditableListChangedEventArgs(ListChangedType.Reset));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
#endregion
#region INotifyCollectionChanged Members
public event NotifyCollectionChangedEventHandler CollectionChanged;
private void FireCollectionChangedEvent(object sender, NotifyCollectionChangedEventArgs ea)
{
if (_notifyChanges && CollectionChanged != null)
CollectionChanged(sender, ea);
}
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs ea)
{
FireCollectionChangedEvent(this, ea);
}
#endregion
}
}
| |
using System;
using System.Buffers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace FakeFx.Runtime.Messaging
{
/// <summary>
/// An <see cref="IBufferWriter{T}"/> that reserves some fixed size for a header.
/// </summary>
/// <typeparam name="T">The type of element written by this writer.</typeparam>
/// <typeparam name="TBufferWriter">The type of underlying buffer writer.</typeparam>
/// <remarks>
/// This type is used for inserting the length of list in the header when the length is not known beforehand.
/// It is optimized to minimize or avoid copying.
/// </remarks>
public class PrefixingBufferWriter<T, TBufferWriter> : IBufferWriter<T>, IDisposable where TBufferWriter : IBufferWriter<T>
{
private readonly MemoryPool<T> memoryPool;
/// <summary>
/// The length of the header.
/// </summary>
private readonly int expectedPrefixSize;
/// <summary>
/// A hint from our owner at the size of the payload that follows the header.
/// </summary>
private readonly int payloadSizeHint;
/// <summary>
/// The underlying buffer writer.
/// </summary>
private TBufferWriter innerWriter;
/// <summary>
/// The memory reserved for the header from the <see cref="innerWriter"/>.
/// This memory is not reserved until the first call from this writer to acquire memory.
/// </summary>
private Memory<T> prefixMemory;
/// <summary>
/// The memory acquired from <see cref="innerWriter"/>.
/// This memory is not reserved until the first call from this writer to acquire memory.
/// </summary>
private Memory<T> realMemory;
/// <summary>
/// The number of elements written to a buffer belonging to <see cref="innerWriter"/>.
/// </summary>
private int advanced;
/// <summary>
/// The fallback writer to use when the caller writes more than we allowed for given the <see cref="payloadSizeHint"/>
/// in anything but the initial call to <see cref="GetSpan(int)"/>.
/// </summary>
private Sequence privateWriter;
/// <summary>
/// Initializes a new instance of the <see cref="PrefixingBufferWriter{T, TBufferWriter}"/> class.
/// </summary>
/// <param name="prefixSize">The length of the header to reserve space for. Must be a positive number.</param>
/// <param name="payloadSizeHint">A hint at the expected max size of the payload. The real size may be more or less than this, but additional copying is avoided if it does not exceed this amount. If 0, a reasonable guess is made.</param>
/// <param name="memoryPool"></param>
public PrefixingBufferWriter(int prefixSize, int payloadSizeHint, MemoryPool<T> memoryPool)
{
if (prefixSize <= 0)
{
ThrowPrefixSize();
}
this.expectedPrefixSize = prefixSize;
this.payloadSizeHint = payloadSizeHint;
this.memoryPool = memoryPool;
[MethodImpl(MethodImplOptions.NoInlining)]
void ThrowPrefixSize() => throw new ArgumentOutOfRangeException(nameof(prefixSize));
}
public int CommittedBytes { get; private set; }
/// <inheritdoc />
public void Advance(int count)
{
if (this.privateWriter != null)
{
this.privateWriter.Advance(count);
}
else
{
this.advanced += count;
}
this.CommittedBytes += count;
}
/// <inheritdoc />
public Memory<T> GetMemory(int sizeHint = 0)
{
this.EnsureInitialized(sizeHint);
if (this.privateWriter != null || sizeHint > this.realMemory.Length - this.advanced)
{
if (this.privateWriter == null)
{
this.privateWriter = new Sequence(this.memoryPool);
}
return this.privateWriter.GetMemory(sizeHint);
}
else
{
return this.realMemory.Slice(this.advanced);
}
}
/// <inheritdoc />
public Span<T> GetSpan(int sizeHint = 0)
{
this.EnsureInitialized(sizeHint);
if (this.privateWriter != null || sizeHint > this.realMemory.Length - this.advanced)
{
if (this.privateWriter == null)
{
this.privateWriter = new Sequence(this.memoryPool);
}
return this.privateWriter.GetSpan(sizeHint);
}
else
{
return this.realMemory.Span.Slice(this.advanced);
}
}
/// <summary>
/// Inserts the prefix and commits the payload to the underlying <see cref="IBufferWriter{T}"/>.
/// </summary>
/// <param name="prefix">The prefix to write in. The length must match the one given in the constructor.</param>
public void Complete(ReadOnlySpan<T> prefix)
{
if (prefix.Length != this.expectedPrefixSize)
{
ThrowPrefixLength();
[MethodImpl(MethodImplOptions.NoInlining)]
void ThrowPrefixLength() => throw new ArgumentOutOfRangeException(nameof(prefix), "Prefix was not expected length.");
}
if (this.prefixMemory.Length == 0)
{
// No payload was actually written, and we never requested memory, so just write it out.
this.innerWriter.Write(prefix);
}
else
{
// Payload has been written, so write in the prefix then commit the payload.
prefix.CopyTo(this.prefixMemory.Span);
this.innerWriter.Advance(prefix.Length + this.advanced);
if (this.privateWriter != null)
{
// Try to minimize segments in the target writer by hinting at the total size.
this.innerWriter.GetSpan((int)this.privateWriter.Length);
foreach (var segment in this.privateWriter.AsReadOnlySequence)
{
this.innerWriter.Write(segment.Span);
}
}
}
}
/// <summary>
/// Resets this instance to a reusable state.
/// </summary>
/// <param name="writer">The underlying writer that should ultimately receive the prefix and payload.</param>
public void Reset(TBufferWriter writer)
{
this.advanced = 0;
this.CommittedBytes = 0;
this.privateWriter?.Dispose();
this.privateWriter = null;
this.prefixMemory = default;
this.realMemory = default;
if (writer.Equals(default(TBufferWriter)))
{
ThrowInnerWriter();
}
this.innerWriter = writer;
[MethodImpl(MethodImplOptions.NoInlining)]
void ThrowInnerWriter() => throw new ArgumentNullException(nameof(writer));
}
public void Dispose()
{
this.privateWriter?.Dispose();
}
/// <summary>
/// Makes the initial call to acquire memory from the underlying writer if it has not been done already.
/// </summary>
/// <param name="sizeHint">The size requested by the caller to either <see cref="GetMemory(int)"/> or <see cref="GetSpan(int)"/>.</param>
private void EnsureInitialized(int sizeHint)
{
if (this.prefixMemory.Length == 0)
{
int sizeToRequest = this.expectedPrefixSize + Math.Max(sizeHint, this.payloadSizeHint);
var memory = this.innerWriter.GetMemory(sizeToRequest);
this.prefixMemory = memory.Slice(0, this.expectedPrefixSize);
this.realMemory = memory.Slice(this.expectedPrefixSize);
}
}
/// <summary>
/// Manages a sequence of elements, readily castable as a <see cref="ReadOnlySequence{T}"/>.
/// </summary>
/// <remarks>
/// Instance members are not thread-safe.
/// </remarks>
[DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")]
public class Sequence : IBufferWriter<T>, IDisposable
{
private const int DefaultBufferSize = 4 * 1024;
private readonly Stack<SequenceSegment> segmentPool = new();
private readonly MemoryPool<T> memoryPool;
private SequenceSegment first;
private SequenceSegment last;
/// <summary>
/// Initializes a new instance of the <see cref="Sequence"/> class.
/// </summary>
/// <param name="memoryPool">The pool to use for recycling backing arrays.</param>
public Sequence(MemoryPool<T> memoryPool)
{
this.memoryPool = memoryPool ?? ThrowNull();
[MethodImpl(MethodImplOptions.NoInlining)]
MemoryPool<T> ThrowNull() => throw new ArgumentNullException(nameof(memoryPool));
}
/// <summary>
/// Gets this sequence expressed as a <see cref="ReadOnlySequence{T}"/>.
/// </summary>
/// <returns>A read only sequence representing the data in this object.</returns>
public ReadOnlySequence<T> AsReadOnlySequence => this;
/// <summary>
/// Gets the length of the sequence.
/// </summary>
public long Length => this.AsReadOnlySequence.Length;
/// <summary>
/// Gets the value to display in a debugger datatip.
/// </summary>
private string DebuggerDisplay => $"Length: {AsReadOnlySequence.Length}";
/// <summary>
/// Expresses this sequence as a <see cref="ReadOnlySequence{T}"/>.
/// </summary>
/// <param name="sequence">The sequence to convert.</param>
public static implicit operator ReadOnlySequence<T>(Sequence sequence)
{
return sequence.first != null
? new ReadOnlySequence<T>(sequence.first, sequence.first.Start, sequence.last, sequence.last.End)
: ReadOnlySequence<T>.Empty;
}
/// <summary>
/// Removes all elements from the sequence from its beginning to the specified position,
/// considering that data to have been fully processed.
/// </summary>
/// <param name="position">
/// The position of the first element that has not yet been processed.
/// This is typically <see cref="ReadOnlySequence{T}.End"/> after reading all elements from that instance.
/// </param>
public void AdvanceTo(SequencePosition position)
{
var firstSegment = (SequenceSegment)position.GetObject();
int firstIndex = position.GetInteger();
// Before making any mutations, confirm that the block specified belongs to this sequence.
var current = this.first;
while (current != firstSegment && current != null)
{
current = current.Next;
}
if (current == null)
{
ThrowCurrentNull();
}
[MethodImpl(MethodImplOptions.NoInlining)]
void ThrowCurrentNull() => throw new ArgumentException("Position does not represent a valid position in this sequence.", nameof(position));
// Also confirm that the position is not a prior position in the block.
if (firstIndex < current.Start)
{
ThrowEarlierPosition();
}
[MethodImpl(MethodImplOptions.NoInlining)]
void ThrowEarlierPosition() => throw new ArgumentException("Position must not be earlier than current position.", nameof(position));
// Now repeat the loop, performing the mutations.
current = this.first;
while (current != firstSegment)
{
var next = current.Next;
current.ResetMemory();
current = next;
}
firstSegment.AdvanceTo(firstIndex);
if (firstSegment.Length == 0)
{
firstSegment = this.RecycleAndGetNext(firstSegment);
}
this.first = firstSegment;
if (this.first == null)
{
this.last = null;
}
}
/// <summary>
/// Advances the sequence to include the specified number of elements initialized into memory
/// returned by a prior call to <see cref="GetMemory(int)"/>.
/// </summary>
/// <param name="count">The number of elements written into memory.</param>
public void Advance(int count)
{
if (count < 0)
{
ThrowNegative();
}
this.last.End += count;
[MethodImpl(MethodImplOptions.NoInlining)]
void ThrowNegative() => throw new ArgumentOutOfRangeException(
nameof(count),
"Value must be greater than or equal to 0");
}
/// <summary>
/// Gets writable memory that can be initialized and added to the sequence via a subsequent call to <see cref="Advance(int)"/>.
/// </summary>
/// <param name="sizeHint">The size of the memory required, or 0 to just get a convenient (non-empty) buffer.</param>
/// <returns>The requested memory.</returns>
public Memory<T> GetMemory(int sizeHint)
{
if (sizeHint < 0)
{
ThrowNegative();
}
if (sizeHint == 0)
{
if (this.last?.WritableBytes > 0)
{
sizeHint = this.last.WritableBytes;
}
else
{
sizeHint = DefaultBufferSize;
}
}
if (this.last == null || this.last.WritableBytes < sizeHint)
{
this.Append(this.memoryPool.Rent(Math.Min(sizeHint, this.memoryPool.MaxBufferSize)));
}
return this.last.TrailingSlack;
[MethodImpl(MethodImplOptions.NoInlining)]
void ThrowNegative() => throw new ArgumentOutOfRangeException(
nameof(sizeHint),
"Value for must be greater than or equal to 0");
}
/// <summary>
/// Gets writable memory that can be initialized and added to the sequence via a subsequent call to <see cref="Advance(int)"/>.
/// </summary>
/// <param name="sizeHint">The size of the memory required, or 0 to just get a convenient (non-empty) buffer.</param>
/// <returns>The requested memory.</returns>
public Span<T> GetSpan(int sizeHint) => this.GetMemory(sizeHint).Span;
/// <summary>
/// Clears the entire sequence, recycles associated memory into pools,
/// and resets this instance for reuse.
/// This invalidates any <see cref="ReadOnlySequence{T}"/> previously produced by this instance.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public void Dispose() => this.Reset();
/// <summary>
/// Clears the entire sequence and recycles associated memory into pools.
/// This invalidates any <see cref="ReadOnlySequence{T}"/> previously produced by this instance.
/// </summary>
public void Reset()
{
var current = this.first;
while (current != null)
{
current = this.RecycleAndGetNext(current);
}
this.first = this.last = null;
}
private void Append(IMemoryOwner<T> array)
{
if (array == null)
{
ThrowNull();
}
var segment = this.segmentPool.Count > 0 ? this.segmentPool.Pop() : new SequenceSegment();
segment.SetMemory(array, 0, 0);
if (this.last == null)
{
this.first = this.last = segment;
}
else
{
if (this.last.Length > 0)
{
// Add a new block.
this.last.SetNext(segment);
}
else
{
// The last block is completely unused. Replace it instead of appending to it.
var current = this.first;
if (this.first != this.last)
{
while (current.Next != this.last)
{
current = current.Next;
}
}
else
{
this.first = segment;
}
current.SetNext(segment);
this.RecycleAndGetNext(this.last);
}
this.last = segment;
}
[MethodImpl(MethodImplOptions.NoInlining)]
void ThrowNull() => throw new ArgumentNullException(nameof(array));
}
private SequenceSegment RecycleAndGetNext(SequenceSegment segment)
{
var recycledSegment = segment;
segment = segment.Next;
recycledSegment.ResetMemory();
this.segmentPool.Push(recycledSegment);
return segment;
}
private class SequenceSegment : ReadOnlySequenceSegment<T>
{
/// <summary>
/// Backing field for the <see cref="End"/> property.
/// </summary>
private int end;
/// <summary>
/// Gets the index of the first element in <see cref="AvailableMemory"/> to consider part of the sequence.
/// </summary>
/// <remarks>
/// The <see cref="Start"/> represents the offset into <see cref="AvailableMemory"/> where the range of "active" bytes begins. At the point when the block is leased
/// the <see cref="Start"/> is guaranteed to be equal to 0. The value of <see cref="Start"/> may be assigned anywhere between 0 and
/// <see cref="AvailableMemory"/>.Length, and must be equal to or less than <see cref="End"/>.
/// </remarks>
internal int Start { get; private set; }
/// <summary>
/// Gets or sets the index of the element just beyond the end in <see cref="AvailableMemory"/> to consider part of the sequence.
/// </summary>
/// <remarks>
/// The <see cref="End"/> represents the offset into <see cref="AvailableMemory"/> where the range of "active" bytes ends. At the point when the block is leased
/// the <see cref="End"/> is guaranteed to be equal to <see cref="Start"/>. The value of <see cref="Start"/> may be assigned anywhere between 0 and
/// <see cref="AvailableMemory"/>.Length, and must be equal to or less than <see cref="End"/>.
/// </remarks>
internal int End
{
get => this.end;
set
{
if (value > this.AvailableMemory.Length)
{
ThrowOutOfRange();
}
this.end = value;
// If we ever support creating these instances on existing arrays, such that
// this.Start isn't 0 at the beginning, we'll have to "pin" this.Start and remove
// Advance, forcing Sequence<T> itself to track it, the way Pipe does it internally.
this.Memory = this.AvailableMemory.Slice(0, value);
[MethodImpl(MethodImplOptions.NoInlining)]
void ThrowOutOfRange() =>
throw new ArgumentOutOfRangeException(nameof(value), "Value must be less than or equal to AvailableMemory.Length");
}
}
internal Memory<T> TrailingSlack => this.AvailableMemory.Slice(this.End);
internal IMemoryOwner<T> MemoryOwner { get; private set; }
internal Memory<T> AvailableMemory { get; private set; }
internal int Length => this.End - this.Start;
/// <summary>
/// Gets the amount of writable bytes in this segment.
/// It is the amount of bytes between <see cref="Length"/> and <see cref="End"/>.
/// </summary>
internal int WritableBytes
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => this.AvailableMemory.Length - this.End;
}
internal new SequenceSegment Next
{
get => (SequenceSegment)base.Next;
set => base.Next = value;
}
internal void SetMemory(IMemoryOwner<T> memoryOwner)
{
this.SetMemory(memoryOwner, 0, memoryOwner.Memory.Length);
}
internal void SetMemory(IMemoryOwner<T> memoryOwner, int start, int end)
{
this.MemoryOwner = memoryOwner;
this.AvailableMemory = this.MemoryOwner.Memory;
this.RunningIndex = 0;
this.Start = start;
this.End = end;
this.Next = null;
}
internal void ResetMemory()
{
this.MemoryOwner.Dispose();
this.MemoryOwner = null;
this.AvailableMemory = default;
this.Memory = default;
this.Next = null;
this.Start = 0;
this.end = 0;
}
internal void SetNext(SequenceSegment segment)
{
if (segment == null)
{
ThrowNull();
}
this.Next = segment;
segment.RunningIndex = this.RunningIndex + this.End;
[MethodImpl(MethodImplOptions.NoInlining)]
SequenceSegment ThrowNull() => throw new ArgumentNullException(nameof(segment));
}
internal void AdvanceTo(int offset)
{
if (offset > this.End)
{
ThrowOutOfRange();
}
this.Start = offset;
[MethodImpl(MethodImplOptions.NoInlining)]
void ThrowOutOfRange() => throw new ArgumentOutOfRangeException(nameof(offset));
}
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_ASYNC
using System;
using System.Globalization;
using System.Threading;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
public partial class JsonTextReader
{
// It's not safe to perform the async methods here in a derived class as if the synchronous equivalent
// has been overriden then the asychronous method will no longer be doing the same operation
#if HAVE_ASYNC // Double-check this isn't included inappropriately.
private readonly bool _safeAsync;
#endif
/// <summary>
/// Asynchronously reads the next JSON token from the source.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns <c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsync(cancellationToken) : base.ReadAsync(cancellationToken);
}
internal Task<bool> DoReadAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
while (true)
{
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
return ParseValueAsync(cancellationToken);
case State.Object:
case State.ObjectStart:
return ParseObjectAsync(cancellationToken);
case State.PostValue:
Task<bool> task = ParsePostValueAsync(false, cancellationToken);
if (task.IsCompletedSucessfully())
{
if (task.Result)
{
return AsyncUtils.True;
}
}
else
{
return DoReadAsync(task, cancellationToken);
}
break;
case State.Finished:
return ReadFromFinishedAsync(cancellationToken);
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
}
private async Task<bool> DoReadAsync(Task<bool> task, CancellationToken cancellationToken)
{
bool result = await task.ConfigureAwait(false);
if (result)
{
return true;
}
return await DoReadAsync(cancellationToken).ConfigureAwait(false);
}
private async Task<bool> ParsePostValueAsync(bool ignoreComments, CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
_currentState = State.Finished;
return false;
}
}
else
{
_charPos++;
}
break;
case '}':
_charPos++;
SetToken(JsonToken.EndObject);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case '/':
await ParseCommentAsync(!ignoreComments, cancellationToken).ConfigureAwait(false);
if (!ignoreComments)
{
return true;
}
break;
case ',':
_charPos++;
// finished parsing
SetStateBasedOnCurrent();
return false;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
// handle multiple content without comma delimiter
if (SupportMultipleContent && Depth == 0)
{
SetStateBasedOnCurrent();
return false;
}
throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
break;
}
}
}
private async Task<bool> ReadFromFinishedAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_isEndOfFile)
{
SetToken(JsonToken.None);
return false;
}
if (_chars[_charPos] == '/')
{
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
}
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
SetToken(JsonToken.None);
return false;
}
private Task<int> ReadDataAsync(bool append, CancellationToken cancellationToken)
{
return ReadDataAsync(append, 0, cancellationToken);
}
private async Task<int> ReadDataAsync(bool append, int charsRequired, CancellationToken cancellationToken)
{
if (_isEndOfFile)
{
return 0;
}
PrepareBufferForReadData(append, charsRequired);
int charsRead = await _reader.ReadAsync(_chars, _charsUsed, _chars.Length - _charsUsed - 1, cancellationToken).ConfigureAwait(false);
_charsUsed += charsRead;
if (charsRead == 0)
{
_isEndOfFile = true;
}
_chars[_charsUsed] = '\0';
return charsRead;
}
private async Task<bool> ParseValueAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return false;
}
}
else
{
_charPos++;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case 't':
await ParseTrueAsync(cancellationToken).ConfigureAwait(false);
return true;
case 'f':
await ParseFalseAsync(cancellationToken).ConfigureAwait(false);
return true;
case 'n':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
switch (_chars[_charPos + 1])
{
case 'u':
await ParseNullAsync(cancellationToken).ConfigureAwait(false);
break;
case 'e':
await ParseConstructorAsync(cancellationToken).ConfigureAwait(false);
break;
default:
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
}
else
{
_charPos++;
throw CreateUnexpectedEndException();
}
return true;
case 'N':
await ParseNumberNaNAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case 'I':
await ParseNumberPositiveInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
await ParseNumberNegativeInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
}
else
{
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
}
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case 'u':
await ParseUndefinedAsync(cancellationToken).ConfigureAwait(false);
return true;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
return true;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ',':
// don't increment position, the next call to read will handle comma
// this is done to handle multiple empty comma values
SetToken(JsonToken.Undefined);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
break;
}
if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.')
{
ParseNumber(ReadType.Read);
return true;
}
throw CreateUnexpectedCharacterException(currentChar);
}
}
}
private async Task ReadStringIntoBufferAsync(char quote, CancellationToken cancellationToken)
{
int charPos = _charPos;
int initialPosition = _charPos;
int lastWritePosition = _charPos;
_stringBuffer.Position = 0;
while (true)
{
switch (_chars[charPos++])
{
case '\0':
if (_charsUsed == charPos - 1)
{
charPos--;
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
_charPos = charPos;
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
}
break;
case '\\':
_charPos = charPos;
if (!await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false))
{
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
// start of escape sequence
int escapeStartPos = charPos - 1;
char currentChar = _chars[charPos];
charPos++;
char writeChar;
switch (currentChar)
{
case 'b':
writeChar = '\b';
break;
case 't':
writeChar = '\t';
break;
case 'n':
writeChar = '\n';
break;
case 'f':
writeChar = '\f';
break;
case 'r':
writeChar = '\r';
break;
case '\\':
writeChar = '\\';
break;
case '"':
case '\'':
case '/':
writeChar = currentChar;
break;
case 'u':
_charPos = charPos;
writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false);
if (StringUtils.IsLowSurrogate(writeChar))
{
// low surrogate with no preceding high surrogate; this char is replaced
writeChar = UnicodeReplacementChar;
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
bool anotherHighSurrogate;
// loop for handling situations where there are multiple consecutive high surrogates
do
{
anotherHighSurrogate = false;
// potential start of a surrogate pair
if (await EnsureCharsAsync(2, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u')
{
char highSurrogate = writeChar;
_charPos += 2;
writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false);
if (StringUtils.IsLowSurrogate(writeChar))
{
// a valid surrogate pair!
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
// another high surrogate; replace current and start check over
highSurrogate = UnicodeReplacementChar;
anotherHighSurrogate = true;
}
else
{
// high surrogate not followed by low surrogate; original char is replaced
highSurrogate = UnicodeReplacementChar;
}
EnsureBufferNotEmpty();
WriteCharToBuffer(highSurrogate, lastWritePosition, escapeStartPos);
lastWritePosition = _charPos;
}
else
{
// there are not enough remaining chars for the low surrogate or is not follow by unicode sequence
// replace high surrogate and continue on as usual
writeChar = UnicodeReplacementChar;
}
} while (anotherHighSurrogate);
}
charPos = _charPos;
break;
default:
_charPos = charPos;
throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar));
}
EnsureBufferNotEmpty();
WriteCharToBuffer(writeChar, lastWritePosition, escapeStartPos);
lastWritePosition = charPos;
break;
case StringUtils.CarriageReturn:
_charPos = charPos - 1;
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
charPos = _charPos;
break;
case StringUtils.LineFeed:
_charPos = charPos - 1;
ProcessLineFeed();
charPos = _charPos;
break;
case '"':
case '\'':
if (_chars[charPos - 1] == quote)
{
FinishReadStringIntoBuffer(charPos - 1, initialPosition, lastWritePosition);
return;
}
break;
}
}
}
private Task ProcessCarriageReturnAsync(bool append, CancellationToken cancellationToken)
{
_charPos++;
Task<bool> task = EnsureCharsAsync(1, append, cancellationToken);
if (task.IsCompletedSucessfully())
{
SetNewLine(task.Result);
return AsyncUtils.CompletedTask;
}
return ProcessCarriageReturnAsync(task);
}
private async Task ProcessCarriageReturnAsync(Task<bool> task)
{
SetNewLine(await task.ConfigureAwait(false));
}
private async Task<char> ParseUnicodeAsync(CancellationToken cancellationToken)
{
return ConvertUnicode(await EnsureCharsAsync(4, true, cancellationToken).ConfigureAwait(false));
}
private Task<bool> EnsureCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken)
{
if (_charPos + relativePosition < _charsUsed)
{
return AsyncUtils.True;
}
if (_isEndOfFile)
{
return AsyncUtils.False;
}
return ReadCharsAsync(relativePosition, append, cancellationToken);
}
private async Task<bool> ReadCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken)
{
int charsRequired = _charPos + relativePosition - _charsUsed + 1;
// it is possible that the TextReader doesn't return all data at once
// repeat read until the required text is returned or the reader is out of content
do
{
int charsRead = await ReadDataAsync(append, charsRequired, cancellationToken).ConfigureAwait(false);
// no more content
if (charsRead == 0)
{
return false;
}
charsRequired -= charsRead;
} while (charsRequired > 0);
return true;
}
private async Task<bool> ParseObjectAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return false;
}
}
else
{
_charPos++;
}
break;
case '}':
SetToken(JsonToken.EndObject);
_charPos++;
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
return await ParsePropertyAsync(cancellationToken).ConfigureAwait(false);
}
break;
}
}
}
private async Task ParseCommentAsync(bool setToken, CancellationToken cancellationToken)
{
// should have already parsed / character before reaching this method
_charPos++;
if (!await EnsureCharsAsync(1, false, cancellationToken).ConfigureAwait(false))
{
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
}
bool singlelineComment;
if (_chars[_charPos] == '*')
{
singlelineComment = false;
}
else if (_chars[_charPos] == '/')
{
singlelineComment = true;
}
else
{
throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
int initialPosition = _charPos;
while (true)
{
switch (_chars[_charPos])
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
if (!singlelineComment)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
}
EndComment(setToken, initialPosition, _charPos);
return;
}
}
else
{
_charPos++;
}
break;
case '*':
_charPos++;
if (!singlelineComment)
{
if (await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos] == '/')
{
EndComment(setToken, initialPosition, _charPos - 1);
_charPos++;
return;
}
}
}
break;
case StringUtils.CarriageReturn:
if (singlelineComment)
{
EndComment(setToken, initialPosition, _charPos);
return;
}
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
if (singlelineComment)
{
EndComment(setToken, initialPosition, _charPos);
return;
}
ProcessLineFeed();
break;
default:
_charPos++;
break;
}
}
}
private async Task EatWhitespaceAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return;
}
}
else
{
_charPos++;
}
break;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (currentChar == ' ' || char.IsWhiteSpace(currentChar))
{
_charPos++;
}
else
{
return;
}
break;
}
}
}
private async Task ParseStringAsync(char quote, ReadType readType, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
_charPos++;
ShiftBufferIfNeeded();
await ReadStringIntoBufferAsync(quote, cancellationToken).ConfigureAwait(false);
ParseReadString(quote, readType);
}
private async Task<bool> MatchValueAsync(string value, CancellationToken cancellationToken)
{
return MatchValue(await EnsureCharsAsync(value.Length - 1, true, cancellationToken).ConfigureAwait(false), value);
}
private async Task<bool> MatchValueWithTrailingSeparatorAsync(string value, CancellationToken cancellationToken)
{
// will match value and then move to the next character, checking that it is a separator character
if (!await MatchValueAsync(value, cancellationToken).ConfigureAwait(false))
{
return false;
}
if (!await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
return true;
}
return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0';
}
private async Task MatchAndSetAsync(string value, JsonToken newToken, object tokenValue, CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync(value, cancellationToken).ConfigureAwait(false))
{
SetToken(newToken, tokenValue);
}
else
{
throw JsonReaderException.Create(this, "Error parsing " + newToken.ToString().ToLowerInvariant() + " value.");
}
}
private Task ParseTrueAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.True, JsonToken.Boolean, true, cancellationToken);
}
private Task ParseFalseAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.False, JsonToken.Boolean, false, cancellationToken);
}
private Task ParseNullAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.Null, JsonToken.Null, null, cancellationToken);
}
private async Task ParseConstructorAsync(CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync("new", cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
int initialPosition = _charPos;
int endPosition;
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing constructor.");
}
}
else
{
endPosition = _charPos;
_charPos++;
break;
}
}
else if (char.IsLetterOrDigit(currentChar))
{
_charPos++;
}
else if (currentChar == StringUtils.CarriageReturn)
{
endPosition = _charPos;
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
break;
}
else if (currentChar == StringUtils.LineFeed)
{
endPosition = _charPos;
ProcessLineFeed();
break;
}
else if (char.IsWhiteSpace(currentChar))
{
endPosition = _charPos;
_charPos++;
break;
}
else if (currentChar == '(')
{
endPosition = _charPos;
break;
}
else
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
_stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition);
string constructorName = _stringReference.ToString();
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_chars[_charPos] != '(')
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
ClearRecentString();
SetToken(JsonToken.StartConstructor, constructorName);
}
else
{
throw JsonReaderException.Create(this, "Unexpected content while parsing JSON.");
}
}
private async Task<object> ParseNumberNaNAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberNaN(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NaN, cancellationToken).ConfigureAwait(false));
}
private async Task<object> ParseNumberPositiveInfinityAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberPositiveInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.PositiveInfinity, cancellationToken).ConfigureAwait(false));
}
private async Task<object> ParseNumberNegativeInfinityAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberNegativeInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NegativeInfinity, cancellationToken).ConfigureAwait(false));
}
private async Task ParseNumberAsync(ReadType readType, CancellationToken cancellationToken)
{
ShiftBufferIfNeeded();
char firstChar = _chars[_charPos];
int initialPosition = _charPos;
await ReadNumberIntoBufferAsync(cancellationToken).ConfigureAwait(false);
ParseReadNumber(readType, firstChar, initialPosition);
}
private Task ParseUndefinedAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.Undefined, JsonToken.Undefined, null, cancellationToken);
}
private async Task<bool> ParsePropertyAsync(CancellationToken cancellationToken)
{
char firstChar = _chars[_charPos];
char quoteChar;
if (firstChar == '"' || firstChar == '\'')
{
_charPos++;
quoteChar = firstChar;
ShiftBufferIfNeeded();
await ReadStringIntoBufferAsync(quoteChar, cancellationToken).ConfigureAwait(false);
}
else if (ValidIdentifierChar(firstChar))
{
quoteChar = '\0';
ShiftBufferIfNeeded();
await ParseUnquotedPropertyAsync(cancellationToken).ConfigureAwait(false);
}
else
{
throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
string propertyName;
if (NameTable != null)
{
propertyName = NameTable.Get(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length)
// no match in name table
?? _stringReference.ToString();
}
else
{
propertyName = _stringReference.ToString();
}
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_chars[_charPos] != ':')
{
throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
SetToken(JsonToken.PropertyName, propertyName);
_quoteChar = quoteChar;
ClearRecentString();
return true;
}
private async Task ReadNumberIntoBufferAsync(CancellationToken cancellationToken)
{
int charPos = _charPos;
while (true)
{
char currentChar = _chars[charPos];
if (currentChar == '\0')
{
_charPos = charPos;
if (_charsUsed == charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
return;
}
}
else
{
return;
}
}
else if (ReadNumberCharIntoBuffer(currentChar, charPos))
{
return;
}
else
{
charPos++;
}
}
}
private async Task ParseUnquotedPropertyAsync(CancellationToken cancellationToken)
{
int initialPosition = _charPos;
// parse unquoted property name until whitespace or colon
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name.");
}
continue;
}
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
return;
}
if (ReadUnquotedPropertyReportIfDone(currentChar, initialPosition))
{
return;
}
}
}
private async Task<bool> ReadNullCharAsync(CancellationToken cancellationToken)
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
_isEndOfFile = true;
return true;
}
}
else
{
_charPos++;
}
return false;
}
private async Task HandleNullAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos + 1] == 'u')
{
await ParseNullAsync(cancellationToken).ConfigureAwait(false);
return;
}
_charPos += 2;
throw CreateUnexpectedCharacterException(_chars[_charPos - 1]);
}
_charPos = _charsUsed;
throw CreateUnexpectedEndException();
}
private async Task ReadFinishedAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_isEndOfFile)
{
SetToken(JsonToken.None);
return;
}
if (_chars[_charPos] == '/')
{
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
}
else
{
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
}
SetToken(JsonToken.None);
}
private async Task<object> ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.PostValue:
if (await ParsePostValueAsync(true, cancellationToken).ConfigureAwait(false))
{
return null;
}
goto case State.Start;
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false);
return FinishReadQuotedStringValue(readType);
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
return ParseNumberNegativeInfinity(readType);
}
else
{
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
}
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (readType != ReadType.ReadAsString)
{
_charPos++;
throw CreateUnexpectedCharacterException(currentChar);
}
await ParseNumberAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
return Value;
case 't':
case 'f':
if (readType != ReadType.ReadAsString)
{
_charPos++;
throw CreateUnexpectedCharacterException(currentChar);
}
string expected = currentChar == 't' ? JsonConvert.True : JsonConvert.False;
if (!await MatchValueWithTrailingSeparatorAsync(expected, cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
SetToken(JsonToken.String, expected);
return expected;
case 'I':
return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
case 'N':
return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task<object> ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.PostValue:
if (await ParsePostValueAsync(true, cancellationToken).ConfigureAwait(false))
{
return null;
}
goto case State.Start;
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false);
return FinishReadQuotedNumber(readType);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case 'N':
return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false);
case 'I':
return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
return await ParseNumberNegativeInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
}
else
{
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
}
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="bool"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="bool"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsBooleanAsync(cancellationToken) : base.ReadAsBooleanAsync(cancellationToken);
}
internal async Task<bool?> DoReadAsBooleanAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.PostValue:
if (await ParsePostValueAsync(true, cancellationToken).ConfigureAwait(false))
{
return null;
}
goto case State.Start;
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false);
return ReadBooleanString(_stringReference.ToString());
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '-':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
bool b;
#if HAVE_BIG_INTEGER
if (Value is BigInteger)
{
b = (BigInteger)Value != 0;
}
else
#endif
{
b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture);
}
SetToken(JsonToken.Boolean, b, false);
return b;
case 't':
case 'f':
bool isTrue = currentChar == 't';
if (!await MatchValueWithTrailingSeparatorAsync(isTrue ? JsonConvert.True : JsonConvert.False, cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
SetToken(JsonToken.Boolean, isTrue);
return isTrue;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="byte"/>[].
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="byte"/>[]. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<byte[]> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsBytesAsync(cancellationToken) : base.ReadAsBytesAsync(cancellationToken);
}
internal async Task<byte[]> DoReadAsBytesAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
bool isWrapped = false;
switch (_currentState)
{
case State.PostValue:
if (await ParsePostValueAsync(true, cancellationToken).ConfigureAwait(false))
{
return null;
}
goto case State.Start;
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.ReadAsBytes, cancellationToken).ConfigureAwait(false);
byte[] data = (byte[])Value;
if (isWrapped)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (TokenType != JsonToken.EndObject)
{
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
SetToken(JsonToken.Bytes, data, false);
}
return data;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
await ReadIntoWrappedTypeObjectAsync(cancellationToken).ConfigureAwait(false);
isWrapped = true;
break;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return await ReadArrayIntoByteArrayAsync(cancellationToken).ConfigureAwait(false);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task ReadIntoWrappedTypeObjectAsync(CancellationToken cancellationToken)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value.ToString() == JsonTypeReflector.ValuePropertyName)
{
return;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTime"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTime"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDateTimeAsync(cancellationToken) : base.ReadAsDateTimeAsync(cancellationToken);
}
internal async Task<DateTime?> DoReadAsDateTimeAsync(CancellationToken cancellationToken)
{
return (DateTime?)await ReadStringValueAsync(ReadType.ReadAsDateTime, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDateTimeOffsetAsync(cancellationToken) : base.ReadAsDateTimeOffsetAsync(cancellationToken);
}
internal async Task<DateTimeOffset?> DoReadAsDateTimeOffsetAsync(CancellationToken cancellationToken)
{
return (DateTimeOffset?)await ReadStringValueAsync(ReadType.ReadAsDateTimeOffset, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="decimal"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="decimal"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDecimalAsync(cancellationToken) : base.ReadAsDecimalAsync(cancellationToken);
}
internal async Task<decimal?> DoReadAsDecimalAsync(CancellationToken cancellationToken)
{
return (decimal?)await ReadNumberValueAsync(ReadType.ReadAsDecimal, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="double"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="double"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDoubleAsync(cancellationToken) : base.ReadAsDoubleAsync(cancellationToken);
}
internal async Task<double?> DoReadAsDoubleAsync(CancellationToken cancellationToken)
{
return (double?)await ReadNumberValueAsync(ReadType.ReadAsDouble, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="int"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="int"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsInt32Async(cancellationToken) : base.ReadAsInt32Async(cancellationToken);
}
internal async Task<int?> DoReadAsInt32Async(CancellationToken cancellationToken)
{
return (int?)await ReadNumberValueAsync(ReadType.ReadAsInt32, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="string"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="string"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<string> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsStringAsync(cancellationToken) : base.ReadAsStringAsync(cancellationToken);
}
internal async Task<string> DoReadAsStringAsync(CancellationToken cancellationToken)
{
return (string)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
}
}
}
#endif
| |
using DG.Tweening;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace EA4S.Assessment
{
public class DefaultQuestionPlacer : IQuestionPlacer
{
protected IAudioManager audioManager;
protected float questionSize;
protected float answerSize;
protected bool alsoDrawing;
public DefaultQuestionPlacer( IAudioManager audioManager, float questionSize, float answerSize, bool alsoDrawing = false)
{
this.audioManager = audioManager;
this.questionSize = questionSize;
this.answerSize = answerSize;
this.alsoDrawing = alsoDrawing;
}
protected bool isAnimating = false;
public bool IsAnimating()
{
return isAnimating;
}
protected IQuestion[] allQuestions;
public void Place( IQuestion[] question)
{
allQuestions = question;
isAnimating = true;
images = new List< LetterObjectView>();
Coroutine.Start( PlaceCoroutine());
}
IEnumerator PlaceCoroutine()
{
return GetPlaceCoroutine();
}
public virtual IEnumerator GetPlaceCoroutine()
{
// Count questions and answers
int questionsNumber = 0;
int placeHoldersNumber = 0;
foreach (var q in allQuestions)
{
questionsNumber++;
placeHoldersNumber += q.PlaceholdersCount();
}
var bounds = WorldBounds.Instance;
// Text justification "algorithm"
var gap = bounds.QuestionGap();
float occupiedSpace = questionsNumber*questionSize + answerSize*placeHoldersNumber;
if (alsoDrawing)
occupiedSpace += questionsNumber * 3f;
float blankSpace = gap - occupiedSpace;
// 3 words => 4 white zones (need increment by 1)
// | O O O |
float spaceIncrement = blankSpace / (questionsNumber + 1);
//Implement Line Break only if needed
if ( blankSpace <= bounds.HalfLetterSize()/2f )
throw new InvalidOperationException( "Need a line break becase 1 line is not enough for all");
var flow = AssessmentConfiguration.Instance.LocaleTextFlow;
float sign;
Vector3 currentPos;
if (flow == AssessmentConfiguration.TextFlow.RightToLeft)
{
currentPos = bounds.ToTheRightQuestionStart();
//currentPos.x -= answerSize / 2.0f;
sign = -1;
}
else
{
currentPos = bounds.ToTheLeftQuestionStart();
currentPos.x += answerSize / 2.0f;
sign = 1;
}
currentPos.y -= 1.5f;
int questionIndex = 0; //TODO: check if this redundant
for (int i = 0; i < questionsNumber; i++)
{
currentPos.x += (spaceIncrement + questionSize/2) * sign;
yield return PlaceQuestion(allQuestions[questionIndex], currentPos);
currentPos.x += (questionSize * sign) / 2;
if (alsoDrawing)
{
currentPos.x += (3f * sign) / 2;
yield return PlaceImage( allQuestions[questionIndex], currentPos);
currentPos.x += (3.3f * sign) / 2;
Debug.Log("PlacedImage######");
}
foreach (var p in allQuestions[ questionIndex].GetPlaceholders())
{
currentPos.x += (answerSize * sign)/2;
yield return PlacePlaceholder( allQuestions[ questionIndex], p, currentPos);
currentPos.x += (answerSize * sign) / 2;
}
questionIndex++;
}
// give time to finish animating elements
yield return TimeEngine.Wait( 0.65f);
isAnimating = false;
}
private List< LetterObjectView> images;
protected IEnumerator PlaceImage( IQuestion q, Vector3 imagePos)
{
var ll = LivingLetterFactory.Instance.SpawnQuestion( q.Image());
images.Add( ll);
ll.transform.position = imagePos;
ll.transform.localScale = Vector3.zero;
ll.Poof( ElementsSize.PoofOffset);
audioManager.PlaySound( Sfx.Poof);
ll.transform.DOScale( 1, 0.3f);
return TimeEngine.Wait( 1.0f);
}
protected IEnumerator PlaceQuestion( IQuestion q, Vector3 position)
{
var ll = q.gameObject.GetComponent< LetterObjectView>();
ll.Poof( ElementsSize.PoofOffset);
audioManager.PlaySound( Sfx.Poof);
ll.transform.localPosition = position;
ll.transform.DOScale( 1, 0.3f);
q.gameObject.GetComponent< QuestionBehaviour>().OnSpawned();
return TimeEngine.Wait( 1.0f);
}
protected IEnumerator PlacePlaceholder( IQuestion q, GameObject placeholder, Vector3 position)
{
Transform tr = placeholder.transform;
tr.localPosition = position + new Vector3( 0, 5, 0);
tr.localScale = new Vector3( 0.5f, 0.5f, 0.5f);
audioManager.PlaySound( Sfx.StarFlower);
float adjust = 4.5f;
if (answerSize == (1.5f * 3f))
adjust = 3;
if (answerSize == (1f * 3f))
adjust = ElementsSize.DropZoneScale;
var seq = DOTween.Sequence();
seq
.Insert( 0, tr.DOScale( new Vector3( adjust, ElementsSize.DropZoneScale, 1), 0.4f))
.Insert( 0, tr.DOMove( position, 0.6f));
return TimeEngine.Wait( 0.4f);
}
public void RemoveQuestions()
{
isAnimating = true;
Coroutine.Start( RemoveCoroutine());
}
IEnumerator RemoveCoroutine()
{
foreach( var q in allQuestions)
{
foreach (var p in q.GetPlaceholders())
yield return FadeOutPlaceholder( p);
foreach (var img in images)
yield return FadeOutImage( img);
yield return FadeOutQuestion( q);
}
// give time to finish animating elements
yield return TimeEngine.Wait( 0.65f);
isAnimating = false;
}
IEnumerator FadeOutImage( LetterObjectView image)
{
audioManager.PlaySound( Sfx.Poof);
image.Poof();
image.transform.DOScale(0, 0.4f).OnComplete( () => GameObject.Destroy( image.gameObject));
yield return TimeEngine.Wait( 0.1f);
}
IEnumerator FadeOutQuestion( IQuestion q)
{
audioManager.PlaySound( Sfx.Poof);
q.gameObject.GetComponent< LetterObjectView>().Poof( ElementsSize.PoofOffset);
q.gameObject.transform.DOScale( 0, 0.4f).OnComplete(() => GameObject.Destroy( q.gameObject));
yield return TimeEngine.Wait( 0.1f);
}
IEnumerator FadeOutPlaceholder( GameObject go)
{
audioManager.PlaySound( Sfx.BalloonPop);
go.transform.DOScale(0, 0.23f).OnComplete(() => GameObject.Destroy( go));
yield return TimeEngine.Wait(0.06f);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// X509Extension.cs
//
namespace System.Security.Cryptography.X509Certificates {
using System.Collections;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
public class X509Extension : AsnEncodedData {
private bool m_critical = false;
internal X509Extension(string oid) : base (new Oid(oid, OidGroup.ExtensionOrAttribute, false)) {}
internal X509Extension(IntPtr pExtension) {
CAPI.CERT_EXTENSION extension = (CAPI.CERT_EXTENSION) Marshal.PtrToStructure(pExtension, typeof(CAPI.CERT_EXTENSION));
m_critical = extension.fCritical;
string oidValue = extension.pszObjId;
m_oid = new Oid(oidValue, OidGroup.ExtensionOrAttribute, false);
byte[] rawData = new byte[extension.Value.cbData];
if (extension.Value.pbData != IntPtr.Zero)
Marshal.Copy(extension.Value.pbData, rawData, 0, rawData.Length);
m_rawData = rawData;
}
protected X509Extension() : base () {}
public X509Extension (string oid, byte[] rawData, bool critical) : this (new Oid(oid, OidGroup.ExtensionOrAttribute, true), rawData, critical) {}
public X509Extension (AsnEncodedData encodedExtension, bool critical) : this (encodedExtension.Oid, encodedExtension.RawData, critical) {}
public X509Extension (Oid oid, byte[] rawData, bool critical) : base (oid, rawData) {
if (base.Oid == null || base.Oid.Value == null)
throw new ArgumentNullException("oid");
if (base.Oid.Value.Length == 0)
throw new ArgumentException(SR.GetString(SR.Arg_EmptyOrNullString), "oid.Value");
m_critical = critical;
}
public bool Critical {
get {
return m_critical;
}
set {
m_critical = value;
}
}
public override void CopyFrom (AsnEncodedData asnEncodedData) {
if (asnEncodedData == null)
{
throw new ArgumentNullException("asnEncodedData");
}
X509Extension extension = asnEncodedData as X509Extension;
if (extension == null)
throw new ArgumentException(SR.GetString(SR.Cryptography_X509_ExtensionMismatch));
base.CopyFrom(asnEncodedData);
m_critical = extension.Critical;
}
}
//
// Key Usage flags map the definition in wincrypt.h, so that no mapping will be necessary.
//
[Flags]
public enum X509KeyUsageFlags {
None = 0x0000,
EncipherOnly = 0x0001,
CrlSign = 0x0002,
KeyCertSign = 0x0004,
KeyAgreement = 0x0008,
DataEncipherment = 0x0010,
KeyEncipherment = 0x0020,
NonRepudiation = 0x0040,
DigitalSignature = 0x0080,
DecipherOnly = 0x8000
}
public sealed class X509KeyUsageExtension : X509Extension {
private uint m_keyUsages = 0;
private bool m_decoded = false;
public X509KeyUsageExtension() : base (CAPI.szOID_KEY_USAGE) {
m_decoded = true;
}
public X509KeyUsageExtension (X509KeyUsageFlags keyUsages, bool critical) :
base (CAPI.szOID_KEY_USAGE, EncodeExtension(keyUsages), critical) {}
public X509KeyUsageExtension (AsnEncodedData encodedKeyUsage, bool critical) :
base (CAPI.szOID_KEY_USAGE, encodedKeyUsage.RawData, critical) {}
public X509KeyUsageFlags KeyUsages {
get {
if (!m_decoded)
DecodeExtension();
return (X509KeyUsageFlags) m_keyUsages;
}
}
public override void CopyFrom (AsnEncodedData asnEncodedData) {
base.CopyFrom(asnEncodedData);
m_decoded = false;
}
private void DecodeExtension () {
uint cbDecoded = 0;
SafeLocalAllocHandle decoded = null;
bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_KEY_USAGE),
m_rawData,
out decoded,
out cbDecoded);
if (result == false)
throw new CryptographicException(Marshal.GetLastWin32Error());
CAPI.CRYPTOAPI_BLOB pKeyUsage = (CAPI.CRYPTOAPI_BLOB) Marshal.PtrToStructure(decoded.DangerousGetHandle(), typeof(CAPI.CRYPTOAPI_BLOB));
if (pKeyUsage.cbData > 4)
pKeyUsage.cbData = 4;
byte[] keyUsage = new byte[4];
if (pKeyUsage.pbData != IntPtr.Zero)
Marshal.Copy(pKeyUsage.pbData, keyUsage, 0, (int) pKeyUsage.cbData);
m_keyUsages = BitConverter.ToUInt32(keyUsage, 0);
m_decoded = true;
decoded.Dispose();
}
private static unsafe byte[] EncodeExtension (X509KeyUsageFlags keyUsages) {
CAPI.CRYPT_BIT_BLOB blob = new CAPI.CRYPT_BIT_BLOB();
blob.cbData = 2;
blob.pbData = new IntPtr(&keyUsages);
blob.cUnusedBits = 0;
byte[] encodedKeyUsages = null;
if (!CAPI.EncodeObject(CAPI.szOID_KEY_USAGE, new IntPtr(&blob), out encodedKeyUsages))
throw new CryptographicException(Marshal.GetLastWin32Error());
return encodedKeyUsages;
}
}
public sealed class X509BasicConstraintsExtension : X509Extension {
private bool m_isCA = false;
private bool m_hasPathLenConstraint = false;
private int m_pathLenConstraint = 0;
private bool m_decoded = false;
public X509BasicConstraintsExtension() : base (CAPI.szOID_BASIC_CONSTRAINTS2) {
m_decoded = true;
}
public X509BasicConstraintsExtension (bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical) :
base (CAPI.szOID_BASIC_CONSTRAINTS2, EncodeExtension(certificateAuthority, hasPathLengthConstraint, pathLengthConstraint), critical) {}
public X509BasicConstraintsExtension (AsnEncodedData encodedBasicConstraints, bool critical) :
base (CAPI.szOID_BASIC_CONSTRAINTS2, encodedBasicConstraints.RawData, critical) {}
public bool CertificateAuthority {
get {
if (!m_decoded)
DecodeExtension();
return m_isCA;
}
}
public bool HasPathLengthConstraint {
get {
if (!m_decoded)
DecodeExtension();
return m_hasPathLenConstraint;
}
}
public int PathLengthConstraint {
get {
if (!m_decoded)
DecodeExtension();
return m_pathLenConstraint;
}
}
public override void CopyFrom (AsnEncodedData asnEncodedData) {
base.CopyFrom(asnEncodedData);
m_decoded = false;
}
private void DecodeExtension () {
uint cbDecoded = 0;
SafeLocalAllocHandle decoded = null;
if (Oid.Value == CAPI.szOID_BASIC_CONSTRAINTS) {
bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_BASIC_CONSTRAINTS),
m_rawData,
out decoded,
out cbDecoded);
if (result == false)
throw new CryptographicException(Marshal.GetLastWin32Error());
CAPI.CERT_BASIC_CONSTRAINTS_INFO pBasicConstraints = (CAPI.CERT_BASIC_CONSTRAINTS_INFO) Marshal.PtrToStructure(decoded.DangerousGetHandle(),
typeof(CAPI.CERT_BASIC_CONSTRAINTS_INFO));
// take the first byte.
byte[] isCA = new byte[1];
Marshal.Copy(pBasicConstraints.SubjectType.pbData, isCA, 0, 1);
m_isCA = (isCA[0] & CAPI.CERT_CA_SUBJECT_FLAG) != 0 ? true : false;
m_hasPathLenConstraint = pBasicConstraints.fPathLenConstraint;
m_pathLenConstraint = (int) pBasicConstraints.dwPathLenConstraint;
} else {
bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_BASIC_CONSTRAINTS2),
m_rawData,
out decoded,
out cbDecoded);
if (result == false)
throw new CryptographicException(Marshal.GetLastWin32Error());
CAPI.CERT_BASIC_CONSTRAINTS2_INFO pBasicConstraints2 = (CAPI.CERT_BASIC_CONSTRAINTS2_INFO) Marshal.PtrToStructure(decoded.DangerousGetHandle(),
typeof(CAPI.CERT_BASIC_CONSTRAINTS2_INFO));
m_isCA = pBasicConstraints2.fCA == 0 ? false : true;
m_hasPathLenConstraint = pBasicConstraints2.fPathLenConstraint == 0 ? false : true;
m_pathLenConstraint = (int) pBasicConstraints2.dwPathLenConstraint;
}
m_decoded = true;
decoded.Dispose();
}
private static unsafe byte[] EncodeExtension (bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint) {
CAPI.CERT_BASIC_CONSTRAINTS2_INFO pBasicConstraints2 = new CAPI.CERT_BASIC_CONSTRAINTS2_INFO();
pBasicConstraints2.fCA = certificateAuthority ? 1 : 0;
pBasicConstraints2.fPathLenConstraint = hasPathLengthConstraint ? 1 : 0;
if (hasPathLengthConstraint) {
if (pathLengthConstraint < 0)
throw new ArgumentOutOfRangeException("pathLengthConstraint", SR.GetString(SR.Arg_OutOfRange_NeedNonNegNum));
pBasicConstraints2.dwPathLenConstraint = (uint) pathLengthConstraint;
}
byte[] encodedBasicConstraints = null;
if (!CAPI.EncodeObject(CAPI.szOID_BASIC_CONSTRAINTS2, new IntPtr(&pBasicConstraints2), out encodedBasicConstraints))
throw new CryptographicException(Marshal.GetLastWin32Error());
return encodedBasicConstraints;
}
}
public sealed class X509EnhancedKeyUsageExtension : X509Extension {
private OidCollection m_enhancedKeyUsages;
private bool m_decoded = false;
public X509EnhancedKeyUsageExtension() : base (CAPI.szOID_ENHANCED_KEY_USAGE) {
m_enhancedKeyUsages = new OidCollection();
m_decoded = true;
}
public X509EnhancedKeyUsageExtension(OidCollection enhancedKeyUsages, bool critical) :
base (CAPI.szOID_ENHANCED_KEY_USAGE, EncodeExtension(enhancedKeyUsages), critical) {}
public X509EnhancedKeyUsageExtension(AsnEncodedData encodedEnhancedKeyUsages, bool critical) :
base (CAPI.szOID_ENHANCED_KEY_USAGE, encodedEnhancedKeyUsages.RawData, critical) {}
public OidCollection EnhancedKeyUsages {
get {
if (!m_decoded)
DecodeExtension();
OidCollection oids = new OidCollection();
foreach(Oid oid in m_enhancedKeyUsages) {
oids.Add(oid);
}
return oids;
}
}
public override void CopyFrom (AsnEncodedData asnEncodedData) {
base.CopyFrom(asnEncodedData);
m_decoded = false;
}
private void DecodeExtension () {
uint cbDecoded = 0;
SafeLocalAllocHandle decoded = null;
bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_ENHANCED_KEY_USAGE),
m_rawData,
out decoded,
out cbDecoded);
if (result == false)
throw new CryptographicException(Marshal.GetLastWin32Error());
CAPI.CERT_ENHKEY_USAGE pEnhKeyUsage = (CAPI.CERT_ENHKEY_USAGE) Marshal.PtrToStructure(decoded.DangerousGetHandle(), typeof(CAPI.CERT_ENHKEY_USAGE));
m_enhancedKeyUsages = new OidCollection();
for (int index = 0; index < pEnhKeyUsage.cUsageIdentifier; index++) {
IntPtr pszOid = Marshal.ReadIntPtr(new IntPtr((long) pEnhKeyUsage.rgpszUsageIdentifier + index * Marshal.SizeOf(typeof(IntPtr))));
string oidValue = Marshal.PtrToStringAnsi(pszOid);
Oid oid = new Oid(oidValue, OidGroup.ExtensionOrAttribute, false);
m_enhancedKeyUsages.Add(oid);
}
m_decoded = true;
decoded.Dispose();
}
private static unsafe byte[] EncodeExtension (OidCollection enhancedKeyUsages) {
if (enhancedKeyUsages == null)
throw new ArgumentNullException("enhancedKeyUsages");
SafeLocalAllocHandle safeLocalAllocHandle = X509Utils.CopyOidsToUnmanagedMemory(enhancedKeyUsages);
byte[] encodedEnhancedKeyUsages = null;
using (safeLocalAllocHandle) {
CAPI.CERT_ENHKEY_USAGE pEnhKeyUsage = new CAPI.CERT_ENHKEY_USAGE();
pEnhKeyUsage.cUsageIdentifier = (uint) enhancedKeyUsages.Count;
pEnhKeyUsage.rgpszUsageIdentifier = safeLocalAllocHandle.DangerousGetHandle();
if (!CAPI.EncodeObject(CAPI.szOID_ENHANCED_KEY_USAGE, new IntPtr(&pEnhKeyUsage), out encodedEnhancedKeyUsages))
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return encodedEnhancedKeyUsages;
}
}
public enum X509SubjectKeyIdentifierHashAlgorithm {
Sha1 = 0,
ShortSha1 = 1,
CapiSha1 = 2,
}
public sealed class X509SubjectKeyIdentifierExtension : X509Extension {
private string m_subjectKeyIdentifier;
private bool m_decoded = false;
public X509SubjectKeyIdentifierExtension() : base (CAPI.szOID_SUBJECT_KEY_IDENTIFIER) {
m_subjectKeyIdentifier = null;
m_decoded = true;
}
public X509SubjectKeyIdentifierExtension (string subjectKeyIdentifier, bool critical) :
base (CAPI.szOID_SUBJECT_KEY_IDENTIFIER, EncodeExtension(subjectKeyIdentifier), critical) {}
public X509SubjectKeyIdentifierExtension (byte[] subjectKeyIdentifier, bool critical) :
base (CAPI.szOID_SUBJECT_KEY_IDENTIFIER, EncodeExtension(subjectKeyIdentifier), critical) {}
public X509SubjectKeyIdentifierExtension (AsnEncodedData encodedSubjectKeyIdentifier, bool critical) :
base (CAPI.szOID_SUBJECT_KEY_IDENTIFIER, encodedSubjectKeyIdentifier.RawData, critical) {}
public X509SubjectKeyIdentifierExtension (PublicKey key, bool critical) :
base (CAPI.szOID_SUBJECT_KEY_IDENTIFIER, EncodePublicKey(key, X509SubjectKeyIdentifierHashAlgorithm.Sha1), critical) {}
public X509SubjectKeyIdentifierExtension (PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm, bool critical) :
base (CAPI.szOID_SUBJECT_KEY_IDENTIFIER, EncodePublicKey(key, algorithm), critical) {}
public string SubjectKeyIdentifier {
get {
if (!m_decoded)
DecodeExtension();
return m_subjectKeyIdentifier;
}
}
public override void CopyFrom (AsnEncodedData asnEncodedData) {
base.CopyFrom(asnEncodedData);
m_decoded = false;
}
private void DecodeExtension () {
uint cbDecoded = 0;
SafeLocalAllocHandle decoded = null;
SafeLocalAllocHandle pb = X509Utils.StringToAnsiPtr(CAPI.szOID_SUBJECT_KEY_IDENTIFIER);
bool result = CAPI.DecodeObject(pb.DangerousGetHandle(),
m_rawData,
out decoded,
out cbDecoded);
if (!result)
throw new CryptographicException(Marshal.GetLastWin32Error());
CAPI.CRYPTOAPI_BLOB pSubjectKeyIdentifier = (CAPI.CRYPTOAPI_BLOB) Marshal.PtrToStructure(decoded.DangerousGetHandle(), typeof(CAPI.CRYPTOAPI_BLOB));
byte[] hexArray = CAPI.BlobToByteArray(pSubjectKeyIdentifier);
m_subjectKeyIdentifier = X509Utils.EncodeHexString(hexArray);
m_decoded = true;
decoded.Dispose();
pb.Dispose();
}
private static unsafe byte[] EncodeExtension (string subjectKeyIdentifier) {
if (subjectKeyIdentifier == null)
throw new ArgumentNullException("subjectKeyIdentifier");
return EncodeExtension(X509Utils.DecodeHexString(subjectKeyIdentifier));
}
private static unsafe byte[] EncodeExtension (byte[] subjectKeyIdentifier) {
if (subjectKeyIdentifier == null)
throw new ArgumentNullException("subjectKeyIdentifier");
if (subjectKeyIdentifier.Length == 0)
throw new ArgumentException("subjectKeyIdentifier");
byte[] encodedSubjectKeyIdentifier = null;
fixed (byte* pb = subjectKeyIdentifier) {
CAPI.CRYPTOAPI_BLOB pSubjectKeyIdentifier = new CAPI.CRYPTOAPI_BLOB();
pSubjectKeyIdentifier.pbData = new IntPtr(pb);
pSubjectKeyIdentifier.cbData = (uint) subjectKeyIdentifier.Length;
if (!CAPI.EncodeObject(CAPI.szOID_SUBJECT_KEY_IDENTIFIER, new IntPtr(&pSubjectKeyIdentifier), out encodedSubjectKeyIdentifier))
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return encodedSubjectKeyIdentifier;
}
// Construct CERT_PUBLIC_KEY_INFO2 in unmanged memory from given encoded blobs.
private static unsafe SafeLocalAllocHandle EncodePublicKey (PublicKey key) {
SafeLocalAllocHandle publicKeyInfo = SafeLocalAllocHandle.InvalidHandle;
CAPI.CERT_PUBLIC_KEY_INFO2 * pPublicKeyInfo = null;
string objId = key.Oid.Value;
byte[] encodedParameters = key.EncodedParameters.RawData;
byte[] encodedKeyValue = key.EncodedKeyValue.RawData;
uint cbPublicKeyInfo = (uint) (Marshal.SizeOf(typeof(CAPI.CERT_PUBLIC_KEY_INFO2)) +
X509Utils.AlignedLength((uint) (objId.Length + 1)) +
X509Utils.AlignedLength((uint) encodedParameters.Length) +
encodedKeyValue.Length);
publicKeyInfo = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(cbPublicKeyInfo));
pPublicKeyInfo = (CAPI.CERT_PUBLIC_KEY_INFO2 *) publicKeyInfo.DangerousGetHandle();
IntPtr pszObjId = new IntPtr((long) pPublicKeyInfo + Marshal.SizeOf(typeof(CAPI.CERT_PUBLIC_KEY_INFO2)));
IntPtr pbParameters = new IntPtr((long) pszObjId + X509Utils.AlignedLength(((uint) (objId.Length + 1))));
IntPtr pbPublicKey = new IntPtr((long) pbParameters + X509Utils.AlignedLength((uint) encodedParameters.Length));
pPublicKeyInfo->Algorithm.pszObjId = pszObjId;
byte[] szObjId = new byte[objId.Length + 1];
Encoding.ASCII.GetBytes(objId, 0, objId.Length, szObjId, 0);
Marshal.Copy(szObjId, 0, pszObjId, szObjId.Length);
if (encodedParameters.Length > 0) {
pPublicKeyInfo->Algorithm.Parameters.cbData = (uint) encodedParameters.Length;
pPublicKeyInfo->Algorithm.Parameters.pbData = pbParameters;
Marshal.Copy(encodedParameters, 0, pbParameters, encodedParameters.Length);
}
pPublicKeyInfo->PublicKey.cbData = (uint) encodedKeyValue.Length;
pPublicKeyInfo->PublicKey.pbData = pbPublicKey;
Marshal.Copy(encodedKeyValue, 0, pbPublicKey, encodedKeyValue.Length);
return publicKeyInfo;
}
private static unsafe byte[] EncodePublicKey (PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm) {
if (key == null)
throw new ArgumentNullException("key");
// Construct CERT_PUBLIC_KEY_INFO2 in unmanged memory from given encoded blobs.
SafeLocalAllocHandle publicKeyInfo = EncodePublicKey(key);
CAPI.CERT_PUBLIC_KEY_INFO2 * pPublicKeyInfo = (CAPI.CERT_PUBLIC_KEY_INFO2 *) publicKeyInfo.DangerousGetHandle();
byte [] buffer = new byte[20];
byte [] identifier = null;
fixed (byte * pBuffer = buffer) {
uint cbData = (uint)buffer.Length;
IntPtr pbData = new IntPtr(pBuffer);
try {
if ((X509SubjectKeyIdentifierHashAlgorithm.Sha1 == algorithm)
|| (X509SubjectKeyIdentifierHashAlgorithm.ShortSha1 == algorithm)) {
//+=================================================================
// (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of
// the value of the BIT STRING subjectPublicKey (excluding the tag,
// length, and number of unused bits).
if (!CAPI.CryptHashCertificate(
IntPtr.Zero, // hCryptProv
CAPI.CALG_SHA1,
0, // dwFlags,
pPublicKeyInfo->PublicKey.pbData,
pPublicKeyInfo->PublicKey.cbData,
pbData,
new IntPtr(&cbData)))
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
}
//+=================================================================
// Microsoft convention: The keyIdentifier is composed of the
// 160-bit SHA-1 hash of the encoded subjectPublicKey BITSTRING
// (including the tag, length, and number of unused bits).
else if (X509SubjectKeyIdentifierHashAlgorithm.CapiSha1 == algorithm) {
if (!CAPI.CryptHashPublicKeyInfo(
IntPtr.Zero, // hCryptProv
CAPI.CALG_SHA1,
0, // dwFlags,
CAPI.X509_ASN_ENCODING,
new IntPtr(pPublicKeyInfo),
pbData,
new IntPtr(&cbData))) {
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
}
} else {
throw new ArgumentException("algorithm");
}
//+=================================================================
// (2) The keyIdentifier is composed of a four bit type field with
// the value 0100 followed by the least significant 60 bits of the
// SHA-1 hash of the value of the BIT STRING subjectPublicKey
// (excluding the tag, length, and number of unused bit string bits)
if (X509SubjectKeyIdentifierHashAlgorithm.ShortSha1 == algorithm) {
identifier = new byte[8];
Array.Copy(buffer, buffer.Length - 8, identifier, 0, identifier.Length);
identifier[0] &= 0x0f;
identifier[0] |= 0x40;
} else {
identifier = buffer;
// return the meaningful part only
if (buffer.Length > (int)cbData) {
identifier = new byte[cbData];
Array.Copy(buffer, 0, identifier, 0, identifier.Length);
}
}
} finally {
publicKeyInfo.Dispose();
}
}
return EncodeExtension(identifier);
}
}
public sealed class X509ExtensionCollection : ICollection {
private ArrayList m_list = new ArrayList();
//
// Constructors.
//
public X509ExtensionCollection() {}
internal unsafe X509ExtensionCollection(SafeCertContextHandle safeCertContextHandle) {
using (SafeCertContextHandle certContext = CAPI.CertDuplicateCertificateContext(safeCertContextHandle)) {
CAPI.CERT_CONTEXT pCertContext = *((CAPI.CERT_CONTEXT*) certContext.DangerousGetHandle());
CAPI.CERT_INFO pCertInfo = (CAPI.CERT_INFO) Marshal.PtrToStructure(pCertContext.pCertInfo, typeof(CAPI.CERT_INFO));
uint cExtensions = pCertInfo.cExtension;
IntPtr rgExtensions = pCertInfo.rgExtension;
for (uint index = 0; index < cExtensions; index++) {
X509Extension extension = new X509Extension(new IntPtr((long)rgExtensions + (index * Marshal.SizeOf(typeof(CAPI.CERT_EXTENSION)))));
X509Extension customExtension = CryptoConfig.CreateFromName(extension.Oid.Value) as X509Extension;
if (customExtension != null) {
customExtension.CopyFrom(extension);
extension = customExtension;
}
Add(extension);
}
}
}
public X509Extension this[int index] {
get {
if (index < 0)
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumNotStarted));
if (index >= m_list.Count)
throw new ArgumentOutOfRangeException("index", SR.GetString(SR.ArgumentOutOfRange_Index));
return (X509Extension) m_list[index];
}
}
// Indexer using an OID friendly name or value.
public X509Extension this[string oid] {
get {
// If we were passed the friendly name, retrieve the value string.
string oidValue = X509Utils.FindOidInfoWithFallback(CAPI.CRYPT_OID_INFO_NAME_KEY, oid, OidGroup.ExtensionOrAttribute);
if (oidValue == null)
oidValue = oid;
foreach (X509Extension extension in m_list) {
if (String.Compare(extension.Oid.Value, oidValue, StringComparison.OrdinalIgnoreCase) == 0)
return extension;
}
return null;
}
}
public int Count {
get {
return m_list.Count;
}
}
public int Add (X509Extension extension) {
if (extension == null)
throw new ArgumentNullException("extension");
return m_list.Add(extension);
}
public X509ExtensionEnumerator GetEnumerator() {
return new X509ExtensionEnumerator(this);
}
/// <internalonly/>
IEnumerator IEnumerable.GetEnumerator() {
return new X509ExtensionEnumerator(this);
}
/// <internalonly/>
void ICollection.CopyTo(Array array, int index) {
if (array == null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException(SR.GetString(SR.Arg_RankMultiDimNotSupported));
if (index < 0 || index >= array.Length)
throw new ArgumentOutOfRangeException("index", SR.GetString(SR.ArgumentOutOfRange_Index));
if (index + this.Count > array.Length)
throw new ArgumentException(SR.GetString(SR.Argument_InvalidOffLen));
for (int i=0; i < this.Count; i++) {
array.SetValue(this[i], index);
index++;
}
}
public void CopyTo(X509Extension[] array, int index) {
((ICollection)this).CopyTo(array, index);
}
public bool IsSynchronized {
get {
return false;
}
}
public Object SyncRoot {
get {
return this;
}
}
}
public sealed class X509ExtensionEnumerator : IEnumerator {
private X509ExtensionCollection m_extensions;
private int m_current;
private X509ExtensionEnumerator() {}
internal X509ExtensionEnumerator(X509ExtensionCollection extensions) {
m_extensions = extensions;
m_current = -1;
}
public X509Extension Current {
get {
return m_extensions[m_current];
}
}
/// <internalonly/>
Object IEnumerator.Current {
get {
return (Object) m_extensions[m_current];
}
}
public bool MoveNext() {
if (m_current == ((int) m_extensions.Count - 1))
return false;
m_current++;
return true;
}
public void Reset() {
m_current = -1;
}
}
}
| |
// 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.
//#define XSLT2
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Xml.Xsl.Xslt
{
using StringConcat = System.Xml.Xsl.Runtime.StringConcat;
// a) Forward only, one pass.
// b) You should call MoveToFirstChildren on nonempty element node. (or may be skip)
internal class XsltInput : IErrorHelper
{
#if DEBUG
private const int InitRecordsSize = 1;
#else
private const int InitRecordsSize = 1 + 21;
#endif
private XmlReader _reader;
private IXmlLineInfo _readerLineInfo;
private bool _topLevelReader;
private CompilerScopeManager<VarPar> _scopeManager;
private KeywordsTable _atoms;
private Compiler _compiler;
private bool _reatomize;
// Cached properties. MoveTo* functions set them.
private XmlNodeType _nodeType;
private Record[] _records = new Record[InitRecordsSize];
private int _currentRecord;
private bool _isEmptyElement;
private int _lastTextNode;
private int _numAttributes;
private ContextInfo _ctxInfo;
private bool _attributesRead;
public XsltInput(XmlReader reader, Compiler compiler, KeywordsTable atoms)
{
Debug.Assert(reader != null);
Debug.Assert(atoms != null);
EnsureExpandEntities(reader);
IXmlLineInfo xmlLineInfo = reader as IXmlLineInfo;
_atoms = atoms;
_reader = reader;
_reatomize = reader.NameTable != atoms.NameTable;
_readerLineInfo = (xmlLineInfo != null && xmlLineInfo.HasLineInfo()) ? xmlLineInfo : null;
_topLevelReader = reader.ReadState == ReadState.Initial;
_scopeManager = new CompilerScopeManager<VarPar>(atoms);
_compiler = compiler;
_nodeType = XmlNodeType.Document;
}
// Cached properties
public XmlNodeType NodeType { get { return _nodeType == XmlNodeType.Element && 0 < _currentRecord ? XmlNodeType.Attribute : _nodeType; } }
public string LocalName { get { return _records[_currentRecord].localName; } }
public string NamespaceUri { get { return _records[_currentRecord].nsUri; } }
public string Prefix { get { return _records[_currentRecord].prefix; } }
public string Value { get { return _records[_currentRecord].value; } }
public string BaseUri { get { return _records[_currentRecord].baseUri; } }
public string QualifiedName { get { return _records[_currentRecord].QualifiedName; } }
public bool IsEmptyElement { get { return _isEmptyElement; } }
public string Uri { get { return _records[_currentRecord].baseUri; } }
public Location Start { get { return _records[_currentRecord].start; } }
public Location End { get { return _records[_currentRecord].end; } }
private static void EnsureExpandEntities(XmlReader reader)
{
XmlTextReader tr = reader as XmlTextReader;
if (tr != null && tr.EntityHandling != EntityHandling.ExpandEntities)
{
Debug.Assert(tr.Settings == null, "XmlReader created with XmlReader.Create should always expand entities.");
tr.EntityHandling = EntityHandling.ExpandEntities;
}
}
private void ExtendRecordBuffer(int position)
{
if (_records.Length <= position)
{
int newSize = _records.Length * 2;
if (newSize <= position)
{
newSize = position + 1;
}
Record[] tmp = new Record[newSize];
Array.Copy(_records, 0, tmp, 0, _records.Length);
_records = tmp;
}
}
public bool FindStylesheetElement()
{
if (!_topLevelReader)
{
if (_reader.ReadState != ReadState.Interactive)
{
return false;
}
}
// The stylesheet may be an embedded stylesheet. If this is the case the reader will be in Interactive state and should be
// positioned on xsl:stylesheet element (or any preceding whitespace) but there also can be namespaces defined on one
// of the ancestor nodes. These namespace definitions have to be copied to the xsl:stylesheet element scope. Otherwise it
// will not be possible to resolve them later and loading the stylesheet will end up with throwing an exception.
IDictionary<string, string> namespacesInScope = null;
if (_reader.ReadState == ReadState.Interactive)
{
// This may be an embedded stylesheet - store namespaces in scope
IXmlNamespaceResolver nsResolver = _reader as IXmlNamespaceResolver;
if (nsResolver != null)
{
namespacesInScope = nsResolver.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml);
}
}
while (MoveToNextSibling() && _nodeType == XmlNodeType.Whitespace) ;
// An Element node was reached. Potentially this is xsl:stylesheet instruction.
if (_nodeType == XmlNodeType.Element)
{
// If namespacesInScope is not null then the stylesheet being read is an embedded stylesheet that can have namespaces
// defined outside of xsl:stylesheet instruction. In this case the namespace definitions collected above have to be added
// to the element scope.
if (namespacesInScope != null)
{
foreach (KeyValuePair<string, string> prefixNamespacePair in namespacesInScope)
{
// The namespace could be redefined on the element we just read. If this is the case scopeManager already has
// namespace definition for this prefix and the old definition must not be added to the scope.
if (_scopeManager.LookupNamespace(prefixNamespacePair.Key) == null)
{
string nsAtomizedValue = _atoms.NameTable.Add(prefixNamespacePair.Value);
_scopeManager.AddNsDeclaration(prefixNamespacePair.Key, nsAtomizedValue);
_ctxInfo.AddNamespace(prefixNamespacePair.Key, nsAtomizedValue);
}
}
}
// return true to indicate that we reached XmlNodeType.Element node - potentially xsl:stylesheet element.
return true;
}
// return false to indicate that we did not reach XmlNodeType.Element node so it is not a valid stylesheet.
return false;
}
public void Finish()
{
_scopeManager.CheckEmpty();
if (_topLevelReader)
{
while (_reader.ReadState == ReadState.Interactive)
{
_reader.Skip();
}
}
}
private void FillupRecord(ref Record rec)
{
rec.localName = _reader.LocalName;
rec.nsUri = _reader.NamespaceURI;
rec.prefix = _reader.Prefix;
rec.value = _reader.Value;
rec.baseUri = _reader.BaseURI;
if (_reatomize)
{
rec.localName = _atoms.NameTable.Add(rec.localName);
rec.nsUri = _atoms.NameTable.Add(rec.nsUri);
rec.prefix = _atoms.NameTable.Add(rec.prefix);
}
if (_readerLineInfo != null)
{
rec.start = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition - PositionAdjustment(_reader.NodeType));
}
}
private void SetRecordEnd(ref Record rec)
{
if (_readerLineInfo != null)
{
rec.end = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition - PositionAdjustment(_reader.NodeType));
if (_reader.BaseURI != rec.baseUri || rec.end.LessOrEqual(rec.start))
{
rec.end = new Location(rec.start.Line, int.MaxValue);
}
}
}
private void FillupTextRecord(ref Record rec)
{
Debug.Assert(
_reader.NodeType == XmlNodeType.Whitespace || _reader.NodeType == XmlNodeType.SignificantWhitespace ||
_reader.NodeType == XmlNodeType.Text || _reader.NodeType == XmlNodeType.CDATA
);
rec.localName = string.Empty;
rec.nsUri = string.Empty;
rec.prefix = string.Empty;
rec.value = _reader.Value;
rec.baseUri = _reader.BaseURI;
if (_readerLineInfo != null)
{
bool isCDATA = (_reader.NodeType == XmlNodeType.CDATA);
int line = _readerLineInfo.LineNumber;
int pos = _readerLineInfo.LinePosition;
rec.start = new Location(line, pos - (isCDATA ? 9 : 0));
char prevChar = ' ';
foreach (char ch in rec.value)
{
switch (ch)
{
case '\n':
if (prevChar != '\r')
{
goto case '\r';
}
break;
case '\r':
line++;
pos = 1;
break;
default:
pos++;
break;
}
prevChar = ch;
}
rec.end = new Location(line, pos + (isCDATA ? 3 : 0));
}
}
private void FillupCharacterEntityRecord(ref Record rec)
{
Debug.Assert(_reader.NodeType == XmlNodeType.EntityReference);
string local = _reader.LocalName;
Debug.Assert(local[0] == '#' || local == "lt" || local == "gt" || local == "quot" || local == "apos");
rec.localName = string.Empty;
rec.nsUri = string.Empty;
rec.prefix = string.Empty;
rec.baseUri = _reader.BaseURI;
if (_readerLineInfo != null)
{
rec.start = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition - 1);
}
_reader.ResolveEntity();
_reader.Read();
Debug.Assert(_reader.NodeType == XmlNodeType.Text || _reader.NodeType == XmlNodeType.Whitespace || _reader.NodeType == XmlNodeType.SignificantWhitespace);
rec.value = _reader.Value;
_reader.Read();
Debug.Assert(_reader.NodeType == XmlNodeType.EndEntity);
if (_readerLineInfo != null)
{
rec.end = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition + 1);
}
}
private StringConcat _strConcat = new StringConcat();
// returns false if attribute is actualy namespace
private bool ReadAttribute(ref Record rec)
{
Debug.Assert(_reader.NodeType == XmlNodeType.Attribute, "reader.NodeType == XmlNodeType.Attribute");
FillupRecord(ref rec);
if (Ref.Equal(rec.prefix, _atoms.Xmlns))
{ // xmlns:foo="NS_FOO"
string atomizedValue = _atoms.NameTable.Add(_reader.Value);
if (!Ref.Equal(rec.localName, _atoms.Xml))
{
_scopeManager.AddNsDeclaration(rec.localName, atomizedValue);
_ctxInfo.AddNamespace(rec.localName, atomizedValue);
}
return false;
}
else if (rec.prefix.Length == 0 && Ref.Equal(rec.localName, _atoms.Xmlns))
{ // xmlns="NS_FOO"
string atomizedValue = _atoms.NameTable.Add(_reader.Value);
_scopeManager.AddNsDeclaration(string.Empty, atomizedValue);
_ctxInfo.AddNamespace(string.Empty, atomizedValue);
return false;
}
/* Read Attribute Value */
{
if (!_reader.ReadAttributeValue())
{
// XmlTextReader never returns false from first call to ReadAttributeValue()
rec.value = string.Empty;
SetRecordEnd(ref rec);
return true;
}
if (_readerLineInfo != null)
{
int correction = (_reader.NodeType == XmlNodeType.EntityReference) ? -2 : -1;
rec.valueStart = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition + correction);
if (_reader.BaseURI != rec.baseUri || rec.valueStart.LessOrEqual(rec.start))
{
int nameLength = ((rec.prefix.Length != 0) ? rec.prefix.Length + 1 : 0) + rec.localName.Length;
rec.end = new Location(rec.start.Line, rec.start.Pos + nameLength + 1);
}
}
string lastText = string.Empty;
_strConcat.Clear();
do
{
switch (_reader.NodeType)
{
case XmlNodeType.EntityReference:
_reader.ResolveEntity();
break;
case XmlNodeType.EndEntity:
break;
default:
Debug.Assert(_reader.NodeType == XmlNodeType.Text, "Unexpected node type inside attribute value");
lastText = _reader.Value;
_strConcat.Concat(lastText);
break;
}
} while (_reader.ReadAttributeValue());
rec.value = _strConcat.GetResult();
if (_readerLineInfo != null)
{
Debug.Assert(_reader.NodeType != XmlNodeType.EntityReference);
int correction = ((_reader.NodeType == XmlNodeType.EndEntity) ? 1 : lastText.Length) + 1;
rec.end = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition + correction);
if (_reader.BaseURI != rec.baseUri || rec.end.LessOrEqual(rec.valueStart))
{
rec.end = new Location(rec.start.Line, int.MaxValue);
}
}
}
return true;
}
// --------------------
public bool MoveToFirstChild()
{
Debug.Assert(_nodeType == XmlNodeType.Element, "To call MoveToFirstChild() XsltInut should be positioned on an Element.");
if (IsEmptyElement)
{
return false;
}
return ReadNextSibling();
}
public bool MoveToNextSibling()
{
Debug.Assert(_nodeType != XmlNodeType.Element || IsEmptyElement, "On non-empty elements we should call MoveToFirstChild()");
if (_nodeType == XmlNodeType.Element || _nodeType == XmlNodeType.EndElement)
{
_scopeManager.ExitScope();
}
return ReadNextSibling();
}
public void SkipNode()
{
if (_nodeType == XmlNodeType.Element && MoveToFirstChild())
{
do
{
SkipNode();
} while (MoveToNextSibling());
}
}
private int ReadTextNodes()
{
bool textPreserveWS = _reader.XmlSpace == XmlSpace.Preserve;
bool textIsWhite = true;
int curTextNode = 0;
do
{
switch (_reader.NodeType)
{
case XmlNodeType.Text:
// XLinq reports WS nodes as Text so we need to analyze them here
case XmlNodeType.CDATA:
if (textIsWhite && !XmlCharType.Instance.IsOnlyWhitespace(_reader.Value))
{
textIsWhite = false;
}
goto case XmlNodeType.SignificantWhitespace;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
ExtendRecordBuffer(curTextNode);
FillupTextRecord(ref _records[curTextNode]);
_reader.Read();
curTextNode++;
break;
case XmlNodeType.EntityReference:
string local = _reader.LocalName;
if (local.Length > 0 && (
local[0] == '#' ||
local == "lt" || local == "gt" || local == "quot" || local == "apos"
))
{
// Special treatment for character and built-in entities
ExtendRecordBuffer(curTextNode);
FillupCharacterEntityRecord(ref _records[curTextNode]);
if (textIsWhite && !XmlCharType.Instance.IsOnlyWhitespace(_records[curTextNode].value))
{
textIsWhite = false;
}
curTextNode++;
}
else
{
_reader.ResolveEntity();
_reader.Read();
}
break;
case XmlNodeType.EndEntity:
_reader.Read();
break;
default:
_nodeType = (
!textIsWhite ? XmlNodeType.Text :
textPreserveWS ? XmlNodeType.SignificantWhitespace :
/*default: */ XmlNodeType.Whitespace
);
return curTextNode;
}
} while (true);
}
private bool ReadNextSibling()
{
if (_currentRecord < _lastTextNode)
{
Debug.Assert(_nodeType == XmlNodeType.Text || _nodeType == XmlNodeType.Whitespace || _nodeType == XmlNodeType.SignificantWhitespace);
_currentRecord++;
if (_currentRecord == _lastTextNode)
{
_lastTextNode = 0; // we are done with text nodes. Reset this counter
}
return true;
}
_currentRecord = 0;
while (!_reader.EOF)
{
switch (_reader.NodeType)
{
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.EntityReference:
int numTextNodes = ReadTextNodes();
if (numTextNodes == 0)
{
// Most likely this was Entity that starts from non-text node
continue;
}
_lastTextNode = numTextNodes - 1;
return true;
case XmlNodeType.Element:
_scopeManager.EnterScope();
_numAttributes = ReadElement();
return true;
case XmlNodeType.EndElement:
_nodeType = XmlNodeType.EndElement;
_isEmptyElement = false;
FillupRecord(ref _records[0]);
_reader.Read();
SetRecordEnd(ref _records[0]);
return false;
default:
_reader.Read();
break;
}
}
return false;
}
private int ReadElement()
{
Debug.Assert(_reader.NodeType == XmlNodeType.Element);
_attributesRead = false;
FillupRecord(ref _records[0]);
_nodeType = XmlNodeType.Element;
_isEmptyElement = _reader.IsEmptyElement;
_ctxInfo = new ContextInfo(this);
int record = 1;
if (_reader.MoveToFirstAttribute())
{
do
{
ExtendRecordBuffer(record);
if (ReadAttribute(ref _records[record]))
{
record++;
}
} while (_reader.MoveToNextAttribute());
_reader.MoveToElement();
}
_reader.Read();
SetRecordEnd(ref _records[0]);
_ctxInfo.lineInfo = BuildLineInfo();
_attributes = null;
return record - 1;
}
public void MoveToElement()
{
Debug.Assert(_nodeType == XmlNodeType.Element, "For MoveToElement() we should be positioned on Element or Attribute");
_currentRecord = 0;
}
private bool MoveToAttributeBase(int attNum)
{
Debug.Assert(_nodeType == XmlNodeType.Element, "For MoveToLiteralAttribute() we should be positioned on Element or Attribute");
if (0 < attNum && attNum <= _numAttributes)
{
_currentRecord = attNum;
return true;
}
else
{
_currentRecord = 0;
return false;
}
}
public bool MoveToLiteralAttribute(int attNum)
{
Debug.Assert(_nodeType == XmlNodeType.Element, "For MoveToLiteralAttribute() we should be positioned on Element or Attribute");
if (0 < attNum && attNum <= _numAttributes)
{
_currentRecord = attNum;
return true;
}
else
{
_currentRecord = 0;
return false;
}
}
public bool MoveToXsltAttribute(int attNum, string attName)
{
Debug.Assert(_attributes != null && _attributes[attNum].name == attName, "Attribute numbering error.");
_currentRecord = _xsltAttributeNumber[attNum];
return _currentRecord != 0;
}
public bool IsRequiredAttribute(int attNum)
{
return (_attributes[attNum].flags & (_compiler.Version == 2 ? XsltLoader.V2Req : XsltLoader.V1Req)) != 0;
}
public bool AttributeExists(int attNum, string attName)
{
Debug.Assert(_attributes != null && _attributes[attNum].name == attName, "Attribute numbering error.");
return _xsltAttributeNumber[attNum] != 0;
}
public struct DelayedQName
{
private string _prefix;
private string _localName;
public DelayedQName(ref Record rec)
{
_prefix = rec.prefix;
_localName = rec.localName;
}
public static implicit operator string (DelayedQName qn)
{
return qn._prefix.Length == 0 ? qn._localName : (qn._prefix + ':' + qn._localName);
}
}
public DelayedQName ElementName
{
get
{
Debug.Assert(_nodeType == XmlNodeType.Element || _nodeType == XmlNodeType.EndElement, "Input is positioned on element or attribute");
return new DelayedQName(ref _records[0]);
}
}
// -------------------- Keywords testing --------------------
public bool IsNs(string ns) { return Ref.Equal(ns, NamespaceUri); }
public bool IsKeyword(string kwd) { return Ref.Equal(kwd, LocalName); }
public bool IsXsltNamespace() { return IsNs(_atoms.UriXsl); }
public bool IsNullNamespace() { return IsNs(string.Empty); }
public bool IsXsltKeyword(string kwd) { return IsKeyword(kwd) && IsXsltNamespace(); }
// -------------------- Scope Management --------------------
// See private class InputScopeManager bellow.
// InputScopeManager handles some flags and values with respect of scope level where they as defined.
// To parse XSLT style sheet we need the folloing values:
// BackwardCompatibility -- this flag is set when compiler.version==2 && xsl:version<2.
// ForwardCompatibility -- this flag is set when compiler.version==2 && xsl:version>1 or compiler.version==1 && xsl:version!=1
// CanHaveApplyImports -- we allow xsl:apply-templates instruction to apear in any template with match!=null, but not inside xsl:for-each
// so it can't be inside global variable and has initial value = false
// ExtentionNamespace -- is defined by extension-element-prefixes attribute on LRE or xsl:stylesheet
public bool CanHaveApplyImports
{
get { return _scopeManager.CanHaveApplyImports; }
set { _scopeManager.CanHaveApplyImports = value; }
}
public bool IsExtensionNamespace(string uri)
{
Debug.Assert(_nodeType != XmlNodeType.Element || _attributesRead, "Should first read attributes");
return _scopeManager.IsExNamespace(uri);
}
public bool ForwardCompatibility
{
get
{
Debug.Assert(_nodeType != XmlNodeType.Element || _attributesRead, "Should first read attributes");
return _scopeManager.ForwardCompatibility;
}
}
public bool BackwardCompatibility
{
get
{
Debug.Assert(_nodeType != XmlNodeType.Element || _attributesRead, "Should first read attributes");
return _scopeManager.BackwardCompatibility;
}
}
public XslVersion XslVersion
{
get { return _scopeManager.ForwardCompatibility ? XslVersion.ForwardsCompatible : XslVersion.Current; }
}
private void SetVersion(int attVersion)
{
MoveToLiteralAttribute(attVersion);
Debug.Assert(IsKeyword(_atoms.Version));
double version = XPathConvert.StringToDouble(Value);
if (double.IsNaN(version))
{
ReportError(/*[XT0110]*/SR.Xslt_InvalidAttrValue, _atoms.Version, Value);
#if XSLT2
version = 2.0;
#else
version = 1.0;
#endif
}
SetVersion(version);
}
private void SetVersion(double version)
{
if (_compiler.Version == 0)
{
#if XSLT2
compiler.Version = version < 2.0 ? 1 : 2;
#else
_compiler.Version = 1;
#endif
}
if (_compiler.Version == 1)
{
_scopeManager.BackwardCompatibility = false;
_scopeManager.ForwardCompatibility = (version != 1.0);
}
else
{
_scopeManager.BackwardCompatibility = version < 2;
_scopeManager.ForwardCompatibility = 2 < version;
}
}
// --------------- GetAttributes(...) -------------------------
// All Xslt Instructions allows fixed set of attributes in null-ns, no in XSLT-ns and any in other ns.
// In ForwardCompatibility mode we should ignore any of this problems.
// We not use these functions for parseing LiteralResultElement and xsl:stylesheet
public struct XsltAttribute
{
public string name;
public int flags;
public XsltAttribute(string name, int flags)
{
this.name = name;
this.flags = flags;
}
}
private XsltAttribute[] _attributes = null;
// Mapping of attribute names as they ordered in 'attributes' array
// to there's numbers in actual stylesheet as they ordered in 'records' array
private int[] _xsltAttributeNumber = new int[21];
public ContextInfo GetAttributes()
{
return GetAttributes(Array.Empty<XsltAttribute>());
}
public ContextInfo GetAttributes(XsltAttribute[] attributes)
{
Debug.Assert(NodeType == XmlNodeType.Element);
Debug.Assert(attributes.Length <= _xsltAttributeNumber.Length);
_attributes = attributes;
// temp hack to fix value? = new AttValue(records[values[?]].value);
_records[0].value = null;
// Standard Attributes:
int attExtension = 0;
int attExclude = 0;
int attNamespace = 0;
int attCollation = 0;
int attUseWhen = 0;
bool isXslOutput = IsXsltNamespace() && IsKeyword(_atoms.Output);
bool SS = IsXsltNamespace() && (IsKeyword(_atoms.Stylesheet) || IsKeyword(_atoms.Transform));
bool V2 = _compiler.Version == 2;
for (int i = 0; i < attributes.Length; i++)
{
_xsltAttributeNumber[i] = 0;
}
_compiler.EnterForwardsCompatible();
if (SS || V2 && !isXslOutput)
{
for (int i = 1; MoveToAttributeBase(i); i++)
{
if (IsNullNamespace() && IsKeyword(_atoms.Version))
{
SetVersion(i);
break;
}
}
}
if (_compiler.Version == 0)
{
Debug.Assert(SS, "First we parse xsl:stylesheet element");
#if XSLT2
SetVersion(2.0);
#else
SetVersion(1.0);
#endif
}
V2 = _compiler.Version == 2;
int OptOrReq = V2 ? XsltLoader.V2Opt | XsltLoader.V2Req : XsltLoader.V1Opt | XsltLoader.V1Req;
for (int attNum = 1; MoveToAttributeBase(attNum); attNum++)
{
if (IsNullNamespace())
{
string localName = LocalName;
int kwd;
for (kwd = 0; kwd < attributes.Length; kwd++)
{
if (Ref.Equal(localName, attributes[kwd].name) && (attributes[kwd].flags & OptOrReq) != 0)
{
_xsltAttributeNumber[kwd] = attNum;
break;
}
}
if (kwd == attributes.Length)
{
if (Ref.Equal(localName, _atoms.ExcludeResultPrefixes) && (SS || V2)) { attExclude = attNum; }
else
if (Ref.Equal(localName, _atoms.ExtensionElementPrefixes) && (SS || V2)) { attExtension = attNum; }
else
if (Ref.Equal(localName, _atoms.XPathDefaultNamespace) && (V2)) { attNamespace = attNum; }
else
if (Ref.Equal(localName, _atoms.DefaultCollation) && (V2)) { attCollation = attNum; }
else
if (Ref.Equal(localName, _atoms.UseWhen) && (V2)) { attUseWhen = attNum; }
else
{
ReportError(/*[XT0090]*/SR.Xslt_InvalidAttribute, QualifiedName, _records[0].QualifiedName);
}
}
}
else if (IsXsltNamespace())
{
ReportError(/*[XT0090]*/SR.Xslt_InvalidAttribute, QualifiedName, _records[0].QualifiedName);
}
else
{
// Ignore the attribute.
// An element from the XSLT namespace may have any attribute not from the XSLT namespace,
// provided that the expanded-name of the attribute has a non-null namespace URI.
// For example, it may be 'xml:space'.
}
}
_attributesRead = true;
// Ignore invalid attributes if forwards-compatible behavior is enabled. Note that invalid
// attributes may encounter before ForwardCompatibility flag is set to true. For example,
// <xsl:stylesheet unknown="foo" version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"/>
_compiler.ExitForwardsCompatible(ForwardCompatibility);
InsertExNamespaces(attExtension, _ctxInfo, /*extensions:*/ true);
InsertExNamespaces(attExclude, _ctxInfo, /*extensions:*/ false);
SetXPathDefaultNamespace(attNamespace);
SetDefaultCollation(attCollation);
if (attUseWhen != 0)
{
ReportNYI(_atoms.UseWhen);
}
MoveToElement();
// Report missing mandatory attributes
for (int i = 0; i < attributes.Length; i++)
{
if (_xsltAttributeNumber[i] == 0)
{
int flags = attributes[i].flags;
if (
_compiler.Version == 2 && (flags & XsltLoader.V2Req) != 0 ||
_compiler.Version == 1 && (flags & XsltLoader.V1Req) != 0 && (!ForwardCompatibility || (flags & XsltLoader.V2Req) != 0)
)
{
ReportError(/*[XT_001]*/SR.Xslt_MissingAttribute, attributes[i].name);
}
}
}
return _ctxInfo;
}
public ContextInfo GetLiteralAttributes(bool asStylesheet)
{
Debug.Assert(NodeType == XmlNodeType.Element);
// Standard Attributes:
int attVersion = 0;
int attExtension = 0;
int attExclude = 0;
int attNamespace = 0;
int attCollation = 0;
int attUseWhen = 0;
for (int i = 1; MoveToLiteralAttribute(i); i++)
{
if (IsXsltNamespace())
{
string localName = LocalName;
if (Ref.Equal(localName, _atoms.Version)) { attVersion = i; }
else
if (Ref.Equal(localName, _atoms.ExtensionElementPrefixes)) { attExtension = i; }
else
if (Ref.Equal(localName, _atoms.ExcludeResultPrefixes)) { attExclude = i; }
else
if (Ref.Equal(localName, _atoms.XPathDefaultNamespace)) { attNamespace = i; }
else
if (Ref.Equal(localName, _atoms.DefaultCollation)) { attCollation = i; }
else
if (Ref.Equal(localName, _atoms.UseWhen)) { attUseWhen = i; }
}
}
_attributesRead = true;
this.MoveToElement();
if (attVersion != 0)
{
// Enable forwards-compatible behavior if version attribute is not "1.0"
SetVersion(attVersion);
}
else
{
if (asStylesheet)
{
ReportError(Ref.Equal(NamespaceUri, _atoms.UriWdXsl) && Ref.Equal(LocalName, _atoms.Stylesheet) ?
/*[XT_025]*/SR.Xslt_WdXslNamespace : /*[XT0150]*/SR.Xslt_WrongStylesheetElement
);
#if XSLT2
SetVersion(2.0);
#else
SetVersion(1.0);
#endif
}
}
// Parse xsl:extension-element-prefixes attribute (now that forwards-compatible mode is known)
InsertExNamespaces(attExtension, _ctxInfo, /*extensions:*/true);
if (!IsExtensionNamespace(_records[0].nsUri))
{
// Parse other attributes (now that it's known this is a literal result element)
if (_compiler.Version == 2)
{
SetXPathDefaultNamespace(attNamespace);
SetDefaultCollation(attCollation);
if (attUseWhen != 0)
{
ReportNYI(_atoms.UseWhen);
}
}
InsertExNamespaces(attExclude, _ctxInfo, /*extensions:*/false);
}
return _ctxInfo;
}
// Get just the 'version' attribute of an unknown XSLT instruction. All other attributes
// are ignored since we do not want to report an error on each of them.
public void GetVersionAttribute()
{
Debug.Assert(NodeType == XmlNodeType.Element && IsXsltNamespace());
bool V2 = _compiler.Version == 2;
if (V2)
{
for (int i = 1; MoveToAttributeBase(i); i++)
{
if (IsNullNamespace() && IsKeyword(_atoms.Version))
{
SetVersion(i);
break;
}
}
}
_attributesRead = true;
}
private void InsertExNamespaces(int attExPrefixes, ContextInfo ctxInfo, bool extensions)
{
// List of Extension namespaces are maintaned by XsltInput's ScopeManager and is used by IsExtensionNamespace() in XsltLoader.LoadLiteralResultElement()
// Both Extension and Exclusion namespaces will not be coppied by LiteralResultElement. Logic of copping namespaces are in QilGenerator.CompileLiteralElement().
// At this time we will have different scope manager and need preserve all required information from load time to compile time.
// Each XslNode contains list of NsDecls (nsList) wich stores prefix+namespaces pairs for each namespace decls as well as exclusion namespaces.
// In addition it also contains Exclusion namespace. They are represented as (null+namespace). Special case is Exlusion "#all" represented as (null+null).
//and Exclusion namespace
if (MoveToLiteralAttribute(attExPrefixes))
{
Debug.Assert(extensions ? IsKeyword(_atoms.ExtensionElementPrefixes) : IsKeyword(_atoms.ExcludeResultPrefixes));
string value = Value;
if (value.Length != 0)
{
if (!extensions && _compiler.Version != 1 && value == "#all")
{
ctxInfo.nsList = new NsDecl(ctxInfo.nsList, /*prefix:*/null, /*nsUri:*/null); // null, null means Exlusion #all
}
else
{
_compiler.EnterForwardsCompatible();
string[] list = XmlConvert.SplitString(value);
for (int idx = 0; idx < list.Length; idx++)
{
if (list[idx] == "#default")
{
list[idx] = this.LookupXmlNamespace(string.Empty);
if (list[idx].Length == 0 && _compiler.Version != 1 && !BackwardCompatibility)
{
ReportError(/*[XTSE0809]*/SR.Xslt_ExcludeDefault);
}
}
else
{
list[idx] = this.LookupXmlNamespace(list[idx]);
}
}
if (!_compiler.ExitForwardsCompatible(this.ForwardCompatibility))
{
// There were errors in the list, ignore the whole list
return;
}
for (int idx = 0; idx < list.Length; idx++)
{
if (list[idx] != null)
{
ctxInfo.nsList = new NsDecl(ctxInfo.nsList, /*prefix:*/null, list[idx]); // null means that this Exlusion NS
if (extensions)
{
_scopeManager.AddExNamespace(list[idx]); // At Load time we need to know Extencion namespaces to ignore such literal elements.
}
}
}
}
}
}
}
private void SetXPathDefaultNamespace(int attNamespace)
{
if (MoveToLiteralAttribute(attNamespace))
{
Debug.Assert(IsKeyword(_atoms.XPathDefaultNamespace));
if (Value.Length != 0)
{
ReportNYI(_atoms.XPathDefaultNamespace);
}
}
}
private void SetDefaultCollation(int attCollation)
{
if (MoveToLiteralAttribute(attCollation))
{
Debug.Assert(IsKeyword(_atoms.DefaultCollation));
string[] list = XmlConvert.SplitString(Value);
int col;
for (col = 0; col < list.Length; col++)
{
if (System.Xml.Xsl.Runtime.XmlCollation.Create(list[col], /*throw:*/false) != null)
{
break;
}
}
if (col == list.Length)
{
ReportErrorFC(/*[XTSE0125]*/SR.Xslt_CollationSyntax);
}
else
{
if (list[col] != XmlReservedNs.NsCollCodePoint)
{
ReportNYI(_atoms.DefaultCollation);
}
}
}
}
// ----------------------- ISourceLineInfo -----------------------
private static int PositionAdjustment(XmlNodeType nt)
{
switch (nt)
{
case XmlNodeType.Element:
return 1; // "<"
case XmlNodeType.CDATA:
return 9; // "<![CDATA["
case XmlNodeType.ProcessingInstruction:
return 2; // "<?"
case XmlNodeType.Comment:
return 4; // "<!--"
case XmlNodeType.EndElement:
return 2; // "</"
case XmlNodeType.EntityReference:
return 1; // "&"
default:
return 0;
}
}
public ISourceLineInfo BuildLineInfo()
{
return new SourceLineInfo(Uri, Start, End);
}
public ISourceLineInfo BuildNameLineInfo()
{
if (_readerLineInfo == null)
{
return BuildLineInfo();
}
// LocalName is checked against null since it is used to calculate QualifiedName used in turn to
// calculate end position.
// LocalName (and other cached properties) can be null only if nothing has been read from the reader.
// This happens for instance when a reader which has already been closed or a reader positioned
// on the very last node of the document is passed to the ctor.
if (LocalName == null)
{
// Fill up the current record to set all the properties used below.
FillupRecord(ref _records[_currentRecord]);
}
Location start = Start;
int line = start.Line;
int pos = start.Pos + PositionAdjustment(NodeType);
return new SourceLineInfo(Uri, new Location(line, pos), new Location(line, pos + QualifiedName.Length));
}
public ISourceLineInfo BuildReaderLineInfo()
{
Location loc;
if (_readerLineInfo != null)
loc = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition);
else
loc = new Location(0, 0);
return new SourceLineInfo(_reader.BaseURI, loc, loc);
}
// Resolve prefix, return null and report an error if not found
public string LookupXmlNamespace(string prefix)
{
Debug.Assert(prefix != null);
string nsUri = _scopeManager.LookupNamespace(prefix);
if (nsUri != null)
{
Debug.Assert(Ref.Equal(_atoms.NameTable.Get(nsUri), nsUri), "Namespaces must be atomized");
return nsUri;
}
if (prefix.Length == 0)
{
return string.Empty;
}
ReportError(/*[XT0280]*/SR.Xslt_InvalidPrefix, prefix);
return null;
}
// ---------------------- Error Handling ----------------------
public void ReportError(string res, params string[] args)
{
_compiler.ReportError(BuildNameLineInfo(), res, args);
}
public void ReportWarning(string res, params string[] args)
{
_compiler.ReportWarning(BuildNameLineInfo(), res, args);
}
public void ReportErrorFC(string res, params string[] args)
{
if (!ForwardCompatibility)
{
_compiler.ReportError(BuildNameLineInfo(), res, args);
}
}
private void ReportNYI(string arg)
{
ReportErrorFC(SR.Xslt_NotYetImplemented, arg);
}
// -------------------------------- ContextInfo ------------------------------------
internal class ContextInfo
{
public NsDecl nsList;
public ISourceLineInfo lineInfo; // Line info for whole start tag
public ISourceLineInfo elemNameLi; // Line info for element name
public ISourceLineInfo endTagLi; // Line info for end tag or '/>'
private int _elemNameLength;
// Create ContextInfo based on existing line info (used during AST rewriting)
internal ContextInfo(ISourceLineInfo lineinfo)
{
this.elemNameLi = lineinfo;
this.endTagLi = lineinfo;
this.lineInfo = lineinfo;
}
public ContextInfo(XsltInput input)
{
_elemNameLength = input.QualifiedName.Length;
}
public void AddNamespace(string prefix, string nsUri)
{
nsList = new NsDecl(nsList, prefix, nsUri);
}
public void SaveExtendedLineInfo(XsltInput input)
{
if (lineInfo.Start.Line == 0)
{
elemNameLi = endTagLi = null;
return;
}
elemNameLi = new SourceLineInfo(
lineInfo.Uri,
lineInfo.Start.Line, lineInfo.Start.Pos + 1, // "<"
lineInfo.Start.Line, lineInfo.Start.Pos + 1 + _elemNameLength
);
if (!input.IsEmptyElement)
{
Debug.Assert(input.NodeType == XmlNodeType.EndElement);
endTagLi = input.BuildLineInfo();
}
else
{
Debug.Assert(input.NodeType == XmlNodeType.Element || input.NodeType == XmlNodeType.Attribute);
endTagLi = new EmptyElementEndTag(lineInfo);
}
}
// We need this wrapper class because elementTagLi is not yet calculated
internal class EmptyElementEndTag : ISourceLineInfo
{
private ISourceLineInfo _elementTagLi;
public EmptyElementEndTag(ISourceLineInfo elementTagLi)
{
_elementTagLi = elementTagLi;
}
public string Uri { get { return _elementTagLi.Uri; } }
public bool IsNoSource { get { return _elementTagLi.IsNoSource; } }
public Location Start { get { return new Location(_elementTagLi.End.Line, _elementTagLi.End.Pos - 2); } }
public Location End { get { return _elementTagLi.End; } }
}
}
internal struct Record
{
public string localName;
public string nsUri;
public string prefix;
public string value;
public string baseUri;
public Location start;
public Location valueStart;
public Location end;
public string QualifiedName { get { return prefix.Length == 0 ? localName : string.Concat(prefix, ":", localName); } }
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
internal sealed partial class RenameTrackingTaggerProvider
{
internal enum TriggerIdentifierKind
{
NotRenamable,
RenamableDeclaration,
RenamableReference,
}
/// <summary>
/// Determines whether the original token was a renamable identifier on a background thread
/// </summary>
private class TrackingSession : ForegroundThreadAffinitizedObject
{
private static readonly Task<TriggerIdentifierKind> s_notRenamableTask = Task.FromResult(TriggerIdentifierKind.NotRenamable);
private readonly Task<TriggerIdentifierKind> _isRenamableIdentifierTask;
private readonly CancellationTokenSource _cancellationTokenSource;
private readonly CancellationToken _cancellationToken;
private readonly IAsynchronousOperationListener _asyncListener;
private Task<bool> _newIdentifierBindsTask = SpecializedTasks.False;
private readonly string _originalName;
public string OriginalName { get { return _originalName; } }
private readonly ITrackingSpan _trackingSpan;
public ITrackingSpan TrackingSpan { get { return _trackingSpan; } }
private bool _forceRenameOverloads;
public bool ForceRenameOverloads { get { return _forceRenameOverloads; } }
public TrackingSession(StateMachine stateMachine, SnapshotSpan snapshotSpan, IAsynchronousOperationListener asyncListener)
{
AssertIsForeground();
_asyncListener = asyncListener;
_trackingSpan = snapshotSpan.Snapshot.CreateTrackingSpan(snapshotSpan.Span, SpanTrackingMode.EdgeInclusive);
_cancellationTokenSource = new CancellationTokenSource();
_cancellationToken = _cancellationTokenSource.Token;
if (snapshotSpan.Length > 0)
{
// If the snapshotSpan is nonempty, then the session began with a change that
// was touching a word. Asynchronously determine whether that word was a
// renamable identifier. If it is, alert the state machine so it can trigger
// tagging.
_originalName = snapshotSpan.GetText();
_isRenamableIdentifierTask = Task.Factory.SafeStartNewFromAsync(
() => DetermineIfRenamableIdentifierAsync(snapshotSpan, initialCheck: true),
_cancellationToken,
TaskScheduler.Default);
var asyncToken = _asyncListener.BeginAsyncOperation(GetType().Name + ".UpdateTrackingSessionAfterIsRenamableIdentifierTask");
_isRenamableIdentifierTask.SafeContinueWith(
t => stateMachine.UpdateTrackingSessionIfRenamable(),
_cancellationToken,
TaskContinuationOptions.OnlyOnRanToCompletion,
ForegroundTaskScheduler).CompletesAsyncOperation(asyncToken);
QueueUpdateToStateMachine(stateMachine, _isRenamableIdentifierTask);
}
else
{
// If the snapshotSpan is empty, that means text was added in a location that is
// not touching an existing word, which happens a fair amount when writing new
// code. In this case we already know that the user is not renaming an
// identifier.
_isRenamableIdentifierTask = s_notRenamableTask;
}
}
private void QueueUpdateToStateMachine(StateMachine stateMachine, Task task)
{
var asyncToken = _asyncListener.BeginAsyncOperation($"{GetType().Name}.{nameof(QueueUpdateToStateMachine)}");
task.SafeContinueWith(t =>
{
AssertIsForeground();
if (_isRenamableIdentifierTask.Result != TriggerIdentifierKind.NotRenamable)
{
stateMachine.OnTrackingSessionUpdated(this);
}
},
_cancellationToken,
TaskContinuationOptions.OnlyOnRanToCompletion,
ForegroundTaskScheduler).CompletesAsyncOperation(asyncToken);
}
internal void CheckNewIdentifier(StateMachine stateMachine, ITextSnapshot snapshot)
{
AssertIsForeground();
_newIdentifierBindsTask = _isRenamableIdentifierTask.SafeContinueWithFromAsync(
async t => t.Result != TriggerIdentifierKind.NotRenamable &&
TriggerIdentifierKind.RenamableReference ==
await DetermineIfRenamableIdentifierAsync(
TrackingSpan.GetSpan(snapshot),
initialCheck: false).ConfigureAwait(false),
_cancellationToken,
TaskContinuationOptions.OnlyOnRanToCompletion,
TaskScheduler.Default);
QueueUpdateToStateMachine(stateMachine, _newIdentifierBindsTask);
}
internal bool IsDefinitelyRenamableIdentifier()
{
// This needs to be able to run on a background thread for the CodeFix
return IsRenamableIdentifier(_isRenamableIdentifierTask, waitForResult: false, cancellationToken: CancellationToken.None);
}
public void Cancel()
{
AssertIsForeground();
_cancellationTokenSource.Cancel();
}
private async Task<TriggerIdentifierKind> DetermineIfRenamableIdentifierAsync(SnapshotSpan snapshotSpan, bool initialCheck)
{
AssertIsBackground();
var document = snapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
var syntaxFactsService = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var syntaxTree = await document.GetSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false);
var token = syntaxTree.GetTouchingWord(snapshotSpan.Start.Position, syntaxFactsService, _cancellationToken);
// The OriginalName is determined with a simple textual check, so for a
// statement such as "Dim [x = 1" the textual check will return a name of "[x".
// The token found for "[x" is an identifier token, but only due to error
// recovery (the "[x" is actually in the trailing trivia). If the OriginalName
// found through the textual check has a different length than the span of the
// touching word, then we cannot perform a rename.
if (initialCheck && token.Span.Length != this.OriginalName.Length)
{
return TriggerIdentifierKind.NotRenamable;
}
if (syntaxFactsService.IsIdentifier(token))
{
var semanticModel = await document.GetSemanticModelForNodeAsync(token.Parent, _cancellationToken).ConfigureAwait(false);
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var renameSymbolInfo = RenameUtilities.GetTokenRenameInfo(semanticFacts, semanticModel, token, _cancellationToken);
if (!renameSymbolInfo.HasSymbols)
{
return TriggerIdentifierKind.NotRenamable;
}
if (renameSymbolInfo.IsMemberGroup)
{
// This is a reference from a nameof expression. Allow the rename but set the RenameOverloads option
_forceRenameOverloads = true;
return await DetermineIfRenamableSymbolsAsync(renameSymbolInfo.Symbols, document, token).ConfigureAwait(false);
}
else
{
return await DetermineIfRenamableSymbolAsync(renameSymbolInfo.Symbols.Single(), document, token).ConfigureAwait(false);
}
}
}
return TriggerIdentifierKind.NotRenamable;
}
private async Task<TriggerIdentifierKind> DetermineIfRenamableSymbolsAsync(IEnumerable<ISymbol> symbols, Document document, SyntaxToken token)
{
foreach (var symbol in symbols)
{
// Get the source symbol if possible
var sourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, _cancellationToken).ConfigureAwait(false) ?? symbol;
if (!sourceSymbol.Locations.All(loc => loc.IsInSource))
{
return TriggerIdentifierKind.NotRenamable;
}
}
return TriggerIdentifierKind.RenamableReference;
}
private async Task<TriggerIdentifierKind> DetermineIfRenamableSymbolAsync(ISymbol symbol, Document document, SyntaxToken token)
{
// Get the source symbol if possible
var sourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, _cancellationToken).ConfigureAwait(false) ?? symbol;
if (!sourceSymbol.Locations.All(loc => loc.IsInSource))
{
return TriggerIdentifierKind.NotRenamable;
}
return sourceSymbol.Locations.Any(loc => loc == token.GetLocation())
? TriggerIdentifierKind.RenamableDeclaration
: TriggerIdentifierKind.RenamableReference;
}
internal bool CanInvokeRename(ISyntaxFactsService syntaxFactsService, bool isSmartTagCheck, bool waitForResult, CancellationToken cancellationToken)
{
if (IsRenamableIdentifier(_isRenamableIdentifierTask, waitForResult, cancellationToken))
{
var isRenamingDeclaration = _isRenamableIdentifierTask.Result == TriggerIdentifierKind.RenamableDeclaration;
var newName = TrackingSpan.GetText(TrackingSpan.TextBuffer.CurrentSnapshot);
var comparison = isRenamingDeclaration || syntaxFactsService.IsCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
if (!string.Equals(OriginalName, newName, comparison) &&
syntaxFactsService.IsValidIdentifier(newName))
{
// At this point, we want to allow renaming if the user invoked Ctrl+. explicitly, but we
// want to avoid showing a smart tag if we're renaming a reference that binds to an existing
// symbol.
if (!isSmartTagCheck || isRenamingDeclaration || !NewIdentifierDefinitelyBindsToReference())
{
return true;
}
}
}
return false;
}
private bool NewIdentifierDefinitelyBindsToReference()
{
return _newIdentifierBindsTask.Status == TaskStatus.RanToCompletion && _newIdentifierBindsTask.Result;
}
}
}
}
| |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using Facebook.Yoga;
namespace Facebook.Yoga.Universal.Tests
{
[TestClass]
public class YogaNodeTest
{
[TestMethod]
public void TestAddChildGetParent()
{
YogaNode parent = new YogaNode();
YogaNode child = new YogaNode();
Assert.IsNull(child.Parent);
Assert.AreEqual(0, parent.Count);
parent.Insert(0, child);
Assert.AreEqual(1, parent.Count);
Assert.AreEqual(child, parent[0]);
Assert.AreEqual(parent, child.Parent);
parent.RemoveAt(0);
Assert.IsNull(child.Parent);
Assert.AreEqual(0, parent.Count);
}
[TestMethod]
public void TestChildren()
{
YogaNode parent = new YogaNode();
foreach (YogaNode node in parent)
{
Assert.Fail(node.ToString());
}
YogaNode child0 = new YogaNode();
Assert.AreEqual(-1, parent.IndexOf(child0));
parent.Insert(0, child0);
foreach (YogaNode node in parent)
{
Assert.AreEqual(0, parent.IndexOf(node));
}
YogaNode child1 = new YogaNode();
parent.Insert(1, child1);
int index = 0;
foreach (YogaNode node in parent)
{
Assert.AreEqual(index++, parent.IndexOf(node));
}
parent.RemoveAt(0);
Assert.AreEqual(-1, parent.IndexOf(child0));
Assert.AreEqual(0, parent.IndexOf(child1));
parent.Clear();
Assert.AreEqual(0, parent.Count);
parent.Clear();
Assert.AreEqual(0, parent.Count);
}
[TestMethod]
public void TestRemoveAtFromEmpty()
{
YogaNode parent = new YogaNode();
try
{
parent.RemoveAt(0);
}
catch (System.NullReferenceException)
{
return;
}
Assert.Fail("Excepted exception of type 'System.NullReferenceException'.");
}
[TestMethod]
public void TestRemoveAtOutOfRange()
{
YogaNode parent = new YogaNode();
YogaNode child = new YogaNode();
parent.Insert(0, child);
try
{
parent.RemoveAt(1);
}
catch (System.ArgumentOutOfRangeException)
{
return;
}
Assert.Fail("Excepted exception of type 'System.ArgumentOutOfRangeException'.");
}
[TestMethod]
public void TestCannotAddChildToMultipleParents()
{
YogaNode parent1 = new YogaNode();
YogaNode parent2 = new YogaNode();
YogaNode child = new YogaNode();
parent1.Insert(0, child);
try
{
parent2.Insert(0, child);
}
catch (System.InvalidOperationException)
{
return;
}
Assert.Fail("Excepted exception of type 'System.InvalidOperationException'.");
}
[TestMethod]
public void TestReset()
{
int instanceCount = YogaNode.GetInstanceCount();
YogaNode node = new YogaNode();
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
node.Reset();
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
}
[TestMethod]
public void TestResetParent()
{
YogaNode parent = new YogaNode();
YogaNode child = new YogaNode();
parent.Insert(0, child);
try
{
parent.Reset();
}
catch (System.InvalidOperationException)
{
return;
}
Assert.Fail("Excepted exception of type 'System.InvalidOperationException'.");
}
[TestMethod]
public void TestResetChild()
{
YogaNode parent = new YogaNode();
YogaNode child = new YogaNode();
parent.Insert(0, child);
try
{
child.Reset();
}
catch (System.InvalidOperationException)
{
return;
}
Assert.Fail("Excepted exception of type 'System.InvalidOperationException'.");
}
[TestMethod]
public void TestClear()
{
int instanceCount = YogaNode.GetInstanceCount();
YogaNode parent = new YogaNode();
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
YogaNode child = new YogaNode();
Assert.AreEqual(instanceCount + 2, YogaNode.GetInstanceCount());
parent.Insert(0, child);
Assert.AreEqual(1, parent.Count);
Assert.AreEqual(parent, child.Parent);
parent.Clear();
Assert.AreEqual(0, parent.Count);
Assert.IsNull(child.Parent);
Assert.AreEqual(instanceCount + 2, YogaNode.GetInstanceCount());
}
[TestMethod]
public void TestMeasureFunc()
{
YogaNode node = new YogaNode();
node.SetMeasureFunction((_, width, widthMode, height, heightMode) => {
return MeasureOutput.Make(100, 150);
});
node.CalculateLayout();
Assert.AreEqual(100, node.LayoutWidth);
Assert.AreEqual(150, node.LayoutHeight);
}
[TestMethod]
public void TestMeasureFuncWithFloat()
{
YogaNode node = new YogaNode();
node.SetMeasureFunction((_, width, widthMode, height, heightMode) => {
return MeasureOutput.Make(123.4f, 81.7f);
});
node.CalculateLayout();
Assert.AreEqual(124, node.LayoutWidth);
Assert.AreEqual(82, node.LayoutHeight);
}
[TestMethod]
public void TestChildWithMeasureFunc()
{
YogaNode node = new YogaNode();
node.SetMeasureFunction((_, width, widthMode, height, heightMode) => {
return MeasureOutput.Make(100, 150);
});
YogaNode child = new YogaNode();
try
{
node.Insert(0, child);
}
catch (System.InvalidOperationException)
{
return;
}
Assert.Fail("Excepted exception of type 'System.InvalidOperationException'.");
}
[TestMethod]
public void TestMeasureFuncWithChild()
{
YogaNode node = new YogaNode();
YogaNode child = new YogaNode();
node.Insert(0, child);
try
{
node.SetMeasureFunction((_, width, widthMode, height, heightMode) => {
return MeasureOutput.Make(100, 150);
});
}
catch (System.InvalidOperationException)
{
return;
}
Assert.Fail("Excepted exception of type 'System.InvalidOperationException'.");
}
[TestMethod]
public void TestPrint()
{
YogaNode parent = new YogaNode();
parent.Width = 100;
parent.Height = 120;
YogaNode child0 = new YogaNode();
child0.Width = 30;
child0.Height = 40;
YogaNode child1 = new YogaNode();
child1.Width = 35;
child1.Height = 45;
parent.Insert(0, child0);
parent.Insert(0, child1);
parent.CalculateLayout();
Assert.AreEqual(parent.Print(),
"<div layout=\"width: 100; height: 120; top: 0; left: 0;\" style=\"width: 100px; height: 120px; \" >\n" +
" <div layout=\"width: 35; height: 45; top: 0; left: 0;\" style=\"width: 35px; height: 45px; \" ></div>\n" +
" <div layout=\"width: 30; height: 40; top: 45; left: 0;\" style=\"width: 30px; height: 40px; \" ></div>\n" +
"</div>"
);
}
[TestMethod]
public void TestCopyStyle()
{
YogaNode node0 = new YogaNode();
Assert.IsTrue(YogaConstants.IsUndefined(node0.MaxHeight));
YogaNode node1 = new YogaNode();
node1.MaxHeight = 100;
node0.CopyStyle(node1);
Assert.AreEqual(100, node0.MaxHeight);
}
#if !UNITY_EDITOR
private void ForceGC()
{
GC.Collect(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
}
[TestMethod]
public void TestDestructor()
{
ForceGC();
int instanceCount = YogaNode.GetInstanceCount();
TestDestructorForGC(instanceCount);
ForceGC();
Assert.AreEqual(instanceCount, YogaNode.GetInstanceCount());
}
private void TestDestructorForGC(int instanceCount)
{
YogaNode node = new YogaNode();
Assert.IsNotNull(node);
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
node = null;
}
[TestMethod]
public void TestDestructorWithChildren()
{
ForceGC();
int instanceCount = YogaNode.GetInstanceCount();
TestDestructorWithChildrenForGC1(instanceCount);
ForceGC();
Assert.AreEqual(instanceCount, YogaNode.GetInstanceCount());
}
private void TestDestructorWithChildrenForGC1(int instanceCount)
{
YogaNode node = new YogaNode();
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
TestDestructorWithChildrenForGC2(node, instanceCount + 1);
ForceGC();
Assert.AreEqual(instanceCount + 2, YogaNode.GetInstanceCount());
TestDestructorWithChildrenForGC2(node, instanceCount + 2);
ForceGC();
Assert.AreEqual(instanceCount + 3, YogaNode.GetInstanceCount());
node = null;
}
private void TestDestructorWithChildrenForGC2(YogaNode parent, int instanceCount)
{
YogaNode child = new YogaNode();
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
parent.Insert(0, child);
child = null;
}
[TestMethod]
public void TestParentDestructor()
{
ForceGC();
int instanceCount = YogaNode.GetInstanceCount();
YogaNode child = new YogaNode();
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
TestParentDestructorForGC(child, instanceCount + 1);
ForceGC();
Assert.IsNull(child.Parent);
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
}
private void TestParentDestructorForGC(YogaNode child, int instanceCount)
{
YogaNode parent = new YogaNode();
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
parent.Insert(0, child);
}
[TestMethod]
public void TestClearWithChildDestructor()
{
ForceGC();
int instanceCount = YogaNode.GetInstanceCount();
YogaNode node = new YogaNode();
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
TestClearWithChildDestructorForGC(node, instanceCount + 1);
ForceGC();
Assert.AreEqual(instanceCount + 2, YogaNode.GetInstanceCount());
node.Clear();
Assert.AreEqual(0, node.Count);
ForceGC();
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
}
private void TestClearWithChildDestructorForGC(YogaNode parent, int instanceCount)
{
YogaNode child = new YogaNode();
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
parent.Insert(0, child);
}
[TestMethod]
public void TestMeasureFuncWithDestructor()
{
ForceGC();
int instanceCount = YogaNode.GetInstanceCount();
YogaNode parent = new YogaNode();
Assert.AreEqual(instanceCount + 1, YogaNode.GetInstanceCount());
TestMeasureFuncWithDestructorForGC(parent);
ForceGC();
Assert.AreEqual(instanceCount + 2, YogaNode.GetInstanceCount());
parent.CalculateLayout();
Assert.AreEqual(120, (int)parent.LayoutWidth);
Assert.AreEqual(130, (int)parent.LayoutHeight);
}
private void TestMeasureFuncWithDestructorForGC(YogaNode parent)
{
YogaNode child = new YogaNode();
parent.Insert(0, child);
child.SetMeasureFunction((_, width, widthMode, height, heightMode) => {
return MeasureOutput.Make(120, 130);
});
}
#endif
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHapi.Base.Model;
using NHapi.Model.V21.Group;
using NHapi.Model.V21.Message;
using NHapi.Model.V21.Segment;
using NHapiTools.Base;
namespace NHapiTools.Model.V21.Message
{
/// <summary>
/// Message extention methods
/// </summary>
public static class MessageExtensions
{
#region Extension methods
/// <summary>
/// Get QUERY_RESPONSE Records from ADR_A19
/// </summary>
public static IEnumerable GetQUERY_RESPONSERecords(this ADR_A19 message)
{
object[] result = message.GetRecords("QUERY_RESPONSERepetitionsUsed", "GetQUERY_RESPONSE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all QUERY_RESPONSE Records from ADR_A19
/// </summary>
public static List<ADR_A19_QUERY_RESPONSE> GetAllQUERY_RESPONSERecords(this ADR_A19 message)
{
return message.GetAllRecords<ADR_A19_QUERY_RESPONSE>("QUERY_RESPONSERepetitionsUsed", "GetQUERY_RESPONSE");
}
/// <summary>
/// Add a new ADR_A19 to QUERY_RESPONSE
/// </summary>
public static ADR_A19_QUERY_RESPONSE AddQUERY_RESPONSE(this ADR_A19 message)
{
return message.GetQUERY_RESPONSE(message.QUERY_RESPONSERepetitionsUsed);
}
/// <summary>
/// Get PATIENT Records from ADT_A17
/// </summary>
public static IEnumerable GetPATIENTRecords(this ADT_A17 message)
{
object[] result = message.GetRecords("PATIENTRepetitionsUsed", "GetPATIENT");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all PATIENT Records from ADT_A17
/// </summary>
public static List<ADT_A17_PATIENT> GetAllPATIENTRecords(this ADT_A17 message)
{
return message.GetAllRecords<ADT_A17_PATIENT>("PATIENTRepetitionsUsed", "GetPATIENT");
}
/// <summary>
/// Add a new ADT_A17 to PATIENT
/// </summary>
public static ADT_A17_PATIENT AddPATIENT(this ADT_A17 message)
{
return message.GetPATIENT(message.PATIENTRepetitionsUsed);
}
/// <summary>
/// Get QUERY_RESPONSE Records from ARD_A19
/// </summary>
public static IEnumerable GetQUERY_RESPONSERecords(this ARD_A19 message)
{
object[] result = message.GetRecords("QUERY_RESPONSERepetitionsUsed", "GetQUERY_RESPONSE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all QUERY_RESPONSE Records from ARD_A19
/// </summary>
public static List<ARD_A19_QUERY_RESPONSE> GetAllQUERY_RESPONSERecords(this ARD_A19 message)
{
return message.GetAllRecords<ARD_A19_QUERY_RESPONSE>("QUERY_RESPONSERepetitionsUsed", "GetQUERY_RESPONSE");
}
/// <summary>
/// Add a new ARD_A19 to QUERY_RESPONSE
/// </summary>
public static ARD_A19_QUERY_RESPONSE AddQUERY_RESPONSE(this ARD_A19 message)
{
return message.GetQUERY_RESPONSE(message.QUERY_RESPONSERepetitionsUsed);
}
/// <summary>
/// Get VISIT Records from BAR_P01
/// </summary>
public static IEnumerable GetVISITRecords(this BAR_P01 message)
{
object[] result = message.GetRecords("VISITRepetitionsUsed", "GetVISIT");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all VISIT Records from BAR_P01
/// </summary>
public static List<BAR_P01_VISIT> GetAllVISITRecords(this BAR_P01 message)
{
return message.GetAllRecords<BAR_P01_VISIT>("VISITRepetitionsUsed", "GetVISIT");
}
/// <summary>
/// Add a new BAR_P01 to VISIT
/// </summary>
public static BAR_P01_VISIT AddVISIT(this BAR_P01 message)
{
return message.GetVISIT(message.VISITRepetitionsUsed);
}
/// <summary>
/// Get PATIENT Records from BAR_P02
/// </summary>
public static IEnumerable GetPATIENTRecords(this BAR_P02 message)
{
object[] result = message.GetRecords("PATIENTRepetitionsUsed", "GetPATIENT");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all PATIENT Records from BAR_P02
/// </summary>
public static List<BAR_P02_PATIENT> GetAllPATIENTRecords(this BAR_P02 message)
{
return message.GetAllRecords<BAR_P02_PATIENT>("PATIENTRepetitionsUsed", "GetPATIENT");
}
/// <summary>
/// Add a new BAR_P02 to PATIENT
/// </summary>
public static BAR_P02_PATIENT AddPATIENT(this BAR_P02 message)
{
return message.GetPATIENT(message.PATIENTRepetitionsUsed);
}
/// <summary>
/// Get FT1 Records from DFT_P03
/// </summary>
public static IEnumerable GetFT1Records(this DFT_P03 message)
{
object[] result = message.GetRecords("FT1RepetitionsUsed", "GetFT1");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all FT1 Records from DFT_P03
/// </summary>
public static List<FT1> GetAllFT1Records(this DFT_P03 message)
{
return message.GetAllRecords<FT1>("FT1RepetitionsUsed", "GetFT1");
}
/// <summary>
/// Add a new DFT_P03 to FT1
/// </summary>
public static FT1 AddFT1(this DFT_P03 message)
{
return message.GetFT1(message.FT1RepetitionsUsed);
}
/// <summary>
/// Get DSP Records from DSR_Q01
/// </summary>
public static IEnumerable GetDSPRecords(this DSR_Q01 message)
{
object[] result = message.GetRecords("DSPRepetitionsUsed", "GetDSP");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all DSP Records from DSR_Q01
/// </summary>
public static List<DSP> GetAllDSPRecords(this DSR_Q01 message)
{
return message.GetAllRecords<DSP>("DSPRepetitionsUsed", "GetDSP");
}
/// <summary>
/// Add a new DSR_Q01 to DSP
/// </summary>
public static DSP AddDSP(this DSR_Q01 message)
{
return message.GetDSP(message.DSPRepetitionsUsed);
}
/// <summary>
/// Get DSP Records from DSR_Q03
/// </summary>
public static IEnumerable GetDSPRecords(this DSR_Q03 message)
{
object[] result = message.GetRecords("DSPRepetitionsUsed", "GetDSP");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all DSP Records from DSR_Q03
/// </summary>
public static List<DSP> GetAllDSPRecords(this DSR_Q03 message)
{
return message.GetAllRecords<DSP>("DSPRepetitionsUsed", "GetDSP");
}
/// <summary>
/// Add a new DSR_Q03 to DSP
/// </summary>
public static DSP AddDSP(this DSR_Q03 message)
{
return message.GetDSP(message.DSPRepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORM_O01
/// </summary>
public static IEnumerable GetNTERecords(this ORM_O01 message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORM_O01
/// </summary>
public static List<NTE> GetAllNTERecords(this ORM_O01 message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORM_O01 to NTE
/// </summary>
public static NTE AddNTE(this ORM_O01 message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get ORDER Records from ORM_O01
/// </summary>
public static IEnumerable GetORDERRecords(this ORM_O01 message)
{
object[] result = message.GetRecords("ORDERRepetitionsUsed", "GetORDER");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all ORDER Records from ORM_O01
/// </summary>
public static List<ORM_O01_ORDER> GetAllORDERRecords(this ORM_O01 message)
{
return message.GetAllRecords<ORM_O01_ORDER>("ORDERRepetitionsUsed", "GetORDER");
}
/// <summary>
/// Add a new ORM_O01 to ORDER
/// </summary>
public static ORM_O01_ORDER AddORDER(this ORM_O01 message)
{
return message.GetORDER(message.ORDERRepetitionsUsed);
}
/// <summary>
/// Get NTE Records from ORR_O02
/// </summary>
public static IEnumerable GetNTERecords(this ORR_O02 message)
{
object[] result = message.GetRecords("NTERepetitionsUsed", "GetNTE");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all NTE Records from ORR_O02
/// </summary>
public static List<NTE> GetAllNTERecords(this ORR_O02 message)
{
return message.GetAllRecords<NTE>("NTERepetitionsUsed", "GetNTE");
}
/// <summary>
/// Add a new ORR_O02 to NTE
/// </summary>
public static NTE AddNTE(this ORR_O02 message)
{
return message.GetNTE(message.NTERepetitionsUsed);
}
/// <summary>
/// Get PATIENT_RESULT Records from ORU_R01
/// </summary>
public static IEnumerable GetPATIENT_RESULTRecords(this ORU_R01 message)
{
object[] result = message.GetRecords("PATIENT_RESULTRepetitionsUsed", "GetPATIENT_RESULT");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all PATIENT_RESULT Records from ORU_R01
/// </summary>
public static List<ORU_R01_PATIENT_RESULT> GetAllPATIENT_RESULTRecords(this ORU_R01 message)
{
return message.GetAllRecords<ORU_R01_PATIENT_RESULT>("PATIENT_RESULTRepetitionsUsed", "GetPATIENT_RESULT");
}
/// <summary>
/// Add a new ORU_R01 to PATIENT_RESULT
/// </summary>
public static ORU_R01_PATIENT_RESULT AddPATIENT_RESULT(this ORU_R01 message)
{
return message.GetPATIENT_RESULT(message.PATIENT_RESULTRepetitionsUsed);
}
/// <summary>
/// Get PATIENT_RESULT Records from ORU_R03
/// </summary>
public static IEnumerable GetPATIENT_RESULTRecords(this ORU_R03 message)
{
object[] result = message.GetRecords("PATIENT_RESULTRepetitionsUsed", "GetPATIENT_RESULT");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all PATIENT_RESULT Records from ORU_R03
/// </summary>
public static List<ORU_R03_PATIENT_RESULT> GetAllPATIENT_RESULTRecords(this ORU_R03 message)
{
return message.GetAllRecords<ORU_R03_PATIENT_RESULT>("PATIENT_RESULTRepetitionsUsed", "GetPATIENT_RESULT");
}
/// <summary>
/// Add a new ORU_R03 to PATIENT_RESULT
/// </summary>
public static ORU_R03_PATIENT_RESULT AddPATIENT_RESULT(this ORU_R03 message)
{
return message.GetPATIENT_RESULT(message.PATIENT_RESULTRepetitionsUsed);
}
/// <summary>
/// Get DSP Records from UDM_Q05
/// </summary>
public static IEnumerable GetDSPRecords(this UDM_Q05 message)
{
object[] result = message.GetRecords("DSPRepetitionsUsed", "GetDSP");
if ((result != null) && (result.Count() > 0))
{
for (int i = 0; i < result.Count(); i++)
yield return result[i];
}
}
/// <summary>
/// Get all DSP Records from UDM_Q05
/// </summary>
public static List<DSP> GetAllDSPRecords(this UDM_Q05 message)
{
return message.GetAllRecords<DSP>("DSPRepetitionsUsed", "GetDSP");
}
/// <summary>
/// Add a new UDM_Q05 to DSP
/// </summary>
public static DSP AddDSP(this UDM_Q05 message)
{
return message.GetDSP(message.DSPRepetitionsUsed);
}
#endregion
}
}
| |
#region License
//
// Copyright (c) 2007-2018, Sean Chambers <[email protected]>
// Copyright (c) 2010, Nathan Brown
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using FluentMigrator.Expressions;
using FluentMigrator.Runner.BatchParser;
using FluentMigrator.Runner.BatchParser.Sources;
using FluentMigrator.Runner.BatchParser.SpecialTokenSearchers;
using FluentMigrator.Runner.Generators.SQLite;
using FluentMigrator.Runner.Initialization;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace FluentMigrator.Runner.Processors.SQLite
{
// ReSharper disable once InconsistentNaming
public class SQLiteProcessor : GenericProcessorBase
{
[CanBeNull]
private readonly IServiceProvider _serviceProvider;
[NotNull]
private readonly SQLiteQuoter _quoter;
public override string DatabaseType
{
get { return "SQLite"; }
}
public override IList<string> DatabaseTypeAliases { get; } = new List<string>();
[Obsolete]
public SQLiteProcessor(
IDbConnection connection,
IMigrationGenerator generator,
IAnnouncer announcer,
[NotNull] IMigrationProcessorOptions options,
IDbFactory factory,
[NotNull] SQLiteQuoter quoter)
: base(connection, factory, generator, announcer, options)
{
_quoter = quoter;
}
public SQLiteProcessor(
[NotNull] SQLiteDbFactory factory,
[NotNull] SQLiteGenerator generator,
[NotNull] ILogger<SQLiteProcessor> logger,
[NotNull] IOptionsSnapshot<ProcessorOptions> options,
[NotNull] IConnectionStringAccessor connectionStringAccessor,
[NotNull] IServiceProvider serviceProvider,
[NotNull] SQLiteQuoter quoter)
: base(() => factory.Factory, generator, logger, options.Value, connectionStringAccessor)
{
_serviceProvider = serviceProvider;
_quoter = quoter;
}
public override bool SchemaExists(string schemaName)
{
return true;
}
public override bool TableExists(string schemaName, string tableName)
{
return Exists("select count(*) from sqlite_master where name={0} and type='table'", _quoter.QuoteValue(tableName));
}
public override bool ColumnExists(string schemaName, string tableName, string columnName)
{
var dataSet = Read("PRAGMA table_info({0})", _quoter.QuoteValue(tableName));
if (dataSet.Tables.Count == 0)
return false;
var table = dataSet.Tables[0];
if (!table.Columns.Contains("Name"))
return false;
return table.Select(string.Format("Name={0}", _quoter.QuoteValue(columnName))).Length > 0;
}
public override bool ConstraintExists(string schemaName, string tableName, string constraintName)
{
return false;
}
public override bool IndexExists(string schemaName, string tableName, string indexName)
{
return Exists("select count(*) from sqlite_master where name={0} and tbl_name={1} and type='index'", _quoter.QuoteValue(indexName), _quoter.QuoteValue(tableName));
}
public override bool SequenceExists(string schemaName, string sequenceName)
{
return false;
}
public override void Execute(string template, params object[] args)
{
Process(string.Format(template, args));
}
public override bool Exists(string template, params object[] args)
{
EnsureConnectionIsOpen();
using (var command = CreateCommand(string.Format(template, args)))
using (var reader = command.ExecuteReader())
{
try
{
if (!reader.Read()) return false;
if (int.Parse(reader[0].ToString()) <= 0) return false;
return true;
}
catch
{
return false;
}
}
}
public override DataSet ReadTableData(string schemaName, string tableName)
{
return Read("select * from {0}", _quoter.QuoteTableName(tableName));
}
public override bool DefaultValueExists(string schemaName, string tableName, string columnName, object defaultValue)
{
return false;
}
public override void Process(PerformDBOperationExpression expression)
{
Logger.LogSay("Performing DB Operation");
if (Options.PreviewOnly)
return;
EnsureConnectionIsOpen();
expression.Operation?.Invoke(Connection, Transaction);
}
protected override void Process(string sql)
{
if (string.IsNullOrEmpty(sql))
return;
if (Options.PreviewOnly)
{
ExecuteBatchNonQuery(
sql,
(sqlBatch) =>
{
Logger.LogSql(sqlBatch);
},
(sqlBatch, goCount) =>
{
Logger.LogSql(sqlBatch);
Logger.LogSql($"GO {goCount}");
});
return;
}
Logger.LogSql(sql);
EnsureConnectionIsOpen();
if (ContainsGo(sql))
{
ExecuteBatchNonQuery(
sql,
(sqlBatch) =>
{
using (var command = CreateCommand(sqlBatch))
{
command.ExecuteNonQuery();
}
},
(sqlBatch, goCount) =>
{
using (var command = CreateCommand(sqlBatch))
{
for (var i = 0; i != goCount; ++i)
{
command.ExecuteNonQuery();
}
}
});
}
else
{
ExecuteNonQuery(sql);
}
}
private bool ContainsGo(string sql)
{
var containsGo = false;
var parser = _serviceProvider?.GetService<SQLiteBatchParser>() ?? new SQLiteBatchParser();
parser.SpecialToken += (sender, args) => containsGo = true;
using (var source = new TextReaderSource(new StringReader(sql), true))
{
parser.Process(source);
}
return containsGo;
}
private void ExecuteNonQuery(string sql)
{
using (var command = CreateCommand(sql))
{
try
{
command.ExecuteNonQuery();
}
catch (DbException ex)
{
throw new Exception(ex.Message + "\r\nWhile Processing:\r\n\"" + command.CommandText + "\"", ex);
}
}
}
private void ExecuteBatchNonQuery(string sql, Action<string> executeBatch, Action<string, int> executeGo)
{
string sqlBatch = string.Empty;
try
{
var parser = _serviceProvider?.GetService<SQLiteBatchParser>() ?? new SQLiteBatchParser();
parser.SqlText += (sender, args) => { sqlBatch = args.SqlText.Trim(); };
parser.SpecialToken += (sender, args) =>
{
if (string.IsNullOrEmpty(sqlBatch))
return;
if (args.Opaque is GoSearcher.GoSearcherParameters goParams)
{
executeGo(sqlBatch, goParams.Count);
}
sqlBatch = null;
};
using (var source = new TextReaderSource(new StringReader(sql), true))
{
parser.Process(source, stripComments: Options.StripComments);
}
if (!string.IsNullOrEmpty(sqlBatch))
{
executeBatch(sqlBatch);
}
}
catch (DbException ex)
{
throw new Exception(ex.Message + "\r\nWhile Processing:\r\n\"" + sqlBatch + "\"", ex);
}
}
public override DataSet Read(string template, params object[] args)
{
EnsureConnectionIsOpen();
using (var command = CreateCommand(string.Format(template, args)))
using (var reader = command.ExecuteReader())
{
return reader.ReadDataSet();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.NotificationHubs
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for NamespacesOperations.
/// </summary>
public static partial class NamespacesOperationsExtensions
{
/// <summary>
/// Checks the availability of the given service namespace across all Windows
/// Azure subscriptions. This is useful because the domain name is created
/// based on the service namespace name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='parameters'>
/// The namespace name.
/// </param>
public static CheckAvailabilityResource CheckAvailability(this INamespacesOperations operations, CheckAvailabilityParameters parameters)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).CheckAvailabilityAsync(parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Checks the availability of the given service namespace across all Windows
/// Azure subscriptions. This is useful because the domain name is created
/// based on the service namespace name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='parameters'>
/// The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CheckAvailabilityResource> CheckAvailabilityAsync(this INamespacesOperations operations, CheckAvailabilityParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckAvailabilityWithHttpMessagesAsync(parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates/Updates a service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a Namespace Resource.
/// </param>
public static NamespaceResource CreateOrUpdate(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).CreateOrUpdateAsync(resourceGroupName, namespaceName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates/Updates a service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a Namespace Resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NamespaceResource> CreateOrUpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// notificationHubs under the namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
public static void Delete(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
{
Task.Factory.StartNew(s => ((INamespacesOperations)s).DeleteAsync(resourceGroupName, namespaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// notificationHubs under the namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// notificationHubs under the namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
public static void BeginDelete(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
{
Task.Factory.StartNew(s => ((INamespacesOperations)s).BeginDeleteAsync(resourceGroupName, namespaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// notificationHubs under the namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns the description for the specified namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
public static NamespaceResource Get(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).GetAsync(resourceGroupName, namespaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns the description for the specified namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NamespaceResource> GetAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates an authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Aauthorization Rule Name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
public static SharedAccessAuthorizationRuleResource CreateOrUpdateAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates an authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Aauthorization Rule Name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SharedAccessAuthorizationRuleResource> CreateOrUpdateAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a namespace authorization rule
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization Rule Name.
/// </param>
public static void DeleteAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName)
{
Task.Factory.StartNew(s => ((INamespacesOperations)s).DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a namespace authorization rule
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization Rule Name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets an authorization rule for a namespace 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='namespaceName'>
/// The namespace name
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization rule name.
/// </param>
public static SharedAccessAuthorizationRuleResource GetAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).GetAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets an authorization rule for a namespace 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='namespaceName'>
/// The namespace name
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization rule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SharedAccessAuthorizationRuleResource> GetAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the specified
/// operation. After calling an asynchronous operation, you can call Get
/// Operation Status to determine whether the operation has succeeded,
/// failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
public static void GetLongRunningOperationStatus(this INamespacesOperations operations, string operationStatusLink)
{
Task.Factory.StartNew(s => ((INamespacesOperations)s).GetLongRunningOperationStatusAsync(operationStatusLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Operation Status operation returns the status of the specified
/// operation. After calling an asynchronous operation, you can call Get
/// Operation Status to determine whether the operation has succeeded,
/// failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='operationStatusLink'>
/// Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetLongRunningOperationStatusAsync(this INamespacesOperations operations, string operationStatusLink, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetLongRunningOperationStatusWithHttpMessagesAsync(operationStatusLink, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. If resourceGroupName value is null the
/// method lists all the namespaces within subscription
/// </param>
public static IPage<NamespaceResource> List(this INamespacesOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. If resourceGroupName value is null the
/// method lists all the namespaces within subscription
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NamespaceResource>> ListAsync(this INamespacesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the available namespaces within the subscription irrespective of
/// the resourceGroups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<NamespaceResource> ListAll(this INamespacesOperations operations)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the available namespaces within the subscription irrespective of
/// the resourceGroups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NamespaceResource>> ListAllAsync(this INamespacesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the authorization rules for a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRules(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAuthorizationRulesAsync(resourceGroupName, namespaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the authorization rules for a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the Primary and Secondary ConnectionStrings to the namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the namespace for the specified authorizationRule.
/// </param>
public static ResourceListKeys ListKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListKeysAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the Primary and Secondary ConnectionStrings to the namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the namespace for the specified authorizationRule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceListKeys> ListKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<NamespaceResource> ListNext(this INamespacesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NamespaceResource>> ListNextAsync(this INamespacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the available namespaces within the subscription irrespective of
/// the resourceGroups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<NamespaceResource> ListAllNext(this INamespacesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the available namespaces within the subscription irrespective of
/// the resourceGroups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NamespaceResource>> ListAllNextAsync(this INamespacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the authorization rules for a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRulesNext(this INamespacesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAuthorizationRulesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the authorization rules for a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesNextAsync(this INamespacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// 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.Text;
namespace System.ServiceModel.Channels
{
internal static class IntEncoder
{
public const int MaxEncodedSize = 5;
public static int Encode(int value, byte[] bytes, int offset)
{
int count = 1;
while ((value & 0xFFFFFF80) != 0)
{
bytes[offset++] = (byte)((value & 0x7F) | 0x80);
count++;
value >>= 7;
}
bytes[offset] = (byte)value;
return count;
}
public static int GetEncodedSize(int value)
{
if (value < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SRServiceModel.ValueMustBeNonNegative));
}
int count = 1;
while ((value & 0xFFFFFF80) != 0)
{
count++;
value >>= 7;
}
return count;
}
}
internal abstract class EncodedFramingRecord
{
private byte[] _encodedBytes;
protected EncodedFramingRecord(byte[] encodedBytes)
{
_encodedBytes = encodedBytes;
}
internal EncodedFramingRecord(FramingRecordType recordType, string value)
{
int valueByteCount = Encoding.UTF8.GetByteCount(value);
int sizeByteCount = IntEncoder.GetEncodedSize(valueByteCount);
_encodedBytes = Fx.AllocateByteArray(checked(1 + sizeByteCount + valueByteCount));
_encodedBytes[0] = (byte)recordType;
int offset = 1;
offset += IntEncoder.Encode(valueByteCount, _encodedBytes, offset);
Encoding.UTF8.GetBytes(value, 0, value.Length, _encodedBytes, offset);
SetEncodedBytes(_encodedBytes);
}
public byte[] EncodedBytes
{
get { return _encodedBytes; }
}
protected void SetEncodedBytes(byte[] encodedBytes)
{
_encodedBytes = encodedBytes;
}
public override int GetHashCode()
{
return (_encodedBytes[0] << 16) |
(_encodedBytes[_encodedBytes.Length / 2] << 8) |
_encodedBytes[_encodedBytes.Length - 1];
}
public override bool Equals(object o)
{
if (o is EncodedFramingRecord)
return Equals((EncodedFramingRecord)o);
return false;
}
public bool Equals(EncodedFramingRecord other)
{
if (other == null)
return false;
if (other == this)
return true;
byte[] otherBytes = other._encodedBytes;
if (_encodedBytes.Length != otherBytes.Length)
return false;
for (int i = 0; i < _encodedBytes.Length; i++)
{
if (_encodedBytes[i] != otherBytes[i])
return false;
}
return true;
}
}
internal class EncodedContentType : EncodedFramingRecord
{
private EncodedContentType(FramingEncodingType encodingType) :
base(new byte[] { (byte)FramingRecordType.KnownEncoding, (byte)encodingType })
{
}
private EncodedContentType(string contentType)
: base(FramingRecordType.ExtensibleEncoding, contentType)
{
}
public static EncodedContentType Create(string contentType)
{
if (contentType == FramingEncodingString.BinarySession)
{
return new EncodedContentType(FramingEncodingType.BinarySession);
}
else if (contentType == FramingEncodingString.Binary)
{
return new EncodedContentType(FramingEncodingType.Binary);
}
else if (contentType == FramingEncodingString.Soap12Utf8)
{
return new EncodedContentType(FramingEncodingType.Soap12Utf8);
}
else if (contentType == FramingEncodingString.Soap11Utf8)
{
return new EncodedContentType(FramingEncodingType.Soap11Utf8);
}
else if (contentType == FramingEncodingString.Soap12Utf16)
{
return new EncodedContentType(FramingEncodingType.Soap12Utf16);
}
else if (contentType == FramingEncodingString.Soap11Utf16)
{
return new EncodedContentType(FramingEncodingType.Soap11Utf16);
}
else if (contentType == FramingEncodingString.Soap12Utf16FFFE)
{
return new EncodedContentType(FramingEncodingType.Soap12Utf16FFFE);
}
else if (contentType == FramingEncodingString.Soap11Utf16FFFE)
{
return new EncodedContentType(FramingEncodingType.Soap11Utf16FFFE);
}
else if (contentType == FramingEncodingString.MTOM)
{
return new EncodedContentType(FramingEncodingType.MTOM);
}
else
{
return new EncodedContentType(contentType);
}
}
}
internal class EncodedVia : EncodedFramingRecord
{
public EncodedVia(string via)
: base(FramingRecordType.Via, via)
{
}
}
internal class EncodedUpgrade : EncodedFramingRecord
{
public EncodedUpgrade(string contentType)
: base(FramingRecordType.UpgradeRequest, contentType)
{
}
}
internal class EncodedFault : EncodedFramingRecord
{
public EncodedFault(string fault)
: base(FramingRecordType.Fault, fault)
{
}
}
// used by SimplexEncoder/DuplexEncoder
internal abstract class SessionEncoder
{
public const int MaxMessageFrameSize = 1 + IntEncoder.MaxEncodedSize;
protected SessionEncoder() { }
public static byte[] PreambleEndBytes = new byte[] {
(byte)FramingRecordType.PreambleEnd
};
public static byte[] EndBytes = new byte[] {
(Byte)FramingRecordType.End
};
public static int CalcStartSize(EncodedVia via, EncodedContentType contentType)
{
return via.EncodedBytes.Length + contentType.EncodedBytes.Length;
}
public static void EncodeStart(byte[] buffer, int offset, EncodedVia via, EncodedContentType contentType)
{
Buffer.BlockCopy(via.EncodedBytes, 0, buffer, offset, via.EncodedBytes.Length);
Buffer.BlockCopy(contentType.EncodedBytes, 0, buffer, offset + via.EncodedBytes.Length, contentType.EncodedBytes.Length);
}
public static ArraySegment<byte> EncodeMessageFrame(ArraySegment<byte> messageFrame)
{
int spaceNeeded = 1 + IntEncoder.GetEncodedSize(messageFrame.Count);
int offset = messageFrame.Offset - spaceNeeded;
if (offset < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("messageFrame.Offset",
messageFrame.Offset, string.Format(SRServiceModel.SpaceNeededExceedsMessageFrameOffset, spaceNeeded)));
}
byte[] buffer = messageFrame.Array;
buffer[offset++] = (byte)FramingRecordType.SizedEnvelope;
IntEncoder.Encode(messageFrame.Count, buffer, offset);
return new ArraySegment<byte>(buffer, messageFrame.Offset - spaceNeeded, messageFrame.Count + spaceNeeded);
}
}
// used by ServerDuplexEncoder/ServerSimplexEncoder
internal abstract class ServerSessionEncoder : SessionEncoder
{
protected ServerSessionEncoder() { }
public static byte[] AckResponseBytes = new byte[] {
(byte)FramingRecordType.PreambleAck
};
public static byte[] UpgradeResponseBytes = new byte[] {
(byte)FramingRecordType.UpgradeResponse
};
}
// Pattern:
// ModeBytes,
// EncodeStart,
// EncodeUpgrade*,
// EncodeMessageFrame*,
// EndBytes
internal class ClientDuplexEncoder : SessionEncoder
{
private ClientDuplexEncoder() { }
public static byte[] ModeBytes = new byte[] {
(byte)FramingRecordType.Version,
(byte)FramingVersion.Major,
(byte)FramingVersion.Minor,
(byte)FramingRecordType.Mode,
(byte)FramingMode.Duplex };
}
// Pattern:
// ModeBytes,
// EncodeStart,
// EncodeUpgrade*,
// EncodeMessageFrame*,
// EndBytes
internal class ClientSimplexEncoder : SessionEncoder
{
private ClientSimplexEncoder() { }
public static byte[] ModeBytes = new byte[] {
(byte)FramingRecordType.Version,
(byte)FramingVersion.Major,
(byte)FramingVersion.Minor,
(byte)FramingRecordType.Mode,
(byte)FramingMode.Simplex };
}
// shared code for client and server
internal abstract class SingletonEncoder
{
protected SingletonEncoder()
{
}
public static byte[] EnvelopeStartBytes = new byte[] {
(byte)FramingRecordType.UnsizedEnvelope };
public static byte[] EnvelopeEndBytes = new byte[] {
(byte)0 };
public static byte[] EnvelopeEndFramingEndBytes = new byte[] {
(byte)0, (byte)FramingRecordType.End };
public static byte[] EndBytes = new byte[] {
(byte)FramingRecordType.End };
public static ArraySegment<byte> EncodeMessageFrame(ArraySegment<byte> messageFrame)
{
int spaceNeeded = IntEncoder.GetEncodedSize(messageFrame.Count);
int offset = messageFrame.Offset - spaceNeeded;
if (offset < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("messageFrame.Offset",
messageFrame.Offset, string.Format(SRServiceModel.SpaceNeededExceedsMessageFrameOffset, spaceNeeded)));
}
byte[] buffer = messageFrame.Array;
IntEncoder.Encode(messageFrame.Count, buffer, offset);
return new ArraySegment<byte>(buffer, offset, messageFrame.Count + spaceNeeded);
}
}
// Pattern:
// ModeBytes,
// EncodeStart,
// EncodeUpgrade*,
// EnvelopeStartBytes,
// streamed-message-bytes*
internal class ClientSingletonEncoder : SingletonEncoder
{
private ClientSingletonEncoder() { }
public static byte[] PreambleEndBytes = new byte[] {
(byte)FramingRecordType.PreambleEnd
};
public static byte[] ModeBytes = new byte[] {
(byte)FramingRecordType.Version,
(byte)FramingVersion.Major,
(byte)FramingVersion.Minor,
(byte)FramingRecordType.Mode,
(byte)FramingMode.Singleton };
public static int CalcStartSize(EncodedVia via, EncodedContentType contentType)
{
return via.EncodedBytes.Length + contentType.EncodedBytes.Length;
}
public static void EncodeStart(byte[] buffer, int offset, EncodedVia via, EncodedContentType contentType)
{
Buffer.BlockCopy(via.EncodedBytes, 0, buffer, offset, via.EncodedBytes.Length);
Buffer.BlockCopy(contentType.EncodedBytes, 0, buffer, offset + via.EncodedBytes.Length, contentType.EncodedBytes.Length);
}
}
// Pattern:
// (UpgradeResponseBytes, upgrade-bytes)?,
internal class ServerSingletonEncoder : SingletonEncoder
{
private ServerSingletonEncoder() { }
public static byte[] AckResponseBytes = new byte[] {
(byte)FramingRecordType.PreambleAck
};
public static byte[] UpgradeResponseBytes = new byte[] {
(byte)FramingRecordType.UpgradeResponse
};
}
}
| |
// Authors:
// Rafael Mizrahi <[email protected]>
// Erez Lotan <[email protected]>
// Oren Gurfinkel <[email protected]>
// Ofer Borstein
//
// Copyright (c) 2004 Mainsoft Co.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.Data;
using System.Data.OleDb;
using GHTUtils;
using GHTUtils.Base;
namespace tests.system_data_dll.System_Data
{
[TestFixture] public class DataSet_Merge_Ds_1 : GHTBase
{
[Test] public void Main()
{
DataSet_Merge_Ds_1 tc = new DataSet_Merge_Ds_1();
Exception exp = null;
try
{
tc.BeginTest("DataSet_Merge_Ds_1");
tc.run();
}
catch(Exception ex){exp = ex;}
finally {tc.EndTest(exp);}
}
public void run()
{
Exception exp = null;
//create source dataset
DataSet ds = new DataSet();
ds.Tables.Add(GHTUtils.DataProvider.CreateParentDataTable());
ds.Tables.Add(GHTUtils.DataProvider.CreateChildDataTable());
ds.Tables["Child"].TableName = "Child2";
ds.Tables.Add(GHTUtils.DataProvider.CreateChildDataTable());
// Console.WriteLine(ds.Tables[0].TableName + ds.Tables[1].TableName + ds.Tables[2].TableName);
// Console.WriteLine(ds.Tables[2].Rows.Count.ToString());
//craete a target dataset to the merge operation
DataSet dsTarget = ds.Copy();
//craete a second target dataset to the merge operation
DataSet dsTarget1 = ds.Copy();
//------------------ make some changes in the second target dataset schema --------------------
//add primary key
dsTarget1.Tables["Parent"].PrimaryKey = new DataColumn[] {dsTarget1.Tables["Parent"].Columns["ParentId"]};
dsTarget1.Tables["Child"].PrimaryKey = new DataColumn[] {dsTarget1.Tables["Child"].Columns["ParentId"],dsTarget1.Tables["Child"].Columns["ChildId"]};
//add Foreign Key (different name)
dsTarget1.Tables["Child2"].Constraints.Add("Child2_FK_2",dsTarget1.Tables["Parent"].Columns["ParentId"],dsTarget1.Tables["Child2"].Columns["ParentId"]);
//add relation (different name)
//dsTarget1.Relations.Add("Parent_Child_1",dsTarget1.Tables["Parent"].Columns["ParentId"],dsTarget1.Tables["Child"].Columns["ParentId"]);
//------------------ make some changes in the source dataset schema --------------------
//add primary key
ds.Tables["Parent"].PrimaryKey = new DataColumn[] {ds.Tables["Parent"].Columns["ParentId"]};
ds.Tables["Child"].PrimaryKey = new DataColumn[] {ds.Tables["Child"].Columns["ParentId"],ds.Tables["Child"].Columns["ChildId"]};
//unique column
ds.Tables["Parent"].Columns["String2"].Unique = true; //will not be merged
//add Foreign Key
ds.Tables["Child2"].Constraints.Add("Child2_FK",ds.Tables["Parent"].Columns["ParentId"],ds.Tables["Child2"].Columns["ParentId"]);
//add relation
ds.Relations.Add("Parent_Child",ds.Tables["Parent"].Columns["ParentId"],ds.Tables["Child"].Columns["ParentId"]);
//add allow null constraint
ds.Tables["Parent"].Columns["ParentBool"].AllowDBNull = false; //will not be merged
//add Indentity column
ds.Tables["Parent"].Columns.Add("Indentity",typeof(int));
ds.Tables["Parent"].Columns["Indentity"].AutoIncrement = true;
ds.Tables["Parent"].Columns["Indentity"].AutoIncrementStep = 2;
//modify default value
ds.Tables["Child"].Columns["String1"].DefaultValue = "Default"; //will not be merged
//remove column
ds.Tables["Child"].Columns.Remove("String2"); //will not be merged
//-------------------- begin to check ----------------------------------------------
try
{
BeginCase("merge 1 - make sure the merge method invoked without exceptions");
dsTarget.Merge(ds);
Compare("Success","Success");
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
CompareResults_1("merge 1",ds,dsTarget);
//merge again,
try
{
BeginCase("merge 2 - make sure the merge method invoked without exceptions");
dsTarget.Merge(ds);
Compare("Success","Success");
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
CompareResults_1("merge 2",ds,dsTarget);
try
{
BeginCase("merge second dataset - make sure the merge method invoked without exceptions");
dsTarget1.Merge(ds);
Compare("Success","Success");
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
CompareResults_2("merge 3",ds,dsTarget1);
}
void CompareResults_1(string Msg,DataSet ds, DataSet dsTarget)
{
Exception exp = null;
try
{
BeginCase(Msg + " check Parent Primary key length");
Compare(ds.Tables["Parent"].PrimaryKey.Length ,dsTarget.Tables["Parent"].PrimaryKey.Length );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Child Primary key length");
Compare(ds.Tables["Child"].PrimaryKey.Length ,dsTarget.Tables["Child"].PrimaryKey.Length );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Parent Primary key columns");
Compare(ds.Tables["Parent"].PrimaryKey[0].ColumnName ,dsTarget.Tables["Parent"].PrimaryKey[0].ColumnName);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Child Primary key columns[0]");
Compare(ds.Tables["Child"].PrimaryKey[0].ColumnName ,dsTarget.Tables["Child"].PrimaryKey[0].ColumnName);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Child Primary key columns[1]");
Compare(ds.Tables["Child"].PrimaryKey[1].ColumnName ,dsTarget.Tables["Child"].PrimaryKey[1].ColumnName);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Parent Unique columns");
Compare(ds.Tables["Parent"].Columns["String2"].Unique ,dsTarget.Tables["Parent"].Columns["String2"].Unique);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Child2 Foreign Key name");
Compare(ds.Tables["Child2"].Constraints[0].ConstraintName ,dsTarget.Tables["Child2"].Constraints[0].ConstraintName );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check dataset relation count");
Compare(ds.Relations.Count ,dsTarget.Relations.Count );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check dataset relation - Parent column");
Compare(ds.Relations[0].ParentColumns[0].ColumnName ,dsTarget.Relations[0].ParentColumns[0].ColumnName );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check dataset relation - Child column ");
Compare(ds.Relations[0].ChildColumns[0].ColumnName ,dsTarget.Relations[0].ChildColumns[0].ColumnName );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check allow null constraint");
Compare(dsTarget.Tables["Parent"].Columns["ParentBool"].AllowDBNull,true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Indentity column");
Compare(ds.Tables["Parent"].Columns.Contains("Indentity"),dsTarget.Tables["Parent"].Columns.Contains("Indentity"));
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Indentity column - AutoIncrementStep");
Compare(ds.Tables["Parent"].Columns["Indentity"].AutoIncrementStep,dsTarget.Tables["Parent"].Columns["Indentity"].AutoIncrementStep);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Indentity column - AutoIncrement");
Compare(ds.Tables["Parent"].Columns["Indentity"].AutoIncrement,dsTarget.Tables["Parent"].Columns["Indentity"].AutoIncrement);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Indentity column - DefaultValue");
Compare(dsTarget.Tables["Child"].Columns["String1"].DefaultValue == DBNull.Value , true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check remove colum");
Compare(dsTarget.Tables["Child"].Columns.Contains("String2"),true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
}
void CompareResults_2(string Msg,DataSet ds, DataSet dsTarget)
{
Exception exp = null;
try
{
BeginCase(Msg + " check Parent Primary key length");
Compare(ds.Tables["Parent"].PrimaryKey.Length ,dsTarget.Tables["Parent"].PrimaryKey.Length );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Child Primary key length");
Compare(ds.Tables["Child"].PrimaryKey.Length ,dsTarget.Tables["Child"].PrimaryKey.Length );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Parent Primary key columns");
Compare(ds.Tables["Parent"].PrimaryKey[0].ColumnName ,dsTarget.Tables["Parent"].PrimaryKey[0].ColumnName);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Child Primary key columns[0]");
Compare(ds.Tables["Child"].PrimaryKey[0].ColumnName ,dsTarget.Tables["Child"].PrimaryKey[0].ColumnName);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Child Primary key columns[1]");
Compare(ds.Tables["Child"].PrimaryKey[1].ColumnName ,dsTarget.Tables["Child"].PrimaryKey[1].ColumnName);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Parent Unique columns");
Compare(ds.Tables["Parent"].Columns["String2"].Unique ,dsTarget.Tables["Parent"].Columns["String2"].Unique);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Child2 Foreign Key name");
Compare(dsTarget.Tables["Child2"].Constraints[0].ConstraintName,"Child2_FK_2" );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check dataset relation count");
Compare(ds.Relations.Count ,dsTarget.Relations.Count );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check dataset relation - Parent column");
Compare(ds.Relations[0].ParentColumns[0].ColumnName ,dsTarget.Relations[0].ParentColumns[0].ColumnName );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check dataset relation - Child column ");
Compare(ds.Relations[0].ChildColumns[0].ColumnName ,dsTarget.Relations[0].ChildColumns[0].ColumnName );
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check allow null constraint");
Compare(dsTarget.Tables["Parent"].Columns["ParentBool"].AllowDBNull,true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Indentity column");
Compare(ds.Tables["Parent"].Columns.Contains("Indentity"),dsTarget.Tables["Parent"].Columns.Contains("Indentity"));
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Indentity column - AutoIncrementStep");
Compare(ds.Tables["Parent"].Columns["Indentity"].AutoIncrementStep,dsTarget.Tables["Parent"].Columns["Indentity"].AutoIncrementStep);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Indentity column - AutoIncrement");
Compare(ds.Tables["Parent"].Columns["Indentity"].AutoIncrement,dsTarget.Tables["Parent"].Columns["Indentity"].AutoIncrement);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check Indentity column - DefaultValue");
Compare(dsTarget.Tables["Child"].Columns["String1"].DefaultValue == DBNull.Value , true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase(Msg + " check remove colum");
Compare(dsTarget.Tables["Child"].Columns.Contains("String2"),true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
//TestCase for bug #3168
BeginCase("Check Relation.Nested value, TestCase for bug #3168");
DataSet orig = new DataSet();
DataTable parent = orig.Tables.Add("Parent");
parent.Columns.Add("Id", typeof(int));
parent.Columns.Add("col1", typeof(string));
parent.Rows.Add(new object[] {0, "aaa"});
DataTable child = orig.Tables.Add("Child");
child.Columns.Add("ParentId", typeof(int));
child.Columns.Add("col1", typeof(string));
child.Rows.Add(new object[] {0, "bbb"});
orig.Relations.Add("Parent_Child", parent.Columns["Id"], child.Columns["ParentId"]);
orig.Relations["Parent_Child"].Nested = true;
DataSet merged = new DataSet();
merged.Merge(orig);
Compare(merged.Relations["Parent_Child"].Nested, orig.Relations["Parent_Child"].Nested);
}
catch (Exception ex) {exp=ex;}
finally{EndCase(exp); exp=null;}
}
//Activate This Construntor to log All To Standard output
//public TestClass():base(true){}
//Activate this constructor to log Failures to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, false){}
//Activate this constructor to log All to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, true){}
//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES
}
}
| |
/*
* 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.CodeDom.Compiler;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.IO;
using Microsoft.CSharp;
using Microsoft.JScript;
using Microsoft.VisualBasic;
using log4net;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenMetaverse;
namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
{
public class Compiler : ICompiler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// * Uses "LSL2Converter" to convert LSL to C# if necessary.
// * Compiles C#-code into an assembly
// * Returns assembly name ready for AppDomain load.
//
// Assembly is compiled using LSL_BaseClass as base. Look at debug C# code file created when LSL script is compiled for full details.
//
internal enum enumCompileType
{
lsl = 0,
cs = 1,
vb = 2,
js = 3,
yp = 4
}
/// <summary>
/// This contains number of lines WE use for header when compiling script. User will get error in line x-LinesToRemoveOnError when error occurs.
/// </summary>
public int LinesToRemoveOnError = 3;
private enumCompileType DefaultCompileLanguage;
private bool WriteScriptSourceToDebugFile;
private bool CompileWithDebugInformation;
private Dictionary<string, bool> AllowedCompilers = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
private Dictionary<string, enumCompileType> LanguageMapping = new Dictionary<string, enumCompileType>(StringComparer.CurrentCultureIgnoreCase);
private string FilePrefix;
private string ScriptEnginesPath = "ScriptEngines";
// mapping between LSL and C# line/column numbers
private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> m_positionMap;
private ICodeConverter LSL_Converter;
private List<string> m_warnings = new List<string>();
// private object m_syncy = new object();
private static CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
private static VBCodeProvider VBcodeProvider = new VBCodeProvider();
private static JScriptCodeProvider JScodeProvider = new JScriptCodeProvider();
private static CSharpCodeProvider YPcodeProvider = new CSharpCodeProvider(); // YP is translated into CSharp
private static YP2CSConverter YP_Converter = new YP2CSConverter();
// private static int instanceID = new Random().Next(0, int.MaxValue); // Unique number to use on our compiled files
private static UInt64 scriptCompileCounter = 0; // And a counter
public IScriptEngine m_scriptEngine;
public Compiler(IScriptEngine scriptEngine)
{
m_scriptEngine = scriptEngine;
ReadConfig();
}
public bool in_startup = true;
public void ReadConfig()
{
// Get some config
WriteScriptSourceToDebugFile = m_scriptEngine.Config.GetBoolean("WriteScriptSourceToDebugFile", false);
CompileWithDebugInformation = m_scriptEngine.Config.GetBoolean("CompileWithDebugInformation", true);
// Get file prefix from scriptengine name and make it file system safe:
FilePrefix = "CommonCompiler";
foreach (char c in Path.GetInvalidFileNameChars())
{
FilePrefix = FilePrefix.Replace(c, '_');
}
// First time we start? Delete old files
if (in_startup)
{
in_startup = false;
DeleteOldFiles();
}
// Map name and enum type of our supported languages
LanguageMapping.Add(enumCompileType.cs.ToString(), enumCompileType.cs);
LanguageMapping.Add(enumCompileType.vb.ToString(), enumCompileType.vb);
LanguageMapping.Add(enumCompileType.lsl.ToString(), enumCompileType.lsl);
LanguageMapping.Add(enumCompileType.js.ToString(), enumCompileType.js);
LanguageMapping.Add(enumCompileType.yp.ToString(), enumCompileType.yp);
// Allowed compilers
string allowComp = m_scriptEngine.Config.GetString("AllowedCompilers", "lsl");
AllowedCompilers.Clear();
#if DEBUG
m_log.Debug("[Compiler]: Allowed languages: " + allowComp);
#endif
foreach (string strl in allowComp.Split(','))
{
string strlan = strl.Trim(" \t".ToCharArray()).ToLower();
if (!LanguageMapping.ContainsKey(strlan))
{
m_log.Error("[Compiler]: Config error. Compiler is unable to recognize language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
}
else
{
#if DEBUG
//m_log.Debug("[Compiler]: Config OK. Compiler recognized language type \"" + strlan + "\" specified in \"AllowedCompilers\".");
#endif
}
AllowedCompilers.Add(strlan, true);
}
if (AllowedCompilers.Count == 0)
m_log.Error("[Compiler]: Config error. Compiler could not recognize any language in \"AllowedCompilers\". Scripts will not be executed!");
// Default language
string defaultCompileLanguage = m_scriptEngine.Config.GetString("DefaultCompileLanguage", "lsl").ToLower();
// Is this language recognized at all?
if (!LanguageMapping.ContainsKey(defaultCompileLanguage))
{
m_log.Error("[Compiler]: " +
"Config error. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is not recognized as a valid language. Changing default to: \"lsl\".");
defaultCompileLanguage = "lsl";
}
// Is this language in allow-list?
if (!AllowedCompilers.ContainsKey(defaultCompileLanguage))
{
m_log.Error("[Compiler]: " +
"Config error. Default language \"" + defaultCompileLanguage + "\"specified in \"DefaultCompileLanguage\" is not in list of \"AllowedCompilers\". Scripts may not be executed!");
}
else
{
#if DEBUG
// m_log.Debug("[Compiler]: " +
// "Config OK. Default language \"" + defaultCompileLanguage + "\" specified in \"DefaultCompileLanguage\" is recognized as a valid language.");
#endif
// LANGUAGE IS IN ALLOW-LIST
DefaultCompileLanguage = LanguageMapping[defaultCompileLanguage];
}
// We now have an allow-list, a mapping list, and a default language
}
/// <summary>
/// Delete old script files
/// </summary>
private void DeleteOldFiles()
{
// CREATE FOLDER IF IT DOESNT EXIST
if (!Directory.Exists(ScriptEnginesPath))
{
try
{
Directory.CreateDirectory(ScriptEnginesPath);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + ScriptEnginesPath + "\": " + ex.ToString());
}
}
if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString())))
{
try
{
Directory.CreateDirectory(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()));
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying to create ScriptEngine directory \"" + Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString())+ "\": " + ex.ToString());
}
}
foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()),FilePrefix + "_compiled*"))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
}
}
foreach (string file in Directory.GetFiles(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()), FilePrefix + "_source*"))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
m_log.Error("[Compiler]: Exception trying delete old script file \"" + file + "\": " + ex.ToString());
}
}
}
////private ICodeCompiler icc = codeProvider.CreateCompiler();
//public string CompileFromFile(string LSOFileName)
//{
// switch (Path.GetExtension(LSOFileName).ToLower())
// {
// case ".txt":
// case ".lsl":
// Common.ScriptEngineBase.Shared.SendToDebug("Source code is LSL, converting to CS");
// return CompileFromLSLText(File.ReadAllText(LSOFileName));
// case ".cs":
// Common.ScriptEngineBase.Shared.SendToDebug("Source code is CS");
// return CompileFromCSText(File.ReadAllText(LSOFileName));
// default:
// throw new Exception("Unknown script type.");
// }
//}
public object GetCompilerOutput(UUID assetID)
{
return Path.Combine(ScriptEnginesPath, Path.Combine(
m_scriptEngine.World.RegionInfo.RegionID.ToString(),
FilePrefix + "_compiled_" + assetID + ".dll"));
}
/// <summary>
/// Converts script from LSL to CS and calls CompileFromCSText
/// </summary>
/// <param name="Script">LSL script</param>
/// <returns>Filename to .dll assembly</returns>
public object PerformScriptCompile(string Script, string asset, UUID ownerUUID)
{
m_positionMap = null;
m_warnings.Clear();
string OutFile = Path.Combine(ScriptEnginesPath, Path.Combine(
m_scriptEngine.World.RegionInfo.RegionID.ToString(),
FilePrefix + "_compiled_" + asset + ".dll"));
// string OutFile = Path.Combine(ScriptEnginesPath,
// FilePrefix + "_compiled_" + asset + ".dll");
if (!Directory.Exists(ScriptEnginesPath))
{
try
{
Directory.CreateDirectory(ScriptEnginesPath);
}
catch (Exception)
{
}
}
if (!Directory.Exists(Path.Combine(ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString())))
{
try
{
Directory.CreateDirectory(ScriptEnginesPath);
}
catch (Exception)
{
}
}
if (Script == String.Empty)
{
if (File.Exists(OutFile))
return OutFile;
throw new Exception("Cannot find script assembly and no script text present");
}
// Don't recompile if we already have it
//
if (File.Exists(OutFile) && File.Exists(OutFile+".text") && File.Exists(OutFile+".map"))
{
ReadMapFile(OutFile+".map");
return OutFile;
}
enumCompileType l = DefaultCompileLanguage;
if (Script.StartsWith("//c#", true, CultureInfo.InvariantCulture))
l = enumCompileType.cs;
if (Script.StartsWith("//vb", true, CultureInfo.InvariantCulture))
{
l = enumCompileType.vb;
// We need to remove //vb, it won't compile with that
Script = Script.Substring(4, Script.Length - 4);
}
if (Script.StartsWith("//lsl", true, CultureInfo.InvariantCulture))
l = enumCompileType.lsl;
if (Script.StartsWith("//js", true, CultureInfo.InvariantCulture))
l = enumCompileType.js;
if (Script.StartsWith("//yp", true, CultureInfo.InvariantCulture))
l = enumCompileType.yp;
if (!AllowedCompilers.ContainsKey(l.ToString()))
{
// Not allowed to compile to this language!
string errtext = String.Empty;
errtext += "The compiler for language \"" + l.ToString() + "\" is not in list of allowed compilers. Script will not be executed!";
throw new Exception(errtext);
}
if (m_scriptEngine.World.Permissions.CanCompileScript(ownerUUID, (int)l) == false) {
// Not allowed to compile to this language!
string errtext = String.Empty;
errtext += ownerUUID + " is not in list of allowed users for this scripting language. Script will not be executed!";
throw new Exception(errtext);
}
string compileScript = Script;
if (l == enumCompileType.lsl)
{
// Its LSL, convert it to C#
LSL_Converter = (ICodeConverter)new CSCodeGenerator();
compileScript = LSL_Converter.Convert(Script);
// copy converter warnings into our warnings.
foreach (string warning in LSL_Converter.GetWarnings())
{
AddWarning(warning);
}
m_positionMap = ((CSCodeGenerator) LSL_Converter).PositionMap;
}
if (l == enumCompileType.yp)
{
// Its YP, convert it to C#
compileScript = YP_Converter.Convert(Script);
}
switch (l)
{
case enumCompileType.cs:
case enumCompileType.lsl:
compileScript = CreateCSCompilerScript(compileScript);
break;
case enumCompileType.vb:
compileScript = CreateVBCompilerScript(compileScript);
break;
case enumCompileType.js:
compileScript = CreateJSCompilerScript(compileScript);
break;
case enumCompileType.yp:
compileScript = CreateYPCompilerScript(compileScript);
break;
}
return CompileFromDotNetText(compileScript, l, asset);
}
public string[] GetWarnings()
{
return m_warnings.ToArray();
}
private void AddWarning(string warning)
{
if (!m_warnings.Contains(warning))
{
m_warnings.Add(warning);
}
}
private static string CreateJSCompilerScript(string compileScript)
{
compileScript = String.Empty +
"import OpenSim.Region.ScriptEngine.Shared; import System.Collections.Generic;\r\n" +
"package SecondLife {\r\n" +
"class Script extends OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
compileScript +
"} }\r\n";
return compileScript;
}
private static string CreateCSCompilerScript(string compileScript)
{
compileScript = String.Empty +
"using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" +
String.Empty + "namespace SecondLife { " +
String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
@"public Script() { } " +
compileScript +
"} }\r\n";
return compileScript;
}
private static string CreateYPCompilerScript(string compileScript)
{
compileScript = String.Empty +
"using OpenSim.Region.ScriptEngine.Shared.YieldProlog; " +
"using OpenSim.Region.ScriptEngine.Shared; using System.Collections.Generic;\r\n" +
String.Empty + "namespace SecondLife { " +
String.Empty + "public class Script : OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass { \r\n" +
//@"public Script() { } " +
@"static OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP YP=null; " +
@"public Script() { YP= new OpenSim.Region.ScriptEngine.Shared.YieldProlog.YP(); } " +
compileScript +
"} }\r\n";
return compileScript;
}
private static string CreateVBCompilerScript(string compileScript)
{
compileScript = String.Empty +
"Imports OpenSim.Region.ScriptEngine.Shared: Imports System.Collections.Generic: " +
String.Empty + "NameSpace SecondLife:" +
String.Empty + "Public Class Script: Inherits OpenSim.Region.ScriptEngine.Shared.ScriptBase.ScriptBaseClass: " +
"\r\nPublic Sub New()\r\nEnd Sub: " +
compileScript +
":End Class :End Namespace\r\n";
return compileScript;
}
/// <summary>
/// Compile .NET script to .Net assembly (.dll)
/// </summary>
/// <param name="Script">CS script</param>
/// <returns>Filename to .dll assembly</returns>
internal string CompileFromDotNetText(string Script, enumCompileType lang, string asset)
{
string ext = "." + lang.ToString();
// Output assembly name
scriptCompileCounter++;
string OutFile = Path.Combine(ScriptEnginesPath, Path.Combine(
m_scriptEngine.World.RegionInfo.RegionID.ToString(),
FilePrefix + "_compiled_" + asset + ".dll"));
try
{
File.Delete(OutFile);
}
catch (Exception e) // NOTLEGIT - Should be just FileIOException
{
throw new Exception("Unable to delete old existing "+
"script-file before writing new. Compile aborted: " +
e.ToString());
}
// DEBUG - write source to disk
if (WriteScriptSourceToDebugFile)
{
string srcFileName = FilePrefix + "_source_" +
Path.GetFileNameWithoutExtension(OutFile) + ext;
try
{
File.WriteAllText(Path.Combine(Path.Combine(
ScriptEnginesPath,
m_scriptEngine.World.RegionInfo.RegionID.ToString()),
srcFileName), Script);
}
catch (Exception ex) //NOTLEGIT - Should be just FileIOException
{
m_log.Error("[Compiler]: Exception while "+
"trying to write script source to file \"" +
srcFileName + "\": " + ex.ToString());
}
}
// Do actual compile
CompilerParameters parameters = new CompilerParameters();
parameters.IncludeDebugInformation = true;
string rootPath =
Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.dll"));
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.Api.Runtime.dll"));
if (lang == enumCompileType.yp)
{
parameters.ReferencedAssemblies.Add(Path.Combine(rootPath,
"OpenSim.Region.ScriptEngine.Shared.YieldProlog.dll"));
}
parameters.GenerateExecutable = false;
parameters.OutputAssembly = OutFile;
parameters.IncludeDebugInformation = CompileWithDebugInformation;
//parameters.WarningLevel = 1; // Should be 4?
parameters.TreatWarningsAsErrors = false;
CompilerResults results;
switch (lang)
{
case enumCompileType.vb:
results = VBcodeProvider.CompileAssemblyFromSource(
parameters, Script);
break;
case enumCompileType.cs:
case enumCompileType.lsl:
bool complete = false;
bool retried = false;
do
{
lock (CScodeProvider)
{
results = CScodeProvider.CompileAssemblyFromSource(
parameters, Script);
}
// Deal with an occasional segv in the compiler.
// Rarely, if ever, occurs twice in succession.
// Line # == 0 and no file name are indications that
// this is a native stack trace rather than a normal
// error log.
if (results.Errors.Count > 0)
{
if (!retried && (results.Errors[0].FileName == null || results.Errors[0].FileName == String.Empty) &&
results.Errors[0].Line == 0)
{
// System.Console.WriteLine("retrying failed compilation");
retried = true;
}
else
{
complete = true;
}
}
else
{
complete = true;
}
} while (!complete);
break;
case enumCompileType.js:
results = JScodeProvider.CompileAssemblyFromSource(
parameters, Script);
break;
case enumCompileType.yp:
results = YPcodeProvider.CompileAssemblyFromSource(
parameters, Script);
break;
default:
throw new Exception("Compiler is not able to recongnize "+
"language type \"" + lang.ToString() + "\"");
}
// Check result
// Go through errors
//
// WARNINGS AND ERRORS
//
bool hadErrors = false;
string errtext = String.Empty;
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
string severity = CompErr.IsWarning ? "Warning" : "Error";
KeyValuePair<int, int> lslPos;
// Show 5 errors max, but check entire list for errors
if (severity == "Error")
{
lslPos = FindErrorPosition(CompErr.Line, CompErr.Column);
string text = CompErr.ErrorText;
// Use LSL type names
if (lang == enumCompileType.lsl)
text = ReplaceTypes(CompErr.ErrorText);
// The Second Life viewer's script editor begins
// countingn lines and columns at 0, so we subtract 1.
errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n",
lslPos.Key - 1, lslPos.Value - 1,
CompErr.ErrorNumber, text, severity);
hadErrors = true;
}
}
}
if (hadErrors)
{
throw new Exception(errtext);
}
// On today's highly asynchronous systems, the result of
// the compile may not be immediately apparent. Wait a
// reasonable amount of time before giving up on it.
if (!File.Exists(OutFile))
{
for (int i=0; i<20 && !File.Exists(OutFile); i++)
{
System.Threading.Thread.Sleep(250);
}
// One final chance...
if (!File.Exists(OutFile))
{
errtext = String.Empty;
errtext += "No compile error. But not able to locate compiled file.";
throw new Exception(errtext);
}
}
// m_log.DebugFormat("[Compiler] Compiled new assembly "+
// "for {0}", asset);
// Because windows likes to perform exclusive locks, we simply
// write out a textual representation of the file here
//
// Read the binary file into a buffer
//
FileInfo fi = new FileInfo(OutFile);
if (fi == null)
{
errtext = String.Empty;
errtext += "No compile error. But not able to stat file.";
throw new Exception(errtext);
}
Byte[] data = new Byte[fi.Length];
try
{
FileStream fs = File.Open(OutFile, FileMode.Open, FileAccess.Read);
fs.Read(data, 0, data.Length);
fs.Close();
}
catch (Exception)
{
errtext = String.Empty;
errtext += "No compile error. But not able to open file.";
throw new Exception(errtext);
}
// Convert to base64
//
string filetext = System.Convert.ToBase64String(data);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
Byte[] buf = enc.GetBytes(filetext);
FileStream sfs = File.Create(OutFile+".text");
sfs.Write(buf, 0, buf.Length);
sfs.Close();
string posmap = String.Empty;
if (m_positionMap != null)
{
foreach (KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> kvp in m_positionMap)
{
KeyValuePair<int, int> k = kvp.Key;
KeyValuePair<int, int> v = kvp.Value;
posmap += String.Format("{0},{1},{2},{3}\n",
k.Key, k.Value, v.Key, v.Value);
}
}
buf = enc.GetBytes(posmap);
FileStream mfs = File.Create(OutFile+".map");
mfs.Write(buf, 0, buf.Length);
mfs.Close();
return OutFile;
}
public KeyValuePair<int, int> FindErrorPosition(int line, int col)
{
return FindErrorPosition(line, col, m_positionMap);
}
private class kvpSorter : IComparer<KeyValuePair<int,int>>
{
public int Compare(KeyValuePair<int,int> a,
KeyValuePair<int,int> b)
{
return a.Key.CompareTo(b.Key);
}
}
public static KeyValuePair<int, int> FindErrorPosition(int line,
int col, Dictionary<KeyValuePair<int, int>,
KeyValuePair<int, int>> positionMap)
{
if (positionMap == null || positionMap.Count == 0)
return new KeyValuePair<int, int>(line, col);
KeyValuePair<int, int> ret = new KeyValuePair<int, int>();
if (positionMap.TryGetValue(new KeyValuePair<int, int>(line, col),
out ret))
return ret;
List<KeyValuePair<int,int>> sorted =
new List<KeyValuePair<int,int>>(positionMap.Keys);
sorted.Sort(new kvpSorter());
int l = 1;
int c = 1;
foreach (KeyValuePair<int, int> cspos in sorted)
{
if (cspos.Key >= line)
{
if (cspos.Key > line)
return new KeyValuePair<int, int>(l, c);
if (cspos.Value > col)
return new KeyValuePair<int, int>(l, c);
c = cspos.Value;
if (c == 0)
c++;
}
else
{
l = cspos.Key;
}
}
return new KeyValuePair<int, int>(l, c);
}
string ReplaceTypes(string message)
{
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString",
"string");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger",
"integer");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat",
"float");
message = message.Replace(
"OpenSim.Region.ScriptEngine.Shared.LSL_Types.list",
"list");
return message;
}
public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> LineMap()
{
if (m_positionMap == null)
return null;
Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> ret =
new Dictionary<KeyValuePair<int,int>, KeyValuePair<int, int>>();
foreach (KeyValuePair<int, int> kvp in m_positionMap.Keys)
ret.Add(kvp, m_positionMap[kvp]);
return ret;
}
private void ReadMapFile(string filename)
{
try
{
StreamReader r = File.OpenText(filename);
m_positionMap = new Dictionary<KeyValuePair<int,int>, KeyValuePair<int, int>>();
string line;
while ((line = r.ReadLine()) != null)
{
String[] parts = line.Split(new Char[] {','});
int kk = System.Convert.ToInt32(parts[0]);
int kv = System.Convert.ToInt32(parts[1]);
int vk = System.Convert.ToInt32(parts[2]);
int vv = System.Convert.ToInt32(parts[3]);
KeyValuePair<int, int> k = new KeyValuePair<int, int>(kk, kv);
KeyValuePair<int, int> v = new KeyValuePair<int, int>(vk, vv);
m_positionMap[k] = v;
}
}
catch
{
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Reflection;
using System.Runtime.Diagnostics;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.Globalization;
using System.Threading;
using System.Collections;
using System.Diagnostics;
using System.Security;
using System.Runtime;
class SyncMethodInvoker : IOperationInvoker
{
Type type;
string methodName;
MethodInfo method;
InvokeDelegate invokeDelegate;
int inputParameterCount;
int outputParameterCount;
public SyncMethodInvoker(MethodInfo method)
{
if (method == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("method"));
this.method = method;
}
public SyncMethodInvoker(Type type, string methodName)
{
if (type == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("type"));
if (methodName == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("methodName"));
this.type = type;
this.methodName = methodName;
}
public bool IsSynchronous
{
get { return true; }
}
public MethodInfo Method
{
get
{
if (method == null)
method = type.GetMethod(methodName);
return method;
}
}
public string MethodName
{
get
{
if (methodName == null)
methodName = method.Name;
return methodName;
}
}
public object[] AllocateInputs()
{
EnsureIsInitialized();
return EmptyArray.Allocate(this.inputParameterCount);
}
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
EnsureIsInitialized();
if (instance == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
if (inputs == null)
{
if (this.inputParameterCount > 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceNull, this.inputParameterCount)));
}
else if (inputs.Length != this.inputParameterCount)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceInvalid, this.inputParameterCount, inputs.Length)));
outputs = EmptyArray.Allocate(this.outputParameterCount);
long startCounter = 0;
long stopCounter = 0;
long beginOperation = 0;
bool callSucceeded = false;
bool callFaulted = false;
if (PerformanceCounters.PerformanceCountersEnabled)
{
PerformanceCounters.MethodCalled(this.MethodName);
try
{
if (System.ServiceModel.Channels.UnsafeNativeMethods.QueryPerformanceCounter(out startCounter) == 0)
{
startCounter = -1;
}
}
catch (SecurityException securityException)
{
DiagnosticUtility.TraceHandledException(securityException, TraceEventType.Warning);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.GetString(
SR.PartialTrustPerformanceCountersNotEnabled), securityException));
}
}
EventTraceActivity eventTraceActivity = null;
if (TD.OperationCompletedIsEnabled() ||
TD.OperationFaultedIsEnabled() ||
TD.OperationFailedIsEnabled())
{
beginOperation = DateTime.UtcNow.Ticks;
OperationContext context = OperationContext.Current;
if (context != null && context.IncomingMessage != null)
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(context.IncomingMessage);
}
}
object returnValue;
try
{
ServiceModelActivity activity = null;
IDisposable boundActivity = null;
if (DiagnosticUtility.ShouldUseActivity)
{
activity = ServiceModelActivity.CreateBoundedActivity(true);
boundActivity = activity;
}
else if (TraceUtility.MessageFlowTracingOnly)
{
Guid activityId = TraceUtility.GetReceivedActivityId(OperationContext.Current);
if (activityId != Guid.Empty)
{
DiagnosticTraceBase.ActivityId = activityId;
}
}
else if (TraceUtility.ShouldPropagateActivity)
{
//Message flow tracing only scenarios use a light-weight ActivityID management logic
Guid activityId = ActivityIdHeader.ExtractActivityId(OperationContext.Current.IncomingMessage);
if (activityId != Guid.Empty)
{
boundActivity = Activity.CreateActivity(activityId);
}
}
using (boundActivity)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityExecuteMethod, this.method.DeclaringType.FullName, this.method.Name), ActivityType.ExecuteUserCode);
}
if (TD.OperationInvokedIsEnabled())
{
TD.OperationInvoked(eventTraceActivity, this.MethodName, TraceUtility.GetCallerInfo(OperationContext.Current));
}
returnValue = this.invokeDelegate(instance, inputs, outputs);
callSucceeded = true;
}
}
catch (System.ServiceModel.FaultException)
{
callFaulted = true;
throw;
}
catch (System.Security.SecurityException e)
{
DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
}
finally
{
if (PerformanceCounters.PerformanceCountersEnabled)
{
long elapsedTime = 0;
if (startCounter >= 0 && System.ServiceModel.Channels.UnsafeNativeMethods.QueryPerformanceCounter(out stopCounter) != 0)
{
elapsedTime = stopCounter - startCounter;
}
if (callSucceeded) // call succeeded
{
PerformanceCounters.MethodReturnedSuccess(this.MethodName, elapsedTime);
}
else if (callFaulted) // call faulted
{
PerformanceCounters.MethodReturnedFault(this.MethodName, elapsedTime);
}
else // call failed
{
PerformanceCounters.MethodReturnedError(this.MethodName, elapsedTime);
}
}
if (beginOperation != 0)
{
if (callSucceeded)
{
if (TD.OperationCompletedIsEnabled())
{
TD.OperationCompleted(eventTraceActivity, this.methodName,
TraceUtility.GetUtcBasedDurationForTrace(beginOperation));
}
}
else if (callFaulted)
{
if (TD.OperationFaultedIsEnabled())
{
TD.OperationFaulted(eventTraceActivity, this.methodName,
TraceUtility.GetUtcBasedDurationForTrace(beginOperation));
}
}
else
{
if (TD.OperationFailedIsEnabled())
{
TD.OperationFailed(eventTraceActivity, this.methodName,
TraceUtility.GetUtcBasedDurationForTrace(beginOperation));
}
}
}
}
return returnValue;
}
public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
}
void EnsureIsInitialized()
{
if (this.invokeDelegate == null)
{
EnsureIsInitializedCore();
}
}
void EnsureIsInitializedCore()
{
// Only pass locals byref because InvokerUtil may store temporary results in the byref.
// If two threads both reference this.count, temporary results may interact.
int inputParameterCount;
int outputParameterCount;
InvokeDelegate invokeDelegate = new InvokerUtil().GenerateInvokeDelegate(this.Method, out inputParameterCount, out outputParameterCount);
this.outputParameterCount = outputParameterCount;
this.inputParameterCount = inputParameterCount;
this.invokeDelegate = invokeDelegate; // must set this last due to ----
}
}
}
| |
using System;
using NUnit.Framework;
using strange.extensions.injector.api;
using strange.extensions.injector.impl;
using strange.extensions.reflector.api;
using strange.extensions.pool.api;
using strange.extensions.pool.impl;
using strange.framework.api;
using System.Collections.Generic;
using strange.framework.impl;
namespace strange.unittests
{
[TestFixture()]
public class TestinjectionBinder
{
IInjectionBinder binder;
[SetUp]
public void SetUp()
{
binder = new InjectionBinder ();
}
[TearDown]
public void TearDown()
{
PostConstructSimple.PostConstructCount = 0;
}
[Test]
public void TestInjectorExists()
{
Assert.That (binder.injector != null);
}
[Test]
public void TestGetBindingFlat ()
{
binder.Bind<InjectableSuperClass> ().To<InjectableSuperClass> ();
IInjectionBinding binding = binder.GetBinding<InjectableSuperClass> ();
Assert.IsNotNull (binding);
}
[Test]
public void TestGetBindingAbstract ()
{
binder.Bind<ISimpleInterface> ().To<ClassWithConstructorParameters> ();
IInjectionBinding binding = binder.GetBinding<ISimpleInterface> ();
Assert.IsNotNull (binding);
}
[Test]
public void TestGetNamedBinding ()
{
binder.Bind<ISimpleInterface> ().To<ClassWithConstructorParameters> ().ToName<MarkerClass>();
IInjectionBinding binding = binder.GetBinding<ISimpleInterface> (typeof(MarkerClass));
Assert.IsNotNull (binding);
}
[Test]
public void TestGetInstance1()
{
binder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> ();
ClassToBeInjected instance = binder.GetInstance (typeof(ClassToBeInjected)) as ClassToBeInjected;
Assert.IsNotNull (instance);
Assert.That (instance is ClassToBeInjected);
}
[Test]
public void TestGetInstance2()
{
binder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> ();
ClassToBeInjected instance = binder.GetInstance<ClassToBeInjected> ();
Assert.IsNotNull (instance);
Assert.That (instance is ClassToBeInjected);
}
[Test]
public void TestGetNamedInstance1()
{
binder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> ().ToName<MarkerClass>();
ClassToBeInjected instance = binder.GetInstance (typeof(ClassToBeInjected), typeof(MarkerClass)) as ClassToBeInjected;
Assert.IsNotNull (instance);
Assert.That (instance is ClassToBeInjected);
}
[Test]
public void TestGetNamedInstance2()
{
binder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> ().ToName<MarkerClass>();
ClassToBeInjected instance = binder.GetInstance<ClassToBeInjected> (typeof(MarkerClass));
Assert.IsNotNull (instance);
Assert.That (instance is ClassToBeInjected);
}
[Test]
public void TestGetNamedInstance3()
{
binder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> ().ToName(SomeEnum.ONE);
ClassToBeInjected instance = binder.GetInstance (typeof(ClassToBeInjected), SomeEnum.ONE) as ClassToBeInjected;
Assert.IsNotNull (instance);
Assert.That (instance is ClassToBeInjected);
}
[Test]
public void TestGetNamedInstance4()
{
binder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> ().ToName(SomeEnum.ONE);
ClassToBeInjected instance = binder.GetInstance<ClassToBeInjected> (SomeEnum.ONE);
Assert.IsNotNull (instance);
Assert.That (instance is ClassToBeInjected);
}
[Test]
public void TestInjectionErrorFailureToProvideDependency()
{
TestDelegate testDelegate = delegate() {
binder.GetInstance<InjectableSuperClass> ();
};
binder.Bind<InjectableSuperClass> ().To<InjectableSuperClass> ();
InjectionException ex = Assert.Throws<InjectionException> (testDelegate);
Assert.That (ex.type == InjectionExceptionType.NULL_BINDING);
}
[Test]
public void TestInjectionProvideIntDependency()
{
binder.Bind<InjectableSuperClass> ().To<InjectableSuperClass> ();
binder.Bind<int> ().ToValue (42);
InjectableSuperClass testValue = binder.GetInstance<InjectableSuperClass> ();
Assert.IsNotNull (testValue);
Assert.That (testValue.intValue == 42);
}
[Test]
public void TestRemoveDependency()
{
binder.Bind<InjectableSuperClass> ().To<InjectableSuperClass> ();
binder.Bind<int> ().ToValue (42);
InjectableSuperClass testValueBeforeUnbinding = binder.GetInstance<InjectableSuperClass> ();
Assert.IsNotNull (testValueBeforeUnbinding);
Assert.That (testValueBeforeUnbinding.intValue == 42);
binder.Unbind<int> ();
TestDelegate testDelegate = delegate() {
binder.GetInstance<InjectableSuperClass> ();
};
InjectionException ex = Assert.Throws<InjectionException> (testDelegate);
Assert.That (ex.type == InjectionExceptionType.NULL_BINDING);
}
[Test]
public void TestValueToSingleton()
{
GuaranteedUniqueInstances uniqueInstance = new GuaranteedUniqueInstances ();
binder.Bind<GuaranteedUniqueInstances> ().ToValue (uniqueInstance);
GuaranteedUniqueInstances instance1 = binder.GetInstance <GuaranteedUniqueInstances> ();
GuaranteedUniqueInstances instance2 = binder.GetInstance <GuaranteedUniqueInstances> ();
Assert.AreEqual (instance1.uid, instance2.uid);
Assert.AreSame (instance1, instance2);
}
//RE: Issue #23. A value-mapping trumps a Singleton mapping
[Test]
public void TestValueToSingletonBinding ()
{
InjectableSuperClass instance = new InjectableSuperClass ();
InjectionBinding binding = binder.Bind<InjectableSuperClass> ().ToValue (instance).ToSingleton() as InjectionBinding;
Assert.AreEqual (InjectionBindingType.VALUE, binding.type);
}
//RE: Issue #23. A value-mapping trumps a Singleton mapping
[Test]
public void TestSingletonToValueBinding ()
{
InjectableSuperClass instance = new InjectableSuperClass ();
InjectionBinding binding = binder.Bind<InjectableSuperClass> ().ToSingleton().ToValue (instance) as InjectionBinding;
Assert.AreEqual (InjectionBindingType.VALUE, binding.type);
}
//RE:Issue #34. Ensure that a Singleton instance can properly use constructor injection
[Test]
public void TestConstructorToSingleton()
{
binder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> ();
binder.Bind<ConstructorInjectsClassToBeInjected>().To<ConstructorInjectsClassToBeInjected>().ToSingleton();
ConstructorInjectsClassToBeInjected instance = binder.GetInstance<ConstructorInjectsClassToBeInjected>();
Assert.IsNotNull (instance.injected);
}
//RE: Issue #32. A value-bound injection should not post-construct twice
//The PostConstruct fires when the class is requested.
[Test]
public void TestDoublePostConstruct()
{
PostConstructSimple.PostConstructCount = 0;
PostConstructSimple instance = new PostConstructSimple ();
binder.Bind<PostConstructSimple> ().ToValue (instance);
binder.Bind<InjectsPostConstructSimple> ().To<InjectsPostConstructSimple>();
InjectsPostConstructSimple instance1 = binder.GetInstance<InjectsPostConstructSimple> ();
InjectsPostConstructSimple instance2 = binder.GetInstance<InjectsPostConstructSimple> ();
Assert.AreSame (instance, instance1.pcs);
Assert.AreNotSame (instance1, instance2);
Assert.AreEqual (1, PostConstructSimple.PostConstructCount);
}
[Test]
public void TestPolymorphicBinding()
{
binder.Bind<ISimpleInterface> ().Bind<IAnotherSimpleInterface> ().To<PolymorphicClass> ();
ISimpleInterface callOnce = binder.GetInstance<ISimpleInterface> ();
Assert.NotNull (callOnce);
Assert.IsInstanceOf<PolymorphicClass> (callOnce);
IAnotherSimpleInterface callAgain = binder.GetInstance<IAnotherSimpleInterface> ();
Assert.NotNull (callAgain);
Assert.IsInstanceOf<PolymorphicClass> (callAgain);
}
[Test]
public void TestPolymorphicSingleton()
{
binder.Bind<ISimpleInterface> ().Bind<IAnotherSimpleInterface> ().To<PolymorphicClass> ().ToSingleton();
ISimpleInterface callOnce = binder.GetInstance<ISimpleInterface> ();
Assert.NotNull (callOnce);
Assert.IsInstanceOf<PolymorphicClass> (callOnce);
IAnotherSimpleInterface callAgain = binder.GetInstance<IAnotherSimpleInterface> ();
Assert.NotNull (callAgain);
Assert.IsInstanceOf<PolymorphicClass> (callAgain);
callOnce.intValue = 42;
Assert.AreSame (callOnce, callAgain);
Assert.AreEqual (42, (callAgain as ISimpleInterface).intValue);
}
[Test]
public void TestNamedInstanceBeforeUnnamedInstance()
{
binder.Bind<ISimpleInterface> ().To<SimpleInterfaceImplementer> ().ToName(SomeEnum.ONE);
binder.Bind<ISimpleInterface> ().To<PolymorphicClass> ();
ISimpleInterface instance1 = binder.GetInstance<ISimpleInterface> (SomeEnum.ONE);
ISimpleInterface instance2 = binder.GetInstance<ISimpleInterface> ();
Assert.That (instance1 is SimpleInterfaceImplementer);
Assert.That (instance2 is PolymorphicClass);
}
[Test]
public void TestUnnamedInstanceBeforeNamedInstance()
{
binder.Bind<ISimpleInterface> ().To<PolymorphicClass> ();
binder.Bind<ISimpleInterface> ().To<SimpleInterfaceImplementer> ().ToName(SomeEnum.ONE);
ISimpleInterface instance1 = binder.GetInstance<ISimpleInterface> (SomeEnum.ONE);
ISimpleInterface instance2 = binder.GetInstance<ISimpleInterface> ();
Assert.That (instance1 is SimpleInterfaceImplementer);
Assert.That (instance2 is PolymorphicClass);
}
[Test]
public void TestPrereflectOne()
{
binder.Bind<ISimpleInterface> ().Bind<IAnotherSimpleInterface> ().To<PolymorphicClass> ();
System.Collections.Generic.List<Type> list = new System.Collections.Generic.List<Type> ();
list.Add (typeof(PolymorphicClass));
int count = binder.Reflect (list);
Assert.AreEqual (1, count);
IReflectedClass reflected = binder.injector.reflector.Get<PolymorphicClass> ();
Assert.True (reflected.preGenerated);
}
[Test]
public void TestPrereflectMany()
{
binder.Bind<HasNamedInjections> ().To<HasNamedInjections> ();
binder.Bind<ISimpleInterface> ().To<SimpleInterfaceImplementer> ().ToName(SomeEnum.ONE);
binder.Bind<ISimpleInterface> ().To<PolymorphicClass> ();
binder.Bind<InjectableSuperClass> ().To<InjectableDerivedClass> ();
binder.Bind<int>().ToValue(42);
binder.Bind<string>().ToValue("zaphod"); //primitives won't get reflected...
System.Collections.Generic.List<Type> list = new System.Collections.Generic.List<Type> ();
list.Add (typeof(HasNamedInjections));
list.Add (typeof(SimpleInterfaceImplementer));
list.Add (typeof(PolymorphicClass));
list.Add (typeof(InjectableDerivedClass));
list.Add(typeof(int));
int count = binder.Reflect (list);
Assert.AreEqual(4, count); //...so list length will not include primitives
IReflectedClass reflected1 = binder.injector.reflector.Get<HasNamedInjections> ();
Assert.True (reflected1.preGenerated);
IReflectedClass reflected2 = binder.injector.reflector.Get<SimpleInterfaceImplementer> ();
Assert.True (reflected2.preGenerated);
IReflectedClass reflected3 = binder.injector.reflector.Get<PolymorphicClass> ();
Assert.True (reflected3.preGenerated);
Assert.AreNotEqual (reflected2.constructor, reflected3.constructor);
IReflectedClass reflected4 = binder.injector.reflector.Get<InjectableDerivedClass> ();
Assert.True (reflected4.preGenerated);
}
[Test]
public void TestPrereflectAll()
{
binder.Bind<HasNamedInjections> ().To<HasNamedInjections> ();
binder.Bind<ISimpleInterface> ().To<SimpleInterfaceImplementer> ().ToName (SomeEnum.ONE);
binder.Bind<ISimpleInterface> ().To<PolymorphicClass> ();
binder.Bind<InjectableSuperClass> ().To<InjectableDerivedClass> ();
binder.Bind<int> ().ToValue (42);
binder.Bind<string> ().ToValue ("zaphod"); //primitives won't get reflected...
int count = binder.ReflectAll ();
Assert.AreEqual (4, count); //...so list length will not include primitives
ISimpleInterface s = binder.GetInstance<ISimpleInterface> ();
Assert.IsTrue (s is PolymorphicClass);
IReflectedClass reflected1 = binder.injector.reflector.Get<HasNamedInjections> ();
Assert.True (reflected1.preGenerated);
IReflectedClass reflected2 = binder.injector.reflector.Get<SimpleInterfaceImplementer> ();
Assert.True (reflected2.preGenerated);
IReflectedClass reflected3 = binder.injector.reflector.Get<PolymorphicClass> ();
Assert.True (reflected3.preGenerated);
Assert.AreNotEqual (reflected2.constructor, reflected3.constructor);
IReflectedClass reflected4 = binder.injector.reflector.Get<InjectableDerivedClass> ();
Assert.True (reflected4.preGenerated);
}
[Test]
public void TestGetPoolInjection()
{
//Pool requires an instance provider. This InjectionBinder is that provider for the integrated test.
//In MVCSContext this is handled automatically.
binder.Bind<IInstanceProvider> ().ToValue (binder);
binder.Bind<SimpleInterfaceImplementer> ().To<SimpleInterfaceImplementer> ();
binder.Bind<Pool<SimpleInterfaceImplementer>> ().ToSingleton();
binder.Bind<IUsesPool> ().To<UsesPool> ().ToSingleton();
IUsesPool instance = binder.GetInstance<IUsesPool>();
Assert.IsNotNull (instance);
Assert.IsNotNull (instance.Instance1);
Assert.IsNotNull (instance.Instance2);
}
[Test]
public void TestOverrideInjections()
{
binder.Bind<ExtendedInheritanceOverride>().ToSingleton();
ISimpleInterface simple = new SimpleInterfaceImplementer();
IExtendedInterface extended = new ExtendedInterfaceImplementer();
binder.Bind<ISimpleInterface>().ToValue(simple);
binder.Bind<IExtendedInterface>().ToValue(extended);
ExtendedInheritanceOverride overridingInjectable = binder.GetInstance<ExtendedInheritanceOverride>();
Assert.NotNull(overridingInjectable);
Assert.NotNull(overridingInjectable.MyInterface);
Assert.AreEqual(overridingInjectable.MyInterface, extended);
}
/// <summary>
/// Test that you will properly inherit values that you aren't overriding
/// </summary>
[Test]
public void TestInheritedInjectionHidingDoesntHappenWithoutHiding()
{
binder.Bind<ExtendedInheritanceOverride>().ToSingleton();
binder.Bind<ExtendedInheritanceNoHide>().ToSingleton();
ISimpleInterface simple = new SimpleInterfaceImplementer();
IExtendedInterface extended = new ExtendedInterfaceImplementer();
binder.Bind<ISimpleInterface>().ToValue(simple);
binder.Bind<IExtendedInterface>().ToValue(extended);
ExtendedInheritanceOverride overridingInjectable = binder.GetInstance<ExtendedInheritanceOverride>();
Assert.NotNull(overridingInjectable);
Assert.NotNull(overridingInjectable.MyInterface);
Assert.AreEqual(overridingInjectable.MyInterface, extended);
ExtendedInheritanceNoHide noHide = binder.GetInstance<ExtendedInheritanceNoHide>();
Assert.NotNull(noHide);
Assert.NotNull(noHide.MyInterface);
Assert.AreEqual(noHide.MyInterface, simple);
}
// Supplied JSON
// [
// {
// "Bind": "strange.unittests.ISimpleInterface",
// "To": "strange.unittests.SimpleInterfaceImplementer"
// }
// ]
[Test]
public void TestSimpleRuntimeInjection()
{
string jsonString = "[{\"Bind\":\"strange.unittests.ISimpleInterface\",\"To\":\"strange.unittests.SimpleInterfaceImplementer\"}]";
binder.ConsumeBindings (jsonString);
IBinding binding = binder.GetBinding<ISimpleInterface> ();
Assert.NotNull (binding);
Assert.AreEqual ((binding as IInjectionBinding).type, InjectionBindingType.DEFAULT);
ISimpleInterface instance = binder.GetInstance (typeof(ISimpleInterface)) as ISimpleInterface;
Assert.IsInstanceOf<SimpleInterfaceImplementer> (instance);
}
// Supplied JSON
// [
// {
// "Bind": "strange.unittests.ISimpleInterface",
// "To": "strange.unittests.SimpleInterfaceImplementer",
// "ToName": "Test1",
// "Options": "ToSingleton"
// },
// {
// "Bind": "strange.unittests.ISimpleInterface",
// "To": "strange.unittests.SimpleInterfaceImplementer",
// "ToName": "Test2",
// "Options": "ToSingleton"
// }
// ]
[Test]
public void TestNamedRuntimeInjection()
{
string jsonString = "[{\"Bind\":\"strange.unittests.ISimpleInterface\",\"To\":\"strange.unittests.SimpleInterfaceImplementer\",\"ToName\":\"Test1\",\"Options\":\"ToSingleton\"}, {\"Bind\":\"strange.unittests.ISimpleInterface\",\"To\":\"strange.unittests.SimpleInterfaceImplementer\",\"ToName\":\"Test2\",\"Options\":\"ToSingleton\"}]";
binder.ConsumeBindings (jsonString);
IBinding binding = binder.GetBinding<ISimpleInterface> ("Test1");
Assert.NotNull (binding);
ISimpleInterface instance = binder.GetInstance (typeof(ISimpleInterface), "Test1") as ISimpleInterface;
Assert.IsInstanceOf<SimpleInterfaceImplementer> (instance);
IBinding binding2 = binder.GetBinding<ISimpleInterface> ("Test2");
Assert.NotNull (binding2);
ISimpleInterface instance2 = binder.GetInstance (typeof(ISimpleInterface), "Test2") as ISimpleInterface;
Assert.IsInstanceOf<SimpleInterfaceImplementer> (instance2);
Assert.AreNotSame (instance, instance2);
}
// Supplied JSON
// [
// {
// "Bind": "strange.unittests.SimpleInterfaceImplementer"
// }
// ]
[Test]
public void TestRuntimeInjectionBindToSelf()
{
string jsonString = "[{\"Bind\":\"strange.unittests.SimpleInterfaceImplementer\"}]";
binder.ConsumeBindings (jsonString);
IBinding binding = binder.GetBinding<SimpleInterfaceImplementer> ();
Assert.NotNull (binding);
Assert.AreEqual ((binding as IInjectionBinding).type, InjectionBindingType.DEFAULT);
SimpleInterfaceImplementer instance = binder.GetInstance (typeof(SimpleInterfaceImplementer)) as SimpleInterfaceImplementer;
Assert.IsInstanceOf<SimpleInterfaceImplementer> (instance);
ISimpleInterface instance2 = binder.GetInstance (typeof(SimpleInterfaceImplementer)) as ISimpleInterface;
Assert.AreNotSame (instance, instance2);
}
// Supplied JSON
// [
// {
// "Bind": "strange.unittests.ISimpleInterface",
// "To": "strange.unittests.SimpleInterfaceImplementer",
// "Options": "ToSingleton"
// }
// ]
[Test]
public void TestRuntimeInjectionSingleton()
{
string jsonString = "[{\"Bind\":\"strange.unittests.ISimpleInterface\",\"To\":\"strange.unittests.SimpleInterfaceImplementer\", \"Options\":\"ToSingleton\"}]";
binder.ConsumeBindings (jsonString);
IBinding binding = binder.GetBinding<ISimpleInterface> ();
Assert.NotNull (binding);
Assert.AreEqual ((binding as IInjectionBinding).type, InjectionBindingType.SINGLETON);
ISimpleInterface instance = binder.GetInstance (typeof(ISimpleInterface)) as ISimpleInterface;
Assert.IsInstanceOf<SimpleInterfaceImplementer> (instance);
ISimpleInterface instance2 = binder.GetInstance (typeof(ISimpleInterface)) as ISimpleInterface;
Assert.AreSame (instance, instance2);
}
// Supplied JSON
// [
// {
// "Bind": "strange.unittests.ISimpleInterface",
// "To": "strange.unittests.SimpleInterfaceImplementer",
// "Options": [
// "ToSingleton",
// "Weak",
// "CrossContext"
// ]
// }
// ]
[Test]
public void TestRuntimeInjectionCrossContext()
{
string jsonString = "[{\"Bind\":\"strange.unittests.ISimpleInterface\",\"To\":\"strange.unittests.SimpleInterfaceImplementer\", \"Options\":[\"ToSingleton\",\"Weak\",\"CrossContext\"]}]";
binder.ConsumeBindings (jsonString);
IBinding binding = binder.GetBinding<ISimpleInterface> ();
Assert.NotNull (binding);
Assert.IsTrue ((binding as IInjectionBinding).isCrossContext);
Assert.IsTrue (binding.isWeak);
Assert.AreEqual ((binding as IInjectionBinding).type, InjectionBindingType.SINGLETON);
ISimpleInterface instance = binder.GetInstance (typeof(ISimpleInterface)) as ISimpleInterface;
Assert.IsInstanceOf<SimpleInterfaceImplementer> (instance);
}
// Supplied JSON
// [
// {
// "Bind": [
// "strange.unittests.ISimpleInterface",
// "strange.unittests.IAnotherSimpleInterface"
// ],
// "To": "strange.unittests.PolymorphicClass"
// }
// ]
[Test]
public void TestRuntimePolymorphism()
{
string jsonString = "[{\"Bind\":[\"strange.unittests.ISimpleInterface\",\"strange.unittests.IAnotherSimpleInterface\"],\"To\":\"strange.unittests.PolymorphicClass\"}]";
binder.ConsumeBindings (jsonString);
IBinding binding = binder.GetBinding<ISimpleInterface> ();
Assert.NotNull (binding);
ISimpleInterface instance = binder.GetInstance (typeof(ISimpleInterface)) as ISimpleInterface;
Assert.IsInstanceOf<PolymorphicClass> (instance);
IBinding binding2 = binder.GetBinding<IAnotherSimpleInterface> ();
Assert.NotNull (binding2);
IAnotherSimpleInterface instance2 = binder.GetInstance (typeof(IAnotherSimpleInterface)) as IAnotherSimpleInterface;
Assert.IsInstanceOf<PolymorphicClass> (instance2);
}
// Supplied JSON
// [
// {
// "Bind": "strange.unittests.ISimpleInterface",
// "To": [
// "strange.unittests.SimpleInterfaceImplementer",
// "strange.unittests.PolymorphicClass"
// ]
// }
// ]
[Test]
public void TestRuntimeExceptionTooManyValues()
{
string jsonString = "[{\"Bind\":\"strange.unittests.ISimpleInterface\",\"To\":[\"strange.unittests.SimpleInterfaceImplementer\",\"strange.unittests.PolymorphicClass\"]}]";
TestDelegate testDelegate = delegate
{
binder.ConsumeBindings(jsonString);
};
BinderException ex = Assert.Throws<BinderException>(testDelegate); //Because we have two values in a Binder that only supports one
Assert.AreEqual (BinderExceptionType.RUNTIME_TOO_MANY_VALUES, ex.type);
}
// Supplied JSON
// [
// {
// "Bind": "ISimpleInterface",
// "To": "strange.unittests.SimpleInterfaceImplementer"
// }
// ]
[Test]
public void TestRuntimeExceptionUnqualifiedKeyException()
{
string jsonString = "[{\"Bind\":\"ISimpleInterface\",\"To\":\"strange.unittests.SimpleInterfaceImplementer\"}]";
TestDelegate testDelegate = delegate
{
binder.ConsumeBindings(jsonString);
};
BinderException ex = Assert.Throws<BinderException>(testDelegate); //Because we haven't fully qualified the key
Assert.AreEqual (BinderExceptionType.RUNTIME_NULL_VALUE, ex.type);
}
[Test]
public void TestRuntimeExceptionUnqualifiedValueException()
{
string jsonString = "[{\"Bind\":\"strange.unittests.ISimpleInterface\",\"To\":\"SimpleInterfaceImplementer\"}]";
TestDelegate testDelegate = delegate
{
binder.ConsumeBindings(jsonString);
};
BinderException ex = Assert.Throws<BinderException>(testDelegate); //Because we haven't fully qualified the value
Assert.AreEqual (BinderExceptionType.RUNTIME_NULL_VALUE, ex.type);
}
// Supplied JSON
// [
// {
// "Bind": "strange.unittests.ClassToBeInjected",
// "To": "strange.unittests.ClassToBeInjected"
// },
// {
// "Bind": "strange.unittests.ClassToBeInjected",
// "To": "strange.unittests.ExtendsClassToBeInjected",
// "ToName": 1,
// "Options": [
// {
// "SupplyTo": "strange.unittests.ConstructorInjectsClassToBeInjected"
// }
// ]
// },
// {
// "Bind": "strange.unittests.ClassToBeInjected",
// "To": "strange.unittests.ClassToBeInjected"
// },
// {
// "Bind": "strange.unittests.ConstructorInjectsClassToBeInjected",
// "To": "strange.unittests.ConstructorInjectsClassToBeInjected"
// }
// ]
[Test]
public void TestRuntimeSimpleSupplyBinding()
{
string jsonString = "[{\"Bind\":\"strange.unittests.ClassToBeInjected\",\"To\":\"strange.unittests.ClassToBeInjected\"},";
jsonString += "{\"Bind\":\"strange.unittests.ClassToBeInjected\",\"To\":\"strange.unittests.ExtendsClassToBeInjected\",\"ToName\": 1,\"Options\": [{\"SupplyTo\": \"strange.unittests.ConstructorInjectsClassToBeInjected\"}]},";
jsonString += "{\"Bind\":\"strange.unittests.InjectsClassToBeInjected\",\"To\": \"strange.unittests.InjectsClassToBeInjected\"},";
jsonString += "{\"Bind\":\"strange.unittests.ConstructorInjectsClassToBeInjected\",\"To\": \"strange.unittests.ConstructorInjectsClassToBeInjected\"}]";
binder.ConsumeBindings (jsonString);
InjectsClassToBeInjected instance1 = binder.GetInstance<InjectsClassToBeInjected> ();
ConstructorInjectsClassToBeInjected instance2 = binder.GetInstance<ConstructorInjectsClassToBeInjected> ();
Assert.IsInstanceOf<ClassToBeInjected> (instance1.injected);
Assert.IsInstanceOf<ClassToBeInjected> (instance2.injected);
Assert.IsNotInstanceOf<ExtendsClassToBeInjected> (instance1.injected);
Assert.IsInstanceOf<ExtendsClassToBeInjected> (instance2.injected);
}
// Supplied JSON
// [
// {
// "Bind": "strange.unittests.ClassToBeInjected",
// "To": "strange.unittests.ExtendsClassToBeInjected",
// "Options": [
// "ToSingleton",
// {
// "SupplyTo": [
// "strange.unittests.HasANamedInjection",
// "strange.unittests.ConstructorInjectsClassToBeInjected",
// "strange.unittests.InjectsClassToBeInjected"
// ]
// }
// ]
// },
// {
// "Bind": "strange.unittests.HasANamedInjection",
// "To": "strange.unittests.HasANamedInjection"
// },
// {
// "Bind": "strange.unittests.ConstructorInjectsClassToBeInjected",
// "To": "strange.unittests.ConstructorInjectsClassToBeInjected"
// },
// {
// "Bind": "strange.unittests.InjectsClassToBeInjected",
// "To": "strange.unittests.InjectsClassToBeInjected"
// }
// ]
[Test]
public void TestRuntimeSupplyBindingWithArray()
{
string jsonString = "[{\"Bind\":\"strange.unittests.ClassToBeInjected\",\"To\":\"strange.unittests.ExtendsClassToBeInjected\",";
jsonString += "\"Options\": [\"ToSingleton\",{\"SupplyTo\": [\"strange.unittests.HasANamedInjection\",\"strange.unittests.ConstructorInjectsClassToBeInjected\",\"strange.unittests.InjectsClassToBeInjected\"]}]},";
jsonString += "{\"Bind\":\"strange.unittests.HasANamedInjection\",\"To\":\"strange.unittests.HasANamedInjection\"},";
jsonString += "{\"Bind\":\"strange.unittests.ConstructorInjectsClassToBeInjected\",\"To\":\"strange.unittests.ConstructorInjectsClassToBeInjected\"},";
jsonString += "{\"Bind\":\"strange.unittests.InjectsClassToBeInjected\",\"To\":\"strange.unittests.InjectsClassToBeInjected\"}]";
binder.ConsumeBindings (jsonString);
HasANamedInjection instance = binder.GetInstance<HasANamedInjection> ();
ConstructorInjectsClassToBeInjected instance2 = binder.GetInstance<ConstructorInjectsClassToBeInjected> ();
InjectsClassToBeInjected instance3 = binder.GetInstance<InjectsClassToBeInjected> ();
Assert.IsInstanceOf<ClassToBeInjected> (instance.injected);
Assert.IsInstanceOf<ClassToBeInjected> (instance2.injected);
Assert.IsInstanceOf<ClassToBeInjected> (instance3.injected);
}
public void TestSimpleSupplyBinding()
{
binder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> ();
binder.Bind<ClassToBeInjected> ().To<ExtendsClassToBeInjected> ().ToName(1)
.SupplyTo<ConstructorInjectsClassToBeInjected>();
binder.Bind<InjectsClassToBeInjected> ().To<InjectsClassToBeInjected> ();
binder.Bind<ConstructorInjectsClassToBeInjected> ().To<ConstructorInjectsClassToBeInjected> ();
InjectsClassToBeInjected instance1 = binder.GetInstance<InjectsClassToBeInjected> ();
ConstructorInjectsClassToBeInjected instance2 = binder.GetInstance<ConstructorInjectsClassToBeInjected> ();
Assert.IsInstanceOf<ClassToBeInjected> (instance1.injected);
Assert.IsInstanceOf<ClassToBeInjected> (instance2.injected);
Assert.IsNotInstanceOf<ExtendsClassToBeInjected> (instance1.injected);
Assert.IsInstanceOf<ExtendsClassToBeInjected> (instance2.injected);
}
[Test]
public void TestSupplyOverridesName()
{
binder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> ().SupplyTo<HasANamedInjection> ();
binder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> ().ToName("CapnJack").SupplyTo<HasANamedInjection2> ();
binder.Bind<HasANamedInjection>().To<HasANamedInjection> ();
binder.Bind<HasANamedInjection2>().To<HasANamedInjection2> ();
HasANamedInjection instance = binder.GetInstance<HasANamedInjection> ();
Assert.IsInstanceOf<ClassToBeInjected> (instance.injected);
HasANamedInjection2 instance2 = binder.GetInstance<HasANamedInjection2> ();
Assert.IsInstanceOf<ClassToBeInjected> (instance2.injected);
}
[Test]
public void TestChainedSupplyBinding()
{
binder.Bind<ClassToBeInjected>().To<ExtendsClassToBeInjected>()
.SupplyTo<HasANamedInjection> ()
.SupplyTo<ConstructorInjectsClassToBeInjected>()
.SupplyTo<InjectsClassToBeInjected>();
binder.Bind<HasANamedInjection>().To<HasANamedInjection> ();
binder.Bind<ConstructorInjectsClassToBeInjected>().To<ConstructorInjectsClassToBeInjected> ();
binder.Bind<InjectsClassToBeInjected>().To<InjectsClassToBeInjected> ();
HasANamedInjection instance = binder.GetInstance<HasANamedInjection> ();
ConstructorInjectsClassToBeInjected instance2 = binder.GetInstance<ConstructorInjectsClassToBeInjected> ();
InjectsClassToBeInjected instance3 = binder.GetInstance<InjectsClassToBeInjected> ();
Assert.IsInstanceOf<ClassToBeInjected> (instance.injected);
Assert.IsInstanceOf<ClassToBeInjected> (instance2.injected);
Assert.IsInstanceOf<ClassToBeInjected> (instance3.injected);
}
[Test]
public void TestUnsupplyBinding()
{
binder.Bind<ClassToBeInjected> ().To<ExtendsClassToBeInjected> ()
.ToName("Supplier")
.SupplyTo<InjectsClassToBeInjected> ();
binder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> ();
binder.Bind<InjectsClassToBeInjected>().To<InjectsClassToBeInjected> ();
InjectsClassToBeInjected instance = binder.GetInstance<InjectsClassToBeInjected> ();
Assert.IsInstanceOf<ClassToBeInjected> (instance.injected);
Assert.IsInstanceOf<ExtendsClassToBeInjected> (instance.injected);
binder.Unsupply<ClassToBeInjected, InjectsClassToBeInjected> ();
InjectsClassToBeInjected instance2 = binder.GetInstance<InjectsClassToBeInjected> ();
Assert.IsInstanceOf<ClassToBeInjected> (instance2.injected);
Assert.IsNotInstanceOf<ExtendsClassToBeInjected> (instance2.injected);
}
[Test]
public void TestGetSupplier()
{
binder.Bind<ClassToBeInjected> ().To<ExtendsClassToBeInjected> ()
.ToName("Supplier")
.SupplyTo<InjectsClassToBeInjected> ();
IInjectionBinding binding = binder.GetSupplier (typeof(ClassToBeInjected), typeof(InjectsClassToBeInjected));
Assert.IsNotNull (binding);
Assert.AreEqual (typeof (ClassToBeInjected), (binding.key as object[]) [0]);
Assert.AreEqual (typeof (ExtendsClassToBeInjected), binding.value);
Assert.AreEqual (typeof (InjectsClassToBeInjected), binding.GetSupply () [0]);
}
[Test]
public void TestComplexSupplyBinding()
{
binder.Bind<ClassToBeInjected> ().To<ClassToBeInjected> ().ToName(SomeEnum.ONE);
binder.Bind<ClassToBeInjected>().To<ExtendsClassToBeInjected>()
.SupplyTo<HasANamedInjection> ()
.SupplyTo<ConstructorInjectsClassToBeInjected>();
binder.Bind<HasANamedInjection>().To<HasANamedInjection> ();
binder.Bind<HasANamedInjection2>().To<HasANamedInjection2> ();
binder.Bind<ConstructorInjectsClassToBeInjected>().To<ConstructorInjectsClassToBeInjected> ();
HasANamedInjection instance = binder.GetInstance<HasANamedInjection> ();
ConstructorInjectsClassToBeInjected instance2 = binder.GetInstance<ConstructorInjectsClassToBeInjected> ();
HasANamedInjection2 instance3 = binder.GetInstance<HasANamedInjection2> ();
Assert.IsInstanceOf<ExtendsClassToBeInjected> (instance.injected);
Assert.IsInstanceOf<ExtendsClassToBeInjected> (instance2.injected);
Assert.IsNotInstanceOf<ExtendsClassToBeInjected> (instance3.injected);
binder.Unsupply<ClassToBeInjected, HasANamedInjection> ();
HasANamedInjection instance4 = binder.GetInstance<HasANamedInjection> ();
Assert.IsNotInstanceOf<ExtendsClassToBeInjected> (instance4.injected);
}
}
interface ITestPooled : IPoolable
{
}
class TestPooled : ITestPooled
{
public void Restore ()
{
throw new NotImplementedException ();
}
public void Retain()
{
}
public void Release()
{
}
public bool retain{ get; set; }
}
interface IUsesPool
{
ISimpleInterface Instance1{ get; set; }
ISimpleInterface Instance2{ get; set; }
}
class UsesPool : IUsesPool
{
[Inject]
public Pool<SimpleInterfaceImplementer> pool { get; set; }
public ISimpleInterface Instance1{ get; set; }
public ISimpleInterface Instance2{ get; set; }
[PostConstruct]
public void PostConstruct()
{
Instance1 = pool.GetInstance () as ISimpleInterface;
Instance2 = pool.GetInstance () as ISimpleInterface;
}
}
class ExtendedInterfaceImplementer : IExtendedInterface
{
public int intValue { get; set; }
public bool Extended()
{
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using NServiceKit.Common.Extensions;
using NServiceKit.Common.Tests;
using NServiceKit.Text.Tests.JsonTests;
namespace NServiceKit.Text.Tests.Support
{
/// <summary>A benchmark tests.</summary>
[Ignore]
[TestFixture]
public class BenchmarkTests
: PerfTestBase
{
/// <summary>Tests string parsing.</summary>
[Test]
public void Test_string_parsing()
{
const int stringSampleSize = 1024 * 10;
var testString = CreateRandomString(stringSampleSize);
var copyTo = new char[stringSampleSize];
CompareMultipleRuns(
"As char array",
() => {
var asChars = testString.ToCharArray();
for (var i = 0; i < stringSampleSize; i++)
{
copyTo[i] = asChars[i];
}
},
"As string",
() => {
for (var i = 0; i < stringSampleSize; i++)
{
copyTo[i] = testString[i];
}
});
}
/// <summary>Creates random string.</summary>
/// <param name="size">The size.</param>
/// <returns>The new random string.</returns>
public string CreateRandomString(int size)
{
var randString = new char[size];
for (var i = 0; i < size; i++)
{
randString[i] = (char)((i % 10) + '0');
}
return new string(randString);
}
/// <summary>The escape characters.</summary>
static readonly char[] EscapeChars = new char[]
{
'"', '\n', '\r', '\t', '"', '\\', '\f', '\b',
};
/// <summary>The jsv escape characters.</summary>
public static readonly char[] JsvEscapeChars = new[]
{
'"', ',', '{', '}', '[', ']',
};
/// <summary>The length from largest character.</summary>
private const int LengthFromLargestChar = '\\' + 1;
/// <summary>The has escape characters.</summary>
private static readonly bool[] HasEscapeChars = new bool[LengthFromLargestChar];
/// <summary>Print escape characters.</summary>
[Test]
public void PrintEscapeChars()
{
JsvEscapeChars.ToList().OrderBy(x => (int)x).ForEach(x => Console.WriteLine(x + ": " + (int)x));
}
/// <summary>Measure index of escape characters.</summary>
[Test]
public void MeasureIndexOfEscapeChars()
{
foreach (var escapeChar in EscapeChars)
{
HasEscapeChars[escapeChar] = true;
}
var value = CreateRandomString(100);
var len = value.Length;
var hasEscapeChars = false;
CompareMultipleRuns(
"With bool flags",
() => {
for (var i = 0; i < len; i++)
{
var c = value[i];
if (c >= LengthFromLargestChar || !HasEscapeChars[c]) continue;
hasEscapeChars = true;
break;
}
},
"With IndexOfAny",
() => {
hasEscapeChars = value.IndexOfAny(EscapeChars) != -1;
});
Console.WriteLine(hasEscapeChars);
}
/// <summary>A runtime type.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
public class RuntimeType<T>
{
/// <summary>The type.</summary>
private static Type type = typeof(T);
/// <summary>Tests variable type.</summary>
/// <returns>true if the test passes, false if the test fails.</returns>
internal static bool TestVarType()
{
return type == typeof(byte) || type == typeof(byte?)
|| type == typeof(short) || type == typeof(short?)
|| type == typeof(ushort) || type == typeof(ushort?)
|| type == typeof(int) || type == typeof(int?)
|| type == typeof(uint) || type == typeof(uint?)
|| type == typeof(long) || type == typeof(long?)
|| type == typeof(ulong) || type == typeof(ulong?)
|| type == typeof(bool) || type == typeof(bool?)
|| type != typeof(DateTime)
|| type != typeof(DateTime?)
|| type != typeof(Guid)
|| type != typeof(Guid?)
|| type != typeof(float) || type != typeof(float?)
|| type != typeof(double) || type != typeof(double?)
|| type != typeof(decimal) || type != typeof(decimal?);
}
/// <summary>Tests generic type.</summary>
/// <returns>true if the test passes, false if the test fails.</returns>
internal static bool TestGenericType()
{
return typeof(T) == typeof(byte) || typeof(T) == typeof(byte?)
|| typeof(T) == typeof(short) || typeof(T) == typeof(short?)
|| typeof(T) == typeof(ushort) || typeof(T) == typeof(ushort?)
|| typeof(T) == typeof(int) || typeof(T) == typeof(int?)
|| typeof(T) == typeof(uint) || typeof(T) == typeof(uint?)
|| typeof(T) == typeof(long) || typeof(T) == typeof(long?)
|| typeof(T) == typeof(ulong) || typeof(T) == typeof(ulong?)
|| typeof(T) == typeof(bool) || typeof(T) == typeof(bool?)
|| typeof(T) != typeof(DateTime)
|| typeof(T) != typeof(DateTime?)
|| typeof(T) != typeof(Guid)
|| typeof(T) != typeof(Guid?)
|| typeof(T) != typeof(float) || typeof(T) != typeof(float?)
|| typeof(T) != typeof(double) || typeof(T) != typeof(double?)
|| typeof(T) != typeof(decimal) || typeof(T) != typeof(decimal?);
}
}
/// <summary>Tests variable or generic type.</summary>
[Test]
public void TestVarOrGenericType()
{
var matchingTypesCount = 0;
CompareMultipleRuns(
"With var type",
() => {
if (RuntimeType<BenchmarkTests>.TestVarType())
{
matchingTypesCount++;
}
},
"With generic type",
() => {
if (RuntimeType<BenchmarkTests>.TestGenericType())
{
matchingTypesCount++;
}
});
Console.WriteLine(matchingTypesCount);
}
/// <summary>Tests for list enumeration.</summary>
[Test]
public void Test_for_list_enumeration()
{
List<Cat> list = 20.Times(x => new Cat { Name = "Cat" });
var results = 0;
var listLength = list.Count;
CompareMultipleRuns(
"With foreach",
() => {
foreach (var cat in list)
{
results++;
}
},
"With for",
() => {
for (var i = 0; i < listLength; i++)
{
var cat = list[i];
results++;
}
});
Console.WriteLine(results);
}
/// <summary>Tests for ilist enumeration.</summary>
[Test]
public void Test_for_Ilist_enumeration()
{
IList<Cat> list = 20.Times(x => new Cat { Name = "Cat" });
var results = 0;
var listLength = list.Count;
CompareMultipleRuns(
"With foreach",
() => {
foreach (var cat in list)
{
results++;
}
},
"With for",
() => {
for (var i = 0; i < listLength; i++)
{
var cat = list[i];
results++;
}
});
Console.WriteLine(results);
}
}
}
| |
// Copyright(c) 2017 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 CommandLine;
using Google.Cloud.Firestore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GoogleCloudSamples
{
public class AddData
{
public static string Usage = @"Usage:
C:\> dotnet run command YOUR_PROJECT_ID
Where command is one of
add-doc-as-map
update-create-if-missing
add-doc-data-types
add-simple-doc-as-entity
set-requires-id
add-doc-data-with-auto-id
add-doc-data-after-auto-id
update-doc
update-nested-fields
update-server-timestamp
update-document-array
";
private static async Task AddDocAsMap(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_add_doc_as_map]
DocumentReference docRef = db.Collection("cities").Document("LA");
Dictionary<string, object> city = new Dictionary<string, object>
{
{ "name", "Los Angeles" },
{ "state", "CA" },
{ "country", "USA" }
};
await docRef.SetAsync(city);
// [END fs_add_doc_as_map]
Console.WriteLine("Added data to the LA document in the cities collection.");
}
private static async Task UpdateCreateIfMissing(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_update_create_if_missing]
DocumentReference docRef = db.Collection("cities").Document("LA");
Dictionary<string, object> update = new Dictionary<string, object>
{
{ "capital", false }
};
await docRef.SetAsync(update, SetOptions.MergeAll);
// [END fs_update_create_if_missing]
Console.WriteLine("Merged data into the LA document in the cities collection.");
}
private static async Task AddDocDataTypes(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_add_doc_data_types]
DocumentReference docRef = db.Collection("data").Document("one");
Dictionary<string, object> docData = new Dictionary<string, object>
{
{ "stringExample", "Hello World" },
{ "booleanExample", false },
{ "numberExample", 3.14159265 },
{ "nullExample", null },
};
ArrayList arrayExample = new ArrayList();
arrayExample.Add(5);
arrayExample.Add(true);
arrayExample.Add("Hello");
docData.Add("arrayExample", arrayExample);
Dictionary<string, object> objectExample = new Dictionary<string, object>
{
{ "a", 5 },
{ "b", true },
};
docData.Add("objectExample", objectExample);
await docRef.SetAsync(docData);
// [END fs_add_doc_data_types]
Console.WriteLine("Set multiple data-type data for the one document in the data collection.");
}
// [START fs_class_definition]
[FirestoreData]
public class City
{
[FirestoreProperty]
public string Name { get; set; }
[FirestoreProperty]
public string State { get; set; }
[FirestoreProperty]
public string Country { get; set; }
[FirestoreProperty]
public bool Capital { get; set; }
[FirestoreProperty]
public long Population { get; set; }
}
// [END fs_class_definition]
private static async Task AddSimpleDocAsEntity(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_add_simple_doc_as_entity]
DocumentReference docRef = db.Collection("cities").Document("LA");
City city = new City
{
Name = "Los Angeles",
State = "CA",
Country = "USA",
Capital = false,
Population = 3900000L
};
await docRef.SetAsync(city);
// [END fs_add_simple_doc_as_entity]
Console.WriteLine("Added custom City object to the cities collection.");
}
private static async Task SetRequiresId(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
Dictionary<string, object> city = new Dictionary<string, object>
{
{ "Name", "Phuket" },
{ "Country", "Thailand" }
};
// [START fs_set_requires_id]
await db.Collection("cities").Document("new-city-id").SetAsync(city);
// [END fs_set_requires_id]
Console.WriteLine("Added document with ID: new-city-id.");
}
private static async Task AddDocDataWithAutoId(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_add_doc_data_with_auto_id]
Dictionary<string, object> city = new Dictionary<string, object>
{
{ "Name", "Tokyo" },
{ "Country", "Japan" }
};
DocumentReference addedDocRef = await db.Collection("cities").AddAsync(city);
Console.WriteLine("Added document with ID: {0}.", addedDocRef.Id);
// [END fs_add_doc_data_with_auto_id]
}
private static async Task AddDocDataAfterAutoId(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
Dictionary<string, object> city = new Dictionary<string, object>
{
{ "Name", "Moscow" },
{ "Country", "Russia" }
};
// [START fs_add_doc_data_after_auto_id]
DocumentReference addedDocRef = db.Collection("cities").Document();
Console.WriteLine("Added document with ID: {0}.", addedDocRef.Id);
await addedDocRef.SetAsync(city);
// [END fs_add_doc_data_after_auto_id]
Console.WriteLine("Added data to the {0} document in the cities collection.", addedDocRef.Id);
}
private static async Task UpdateDoc(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_update_doc]
DocumentReference cityRef = db.Collection("cities").Document("new-city-id");
Dictionary<string, object> updates = new Dictionary<string, object>
{
{ "Capital", false }
};
await cityRef.UpdateAsync(updates);
// You can also update a single field with: await cityRef.UpdateAsync("Capital", false);
// [END fs_update_doc]
Console.WriteLine("Updated the Capital field of the new-city-id document in the cities collection.");
}
private static async Task UpdateNestedFields(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_update_nested_fields]
DocumentReference frankDocRef = db.Collection("users").Document("frank");
Dictionary<string, object> initialData = new Dictionary<string, object>
{
{ "Name", "Frank" },
{ "Age", 12 }
};
Dictionary<string, object> favorites = new Dictionary<string, object>
{
{ "Food", "Pizza" },
{ "Color", "Blue" },
{ "Subject", "Recess" },
};
initialData.Add("Favorites", favorites);
await frankDocRef.SetAsync(initialData);
// Update age and favorite color
Dictionary<string, object> updates = new Dictionary<string, object>
{
{ "Age", 13 },
{ "Favorites.Color", "Red" },
};
// Asynchronously update the document
await frankDocRef.UpdateAsync(updates);
// [END fs_update_nested_fields]
Console.WriteLine("Updated the age and favorite color fields of the Frank document in the users collection.");
}
private static async Task UpdateServerTimestamp(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_update_server_timestamp]
DocumentReference cityRef = db.Collection("cities").Document("new-city-id");
await cityRef.UpdateAsync("Timestamp", Timestamp.GetCurrentTimestamp());
// [END fs_update_server_timestamp]
Console.WriteLine("Updated the Timestamp field of the new-city-id document in the cities collection.");
}
private static async Task UpdateDocumentArray(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_update_document_array]
DocumentReference washingtonRef = db.Collection("cities").Document("DC");
// Atomically add a new region to the "regions" array field.
await washingtonRef.UpdateAsync("Regions", FieldValue.ArrayUnion("greater_virginia"));
// Atomically remove a region from the "regions" array field.
await washingtonRef.UpdateAsync("Regions", FieldValue.ArrayRemove("east_coast"));
// [END fs_update_document_array]
Console.WriteLine("Updated the Regions array of the DC document in the cities collection.");
}
private static async Task UpdateDocumentIncrement(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_update_document_increment]
DocumentReference washingtonRef = db.Collection("cities").Document("DC");
// Atomically increment the population of the city by 50.
await washingtonRef.UpdateAsync("Regions", FieldValue.Increment(50));
// [END fs_update_document_increment]
Console.WriteLine("Updated the population of the DC document in the cities collection.");
}
public static void Main(string[] args)
{
if (args.Length < 2)
{
Console.Write(Usage);
return;
}
string command = args[0].ToLower();
string project = string.Join(" ",
new ArraySegment<string>(args, 1, args.Length - 1));
switch (command)
{
case "add-doc-as-map":
AddDocAsMap(project).Wait();
break;
case "update-create-if-missing":
UpdateCreateIfMissing(project).Wait();
break;
case "add-doc-data-types":
AddDocDataTypes(project).Wait();
break;
case "add-simple-doc-as-entity":
AddSimpleDocAsEntity(project).Wait();
break;
case "set-requires-id":
SetRequiresId(project).Wait();
break;
case "add-doc-data-with-auto-id":
AddDocDataWithAutoId(project).Wait();
break;
case "add-doc-data-after-auto-id":
AddDocDataAfterAutoId(project).Wait();
break;
case "update-doc":
UpdateDoc(project).Wait();
break;
case "update-nested-fields":
UpdateNestedFields(project).Wait();
break;
case "update-server-timestamp":
UpdateServerTimestamp(project).Wait();
break;
case "update-document-array":
UpdateDocumentArray(project).Wait();
break;
case "update-document-increment":
UpdateDocumentIncrement(project).Wait();
break;
default:
Console.Write(Usage);
return;
}
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Net;
/// <summary>
/// Summary description for MailService
/// </summary>
public class MailService
{
public enum CommonEmailType
{
Commercial,
Production,
Laboratory,
Management,
Consultant,
ApplicationRepository,
ApplicationDefaultSender,
ApplicationExceptionSender,
ApplicationTaskDoneSender
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
public static string DefaultBodySuffix =
((Membership.GetUser() != null) ? (
"\n\n-----------------------------------\n" +
"Utente: " + Membership.GetUser().UserName ) :
( "\n" ) ) +
"\n-----------------------------------\n\n" +
"Messaggio generato automaticamente dall'applicazione ProdProcess.\n" +
"Si prega cortesemente di non rispondere a questa email.\n" +
"Per informazioni o problemi contattare l'amministratore dell'applicazione: [email protected]";
public MailService()
{
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
public static void SendMessage(
CommonEmailType toEmail,
string objectText,
string bodyText)
{
SendMessage(GetEmail(
CommonEmailType.ApplicationDefaultSender),
GetEmail(toEmail), objectText, bodyText);
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
public static void SendMessage(
CommonEmailType fromEmail,
CommonEmailType toEmail,
string objectText,
string bodyText)
{
SendMessage(GetEmail(fromEmail), GetEmail(toEmail), objectText, bodyText);
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
public static void SendMessage(
string toEmail,
string objectText,
string bodyText)
{
SendMessage(GetEmail(
CommonEmailType.ApplicationDefaultSender),
toEmail, objectText, bodyText);
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
private static System.Net.Mail.MailMessage createMailMessage(
string fromEmail,
string toEmail,
string objectText,
string bodyText)
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(
new System.Net.Mail.MailAddress(fromEmail),
new System.Net.Mail.MailAddress(toEmail));
message.Subject = objectText;
message.Body = bodyText;
message.Body += DefaultBodySuffix;
return message;
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
private static void sendMailMessage(System.Net.Mail.MailMessage message)
{
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
System.Net.Mail.SmtpClient smtpClient =
new System.Net.Mail.SmtpClient();
System.Net.NetworkCredential SMTPUserInfo =
new System.Net.NetworkCredential("[email protected]", "scyther85");
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = SMTPUserInfo;
smtpClient.Port = 587; // Gmail works on this port
smtpClient.Host = "smtp.gmail.com";
smtpClient.EnableSsl = true; //Gmail works on Server Secured
try
{
smtpClient.Send(message);
}
catch (Exception exp)
{
// Log Mail Error
}
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
public static void SendMessage(
string fromEmail,
string toEmail,
string objectText,
string bodyText)
{
System.Net.Mail.MailMessage message = createMailMessage(
fromEmail, toEmail, objectText, bodyText);
sendMailMessage(message);
}
public static void SendMessageWithAttachment(
string fromEmail,
string toEmail,
string objectText,
string bodyText,
string attachmentPath,
string mediaType) // application/pdf
{
System.Net.Mail.MailMessage message = createMailMessage(
fromEmail, toEmail, objectText, bodyText);
// generate the contentID string using the datetime
string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "@zofm";
//string attachmentPath = Environment.CurrentDirectory + @"\test.png";
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = mediaType;
inline.ContentType.Name = Path.GetFileName(attachmentPath);
message.Attachments.Add(inline);
sendMailMessage(message);
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
public static string GetEmail(CommonEmailType emailType)
{
switch (emailType)
{
case CommonEmailType.Commercial:
return "[email protected]";
case CommonEmailType.Laboratory:
return "[email protected]";
case CommonEmailType.Production:
return "[email protected]";
case CommonEmailType.ApplicationRepository:
return "[email protected]";
case CommonEmailType.ApplicationDefaultSender:
return "[email protected]";
case CommonEmailType.ApplicationTaskDoneSender:
return "[email protected]";
case CommonEmailType.ApplicationExceptionSender:
return "[email protected]";
case CommonEmailType.Management:
return "[email protected]";
case CommonEmailType.Consultant:
return "[email protected]";
}
return "";
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
}// Class
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using ScreenCasting.Controls;
using ScreenCasting.Data.Azure;
using ScreenCasting.Data.Common;
using System;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Media.DialProtocol;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace ScreenCasting
{
public sealed partial class Scenario03 : Page
{
private MainPage rootPage;
private DialDevicePicker picker = null;
private VideoMetaData video = null;
private DialDevice activeDialDevice = null;
private DeviceInformation activeDeviceInformation = null;
public Scenario03()
{
this.InitializeComponent();
rootPage = MainPage.Current;
//Subscribe to player events
player.MediaOpened += Player_MediaOpened;
player.MediaFailed += Player_MediaFailed;
player.CurrentStateChanged += Player_CurrentStateChanged;
// Get an Azure hosted video
AzureDataProvider dataProvider = new AzureDataProvider();
video = dataProvider.GetRandomVideo();
//Set the source on the player
rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage);
this.player.Source = video.VideoLink;
//Subscribe for the clicked event on the custom cast button
((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked;
//Configure the DIAL launch arguments for the current video
this.dial_launch_args_textbox.Text = string.Format("v={0}&t=0&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id);
//Subscribe for the clicked event on the custom cast button
((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked;
// Instantiate the Device Picker
picker = new DialDevicePicker();
//Add the DIAL Filter, so that the application only shows DIAL devices that have
// the application installed or advertise that they can install them.
picker.Filter.SupportedAppNames.Add(this.dial_appname_textbox.Text);
//Hook up device selected event
picker.DialDeviceSelected += Picker_DeviceSelected;
//Hook up the picker disconnected event
picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked;
//Hook up the picker dismissed event
picker.DialDevicePickerDismissed += Picker_DevicePickerDismissed;
}
private void TransportControls_CastButtonClicked(object sender, EventArgs e)
{
rootPage.NotifyUser("Show Device Picker Button Clicked", NotifyType.StatusMessage);
//Pause Current Playback
player.Pause();
//Get the custom transport controls
MediaTransportControlsWithCustomCastButton mtc = (MediaTransportControlsWithCustomCastButton)this.player.TransportControls;
//Retrieve the location of the casting button
GeneralTransform transform = mtc.CastButton.TransformToVisual(Window.Current.Content as UIElement);
Point pt = transform.TransformPoint(new Point(0, 0));
//Show the picker above our Show Device Picker button
picker.Show(new Rect(pt.X, pt.Y, mtc.CastButton.ActualWidth, mtc.CastButton.ActualHeight), Windows.UI.Popups.Placement.Above);
try
{
if (activeDialDevice != null)
picker.SetDisplayStatus(activeDialDevice, DialDeviceDisplayStatus.Connected);
}
catch (Exception ex)
{
UnhandledExceptionPage.ShowUnhandledException(ex);
}
}
#region Device Picker Methods
private async void Picker_DevicePickerDismissed(DialDevicePicker sender, object args)
{
//Casting must occur from the UI thread. This dispatches the casting calls to the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try
{
rootPage.NotifyUser(string.Format("Picker DevicePickerDismissed event fired for device"), NotifyType.StatusMessage);
if (activeDialDevice != null)
{
// Resume video playback
this.player.Play();
}
}
catch (Exception ex)
{
UnhandledExceptionPage.ShowUnhandledException(ex);
}
});
}
private async void Picker_DisconnectButtonClicked(DialDevicePicker sender, DialDisconnectButtonClickedEventArgs args)
{
//Casting must occur from the UI thread. This dispatches the casting calls to the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
try
{
rootPage.NotifyUser(string.Format("Picker DisconnectButtonClicked event fired for device '{0}'", activeDeviceInformation.Name), NotifyType.StatusMessage);
// Get the DialDevice instance for the selected device
DialDevice selectedDialDevice = await DialDevice.FromIdAsync(args.Device.Id);
// Update the picker status
picker.SetDisplayStatus(selectedDialDevice, DialDeviceDisplayStatus.Connecting);
DialApp app = selectedDialDevice.GetDialApp(this.dial_appname_textbox.Text);
//Get the current application state
//DialAppStateDetails stateDetails = await app.GetAppStateAsync();
DialAppStopResult result = await app.StopAsync();
if (result == DialAppStopResult.Stopped)
{
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Application stopped successfully.", NotifyType.StatusMessage);
picker.SetDisplayStatus(args.Device, DialDeviceDisplayStatus.Disconnected);
activeDialDevice = null;
activeDeviceInformation = null;
picker.Hide();
}
else
{
if (result == DialAppStopResult.StopFailed || result == DialAppStopResult.NetworkFailure)
{
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser(string.Format("Error occured trying to stop application. Status: '{0}'", result.ToString()), NotifyType.StatusMessage);
picker.SetDisplayStatus(args.Device, DialDeviceDisplayStatus.Error);
}
else //in case of DialAppStopResult.OperationNotSupported, there is not much more you can do. You could implement your own
// mechanism to stop the application on that device.
{
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser(string.Format("Stop is not supported by device: '{0}'", activeDeviceInformation.Name), NotifyType.ErrorMessage);
activeDialDevice = null;
activeDeviceInformation = null;
}
}
}
catch (Exception ex)
{
UnhandledExceptionPage.ShowUnhandledException(ex);
}
});
}
private async void Picker_DeviceSelected(DialDevicePicker sender, DialDeviceSelectedEventArgs args)
{
//Casting must occur from the UI thread. This dispatches the casting calls to the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
try {
rootPage.NotifyUser(string.Format("Picker DeviceSelected event fired"), NotifyType.StatusMessage);
// Set the status to connecting
picker.SetDisplayStatus(args.SelectedDialDevice, DialDeviceDisplayStatus.Connecting);
rootPage.NotifyUser(string.Format("Resolving DialDevice'"), NotifyType.StatusMessage);
//Get the DialApp object for the specific application on the selected device
DialApp app = args.SelectedDialDevice.GetDialApp(this.dial_appname_textbox.Text);
if (app == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
//rootPage.NotifyUser(string.Format("'{0}' cannot find app with ID '{1}'", selectedDeviceInformation.Name, this.dial_appname_textbox.Text), NotifyType.StatusMessage);
picker.SetDisplayStatus(args.SelectedDialDevice, DialDeviceDisplayStatus.Error);
}
else
{
rootPage.NotifyUser(string.Format("Attempting to launch '{0}'", app.AppName), NotifyType.StatusMessage);
//Launch the application on the 1st screen device
DialAppLaunchResult result = await app.RequestLaunchAsync(this.dial_launch_args_textbox.Text);
//Verify to see whether the application was launched
if (result == DialAppLaunchResult.Launched)
{
rootPage.NotifyUser(string.Format("Launched '{0}'", app.AppName), NotifyType.StatusMessage);
activeDialDevice = args.SelectedDialDevice;
DeviceInformation selectedDeviceInformation = await DeviceInformation.CreateFromIdAsync(args.SelectedDialDevice.Id);
activeDeviceInformation = selectedDeviceInformation;
//This is where you will need to add you application specific communication between your 1st and 2nd screen applications
//...
//...
//...
picker.SetDisplayStatus(activeDialDevice, DialDeviceDisplayStatus.Connected);
picker.Hide();
}
else
{
rootPage.NotifyUser(string.Format("Attempting to launch '{0}'", app.AppName), NotifyType.StatusMessage);
picker.SetDisplayStatus(args.SelectedDialDevice, DialDeviceDisplayStatus.Error);
}
}
}
catch (Exception ex)
{
UnhandledExceptionPage.ShowUnhandledException(ex);
}
});
}
#endregion
#region Media Element Status Methods
private void Player_CurrentStateChanged(object sender, RoutedEventArgs e)
{
// Update status
rootPage.NotifyUser(string.Format("{0} '{1}'", this.player.CurrentState, video.Title), NotifyType.StatusMessage);
}
private void Player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
// Update status
rootPage.NotifyUser(string.Format("Failed to load '{0}'", video.Title), NotifyType.ErrorMessage);
}
private void Player_MediaOpened(object sender, RoutedEventArgs e)
{
// Update status
rootPage.NotifyUser(string.Format("Openend '{0}'", video.Title), NotifyType.StatusMessage);
// Start playback
player.Play();
}
#endregion
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using Caliburn.Micro;
using Eagle.FilePicker.ViewModels;
using Eagle.Services;
using Microsoft.Win32;
namespace Eagle.ViewModels
{
[Export(typeof(IShell))]
public class ShellViewModel : Screen, IShell
{
private readonly IFileManager _fileManager;
private bool _showLineNumbers = false;
private bool _followTail;
private bool _isFileOpen = false;
private FileViewModel _file;
private readonly IStateService _stateService;
private readonly IClipboardService _clipboardService;
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
[ImportingConstructor]
public ShellViewModel(
IFileManagerEventSource fileManagerEventSource,
IFileManager fileManager,
IStateService stateService,
IClipboardService clipboardService)
{
_clipboardService = clipboardService;
_stateService = stateService;
_stateService.SavingEvent.Subscribe(this.SaveState);
_fileManager = fileManager;
fileManagerEventSource.OpenFileEventStream.Subscribe(this.OpenFile);
this.DisplayName = "Eagle";
this.FollowTail = true;
if (Execute.InDesignMode)
{
this.IsFileOpen = true;
this.File = new FileViewModel("Test File");
}
else
{
//this.FilePicker.Items.Add(new FileLocationViewModel("Documents") { SubLocations = { new FileLocationViewModel("File1"), new FileLocationViewModel("File2"), new FileLocationViewModel("File3") } });
//this.FilePicker.Items.Add(new FileLocationViewModel("Projects"));
//this.FilePicker.Items.Add(new FileLocationViewModel("Logs"));
}
}
public ShellViewModel()
{
this.DisplayName = "Eagle";
this.FollowTail = true;
this.IsFileOpen = true;
this.File = new FileViewModel("Test File", null);
this.FilePicker = new FilePickerViewModel();
this.FilePicker.Items.Add(new FileLocationViewModel("Documents") { SubLocations = { new FileLocationViewModel("File1"), new FileLocationViewModel("File2"), new FileLocationViewModel("File3") } });
this.FilePicker.Items.Add(new FileLocationViewModel("Projects"));
this.FilePicker.Items.Add(new FileLocationViewModel("Logs"));
}
private void SaveState(IStateCaptureContext context)
{
context.SaveState("Shell",
new ShellState
{
HasFile = _file != null,
OpenFile = (_file == null) ? null : _file.FileName
});
}
public void CopySelectedLines(IEnumerable selection)
{
if (selection != null)
{
var lines = selection.Cast<LineViewModel>();
if (lines.Any())
{
var str = new StringBuilder();
foreach (var line in lines.OrderBy(l => l.LineNumber))
{
str.AppendLine(line.Text);
}
_clipboardService.CopyText(str.ToString());
}
}
}
public bool IsFileOpen
{
get
{
return _isFileOpen;
}
set
{
if (_isFileOpen != value)
{
_isFileOpen = value;
this.NotifyOfPropertyChange(() => this.IsFileOpen);
// Fire change notifications for depend properties
this.NotifyOfPropertyChange(() => this.CanCloseFile);
this.NotifyOfPropertyChange(() => this.CanRefreshFile);
this.NotifyOfPropertyChange(() => this.CanReload);
this.NotifyOfPropertyChange(() => this.CanClear);
}
}
}
public FileViewModel File
{
get
{
return _file;
}
set
{
if (_file != value)
{
_file = value;
this.NotifyOfPropertyChange(() => this.File);
}
}
}
[Import]
public FilePickerViewModel FilePicker { get; private set; }
public void SaveState()
{
_stateService.MarkAsDirty();
}
public bool FollowTail
{
get
{
return _followTail;
}
set
{
if (_followTail != value)
{
_followTail = value;
this.NotifyOfPropertyChange(() => this.FollowTail);
}
}
}
public bool ShowLineNumbers
{
get
{
return _showLineNumbers;
}
set
{
if (_showLineNumbers != value)
{
_showLineNumbers = value;
this.NotifyOfPropertyChange(() => this.ShowLineNumbers);
}
}
}
public void OpenFile(string fileName)
{
this.File = new FileViewModel(fileName, Encoding.UTF8);
this.IsFileOpen = true;
this.File.LoadFileContent();
}
public void Open()
{
var dialog = new OpenFileDialog();
if (dialog.ShowDialog() == true)
{
_fileManager.OpenFile(dialog.FileName);
}
}
public void RefreshFile()
{
if (this.File != null)
{
this.File.RefreshFile();
}
}
public bool CanRefreshFile { get { return this.IsFileOpen; } }
public void CloseFile()
{
using (this.File)
{
this.File = null;
this.IsFileOpen = false;
}
}
public bool CanCloseFile { get { return this.IsFileOpen; } }
public void Reload()
{
if (this.File != null)
{
this.File.LoadFileContent();
}
}
public bool CanReload { get { return this.IsFileOpen; } }
public void Clear()
{
if (this.File != null)
{
this.File.ClearContent();
}
}
public bool CanClear { get { return this.IsFileOpen; } }
public void RestoreState(ShellState state)
{
if (state.OpenFile != null)
{
_fileManager.OpenFile(state.OpenFile);
}
else
{
this.CloseFile();
}
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Timers;
using log4net;
using Nwc.XmlRpc;
using ProtoBuf;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Messages;
using OpenSim.Grid.Framework;
using Timer=System.Timers.Timer;
namespace OpenSim.Grid.MessagingServer.Modules
{
public class MessageService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private MessageServerConfig m_cfg;
private UserDataBaseService m_userDataBaseService;
private IGridServiceCore m_messageCore;
private IInterServiceUserService m_userServerModule;
private IMessageRegionLookup m_regionModule;
// a dictionary of all current presences this server knows about
private Dictionary<UUID, UserPresenceData> m_presences = new Dictionary<UUID,UserPresenceData>();
public MessageService(MessageServerConfig cfg, IGridServiceCore messageCore, UserDataBaseService userDataBaseService)
{
m_cfg = cfg;
m_messageCore = messageCore;
m_userDataBaseService = userDataBaseService;
//???
UserConfig uc = new UserConfig();
uc.DatabaseConnect = cfg.DatabaseConnect;
uc.DatabaseProvider = cfg.DatabaseProvider;
}
public void Initialise()
{
}
public void PostInitialise()
{
IInterServiceUserService messageUserServer;
if (m_messageCore.TryGet<IInterServiceUserService>(out messageUserServer))
{
m_userServerModule = messageUserServer;
}
IMessageRegionLookup messageRegion;
if (m_messageCore.TryGet<IMessageRegionLookup>(out messageRegion))
{
m_regionModule = messageRegion;
}
}
public void RegisterHandlers()
{
//have these in separate method as some servers restart the http server and reregister all the handlers.
}
#region FriendList Methods
/// <summary>
/// Process Friendlist subscriptions for a user
/// The login method calls this for a User
/// </summary>
/// <param name="userpresence">The Agent we're processing the friendlist subscriptions for</param>
private void ProcessFriendListSubscriptions(UserPresenceData userpresence)
{
lock (m_presences)
{
m_presences[userpresence.agentData.AgentID] = userpresence;
}
Dictionary<UUID, FriendListItem> uFriendList = userpresence.friendData;
foreach (KeyValuePair<UUID, FriendListItem> pair in uFriendList)
{
UserPresenceData friendup = null;
lock (m_presences)
{
m_presences.TryGetValue(pair.Key, out friendup);
}
if (friendup != null)
{
SubscribeToPresenceUpdates(userpresence, friendup, pair.Value);
}
}
}
/// <summary>
/// Enqueues a presence update, sending info about user 'talkingAbout' to user 'receiver'.
/// </summary>
/// <param name="talkingAbout">We are sending presence information about this user.</param>
/// <param name="receiver">We are sending the presence update to this user</param>
private void enqueuePresenceUpdate(UserPresenceData talkingAbout, UserPresenceData receiver)
{
UserAgentData p2Handle = m_userDataBaseService.GetUserAgentData(receiver.agentData.AgentID);
if (p2Handle != null)
{
if (receiver.lookupUserRegionYN)
{
receiver.regionData.regionHandle = p2Handle.Handle;
}
else
{
receiver.lookupUserRegionYN = true; // TODO Huh?
}
PresenceInformer friendlistupdater = new PresenceInformer();
friendlistupdater.presence1 = talkingAbout;
friendlistupdater.presence2 = receiver;
friendlistupdater.OnGetRegionData += m_regionModule.GetRegionInfo;
friendlistupdater.OnDone += PresenceUpdateDone;
WaitCallback cb = new WaitCallback(friendlistupdater.go);
ThreadPool.QueueUserWorkItem(cb);
}
else
{
m_log.WarnFormat("[PRESENCE]: no data found for user {0}", receiver.agentData.AgentID);
// Skip because we can't find any data on the user
}
}
/// <summary>
/// Does the necessary work to subscribe one agent to another's presence notifications
/// Gets called by ProcessFriendListSubscriptions. You shouldn't call this directly
/// unless you know what you're doing
/// </summary>
/// <param name="userpresence">P1</param>
/// <param name="friendpresence">P2</param>
/// <param name="uFriendListItem"></param>
private void SubscribeToPresenceUpdates(UserPresenceData userpresence,
UserPresenceData friendpresence,
FriendListItem uFriendListItem)
{
// Can the friend see me online?
if ((uFriendListItem.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0)
{
// tell user to update friend about user's presence changes
if (!userpresence.subscriptionData.Contains(friendpresence.agentData.AgentID))
{
userpresence.subscriptionData.Add(friendpresence.agentData.AgentID);
}
// send an update about user's presence to the friend
enqueuePresenceUpdate(userpresence, friendpresence);
}
// Can I see the friend online?
if ((uFriendListItem.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0)
{
// tell friend to update user about friend's presence changes
if (!friendpresence.subscriptionData.Contains(userpresence.agentData.AgentID))
{
friendpresence.subscriptionData.Add(userpresence.agentData.AgentID);
}
// send an update about friend's presence to user.
enqueuePresenceUpdate(friendpresence, userpresence);
}
}
/// <summary>
/// Logoff Processor. Call this to clean up agent presence data and send logoff presence notifications
/// </summary>
/// <param name="AgentID"></param>
private void ProcessLogOff(UUID AgentID)
{
m_log.Info("[LOGOFF]: Processing Logoff");
UserPresenceData userPresence = null;
lock (m_presences)
{
m_presences.TryGetValue(AgentID, out userPresence);
}
if (userPresence != null) // found the user
{
List<UUID> AgentsNeedingNotification = userPresence.subscriptionData;
userPresence.OnlineYN = false;
for (int i = 0; i < AgentsNeedingNotification.Count; i++)
{
UserPresenceData friendPresence = null;
lock (m_presences)
{
m_presences.TryGetValue(AgentsNeedingNotification[i], out friendPresence);
}
// This might need to be enumerated and checked before we try to remove it.
if (friendPresence != null)
{
lock (friendPresence)
{
// no updates for this user anymore
friendPresence.subscriptionData.Remove(AgentID);
// set user's entry in the friend's list to offline (if it exists)
if (friendPresence.friendData.ContainsKey(AgentID))
{
friendPresence.friendData[AgentID].onlinestatus = false;
}
}
enqueuePresenceUpdate(userPresence, friendPresence);
}
}
}
}
#endregion
private void PresenceUpdateDone(PresenceInformer obj)
{
obj.OnGetRegionData -= m_regionModule.GetRegionInfo;
obj.OnDone -= PresenceUpdateDone;
}
#region UserServer Comms
/// <summary>
/// Returns a list of FriendsListItems that describe the friends and permissions in the friend
/// relationship for UUID friendslistowner. For faster lookup, we index by friend's UUID.
/// </summary>
/// <param name="friendlistowner">The agent that we're retreiving the friends Data for.</param>
private Dictionary<UUID, FriendListItem> GetUserFriendListOld(UUID friendlistowner)
{
m_log.Warn("[FRIEND]: Calling Messaging/GetUserFriendListOld for " + friendlistowner.ToString());
Dictionary<UUID, FriendListItem> buddies = new Dictionary<UUID, FriendListItem>();
try
{
Hashtable param = new Hashtable();
param["ownerID"] = friendlistowner.ToString();
IList parameters = new ArrayList();
parameters.Add(param);
string methodName = "get_user_friend_list";
XmlRpcRequest req = new XmlRpcRequest(methodName, parameters);
XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(m_cfg.UserServerURL, methodName), 3000);
Hashtable respData = (Hashtable)resp.Value;
if (respData.Contains("avcount"))
{
buddies = ConvertXMLRPCDataToFriendListItemList(respData);
}
}
catch (WebException e)
{
m_log.Warn("[FRIEND]: Error when trying to fetch Avatar's friends list: " +
e.Message);
// Return Empty list (no friends)
}
return buddies;
}
/// <summary>
/// The response that will be returned from a command
/// </summary>
public enum GetUserFriendListResult
{
OK = 0,
ERROR = 1,
UNAUTHORIZED = 2,
INVALID = 3,
// NOTIMPLEMENTED means no such URL/operation (older servers return this when new commands are added)
NOTIMPLEMENTED = 4
}
/// <summary>
/// Returns a list of FriendsListItems that describe the friends and permissions in the friend
/// relationship for UUID friendslistowner. For faster lookup, we index by friend's UUID.
/// </summary>
/// <param name="friendlistowner">The agent that we're retreiving the friends Data for.</param>
private GetUserFriendListResult GetUserFriendList2(UUID friendlistowner, out Dictionary<UUID, FriendListItem> results)
{
Util.SlowTimeReporter slowCheck = new Util.SlowTimeReporter("[FRIEND]: GetUserFriendList2 for " + friendlistowner.ToString() + " took", TimeSpan.FromMilliseconds(1000));
try
{
Dictionary<UUID, FriendListItem> EMPTY_RESULTS = new Dictionary<UUID, FriendListItem>();
string uri = m_cfg.UserServerURL + "/get_user_friend_list2/";
HttpWebRequest friendListRequest = (HttpWebRequest)WebRequest.Create(uri);
friendListRequest.Method = "POST";
friendListRequest.ContentType = "application/octet-stream";
friendListRequest.Timeout = FriendsListRequest.TIMEOUT;
// Default results are empty
results = EMPTY_RESULTS;
// m_log.WarnFormat("[FRIEND]: Msg/GetUserFriendList2({0}) using URI '{1}'", friendlistowner, uri);
FriendsListRequest request = FriendsListRequest.FromUUID(friendlistowner);
try
{
// send the Post
Stream os = friendListRequest.GetRequestStream();
ProtoBuf.Serializer.Serialize(os, request);
os.Flush();
os.Close();
}
catch (Exception e)
{
m_log.InfoFormat("[FRIEND]: GetUserFriendList2 call failed {0}", e);
return GetUserFriendListResult.ERROR;
}
// Let's wait for the response
try
{
HttpWebResponse webResponse = (HttpWebResponse)friendListRequest.GetResponse();
if (webResponse == null)
{
m_log.Error("[FRIEND]: Null reply on GetUserFriendList2 put");
return GetUserFriendListResult.ERROR;
}
//this will happen during the initial rollout and tells us we need to fall back to the old method
if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
m_log.WarnFormat("[FRIEND]: NotFound on reply of GetUserFriendList2");
return GetUserFriendListResult.NOTIMPLEMENTED;
}
if (webResponse.StatusCode != HttpStatusCode.OK)
{
m_log.ErrorFormat("[FRIEND]: Error on reply of GetUserFriendList2 {0}", friendlistowner);
return GetUserFriendListResult.ERROR;
}
// We have a reply.
FriendsListResponse response = ProtoBuf.Serializer.Deserialize<FriendsListResponse>(webResponse.GetResponseStream());
if (response == null)
{
m_log.ErrorFormat("[FRIEND]: Could not deserialize reply of GetUserFriendList2");
return GetUserFriendListResult.ERROR;
}
// Request/response succeeded.
results = response.ToDict();
// m_log.InfoFormat("[FRIEND]: Returning {0} friends for {1}", results.Count, friendlistowner);
return GetUserFriendListResult.OK;
}
catch (WebException ex)
{
HttpWebResponse webResponse = ex.Response as HttpWebResponse;
if (webResponse != null)
{
//this will happen during the initial rollout and tells us we need to fall back to the
//old method
if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
m_log.InfoFormat("[FRIEND]: NotFound exception on reply of GetUserFriendList2");
return GetUserFriendListResult.NOTIMPLEMENTED;
}
}
m_log.ErrorFormat("[FRIEND]: exception on reply of GetUserFriendList2 for {0}", request.FriendListOwner);
}
return GetUserFriendListResult.ERROR;
}
finally
{
slowCheck.Complete();
}
}
private Dictionary<UUID, FriendListItem> GetUserFriendList(UUID friendlistowner)
{
Dictionary<UUID, FriendListItem> results;
GetUserFriendListResult rc = GetUserFriendList2(friendlistowner, out results);
if (rc == GetUserFriendListResult.NOTIMPLEMENTED)
results = GetUserFriendListOld(friendlistowner);
return results;
}
/// <summary>
/// Converts XMLRPC Friend List to FriendListItem Object
/// </summary>
/// <param name="data">XMLRPC response data Hashtable</param>
/// <returns></returns>
public Dictionary<UUID, FriendListItem> ConvertXMLRPCDataToFriendListItemList(Hashtable data)
{
Dictionary<UUID, FriendListItem> buddies = new Dictionary<UUID,FriendListItem>();
int buddycount = Convert.ToInt32((string)data["avcount"]);
for (int i = 0; i < buddycount; i++)
{
FriendListItem buddylistitem = new FriendListItem();
buddylistitem.FriendListOwner = new UUID((string)data["ownerID" + i.ToString()]);
buddylistitem.Friend = new UUID((string)data["friendID" + i.ToString()]);
buddylistitem.FriendListOwnerPerms = (uint)Convert.ToInt32((string)data["ownerPerms" + i.ToString()]);
buddylistitem.FriendPerms = (uint)Convert.ToInt32((string)data["friendPerms" + i.ToString()]);
buddies.Add(buddylistitem.Friend, buddylistitem);
}
return buddies;
}
/// <summary>
/// UserServer sends an expect_user method
/// this handles the method and provisions the
/// necessary info for presence to work
/// </summary>
/// <param name="request">UserServer Data</param>
/// <returns></returns>
public XmlRpcResponse UserLoggedOn(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
AgentCircuitData agentData = new AgentCircuitData();
agentData.SessionID = new UUID((string)requestData["sessionid"]);
agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]);
agentData.FirstName = (string)requestData["firstname"];
agentData.LastName = (string)requestData["lastname"];
agentData.AgentID = new UUID((string)requestData["agentid"]);
agentData.CircuitCode = Convert.ToUInt32(requestData["circuit_code"]);
agentData.CapsPath = (string)requestData["caps_path"];
if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
{
agentData.child = true;
}
else
{
agentData.startpos =
new Vector3(Convert.ToSingle(requestData["positionx"]),
Convert.ToSingle(requestData["positiony"]),
Convert.ToSingle(requestData["positionz"]));
agentData.child = false;
}
ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
m_log.InfoFormat("[LOGON]: User {0} {1} logged into region {2} as {3} agent, building indexes for user",
agentData.FirstName, agentData.LastName, regionHandle, agentData.child ? "child" : "root");
UserPresenceData up = new UserPresenceData();
up.agentData = agentData;
up.friendData = GetUserFriendList(agentData.AgentID);
up.regionData = m_regionModule.GetRegionInfo(regionHandle);
up.OnlineYN = true;
up.lookupUserRegionYN = false;
ProcessFriendListSubscriptions(up);
return new XmlRpcResponse();
}
/// <summary>
/// The UserServer got a Logoff message
/// Cleanup time for that user. Send out presence notifications
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse UserLoggedOff(XmlRpcRequest request, IPEndPoint remoteClient)
{
m_log.Info("[LOGOFF]: User logged off called");
Hashtable requestData = (Hashtable)request.Params[0];
UUID AgentID = new UUID((string)requestData["agentid"]);
ProcessLogOff(AgentID);
return new XmlRpcResponse();
}
#endregion
public XmlRpcResponse GetPresenceInfoBulk(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable paramHash = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
// TODO check access (recv_key/send_key)
IList list = (IList)paramHash["uuids"];
// convert into List<UUID>
List<UUID> uuids = new List<UUID>();
for (int i = 0; i < list.Count; ++i)
{
UUID uuid;
if (UUID.TryParse((string)list[i], out uuid))
{
uuids.Add(uuid);
}
}
try {
Dictionary<UUID, FriendRegionInfo> infos = m_userDataBaseService.GetFriendRegionInfos(uuids);
m_log.DebugFormat("[FRIEND]: Got {0} region entries back.", infos.Count);
int count = 0;
foreach (KeyValuePair<UUID, FriendRegionInfo> pair in infos)
{
result["uuid_" + count] = pair.Key.ToString();
result["isOnline_" + count] = pair.Value.isOnline;
result["regionHandle_" + count] = pair.Value.regionHandle.ToString(); // XML-RPC doesn't know ulongs
++count;
}
result["count"] = count;
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
catch(Exception e) {
m_log.Error("[PRESENCE]: Got exception:", e);
throw e;
}
}
public XmlRpcResponse AgentLocation(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
result["success"] = "FALSE";
if (m_userServerModule.SendToUserServer(requestData, "agent_location"))
result["success"] = "TRUE";
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
public XmlRpcResponse AgentLeaving(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
result["success"] = "FALSE";
if (m_userServerModule.SendToUserServer(requestData, "agent_leaving"))
result["success"] = "TRUE";
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
public XmlRpcResponse ProcessRegionShutdown(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
result["success"] = "FALSE";
UUID regionID;
if (UUID.TryParse((string)requestData["regionid"], out regionID))
{
m_log.DebugFormat("[PRESENCE]: Processing region shutdown for {0}", regionID);
result["success"] = "TRUE";
foreach (UserPresenceData up in m_presences.Values)
{
if (up.regionData.UUID == regionID)
{
if (up.OnlineYN)
{
m_log.DebugFormat("[PRESENCE]: Logging off {0} because the region they were in has gone", up.agentData.AgentID);
ProcessLogOff(up.agentData.AgentID);
}
}
}
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using MixedRealityToolkit.Sharing;
using UnityEngine;
using Random = System.Random;
namespace MixedRealityToolkit.Examples.Sharing
{
/// <summary>
/// Test class for demonstrating creating rooms and anchors.
/// </summary>
public class RoomTest : MonoBehaviour
{
private RoomManagerAdapter listener;
private RoomManager roomMgr;
private string roomName = "New Room";
private Vector2 scrollViewVector = Vector2.zero;
private int padding = 4;
private int areaWidth = 400;
private int areaHeight = 300;
private int buttonWidth = 80;
private int lineHeight = 20;
private Vector2 anchorScrollVector = Vector2.zero;
private string anchorName = "New Anchor";
private readonly byte[] anchorTestData = new byte[5 * 1024 * 1024]; // 5 meg test buffer
private void Start()
{
for (int i = 0; i < anchorTestData.Length; ++i)
{
anchorTestData[i] = (byte)(i % 256);
}
SharingStage stage = SharingStage.Instance;
if (stage != null)
{
SharingManager sharingMgr = stage.Manager;
if (sharingMgr != null)
{
roomMgr = sharingMgr.GetRoomManager();
listener = new RoomManagerAdapter();
listener.RoomAddedEvent += OnRoomAdded;
listener.RoomClosedEvent += OnRoomClosed;
listener.UserJoinedRoomEvent += OnUserJoinedRoom;
listener.UserLeftRoomEvent += OnUserLeftRoom;
listener.AnchorsChangedEvent += OnAnchorsChanged;
listener.AnchorsDownloadedEvent += OnAnchorsDownloaded;
listener.AnchorUploadedEvent += OnAnchorUploadComplete;
roomMgr.AddListener(listener);
}
}
}
private void OnDestroy()
{
roomMgr.RemoveListener(listener);
listener.Dispose();
}
private void OnGUI()
{
// Make a background box
scrollViewVector = GUI.BeginScrollView(
new Rect(25, 25, areaWidth, areaHeight),
scrollViewVector,
new Rect(0, 0, areaWidth, areaHeight));
if (roomMgr != null)
{
SessionManager sessionMgr = SharingStage.Instance.Manager.GetSessionManager();
if (sessionMgr != null)
{
roomName = GUI.TextField(
new Rect(buttonWidth + padding, 0, areaWidth - (buttonWidth + padding), lineHeight),
roomName);
if (GUI.Button(new Rect(0, 0, buttonWidth, lineHeight), "Create"))
{
Random rnd = new Random();
Room newRoom = roomMgr.CreateRoom(roomName, rnd.Next(), false);
if (newRoom == null)
{
Debug.LogWarning("Cannot create room");
}
}
Room currentRoom = roomMgr.GetCurrentRoom();
for (int i = 0; i < roomMgr.GetRoomCount(); ++i)
{
Room room = roomMgr.GetRoom(i);
int vOffset = (padding + lineHeight) * (i + 1);
int hOffset = 0;
bool keepOpen = GUI.Toggle(new Rect(hOffset, vOffset, lineHeight, lineHeight), room.GetKeepOpen(), "");
room.SetKeepOpen(keepOpen);
hOffset += lineHeight + padding;
if (currentRoom != null && room.GetID() == currentRoom.GetID())
{
if (GUI.Button(new Rect(hOffset, vOffset, buttonWidth, lineHeight), "Leave"))
{
roomMgr.LeaveRoom();
}
}
else
{
if (GUI.Button(new Rect(hOffset, vOffset, buttonWidth, lineHeight), "Join"))
{
if (!roomMgr.JoinRoom(room))
{
Debug.LogWarning("Cannot join room");
}
}
}
hOffset += buttonWidth + padding;
GUI.Label(new Rect(hOffset, vOffset, areaWidth - (buttonWidth + padding), lineHeight),
room.GetName().GetString());
}
}
}
// End the ScrollView
GUI.EndScrollView();
if (roomMgr != null)
{
Room currentRoom = roomMgr.GetCurrentRoom();
if (currentRoom != null)
{
// Display option to upload anchor
anchorScrollVector = GUI.BeginScrollView(
new Rect(areaWidth + 50, 25, areaWidth, areaHeight),
anchorScrollVector,
new Rect(0, 0, areaWidth, areaHeight));
anchorName =
GUI.TextField(
new Rect(
buttonWidth + padding,
0,
areaWidth - (buttonWidth + padding),
lineHeight),
anchorName);
if (GUI.Button(new Rect(0, 0, buttonWidth, lineHeight), "Create"))
{
if (!roomMgr.UploadAnchor(currentRoom, anchorName, anchorTestData, anchorTestData.Length))
{
Debug.LogError("Failed to start anchor upload");
}
}
for (int i = 0; i < currentRoom.GetAnchorCount(); ++i)
{
int vOffset = (padding + lineHeight) * (i + 1);
XString currentRoomAnchor = currentRoom.GetAnchorName(i);
GUI.Label(
new Rect(
buttonWidth + padding,
vOffset,
areaWidth - (buttonWidth + padding),
lineHeight),
currentRoomAnchor);
if (GUI.Button(new Rect(0, vOffset, buttonWidth, lineHeight), "Download"))
{
if (!roomMgr.DownloadAnchor(currentRoom, currentRoomAnchor))
{
Debug.LogWarning("Failed to start anchor download");
}
}
}
GUI.EndScrollView();
}
}
}
private void OnRoomAdded(Room newRoom)
{
Debug.LogFormat("Room {0} added", newRoom.GetName().GetString());
}
private void OnRoomClosed(Room room)
{
Debug.LogFormat("Room {0} closed", room.GetName().GetString());
}
private void OnUserJoinedRoom(Room room, int user)
{
User joinedUser = SharingStage.Instance.SessionUsersTracker.GetUserById(user);
Debug.LogFormat("User {0} joined Room {1}", joinedUser.GetName(), room.GetName().GetString());
}
private void OnUserLeftRoom(Room room, int user)
{
User leftUser = SharingStage.Instance.SessionUsersTracker.GetUserById(user);
Debug.LogFormat("User {0} left Room {1}", leftUser.GetName(), room.GetName().GetString());
}
private void OnAnchorsChanged(Room room)
{
Debug.LogFormat("Anchors changed for Room {0}", room.GetName().GetString());
}
private void OnAnchorsDownloaded(bool successful, AnchorDownloadRequest request, XString failureReason)
{
if (successful)
{
Debug.LogFormat("Anchors download succeeded for Room {0}", request.GetRoom().GetName().GetString());
}
else
{
Debug.LogFormat("Anchors download failed: {0}", failureReason.GetString());
}
}
private void OnAnchorUploadComplete(bool successful, XString failureReason)
{
if (successful)
{
Debug.Log("Anchors upload succeeded");
}
else
{
Debug.LogFormat("Anchors upload failed: {0}", failureReason.GetString());
}
}
}
}
| |
// Copyright (c) 2013 Krkadoni.com - Released under The MIT License.
// Full license text can be found at http://opensource.org/licenses/MIT
using System;
using System.Globalization;
using System.Runtime.Serialization;
using Krkadoni.EnigmaSettings.Interfaces;
namespace Krkadoni.EnigmaSettings
{
[DataContract]
public class BouquetItemStream : BouquetItem, IBouquetItemStream
{
private string _description = string.Empty;
private string _extraFlag1 = "0";
private string _extraFlag2 = "0";
private string _serviceId = "0";
private string _streamFlag = "1";
private string _url = string.Empty;
#region "IEditable"
private bool _isEditing;
private string _mDescription;
private string _mExtraFlag1;
private string _mExtraFlag2;
private string _mServiceId;
private string _mStreamFlag;
private string _mUrl;
public override void BeginEdit()
{
base.BeginEdit();
if (_isEditing) return;
_mDescription = _description;
_mExtraFlag1 = _extraFlag1;
_mExtraFlag2 = _extraFlag2;
_mServiceId = _serviceId;
_mStreamFlag = _streamFlag;
_mUrl = _url;
_isEditing = true;
}
public override void EndEdit()
{
base.EndEdit();
_isEditing = false;
}
public override void CancelEdit()
{
base.CancelEdit();
if (!_isEditing) return;
Description = _mDescription;
ExtraFlag1 = _mExtraFlag1;
ExtraFlag2 = _mExtraFlag2;
ServiceID = _mServiceId;
StreamFlag = _mStreamFlag;
URL = _mUrl;
_isEditing = false;
}
#endregion
#region "ICloneable"
/// <summary>
/// Performs Memberwise Clone on the object
/// </summary>
/// <returns></returns>
public new object Clone()
{
return MemberwiseClone();
}
#endregion
/// <summary>
/// Initializes new stream
/// </summary>
/// <param name="description">Without leading #DESCRIPTION tag</param>
/// <param name="url">URL of the stream. Will be automatically URL encoded</param>
/// <param name="streamFlag">Stream Flag (3rd field in line) in Hex format</param>
/// <remarks></remarks>
/// <exception cref="ArgumentNullException">
/// Throws argument null exception if description is null, URL or streamFlag is
/// null or empty
/// </exception>
public BouquetItemStream(string description, string url, string streamFlag)
{
if (description == null)
throw new ArgumentNullException();
if (string.IsNullOrEmpty(url))
throw new ArgumentNullException();
if (string.IsNullOrEmpty(streamFlag))
throw new ArgumentNullException();
_description = description.Trim();
_url = url;
_streamFlag = streamFlag;
_lineSpecifierFlag = "0";
}
/// <summary>
/// Initializes new stream
/// </summary>
/// <param name="bouquetLine"></param>
/// <param name="description"></param>
/// <remarks></remarks>
/// <exception cref="ArgumentNullException">
/// Throws argument null exception if description is null or bouquetline is null or
/// empty
/// </exception>
public BouquetItemStream(string bouquetLine, string description)
{
if (string.IsNullOrEmpty(bouquetLine))
throw new ArgumentNullException();
if (description == null)
throw new ArgumentNullException();
if (bouquetLine.ToUpper().StartsWith("#SERVICE"))
{
bouquetLine = bouquetLine.Substring(9).Trim();
}
string[] sData = bouquetLine.Trim().Split(':');
FavoritesTypeFlag = sData[0];
LineSpecifierFlag = sData[1];
StreamFlag = sData[2];
ServiceID = sData[3];
ExtraFlag1 = sData[4];
ExtraFlag2 = sData[5];
URL = sData[10];
Description = description;
}
/// <summary>
/// URL of the stream
/// </summary>
/// <value></value>
/// <returns>URL decoded string</returns>
/// <remarks>Will automatically encode string</remarks>
[DataMember]
public string URL
{
get { return Uri.UnescapeDataString(_url); }
set
{
if (value == _url) return;
if (value == null)
value = string.Empty;
_url = Uri.EscapeDataString(value);
OnPropertyChanged("URL");
}
}
/// <summary>
/// Type of bouquet item
/// </summary>
/// <value></value>
/// <returns>Enums.BouquetItemType.Stream</returns>
/// <remarks></remarks>
[DataMember]
public override Enums.BouquetItemType BouquetItemType
{
get { return Enums.BouquetItemType.Stream; }
}
/// <summary>
/// Text as seen in settings
/// </summary>
/// <value></value>
/// <returns>'Stream' if empty</returns>
/// <remarks></remarks>
[DataMember]
public string Description
{
get { return _description; }
set
{
if (value == _description) return;
if (string.IsNullOrEmpty(value))
value = "Stream";
_description = value.Trim();
OnPropertyChanged("Description");
}
}
/// <summary>
/// Value of the current flag without flag type
/// </summary>
/// <value></value>
/// <returns>Hex value</returns>
/// <remarks></remarks>
[DataMember]
public string StreamFlag
{
get { return _streamFlag; }
set
{
if (value == _streamFlag) return;
if (string.IsNullOrEmpty(value))
value = "1";
_streamFlag = value;
OnPropertyChanged("StreamFlag");
OnPropertyChanged("StreamFlagInt");
}
}
/// <summary>
/// StreamFlag value as integer
/// </summary>
/// <value></value>
/// <returns>0 if flag is not valid hex</returns>
/// <remarks></remarks>
[DataMember]
public int StreamFlagInt
{
get
{
try
{
return Int32.Parse(StreamFlag, NumberStyles.HexNumber);
}
catch (Exception)
{
return 0;
}
}
set
{
if (value == StreamFlagInt) return;
_streamFlag = value.ToString("X");
OnPropertyChanged("StreamFlag");
OnPropertyChanged("StreamFlagInt");
}
}
/// <summary>
/// Extra flag as 5th item in service line
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks>In hex format</remarks>
[DataMember]
public string ExtraFlag1
{
get { return _extraFlag1; }
set
{
if (value == _extraFlag1) return;
if (string.IsNullOrEmpty(value))
return;
_extraFlag1 = value;
OnPropertyChanged("ExtraFlag1");
OnPropertyChanged("ExtraFlag1Int");
}
}
/// <summary>
/// Extra flag as 5th item in service line
/// </summary>
/// <value></value>
/// <returns>Integer value of flag</returns>
/// <remarks></remarks>
[DataMember]
public int ExtraFlag1Int
{
get
{
try
{
return Int32.Parse(_extraFlag1, NumberStyles.HexNumber);
}
catch (Exception)
{
return 0;
}
}
set
{
if (value == ExtraFlag1Int) return;
_extraFlag1 = value.ToString("X");
OnPropertyChanged("ExtraFlag1");
OnPropertyChanged("ExtraFlag1Int");
}
}
/// <summary>
/// Extra flag as 6th item in service line
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks>In hex format</remarks>
[DataMember]
public string ExtraFlag2
{
get { return _extraFlag2; }
set
{
if (value == _extraFlag2) return;
if (string.IsNullOrEmpty(value))
return;
_extraFlag2 = value;
OnPropertyChanged("ExtraFlag2");
OnPropertyChanged("ExtraFlag2Int");
}
}
/// <summary>
/// Extra flag as 6th item in service line
/// </summary>
/// <value></value>
/// <returns>Integer value of flag</returns>
/// <remarks></remarks>
[DataMember]
public int ExtraFlag2Int
{
get
{
try
{
return Int32.Parse(_extraFlag2, NumberStyles.HexNumber);
}
catch (Exception)
{
return 0;
}
}
set
{
if (value == ExtraFlag2Int) return;
_extraFlag2 = value.ToString("X");
OnPropertyChanged("ExtraFlag2");
OnPropertyChanged("ExtraFlag2Int");
}
}
/// <summary>
/// Extra flag as 4th item in service line
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks>In hex format</remarks>
[DataMember]
public string ServiceID
{
get { return _serviceId; }
set
{
if (value == _serviceId) return;
if (string.IsNullOrEmpty(value))
return;
_serviceId = value;
OnPropertyChanged("ServiceID");
OnPropertyChanged("ServiceIDInt");
}
}
/// <summary>
/// Extra flag as 4th item in service line
/// </summary>
/// <value></value>
/// <returns>Integer value of flag</returns>
/// <remarks></remarks>
[DataMember]
public int ServiceIDInt
{
get
{
try
{
return Int32.Parse(_serviceId, NumberStyles.HexNumber);
}
catch (Exception)
{
return 0;
}
}
set
{
if (value == ExtraFlag2Int) return;
_serviceId = value.ToString("X");
OnPropertyChanged("ServiceID");
OnPropertyChanged("ServiceIDInt");
}
}
/// <summary>
/// Return line in format ready to be written to bouquet
/// </summary>
/// <returns></returns>
/// <remarks></remarks>
public override string ToString()
{
return string.Join("\t", new[]
{
string.Join(":", new[]
{
FavoritesType.ToString(),
LineSpecifierFlag,
StreamFlag,
"0",
ExtraFlag1,
ExtraFlag2,
"0",
"0",
"0",
"0",
_url
}),
string.Join(" ", new[]
{
"#DESCRIPTION",
Description
})
});
}
}
}
| |
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Torque6.Engine.SimObjects;
using Torque6.Engine.SimObjects.Scene;
using Torque6.Engine.Namespaces;
using Torque6.Utility;
namespace Torque6.Engine.SimObjects.GuiControls
{
public unsafe class GuiStackControl : GuiControl
{
public GuiStackControl()
{
ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.GuiStackControlCreateInstance());
}
public GuiStackControl(uint pId) : base(pId)
{
}
public GuiStackControl(string pName) : base(pName)
{
}
public GuiStackControl(IntPtr pObjPtr) : base(pObjPtr)
{
}
public GuiStackControl(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr)
{
}
public GuiStackControl(SimObject pObj) : base(pObj)
{
}
#region UnsafeNativeMethods
new internal struct InternalUnsafeMethods
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiStackControlGetStackingType(IntPtr ctrl);
private static _GuiStackControlGetStackingType _GuiStackControlGetStackingTypeFunc;
internal static int GuiStackControlGetStackingType(IntPtr ctrl)
{
if (_GuiStackControlGetStackingTypeFunc == null)
{
_GuiStackControlGetStackingTypeFunc =
(_GuiStackControlGetStackingType)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiStackControlGetStackingType"), typeof(_GuiStackControlGetStackingType));
}
return _GuiStackControlGetStackingTypeFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiStackControlSetStackingType(IntPtr ctrl, int type);
private static _GuiStackControlSetStackingType _GuiStackControlSetStackingTypeFunc;
internal static void GuiStackControlSetStackingType(IntPtr ctrl, int type)
{
if (_GuiStackControlSetStackingTypeFunc == null)
{
_GuiStackControlSetStackingTypeFunc =
(_GuiStackControlSetStackingType)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiStackControlSetStackingType"), typeof(_GuiStackControlSetStackingType));
}
_GuiStackControlSetStackingTypeFunc(ctrl, type);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiStackControlGetHorizStacking(IntPtr ctrl);
private static _GuiStackControlGetHorizStacking _GuiStackControlGetHorizStackingFunc;
internal static int GuiStackControlGetHorizStacking(IntPtr ctrl)
{
if (_GuiStackControlGetHorizStackingFunc == null)
{
_GuiStackControlGetHorizStackingFunc =
(_GuiStackControlGetHorizStacking)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiStackControlGetHorizStacking"), typeof(_GuiStackControlGetHorizStacking));
}
return _GuiStackControlGetHorizStackingFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiStackControlSetHorizStacking(IntPtr ctrl, int type);
private static _GuiStackControlSetHorizStacking _GuiStackControlSetHorizStackingFunc;
internal static void GuiStackControlSetHorizStacking(IntPtr ctrl, int type)
{
if (_GuiStackControlSetHorizStackingFunc == null)
{
_GuiStackControlSetHorizStackingFunc =
(_GuiStackControlSetHorizStacking)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiStackControlSetHorizStacking"), typeof(_GuiStackControlSetHorizStacking));
}
_GuiStackControlSetHorizStackingFunc(ctrl, type);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiStackControlGetVertStacking(IntPtr ctrl);
private static _GuiStackControlGetVertStacking _GuiStackControlGetVertStackingFunc;
internal static int GuiStackControlGetVertStacking(IntPtr ctrl)
{
if (_GuiStackControlGetVertStackingFunc == null)
{
_GuiStackControlGetVertStackingFunc =
(_GuiStackControlGetVertStacking)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiStackControlGetVertStacking"), typeof(_GuiStackControlGetVertStacking));
}
return _GuiStackControlGetVertStackingFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiStackControlSetVertStacking(IntPtr ctrl, int type);
private static _GuiStackControlSetVertStacking _GuiStackControlSetVertStackingFunc;
internal static void GuiStackControlSetVertStacking(IntPtr ctrl, int type)
{
if (_GuiStackControlSetVertStackingFunc == null)
{
_GuiStackControlSetVertStackingFunc =
(_GuiStackControlSetVertStacking)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiStackControlSetVertStacking"), typeof(_GuiStackControlSetVertStacking));
}
_GuiStackControlSetVertStackingFunc(ctrl, type);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiStackControlGetPadding(IntPtr ctrl);
private static _GuiStackControlGetPadding _GuiStackControlGetPaddingFunc;
internal static int GuiStackControlGetPadding(IntPtr ctrl)
{
if (_GuiStackControlGetPaddingFunc == null)
{
_GuiStackControlGetPaddingFunc =
(_GuiStackControlGetPadding)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiStackControlGetPadding"), typeof(_GuiStackControlGetPadding));
}
return _GuiStackControlGetPaddingFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiStackControlSetPadding(IntPtr ctrl, int padding);
private static _GuiStackControlSetPadding _GuiStackControlSetPaddingFunc;
internal static void GuiStackControlSetPadding(IntPtr ctrl, int padding)
{
if (_GuiStackControlSetPaddingFunc == null)
{
_GuiStackControlSetPaddingFunc =
(_GuiStackControlSetPadding)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiStackControlSetPadding"), typeof(_GuiStackControlSetPadding));
}
_GuiStackControlSetPaddingFunc(ctrl, padding);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _GuiStackControlCreateInstance();
private static _GuiStackControlCreateInstance _GuiStackControlCreateInstanceFunc;
internal static IntPtr GuiStackControlCreateInstance()
{
if (_GuiStackControlCreateInstanceFunc == null)
{
_GuiStackControlCreateInstanceFunc =
(_GuiStackControlCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiStackControlCreateInstance"), typeof(_GuiStackControlCreateInstance));
}
return _GuiStackControlCreateInstanceFunc();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiStackControlUpdateStack(IntPtr ctrl);
private static _GuiStackControlUpdateStack _GuiStackControlUpdateStackFunc;
internal static void GuiStackControlUpdateStack(IntPtr ctrl)
{
if (_GuiStackControlUpdateStackFunc == null)
{
_GuiStackControlUpdateStackFunc =
(_GuiStackControlUpdateStack)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiStackControlUpdateStack"), typeof(_GuiStackControlUpdateStack));
}
_GuiStackControlUpdateStackFunc(ctrl);
}
}
#endregion
#region Properties
public int StackingType
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiStackControlGetStackingType(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiStackControlSetStackingType(ObjectPtr->ObjPtr, value);
}
}
public int HorizStacking
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiStackControlGetHorizStacking(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiStackControlSetHorizStacking(ObjectPtr->ObjPtr, value);
}
}
public int VertStacking
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiStackControlGetVertStacking(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiStackControlSetVertStacking(ObjectPtr->ObjPtr, value);
}
}
public int Padding
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiStackControlGetPadding(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiStackControlSetPadding(ObjectPtr->ObjPtr, value);
}
}
#endregion
#region Methods
public void UpdateStack()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiStackControlUpdateStack(ObjectPtr->ObjPtr);
}
#endregion
}
}
| |
/*******************************************************************************
* The MIT License (MIT)
* Copyright (c) 2015 Frank Benoit, Stuttgart, Germany <[email protected]>
*
* See the LICENSE.md or the online documentation:
* https://docs.google.com/document/d/1Wqa8rDi0QYcqcf0oecD8GW53nMVXj3ZFSmcF81zAa8g/edit#heading=h.2kvlhpr5zi2u
*
* Contributors:
* Frank Benoit - initial API and implementation
*******************************************************************************/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Org.Chabu.Prot.V1.Internal
{
using global::System.Collections.Generic;
using Moq;
using Runnable = global::System.Action;
[TestClass]
public class ChabuReceiverStartupTest {
Setup setup;
Mock<AbortMessage> abortMessage;
Mock<ChabuChannel> channel;
Mock<Runnable> completionListener;
List<ChabuChannel> channels = new List<ChabuChannel>();
private ChabuReceiverStartup sut;
private TestByteChannel byteChannel;
[TestInitialize] public void
Setup() {
abortMessage = new Mock<AbortMessage>();
channel = new Mock<ChabuChannel>();
completionListener = new Mock<Runnable>();
setup = new Setup(new ChabuSetupInfo(), abortMessage.Object, null );
sut = new ChabuReceiverStartup(abortMessage.Object, setup, completionListener.Object);
channels.Add( new Mock<ChabuChannel>().Object );
byteChannel = new TestByteChannel( 1000, 1000 );
}
private String getStringData( String text ){
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
int length = Utils.alignUpTo4(bytes.Length);
byte[] data = new byte[length+4];
data[0] = (byte)(bytes.Length >> 24);
data[1] = (byte)(bytes.Length >> 16);
data[2] = (byte)(bytes.Length >> 8);
data[3] = (byte)(bytes.Length >> 0);
System.arraycopy(bytes, 0, data, 4, bytes.Length );
String res = TestUtils.toHexString(data, true);
return res + " ";
}
private String getIntData( int v ){
return String.Format("{0:X2} {1:X2} {2:X2} {3:X2} ",
( v >> 24 ) & 0xFF,
( v >> 16 ) & 0xFF,
( v >> 8 ) & 0xFF,
( v >> 0 ) & 0xFF);
}
[TestMethod]
public void getStringDataIsGood() {
Assert.AreEqual(getStringData("ABC"), "00 00 00 03 41 42 43 00 ");
}
[TestMethod]
public void getSetupRecvDataIsGood() {
Assert.AreEqual(getSetupRecvData("CHABU", Constants.PROTOCOL_VERSION, 1000, 0x12345678, "ABC")
,"00 00 00 28 77 77 00 F0 00 00 00 05 43 48 41 42 " +
"55 00 00 00 "+TestUtils.getChabuVersionAsHex()+"00 00 03 E8 12 34 56 78 " +
"00 00 00 03 41 42 43 00 ");
}
private String getSetupRecvData(String protocolName, int chabuProtVersion, int recvPacketSize, int applProtVersion, String applProtName ) {
return getIntData(0x1C + Utils.alignUpTo4(applProtName.length()) + Utils.alignUpTo4(protocolName.length()) ) +
"77 77 00 F0 " +
getStringData( protocolName) +
getIntData(chabuProtVersion) +
getIntData(recvPacketSize) +
getIntData(applProtVersion) +
getStringData( applProtName );
}
private String getSetupRecvData() {
return getSetupRecvData("CHABU", Constants.PROTOCOL_VERSION, 1000, 0x12345678, "ABC");
}
private String getAcceptData() {
return "00 00 00 08 77 77 00 E1 ";
}
private void prepareSetupData() {
byteChannel.putRecvData( getSetupRecvData());
}
[TestMethod] public void
recv_remote_setup() {
prepareSetupData();
sut.recv(byteChannel);
Assert.AreEqual(setup.getInfoRemote(), new ChabuSetupInfo( 1000, 0x12345678 , "ABC" ));
}
[TestMethod] public void
recv_remote_setup_with_wrong_protocol_name() {
byteChannel.putRecvData(getSetupRecvData("Thabu", Constants.PROTOCOL_VERSION, 1000, 0x12345678, "ABC"));
sut.recv(byteChannel);
sut.recv(byteChannel);
abortMessage.Verify( a => a.setPending(ChabuErrorCode.SETUP_REMOTE_CHABU_NAME, It.IsAny<String>()));
}
[TestMethod] public void
recv_remote_setup_with_wrong_protocol_major_version() {
byteChannel.putRecvData(getSetupRecvData("CHABU", Constants.PROTOCOL_VERSION + 0x10000, 1000, 0x12345678, "ABC"));
sut.recv(byteChannel);
abortMessage.Verify(a => a.setPending(ChabuErrorCode.SETUP_REMOTE_CHABU_VERSION, It.IsAny<String>()));
}
[TestMethod] public void
recv_remote_setup_with_wrong_protocol_minor_version_ignored() {
byteChannel.putRecvData(getSetupRecvData("CHABU", Constants.PROTOCOL_VERSION + 0x1000, 1000, 0x12345678, "ABC"));
sut.recv(byteChannel);
abortMessage.Verify(am => am.setPending(
ChabuErrorCode.SETUP_REMOTE_CHABU_VERSION, It.IsAny<String>()), Times.Never );
}
[TestMethod] public void
recv_remote_setup_with_single_bytes() {
String data = getSetupRecvData();
while( !data.isEmpty() ){
String singleData = data.Substring(0, 3);
data = data.Substring(3);
byteChannel.putRecvData( singleData );
sut.recv(byteChannel);
}
Assert.AreEqual(setup.getInfoRemote(), new ChabuSetupInfo( 1000, 0x12345678 , "ABC" ));
}
[TestMethod]
[ExpectedException(typeof(ChabuException),
"A userId of null was inappropriately allowed.")]
public void
recv_remote_setup_with_too_long_protocol_name() {
String data = "00 00 00 2C 77 77 00 F0 00 00 00 09 43 48 41 42 " +
"55 00 00 00 00 00 00 00 "+TestUtils.getChabuVersionAsHex()+"00 00 03 E8 12 34 56 78 " +
"00 00 00 03 41 42 43 00 ";
byteChannel.putRecvData( data );
sut.recv(byteChannel);
//.isInstanceOf(ChabuException.class)
//.hasMessageContaining("exceeds max allowed length");
}
[TestMethod]
[ExpectedException(typeof(ChabuException),
"A userId of null was inappropriately allowed.")]
public void
recv_remote_setup_with_too_long_appl_protocol_name() {
String data = "00 00 00 60 77 77 00 F0 00 00 00 05 43 48 41 42 " +
"55 00 00 00 "+TestUtils.getChabuVersionAsHex()+"00 00 03 E8 12 34 56 78 " +
"00 00 00 39 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 ";
byteChannel.putRecvData( data );
sut.recv(byteChannel);
//.isInstanceOf(ChabuException.class)
//.hasMessageContaining("exceeds max allowed length");
}
[TestMethod]
[ExpectedException(typeof(ChabuException),
"A userId of null was inappropriately allowed.")]
public void
recv_remote_setup_with_appl_protocol_name_not_fully_contained_in_recv_buffer() {
String data = "00 00 00 30 77 77 00 F0 00 00 00 05 43 48 41 42 " +
"55 00 00 00 "+TestUtils.getChabuVersionAsHex()+"00 00 03 E8 12 34 56 78 " +
"00 00 00 30 41 42 43 00 41 42 43 00 41 42 43 00 41 42 43 00 41 ";
byteChannel.putRecvData( data );
sut.recv(byteChannel);
//.isInstanceOf(ChabuException.class)
//.hasMessageContaining("exceeds packet length");
}
[TestMethod] public void
recv_accept() {
byteChannel.putRecvData(
"00 00 00 28 77 77 00 F0 00 00 00 05 43 48 41 42 " +
"55 00 00 00 "+TestUtils.getChabuVersionAsHex()+"00 00 03 E8 12 34 56 78 " +
"00 00 00 03 41 42 43 00 " +
getAcceptData());
sut.recv(byteChannel);
Assert.IsTrue(setup.isRemoteAcceptReceived());
completionListener.Verify( r => r());
}
[TestMethod] public void
recv_accept_without_setup() {
String data = getAcceptData();
byteChannel.putRecvData( data );
sut.recv(byteChannel);
abortMessage.Verify(m => m.setPending(
ChabuErrorCode.PROTOCOL_ACCEPT_WITHOUT_SETUP,
It.IsAny<String>()));
}
[TestMethod]
[ExpectedException(typeof(ChabuException),
"A userId of null was inappropriately allowed.")]
public void recv_abort() {
String data = "00 00 00 08 77 77 00 D2 00 02 00 00 00 00 00 03 41 42 43 00";
byteChannel.putRecvData( data );
sut.recv(byteChannel);
//.isInstanceOf(ChabuException.class)
//.hasMessageContaining("ABC");
}
}
}
| |
using FluentMigrator.Exceptions;
using FluentMigrator.Runner.Generators.Oracle;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.OracleWithQuotedIdentifier
{
[TestFixture]
public class OracleTableTests : BaseTableTests
{
protected OracleGenerator Generator;
[SetUp]
public void Setup()
{
Generator = new OracleGenerator(new OracleQuoterQuotedIdentifier());
}
[Test]
public override void CanCreateTableWithCustomColumnTypeWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].IsPrimaryKey = true;
expression.Columns[1].Type = null;
expression.Columns[1].CustomType = "BINARY_DOUBLE";
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestSchema\".\"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) NOT NULL, \"TestColumn2\" BINARY_DOUBLE NOT NULL, PRIMARY KEY (\"TestColumn1\"))");
}
[Test]
public override void CanCreateTableWithCustomColumnTypeWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].IsPrimaryKey = true;
expression.Columns[1].Type = null;
expression.Columns[1].CustomType = "BINARY_DOUBLE";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) NOT NULL, \"TestColumn2\" BINARY_DOUBLE NOT NULL, PRIMARY KEY (\"TestColumn1\"))");
}
[Test]
public override void CanCreateTableWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestSchema\".\"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) NOT NULL, \"TestColumn2\" NUMBER(10,0) NOT NULL)");
}
[Test]
public override void CanCreateTableWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) NOT NULL, \"TestColumn2\" NUMBER(10,0) NOT NULL)");
}
[Test]
public override void CanCreateTableWithDefaultValueExplicitlySetToNullWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].DefaultValue = null;
expression.Columns[0].TableName = expression.TableName;
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestSchema\".\"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) DEFAULT NULL NOT NULL, \"TestColumn2\" NUMBER(10,0) NOT NULL)");
}
[Test]
public override void CanCreateTableWithDefaultValueExplicitlySetToNullWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].DefaultValue = null;
expression.Columns[0].TableName = expression.TableName;
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) DEFAULT NULL NOT NULL, \"TestColumn2\" NUMBER(10,0) NOT NULL)");
}
[Test]
public override void CanCreateTableWithDefaultValueWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithDefaultValue();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestSchema\".\"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) DEFAULT 'Default' NOT NULL, \"TestColumn2\" NUMBER(10,0) DEFAULT 0 NOT NULL)");
}
[Test]
public override void CanCreateTableWithDefaultValueWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithDefaultValue();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) DEFAULT 'Default' NOT NULL, \"TestColumn2\" NUMBER(10,0) DEFAULT 0 NOT NULL)");
}
[Test]
public override void CanCreateTableWithIdentityWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithAutoIncrementExpression();
expression.SchemaName = "TestSchema";
Assert.Throws<DatabaseOperationNotSupportedException>(() => Generator.Generate(expression));
}
[Test]
public override void CanCreateTableWithIdentityWithDefaultSchema()
{
Assert.Throws<DatabaseOperationNotSupportedException>(() => Generator.Generate(GeneratorTestHelper.GetCreateTableWithAutoIncrementExpression()));
}
[Test]
public override void CanCreateTableWithMultiColumnPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithMultiColumnPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestSchema\".\"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) NOT NULL, \"TestColumn2\" NUMBER(10,0) NOT NULL, PRIMARY KEY (\"TestColumn1\", \"TestColumn2\"))");
}
[Test]
public override void CanCreateTableWithMultiColumnPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) NOT NULL, \"TestColumn2\" NUMBER(10,0) NOT NULL, PRIMARY KEY (\"TestColumn1\", \"TestColumn2\"))");
}
[Test]
public override void CanCreateTableWithNamedMultiColumnPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedMultiColumnPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestSchema\".\"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) NOT NULL, \"TestColumn2\" NUMBER(10,0) NOT NULL, CONSTRAINT \"TestKey\" PRIMARY KEY (\"TestColumn1\", \"TestColumn2\"))");
}
[Test]
public override void CanCreateTableWithNamedMultiColumnPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) NOT NULL, \"TestColumn2\" NUMBER(10,0) NOT NULL, CONSTRAINT \"TestKey\" PRIMARY KEY (\"TestColumn1\", \"TestColumn2\"))");
}
[Test]
public override void CanCreateTableWithNamedPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestSchema\".\"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) NOT NULL, \"TestColumn2\" NUMBER(10,0) NOT NULL, CONSTRAINT \"TestKey\" PRIMARY KEY (\"TestColumn1\"))");
}
[Test]
public override void CanCreateTableWithNamedPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) NOT NULL, \"TestColumn2\" NUMBER(10,0) NOT NULL, CONSTRAINT \"TestKey\" PRIMARY KEY (\"TestColumn1\"))");
}
[Test]
public override void CanCreateTableWithNullableFieldWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNullableColumn();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestSchema\".\"TestTable1\" (\"TestColumn1\" NVARCHAR2(255), \"TestColumn2\" NUMBER(10,0) NOT NULL)");
}
[Test]
public override void CanCreateTableWithNullableFieldWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNullableColumn();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestTable1\" (\"TestColumn1\" NVARCHAR2(255), \"TestColumn2\" NUMBER(10,0) NOT NULL)");
}
[Test]
public override void CanCreateTableWithPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestSchema\".\"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) NOT NULL, \"TestColumn2\" NUMBER(10,0) NOT NULL, PRIMARY KEY (\"TestColumn1\"))");
}
[Test]
public override void CanCreateTableWithPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE \"TestTable1\" (\"TestColumn1\" NVARCHAR2(255) NOT NULL, \"TestColumn2\" NUMBER(10,0) NOT NULL, PRIMARY KEY (\"TestColumn1\"))");
}
[Test]
public override void CanDropTableWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteTableExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("DROP TABLE \"TestSchema\".\"TestTable1\"");
}
[Test]
public override void CanDropTableWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteTableExpression();
var result = Generator.Generate(expression);
result.ShouldBe("DROP TABLE \"TestTable1\"");
}
[Test]
public override void CanRenameTableWithCustomSchema()
{
var expression = GeneratorTestHelper.GetRenameTableExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" RENAME TO \"TestTable2\"");
}
[Test]
public override void CanRenameTableWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetRenameTableExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" RENAME TO \"TestTable2\"");
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Zenject
{
// We don't bother implementing IValidatable here because it is assumed that the nested
// factory handles that for us
// Zero parameters
[System.Diagnostics.DebuggerStepThrough]
public class FactoryNested<TContract, TConcrete> : IFactory<TContract>
where TConcrete : TContract
{
readonly IFactory<TConcrete> _concreteFactory;
public FactoryNested(IFactory<TConcrete> concreteFactory)
{
_concreteFactory = concreteFactory;
}
public virtual TContract Create()
{
return _concreteFactory.Create();
}
}
// One parameter
[System.Diagnostics.DebuggerStepThrough]
public class FactoryNested<TParam1, TContract, TConcrete> : IFactory<TParam1, TContract>
where TConcrete : TContract
{
readonly IFactory<TParam1, TConcrete> _concreteFactory;
public FactoryNested(IFactory<TParam1, TConcrete> concreteFactory)
{
_concreteFactory = concreteFactory;
}
public virtual TContract Create(TParam1 param)
{
return _concreteFactory.Create(param);
}
}
// Two parameters
[System.Diagnostics.DebuggerStepThrough]
public class FactoryNested<TParam1, TParam2, TContract, TConcrete> : IFactory<TParam1, TParam2, TContract>
where TConcrete : TContract
{
readonly IFactory<TParam1, TParam2, TConcrete> _concreteFactory;
public FactoryNested(IFactory<TParam1, TParam2, TConcrete> concreteFactory)
{
_concreteFactory = concreteFactory;
}
public virtual TContract Create(TParam1 param1, TParam2 param2)
{
return _concreteFactory.Create(param1, param2);
}
}
// Three parameters
[System.Diagnostics.DebuggerStepThrough]
public class FactoryNested<TParam1, TParam2, TParam3, TContract, TConcrete> : IFactory<TParam1, TParam2, TParam3, TContract>
where TConcrete : TContract
{
readonly IFactory<TParam1, TParam2, TParam3, TConcrete> _concreteFactory;
public FactoryNested(IFactory<TParam1, TParam2, TParam3, TConcrete> concreteFactory)
{
_concreteFactory = concreteFactory;
}
public virtual TContract Create(TParam1 param1, TParam2 param2, TParam3 param3)
{
return _concreteFactory.Create(param1, param2, param3);
}
}
// Four parameters
[System.Diagnostics.DebuggerStepThrough]
public class FactoryNested<TParam1, TParam2, TParam3, TParam4, TContract, TConcrete> :
IFactory<TParam1, TParam2, TParam3, TParam4, TContract>
where TConcrete : TContract
{
readonly IFactory<TParam1, TParam2, TParam3, TParam4, TConcrete> _concreteFactory;
public FactoryNested(IFactory<TParam1, TParam2, TParam3, TParam4, TConcrete> concreteFactory)
{
_concreteFactory = concreteFactory;
}
public virtual TContract Create(
TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4)
{
return _concreteFactory.Create(param1, param2, param3, param4);
}
}
// Five parameters
[System.Diagnostics.DebuggerStepThrough]
public class FactoryNested<TParam1, TParam2, TParam3, TParam4, TParam5, TContract, TConcrete> :
IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TContract>
where TConcrete : TContract
{
readonly IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TConcrete> _concreteFactory;
public FactoryNested(IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TConcrete> concreteFactory)
{
_concreteFactory = concreteFactory;
}
public virtual TContract Create(
TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5)
{
return _concreteFactory.Create(param1, param2, param3, param4, param5);
}
}
// Six parameters
[System.Diagnostics.DebuggerStepThrough]
public class FactoryNested<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TContract, TConcrete> :
IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TContract>
where TConcrete : TContract
{
readonly IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TConcrete> _concreteFactory;
public FactoryNested(IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TConcrete> concreteFactory)
{
_concreteFactory = concreteFactory;
}
public virtual TContract Create(
TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6)
{
return _concreteFactory.Create(param1, param2, param3, param4, param5, param6);
}
}
// Seven parameters
[System.Diagnostics.DebuggerStepThrough]
public class FactoryNested<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TContract, TConcrete> :
IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TContract>
where TConcrete : TContract
{
readonly IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TConcrete> _concreteFactory;
public FactoryNested(IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TConcrete> concreteFactory)
{
_concreteFactory = concreteFactory;
}
public virtual TContract Create(
TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7)
{
return _concreteFactory.Create(param1, param2, param3, param4, param5, param6, param7);
}
}
// Eigth parameters
[System.Diagnostics.DebuggerStepThrough]
public class FactoryNested<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TContract, TConcrete> :
IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TContract>
where TConcrete : TContract
{
readonly IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TConcrete> _concreteFactory;
public FactoryNested(IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TConcrete> concreteFactory)
{
_concreteFactory = concreteFactory;
}
public virtual TContract Create(
TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8)
{
return _concreteFactory.Create(param1, param2, param3, param4, param5, param6, param7, param8);
}
}
// Nine parameters
[System.Diagnostics.DebuggerStepThrough]
public class FactoryNested<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TContract, TConcrete> :
IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TContract>
where TConcrete : TContract
{
readonly IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TConcrete> _concreteFactory;
public FactoryNested(IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TConcrete> concreteFactory)
{
_concreteFactory = concreteFactory;
}
public virtual TContract Create(
TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8, TParam9 param9)
{
return _concreteFactory.Create(param1, param2, param3, param4, param5, param6, param7, param8, param9);
}
}
// Ten parameters
[System.Diagnostics.DebuggerStepThrough]
public class FactoryNested<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TContract, TConcrete> :
IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TContract>
where TConcrete : TContract
{
readonly IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TConcrete> _concreteFactory;
public FactoryNested(IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TConcrete> concreteFactory)
{
_concreteFactory = concreteFactory;
}
public virtual TContract Create(
TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8, TParam9 param9, TParam10 param10)
{
return _concreteFactory.Create(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10);
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V10.Services
{
/// <summary>Settings for <see cref="AssetGroupServiceClient"/> instances.</summary>
public sealed partial class AssetGroupServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AssetGroupServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AssetGroupServiceSettings"/>.</returns>
public static AssetGroupServiceSettings GetDefault() => new AssetGroupServiceSettings();
/// <summary>Constructs a new <see cref="AssetGroupServiceSettings"/> object with default settings.</summary>
public AssetGroupServiceSettings()
{
}
private AssetGroupServiceSettings(AssetGroupServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateAssetGroupsSettings = existing.MutateAssetGroupsSettings;
OnCopy(existing);
}
partial void OnCopy(AssetGroupServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AssetGroupServiceClient.MutateAssetGroups</c> and <c>AssetGroupServiceClient.MutateAssetGroupsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateAssetGroupsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="AssetGroupServiceSettings"/> object.</returns>
public AssetGroupServiceSettings Clone() => new AssetGroupServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AssetGroupServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
internal sealed partial class AssetGroupServiceClientBuilder : gaxgrpc::ClientBuilderBase<AssetGroupServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AssetGroupServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AssetGroupServiceClientBuilder()
{
UseJwtAccessWithScopes = AssetGroupServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AssetGroupServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AssetGroupServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AssetGroupServiceClient Build()
{
AssetGroupServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AssetGroupServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AssetGroupServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AssetGroupServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AssetGroupServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AssetGroupServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AssetGroupServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AssetGroupServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AssetGroupServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AssetGroupServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>AssetGroupService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage asset group
/// </remarks>
public abstract partial class AssetGroupServiceClient
{
/// <summary>
/// The default endpoint for the AssetGroupService service, which is a host of "googleads.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default AssetGroupService scopes.</summary>
/// <remarks>
/// The default AssetGroupService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="AssetGroupServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="AssetGroupServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AssetGroupServiceClient"/>.</returns>
public static stt::Task<AssetGroupServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AssetGroupServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AssetGroupServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="AssetGroupServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AssetGroupServiceClient"/>.</returns>
public static AssetGroupServiceClient Create() => new AssetGroupServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AssetGroupServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="AssetGroupServiceSettings"/>.</param>
/// <returns>The created <see cref="AssetGroupServiceClient"/>.</returns>
internal static AssetGroupServiceClient Create(grpccore::CallInvoker callInvoker, AssetGroupServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AssetGroupService.AssetGroupServiceClient grpcClient = new AssetGroupService.AssetGroupServiceClient(callInvoker);
return new AssetGroupServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC AssetGroupService client</summary>
public virtual AssetGroupService.AssetGroupServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes asset groups. Operation statuses are
/// returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAssetGroupsResponse MutateAssetGroups(MutateAssetGroupsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes asset groups. Operation statuses are
/// returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAssetGroupsResponse> MutateAssetGroupsAsync(MutateAssetGroupsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes asset groups. Operation statuses are
/// returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAssetGroupsResponse> MutateAssetGroupsAsync(MutateAssetGroupsRequest request, st::CancellationToken cancellationToken) =>
MutateAssetGroupsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates or removes asset groups. Operation statuses are
/// returned.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose asset groups are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual asset groups.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAssetGroupsResponse MutateAssetGroups(string customerId, scg::IEnumerable<AssetGroupOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAssetGroups(new MutateAssetGroupsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates or removes asset groups. Operation statuses are
/// returned.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose asset groups are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual asset groups.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAssetGroupsResponse> MutateAssetGroupsAsync(string customerId, scg::IEnumerable<AssetGroupOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAssetGroupsAsync(new MutateAssetGroupsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates or removes asset groups. Operation statuses are
/// returned.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose asset groups are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual asset groups.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateAssetGroupsResponse> MutateAssetGroupsAsync(string customerId, scg::IEnumerable<AssetGroupOperation> operations, st::CancellationToken cancellationToken) =>
MutateAssetGroupsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AssetGroupService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage asset group
/// </remarks>
public sealed partial class AssetGroupServiceClientImpl : AssetGroupServiceClient
{
private readonly gaxgrpc::ApiCall<MutateAssetGroupsRequest, MutateAssetGroupsResponse> _callMutateAssetGroups;
/// <summary>
/// Constructs a client wrapper for the AssetGroupService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="AssetGroupServiceSettings"/> used within this client.</param>
public AssetGroupServiceClientImpl(AssetGroupService.AssetGroupServiceClient grpcClient, AssetGroupServiceSettings settings)
{
GrpcClient = grpcClient;
AssetGroupServiceSettings effectiveSettings = settings ?? AssetGroupServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateAssetGroups = clientHelper.BuildApiCall<MutateAssetGroupsRequest, MutateAssetGroupsResponse>(grpcClient.MutateAssetGroupsAsync, grpcClient.MutateAssetGroups, effectiveSettings.MutateAssetGroupsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAssetGroups);
Modify_MutateAssetGroupsApiCall(ref _callMutateAssetGroups);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_MutateAssetGroupsApiCall(ref gaxgrpc::ApiCall<MutateAssetGroupsRequest, MutateAssetGroupsResponse> call);
partial void OnConstruction(AssetGroupService.AssetGroupServiceClient grpcClient, AssetGroupServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AssetGroupService client</summary>
public override AssetGroupService.AssetGroupServiceClient GrpcClient { get; }
partial void Modify_MutateAssetGroupsRequest(ref MutateAssetGroupsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates, updates or removes asset groups. Operation statuses are
/// returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateAssetGroupsResponse MutateAssetGroups(MutateAssetGroupsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAssetGroupsRequest(ref request, ref callSettings);
return _callMutateAssetGroups.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates or removes asset groups. Operation statuses are
/// returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateAssetGroupsResponse> MutateAssetGroupsAsync(MutateAssetGroupsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAssetGroupsRequest(ref request, ref callSettings);
return _callMutateAssetGroups.Async(request, callSettings);
}
}
}
| |
// 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.Globalization;
using Xunit;
namespace System.Tests
{
public class Int16Tests
{
[Fact]
public static void Ctor_Empty()
{
var i = new short();
Assert.Equal(0, i);
}
[Fact]
public static void Ctor_Value()
{
short i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0x7FFF, short.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(unchecked((short)0x8000), short.MinValue);
}
[Theory]
[InlineData((short)234, (short)234, 0)]
[InlineData((short)234, short.MinValue, 1)]
[InlineData((short)234, (short)-123, 1)]
[InlineData((short)234, (short)0, 1)]
[InlineData((short)234, (short)123, 1)]
[InlineData((short)234, (short)456, -1)]
[InlineData((short)234, short.MaxValue, -1)]
[InlineData((short)-234, (short)-234, 0)]
[InlineData((short)-234, (short)234, -1)]
[InlineData((short)-234, (short)-432, 1)]
[InlineData((short)234, null, 1)]
public void CompareTo_Other_ReturnsExpected(short i, object value, int expected)
{
if (value is short shortValue)
{
Assert.Equal(expected, Math.Sign(i.CompareTo(shortValue)));
}
Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
[Theory]
[InlineData("a")]
[InlineData(234)]
public void CompareTo_ObjectNotShort_ThrowsArgumentException(object value)
{
AssertExtensions.Throws<ArgumentException>(null, () => ((short)123).CompareTo(value));
}
[Theory]
[InlineData((short)789, (short)789, true)]
[InlineData((short)789, (short)-789, false)]
[InlineData((short)789, (short)0, false)]
[InlineData((short)0, (short)0, true)]
[InlineData((short)-789, (short)-789, true)]
[InlineData((short)-789, (short)789, false)]
[InlineData((short)789, null, false)]
[InlineData((short)789, "789", false)]
[InlineData((short)789, 789, false)]
public static void Equals(short i1, object obj, bool expected)
{
if (obj is short)
{
short i2 = (short)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
}
Assert.Equal(expected, i1.Equals(obj));
}
[Fact]
public void GetTypeCode_Invoke_ReturnsInt16()
{
Assert.Equal(TypeCode.Int16, ((short)1).GetTypeCode());
}
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
yield return new object[] { short.MinValue, "G", emptyFormat, "-32768" };
yield return new object[] { (short)-4567, "G", emptyFormat, "-4567" };
yield return new object[] { (short)0, "G", emptyFormat, "0" };
yield return new object[] { (short)4567, "G", emptyFormat, "4567" };
yield return new object[] { short.MaxValue, "G", emptyFormat, "32767" };
yield return new object[] { (short)0x2468, "x", emptyFormat, "2468" };
yield return new object[] { (short)-0x2468, "x", emptyFormat, "DB98" };
yield return new object[] { (short)2468, "N", emptyFormat, string.Format("{0:N}", 2468.00) };
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.NegativeSign = "#";
customFormat.NumberDecimalSeparator = "~";
customFormat.NumberGroupSeparator = "*";
yield return new object[] { (short)-2468, "N", customFormat, "#2*468~00" };
yield return new object[] { (short)2468, "N", customFormat, "2*468~00" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(short i, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
short i = 123;
Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo emptyFormat = new NumberFormatInfo();
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
yield return new object[] { "-32768", defaultStyle, null, (short)-32768 };
yield return new object[] { "-123", defaultStyle, null, (short)-123 };
yield return new object[] { "0", defaultStyle, null, (short)0 };
yield return new object[] { "123", defaultStyle, null, (short)123 };
yield return new object[] { "+123", defaultStyle, null, (short)123 };
yield return new object[] { " 123 ", defaultStyle, null, (short)123 };
yield return new object[] { "32767", defaultStyle, null, (short)32767 };
yield return new object[] { "123", NumberStyles.HexNumber, null, (short)0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, null, (short)0xabc };
yield return new object[] { "ABC", NumberStyles.HexNumber, null, (short)0xabc };
yield return new object[] { "1000", NumberStyles.AllowThousands, null, (short)1000 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, (short)-123 }; // Parentheses = negative
yield return new object[] { "123", defaultStyle, emptyFormat, (short)123 };
yield return new object[] { "123", NumberStyles.Any, emptyFormat, (short)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (short)0x12 };
yield return new object[] { "$1,000", NumberStyles.Currency, customFormat, (short)1000 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse(string value, NumberStyles style, IFormatProvider provider, short expected)
{
short result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.True(short.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, short.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Equal(expected, short.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.True(short.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Equal(expected, short.Parse(value, style));
}
Assert.Equal(expected, short.Parse(value, style, provider ?? new NumberFormatInfo()));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
customFormat.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, null, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "abc", defaultStyle, null, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, null, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, null, typeof(FormatException) }; // Parentheses
yield return new object[] { 1000.ToString("C0"), defaultStyle, null, typeof(FormatException) }; // Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, null, typeof(FormatException) }; // Thousands
yield return new object[] { 678.90.ToString("F2"), defaultStyle, null, typeof(FormatException) }; // Decimal
yield return new object[] { "+-123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "-+123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "- 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+ 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) }; // Hex value
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "67.90", defaultStyle, customFormat, typeof(FormatException) }; // Decimal
yield return new object[] { "-32769", defaultStyle, null, typeof(OverflowException) }; // < min value
yield return new object[] { "32768", defaultStyle, null, typeof(OverflowException) }; // > max value
yield return new object[] { "2147483648", defaultStyle, null, typeof(OverflowException) }; // Internally, Parse pretends we are inputting an Int32, so this overflows
yield return new object[] { "FFFFFFFF", NumberStyles.HexNumber, null, typeof(OverflowException) }; // Hex number < 0
yield return new object[] { "10000", NumberStyles.HexNumber, null, typeof(OverflowException) }; // Hex number > max value
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
short result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.False(short.TryParse(value, out result));
Assert.Equal(default(short), result);
Assert.Throws(exceptionType, () => short.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Throws(exceptionType, () => short.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.False(short.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(default(short), result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Throws(exceptionType, () => short.Parse(value, style));
}
Assert.Throws(exceptionType, () => short.Parse(value, style, provider ?? new NumberFormatInfo()));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName)
{
short result = 0;
AssertExtensions.Throws<ArgumentException>(paramName, () => short.TryParse("1", style, null, out result));
Assert.Equal(default(short), result);
AssertExtensions.Throws<ArgumentException>(paramName, () => short.Parse("1", style));
AssertExtensions.Throws<ArgumentException>(paramName, () => short.Parse("1", style, null));
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using Kudu.SiteManagement.Configuration;
using Kudu.SiteManagement.Configuration.Section;
using Kudu.SiteManagement.Test.Configuration.Fakes;
using Xunit;
namespace Kudu.SiteManagement.Test.Configuration
{
public class KuduConfigurationFacts
{
[Fact]
public void BasicAuthCredential_NoConfiguration_ReturnDefaultCredential()
{
var appSettingsFake = new NameValueCollection();
IKuduConfiguration config = CreateConfiguration(null, appSettingsFake);
var defaultCredential = new NetworkCredential("admin", "kudu");
var configCredentials = (NetworkCredential)config.BasicAuthCredential.GetCredentials();
Assert.Equal(defaultCredential.UserName, configCredentials.UserName);
Assert.Equal(defaultCredential.Password, configCredentials.Password);
}
[Fact]
public void BasicAuthCredential_WithConfigurationSection_ReturnBasicAuthCredentialProvider()
{
var configFake = new KuduConfigurationSectionFake();
configFake.SetFake("basicAuth", BasicAuthConfigurationElementFake.Fake("testingUser", "testingPw"));
IKuduConfiguration config = CreateConfiguration(configFake, new NameValueCollection());
var testingCredential = new NetworkCredential("testingUser", "testingPw");
var configCredentials = (NetworkCredential)config.BasicAuthCredential.GetCredentials();
Assert.Equal(testingCredential.UserName, configCredentials.UserName);
Assert.Equal(testingCredential.Password, configCredentials.Password);
}
[Fact]
public void CustomHostNamesEnabled_NoConfiguration_DefaultsToFalse()
{
var appSettingsFake = new NameValueCollection();
IKuduConfiguration config = CreateConfiguration(null, appSettingsFake);
Assert.Equal(false, config.CustomHostNamesEnabled);
}
[Fact]
public void CustomHostNamesEnabled_WithoutConfigurationSection_ReturnsLegacySetting()
{
var appSettingsFake = new NameValueCollection();
appSettingsFake.Add("enableCustomHostNames", "true");
IKuduConfiguration config = CreateConfiguration(null, appSettingsFake);
Assert.Equal(true, config.CustomHostNamesEnabled);
}
[Fact]
public void CustomHostNamesEnabled_WithoutConfigurationSectionInvalid_ReturnsFalse()
{
var appSettingsFake = new NameValueCollection();
appSettingsFake.Add("enableCustomHostNames", "fubar");
IKuduConfiguration config = CreateConfiguration(null, appSettingsFake);
Assert.Equal(false, config.CustomHostNamesEnabled);
}
[Fact]
public void CustomHostNamesEnabled_WithConfigurationSectionTrue_ReturnsTrue()
{
var configFake = new KuduConfigurationSectionFake();
configFake.SetFake("enableCustomHostNames", true);
IKuduConfiguration config = CreateConfiguration(configFake, new NameValueCollection());
Assert.Equal(true, config.CustomHostNamesEnabled);
}
[Fact]
public void ApplicationsPath_WithoutConfigurationSection_ReturnsCombinedPathUsingLegacySeeting()
{
var appSettingsFake = new NameValueCollection();
appSettingsFake.Add("sitesPath", ".\\sitespath");
IKuduConfiguration config = CreateConfiguration(null, appSettingsFake);
string expected = Path.GetFullPath(".\\root_path\\sitespath");
Assert.Equal(expected, config.ApplicationsPath);
}
[Fact]
public void ApplicationsPath_WithConfigurationSection_ReturnsCombinedPath()
{
var configFake = new KuduConfigurationSectionFake();
configFake.SetFake("applications", PathConfigurationElementFake.Fake("path", ".\\sitespath"));
IKuduConfiguration config = CreateConfiguration(configFake, new NameValueCollection());
string expected = Path.GetFullPath(".\\root_path\\sitespath");
Assert.Equal(expected, config.ApplicationsPath);
}
[Fact]
public void ServiceSitePath_WithoutConfigurationSection_ReturnsCombinedPathUsingLegacySeeting()
{
var appSettingsFake = new NameValueCollection();
appSettingsFake.Add("serviceSitePath", ".\\servicepath");
IKuduConfiguration config = CreateConfiguration(null, appSettingsFake);
string expected = Path.GetFullPath(".\\root_path\\servicepath");
Assert.Equal(expected, config.ServiceSitePath);
}
[Fact]
public void ServiceSitePath_WithConfigurationSection_ReturnsSetting()
{
var configFake = new KuduConfigurationSectionFake();
configFake.SetFake("serviceSite", PathConfigurationElementFake.Fake("path", ".\\servicepath"));
IKuduConfiguration config = CreateConfiguration(configFake, new NameValueCollection());
string expected = Path.GetFullPath(".\\root_path\\servicepath");
Assert.Equal(expected, config.ServiceSitePath);
}
[Fact]
public void Bindings_LegacyApplicationBinding_MapsToBindingConfiguration()
{
var appSettingsFake = new NameValueCollection();
appSettingsFake.Add("urlBaseValue", "kudu.domain.com");
IKuduConfiguration config = CreateConfiguration(null, appSettingsFake);
Assert.Equal(1, config.Bindings.Count());
Assert.Equal(UriScheme.Http, config.Bindings.First().Scheme);
Assert.Equal("kudu.domain.com", config.Bindings.First().Url);
Assert.Equal(SiteType.Live, config.Bindings.First().SiteType);
}
[Fact]
public void Bindings_LegacyServiceBinding_MapsToBindingConfiguration()
{
var appSettingsFake = new NameValueCollection();
appSettingsFake.Add("serviceUrlBaseValue", "kudu.svc.domain.com");
IKuduConfiguration config = CreateConfiguration(null, appSettingsFake);
Assert.Equal(1, config.Bindings.Count());
Assert.Equal(UriScheme.Http, config.Bindings.First().Scheme);
Assert.Equal("kudu.svc.domain.com", config.Bindings.First().Url);
Assert.Equal(SiteType.Service, config.Bindings.First().SiteType);
}
[Fact]
public void Bindings_SingleApplicationBinding_MapsToBindingConfiguration()
{
var configFake = new KuduConfigurationSectionFake();
var bindingsFake = new BindingsConfigurationElementCollectionFake();
bindingsFake.AddFake(new ApplicationBindingConfigurationElementFake()
.SetFake("scheme", UriScheme.Http)
.SetFake("url", "kudu.domain.com"));
configFake.SetFake("bindings", bindingsFake);
IKuduConfiguration config = CreateConfiguration(configFake, new NameValueCollection());
Assert.Equal(1, config.Bindings.Count());
Assert.Equal(UriScheme.Http, config.Bindings.First().Scheme);
Assert.Equal("kudu.domain.com", config.Bindings.First().Url);
Assert.Equal(SiteType.Live, config.Bindings.First().SiteType);
}
[Fact]
public void Bindings_SingleServiceBinding_MapsToBindingConfiguration()
{
var configFake = new KuduConfigurationSectionFake();
var bindingsFake = new BindingsConfigurationElementCollectionFake();
bindingsFake.AddFake(new ServiceBindingConfigurationElementFake()
.SetFake("scheme", UriScheme.Http)
.SetFake("url", "kudu.svc.domain.com"));
configFake.SetFake("bindings", bindingsFake);
IKuduConfiguration config = CreateConfiguration(configFake, new NameValueCollection());
Assert.Equal(1, config.Bindings.Count());
Assert.Equal(UriScheme.Http, config.Bindings.First().Scheme);
Assert.Equal("kudu.svc.domain.com", config.Bindings.First().Url);
Assert.Equal(SiteType.Service, config.Bindings.First().SiteType);
}
[Fact]
public void CertificateStores_WithoutStoresConfiguration_DefaultsToSingleStoreMy()
{
IKuduConfiguration config = CreateConfiguration(null, new NameValueCollection());
Assert.Equal(StoreName.My, config.CertificateStores.Single().Name);
}
[Fact]
public void CertificateStores_WithEmptyConfigurationSection_DefaultsToSingleStoreMy()
{
var configFake = new KuduConfigurationSectionFake();
var storesFake = new CertificateStoresConfigurationElementCollectionFake();
configFake.SetFake("certificateStores", storesFake);
IKuduConfiguration config = CreateConfiguration(configFake, new NameValueCollection());
Assert.Equal(StoreName.My, config.CertificateStores.Single().Name);
}
[Fact]
public void CertificateStores_WithSingleElement_ConstainsSingleItem()
{
var configFake = new KuduConfigurationSectionFake();
var storesFake = new CertificateStoresConfigurationElementCollectionFake();
storesFake.Add(new CertificateStoreConfigurationElementFake()
.SetFake("name", StoreName.Root));
configFake.SetFake("certificateStores", storesFake);
IKuduConfiguration config = CreateConfiguration(configFake, new NameValueCollection());
Assert.Equal(StoreName.Root, config.CertificateStores.Single().Name);
}
[Fact]
public void CertificateStores_WithMultipleElements_ConstainsSingleItem()
{
var configFake = new KuduConfigurationSectionFake();
var storesFake = new CertificateStoresConfigurationElementCollectionFake();
storesFake.Add(new CertificateStoreConfigurationElementFake()
.SetFake("name", StoreName.Root));
storesFake.Add(new CertificateStoreConfigurationElementFake()
.SetFake("name", StoreName.My));
configFake.SetFake("certificateStores", storesFake);
IKuduConfiguration config = CreateConfiguration(configFake, new NameValueCollection());
Assert.Equal(2, config.CertificateStores.Count());
Assert.Equal(StoreName.Root, config.CertificateStores.ElementAt(0).Name);
Assert.Equal(StoreName.My, config.CertificateStores.ElementAt(1).Name);
}
private IKuduConfiguration CreateConfiguration(KuduConfigurationSectionFake configFake, NameValueCollection appSettingsFake)
{
Type type = typeof(KuduConfiguration);
ConstructorInfo ctor = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null,
new[] { typeof(string), typeof(KuduConfigurationSection), typeof(NameValueCollection) }, null);
return (IKuduConfiguration)ctor.Invoke(new object[] { "root_path", configFake, appSettingsFake });
}
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;
namespace EdiEngine.Standards.X12_004010.Maps
{
public class M_273 : MapLoop
{
public M_273() : base(null)
{
Content.AddRange(new MapBaseEntity[] {
new BGN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new UD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_NM1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new L_ACT(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
});
}
//1000
public class L_NM1 : MapLoop
{
public L_NM1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
});
}
}
//2000
public class L_ACT : MapLoop
{
public L_ACT(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new ACT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new UD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 19 },
new BLI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new K3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new L_LX(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 },
new L_MSG(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2100
public class L_LX : MapLoop
{
public L_LX(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new BLI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new INV() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new UD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new M1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new RPA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new K3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new L_BEN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_ENT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2110
public class L_BEN : MapLoop
{
public L_BEN(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new BEN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2120
public class L_ENT : MapLoop
{
public L_ENT(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new ENT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DMA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new REL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new UD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new K3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new L_LQ(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_BEN_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new L_BLI(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2121
public class L_LQ : MapLoop
{
public L_LQ(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LQ() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new V9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new K3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new L_NM1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2122
public class L_NM1_1 : MapLoop
{
public L_NM1_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new G61() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
});
}
}
//2125
public class L_BEN_1 : MapLoop
{
public L_BEN_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new BEN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2126
public class L_BLI : MapLoop
{
public L_BLI(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new BLI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new INV() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new UD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new UDA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new M1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9 },
new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new RPA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
new K3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 },
new L_BEN_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
});
}
}
//2127
public class L_BEN_2 : MapLoop
{
public L_BEN_2(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new BEN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2200
public class L_MSG : MapLoop
{
public L_MSG(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new MSG() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new NM1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
/// <summary>
/// StringBuilder.Length Property
/// Gets or sets the length of this instance.
/// </summary>
public class StringBuilderLength
{
private const int c_MIN_STR_LEN = 1;
private const int c_MAX_STR_LEN = 260;
private const int c_MAX_CAPACITY = Int16.MaxValue;
public static int Main()
{
StringBuilderLength testObj = new StringBuilderLength();
TestLibrary.TestFramework.BeginTestCase("for property: StringBuilder.Length");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_ID = "P001";
const string c_TEST_DESC = "PosTest1: Get the Length property";
string errorDesc;
StringBuilder sb;
int actualLength, expectedLength;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
sb = new StringBuilder(str);
expectedLength = str.Length;
actualLength = sb.Length;
if (actualLength != expectedLength)
{
errorDesc = "Length of current StringBuilder " + sb + " is not the value ";
errorDesc += string.Format("{0} as expected: actual({1})", expectedLength, actualLength);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_ID = "P002";
const string c_TEST_DESC = "PosTest2: Set the Length property";
string errorDesc;
StringBuilder sb;
int actualLength, expectedLength;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
sb = new StringBuilder(str);
expectedLength = TestLibrary.Generator.GetInt32(-55) % c_MAX_STR_LEN + 1;
sb.Length = expectedLength;
actualLength = sb.Length;
if (actualLength != expectedLength)
{
errorDesc = "Length of current StringBuilder " + sb + " is not the value ";
errorDesc += string.Format("{0} as expected: actual({1})", expectedLength, actualLength);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//ArgumentOutOfRangeException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: The value specified for a set operation is less than zero.";
string errorDesc;
StringBuilder sb;
int length;
string str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
sb = new StringBuilder(str);
length = -1 * TestLibrary.Generator.GetInt32(-55) - 1;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
sb.Length = length;
errorDesc = "ArgumentOutOfRangeException is not thrown as expected.";
errorDesc += string.Format("\nLength specified is {0}", length);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nLength specified is {0}", length);
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: The value specified for a set operation is greater than MaxCapacity.";
string errorDesc;
StringBuilder sb;
int length;
sb = new StringBuilder(0, c_MAX_CAPACITY);
length = c_MAX_CAPACITY + 1 +
TestLibrary.Generator.GetInt32(-55) % (int.MaxValue - c_MAX_CAPACITY);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
sb.Length = length;
errorDesc = "ArgumentOutOfRangeException is not thrown as expected.";
errorDesc += string.Format("\nLength specified is {0}", length);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nLength specified is {0}", length);
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| |
// ReSharper disable RedundantArgumentDefaultValue
namespace Gu.State.Tests.CopyTests
{
using System;
using NUnit.Framework;
using static CopyTypes;
public abstract class ClassesTests
{
public abstract void CopyMethod<T>(
T source,
T target,
ReferenceHandling referenceHandling = ReferenceHandling.Structural,
string excluded = null,
Type ignoredType = null,
Type immutableType = null)
where T : class;
[TestCase(ReferenceHandling.Throw)]
[TestCase(ReferenceHandling.Structural)]
[TestCase(ReferenceHandling.References)]
public void WithSimpleHappyPath(ReferenceHandling referenceHandling)
{
var source = new WithSimpleProperties(1, 2, "3", StringSplitOptions.RemoveEmptyEntries);
var target = new WithSimpleProperties { IntValue = 3, NullableIntValue = 4 };
this.CopyMethod(source, target, referenceHandling);
Assert.AreEqual(1, source.IntValue);
Assert.AreEqual(1, target.IntValue);
Assert.AreEqual(2, source.NullableIntValue);
Assert.AreEqual(2, target.NullableIntValue);
Assert.AreEqual("3", source.StringValue);
Assert.AreEqual("3", target.StringValue);
Assert.AreEqual(StringSplitOptions.RemoveEmptyEntries, source.EnumValue);
Assert.AreEqual(StringSplitOptions.RemoveEmptyEntries, target.EnumValue);
}
[Test]
public void WithExplitImmutable()
{
var source = new WithComplexProperty
{
Name = "a",
Value = 1,
ComplexType = new ComplexType { Name = "b", Value = 2 },
};
var target = new WithComplexProperty();
this.CopyMethod(source, target, ReferenceHandling.Structural, immutableType: typeof(ComplexType));
Assert.AreEqual(source.Name, target.Name);
Assert.AreEqual(source.Value, target.Value);
Assert.AreSame(source.ComplexType, target.ComplexType);
}
[Test]
public void WithComplexStructuralHappyPath()
{
var source = new WithComplexProperty
{
Name = "a",
Value = 1,
ComplexType = new ComplexType { Name = "b", Value = 2 },
};
var target = new WithComplexProperty();
this.CopyMethod(source, target, ReferenceHandling.Structural);
Assert.AreEqual(source.Name, target.Name);
Assert.AreEqual(source.Value, target.Value);
Assert.AreEqual(source.ComplexType.Name, target.ComplexType.Name);
Assert.AreEqual(source.ComplexType.Value, target.ComplexType.Value);
}
[Test]
public void WithComplexStructuralHappyPathWhenTargetMemberIsNull()
{
var source = new WithComplexProperty { Name = "a", Value = 1 };
var target = new WithComplexProperty();
this.CopyMethod(source, target, ReferenceHandling.Structural);
Assert.AreEqual(source.Name, target.Name);
Assert.AreEqual(source.Value, target.Value);
Assert.IsNull(source.ComplexType);
Assert.IsNull(target.ComplexType);
}
[Test]
public void WithComplexReferenceHappyPath()
{
var source = new WithComplexProperty
{
Name = "a",
Value = 1,
ComplexType = new ComplexType { Name = "b", Value = 2 },
};
var target = new WithComplexProperty();
this.CopyMethod(source, target, ReferenceHandling.References);
Assert.AreEqual(source.Name, target.Name);
Assert.AreEqual(source.Value, target.Value);
Assert.AreSame(source.ComplexType, target.ComplexType);
}
[Test]
public void WithComplexReferenceHappyPathSourceMemberIsNull()
{
var source = new WithComplexProperty { Name = "a", Value = 1 };
var target = new WithComplexProperty();
this.CopyMethod(source, target, ReferenceHandling.References);
Assert.AreEqual(source.Name, target.Name);
Assert.AreEqual(source.Value, target.Value);
Assert.IsNull(source.ComplexType);
Assert.IsNull(target.ComplexType);
}
[Test]
public void WithComplexReferenceHappyPathTargetMemberIsNull()
{
var source = new WithComplexProperty { Name = "a", Value = 1 };
var target = new WithComplexProperty { ComplexType = new ComplexType("b", 1) };
this.CopyMethod(source, target, ReferenceHandling.References);
Assert.AreEqual(source.Name, target.Name);
Assert.AreEqual(source.Value, target.Value);
Assert.IsNull(source.ComplexType);
Assert.IsNull(target.ComplexType);
}
[Test]
public void WithInheritanceWhenSameType()
{
var source = new With<BaseClass> { Value = new Derived1 { BaseValue = 1, Derived1Value = 2 } };
var target = new With<BaseClass>();
Copy.PropertyValues(source, target, ReferenceHandling.Structural);
Assert.IsInstanceOf<Derived1>(source.Value);
Assert.IsInstanceOf<Derived1>(target.Value);
Assert.AreEqual(1, source.Value.BaseValue);
Assert.AreEqual(1, target.Value.BaseValue);
Assert.AreEqual(2, ((Derived1)source.Value).Derived1Value);
Assert.AreEqual(2, ((Derived1)target.Value).Derived1Value);
}
[Test]
public void WithInheritanceWhenDifferentTypes()
{
var source = new With<BaseClass> { Value = new Derived1 { BaseValue = 1, Derived1Value = 2 } };
var target = new With<BaseClass> { Value = new Derived2() };
Copy.PropertyValues(source, target, ReferenceHandling.Structural);
Assert.IsInstanceOf<Derived1>(source.Value);
Assert.IsInstanceOf<Derived1>(target.Value);
Assert.AreEqual(1, source.Value.BaseValue);
Assert.AreEqual(1, target.Value.BaseValue);
Assert.AreEqual(2, ((Derived1)source.Value).Derived1Value);
//// ReSharper disable once PossibleInvalidCastException
Assert.AreEqual(2, ((Derived1)target.Value).Derived1Value);
}
[Test]
public void WithReadonlyHappyPath()
{
var x = new WithReadonlyProperty<int>(1);
var y = new WithReadonlyProperty<int>(1);
this.CopyMethod(x, y);
Assert.AreEqual(1, x.Value);
Assert.AreEqual(1, y.Value);
}
[Test]
public void WithReadonlyComplex()
{
var source = new WithReadonlyProperty<ComplexType>(new ComplexType("a", 1));
var target = new WithReadonlyProperty<ComplexType>(new ComplexType("b", 2));
this.CopyMethod(source, target, ReferenceHandling.Structural);
Assert.AreEqual("a", source.Value.Name);
Assert.AreEqual("a", target.Value.Name);
Assert.AreEqual(1, source.Value.Value);
Assert.AreEqual(1, target.Value.Value);
}
[TestCase(null)]
[TestCase(ReferenceHandling.Throw)]
[TestCase(ReferenceHandling.Structural)]
[TestCase(ReferenceHandling.References)]
public void WithImmutableStructural(ReferenceHandling? referenceHandling)
{
var source = new With<Immutable>(new Immutable(1));
var target = new With<Immutable>(new Immutable(2));
if (referenceHandling is null)
{
this.CopyMethod(source, target);
}
else
{
this.CopyMethod(source, target, referenceHandling.Value);
}
Assert.AreEqual(1, source.Value.Value);
Assert.AreEqual(1, target.Value.Value);
Assert.AreSame(source.Value, target.Value);
}
[Test]
public void WithListOfIntsToEmpty()
{
var source = new WithListProperty<int>();
source.Items.AddRange(new[] { 1, 2, 3 });
var target = new WithListProperty<int>();
this.CopyMethod(source, target, ReferenceHandling.Structural);
CollectionAssert.AreEqual(source.Items, target.Items);
}
[TestCase(ReferenceHandling.Structural)]
[TestCase(ReferenceHandling.References)]
public void WithArrayWhenTargetArrayIsNullStructural(ReferenceHandling referenceHandling)
{
var source = new WithArrayProperty("a", 1, new[] { 1, 2 });
var target = new WithArrayProperty("a", 1, null);
this.CopyMethod(source, target, referenceHandling);
Assert.AreEqual("a", source.Name);
Assert.AreEqual("a", target.Name);
Assert.AreEqual(1, source.Value);
Assert.AreEqual(1, target.Value);
if (referenceHandling == ReferenceHandling.Structural)
{
Assert.AreNotSame(source.Array, target.Array);
}
else
{
Assert.AreSame(source.Array, target.Array);
}
CollectionAssert.AreEqual(new[] { 1, 2 }, source.Array);
CollectionAssert.AreEqual(new[] { 1, 2 }, target.Array);
}
[Test]
public void WithArrayWhenTargetArrayIsNullReference()
{
var source = new WithArrayProperty("a", 1, new[] { 1, 2 });
var target = new WithArrayProperty("a", 1, null);
this.CopyMethod(source, target, ReferenceHandling.References);
Assert.AreEqual("a", source.Name);
Assert.AreEqual("a", target.Name);
Assert.AreEqual(1, source.Value);
Assert.AreEqual(1, target.Value);
Assert.AreSame(source.Array, target.Array);
CollectionAssert.AreEqual(new[] { 1, 2 }, source.Array);
}
[Test]
public void WithListOfIntsPropertyToLonger()
{
var source = new WithListProperty<int>();
source.Items.AddRange(new[] { 1, 2, 3 });
var target = new WithListProperty<int>();
target.Items.AddRange(new[] { 1, 2, 3, 4 });
this.CopyMethod(source, target, ReferenceHandling.Structural);
CollectionAssert.AreEqual(source.Items, target.Items);
}
[Test]
public void WithListOfComplexPropertyToEmptyStructural()
{
var source = new WithListProperty<ComplexType>();
source.Items.Add(new ComplexType("a", 1));
var target = new WithListProperty<ComplexType>();
this.CopyMethod(source, target, ReferenceHandling.Structural);
var expected = new[] { new ComplexType("a", 1) };
CollectionAssert.AreEqual(expected, source.Items, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target.Items, ComplexType.Comparer);
Assert.AreNotSame(source.Items[0], target.Items[0]);
}
[Test]
public void WithListOfComplexPropertyToEmptyReference()
{
var source = new WithListProperty<ComplexType>();
source.Items.Add(new ComplexType("a", 1));
var target = new WithListProperty<ComplexType>();
this.CopyMethod(source, target, ReferenceHandling.References);
var expected = new[] { new ComplexType("a", 1) };
CollectionAssert.AreEqual(expected, source.Items, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target.Items, ComplexType.Comparer);
Assert.AreSame(source.Items[0], target.Items[0]);
}
[Test]
public void WithListOfComplexPropertyToLonger()
{
var source = new WithListProperty<ComplexType>();
source.Items.Add(new ComplexType("a", 1));
var target = new WithListProperty<ComplexType>();
target.Items.AddRange(new[] { new ComplexType("b", 2), new ComplexType("c", 3) });
var item = target.Items[0];
this.CopyMethod(source, target, ReferenceHandling.Structural);
var expected = new[] { new ComplexType("a", 1) };
CollectionAssert.AreEqual(expected, source.Items, ComplexType.Comparer);
CollectionAssert.AreEqual(expected, target.Items, ComplexType.Comparer);
Assert.AreSame(item, target.Items[0]);
}
[Test]
public void Ignores()
{
var source = new WithSimpleProperties { IntValue = 1, NullableIntValue = 2, StringValue = "3", EnumValue = StringSplitOptions.RemoveEmptyEntries };
var target = new WithSimpleProperties { IntValue = 2, NullableIntValue = 4, StringValue = "4", EnumValue = StringSplitOptions.None };
var excluded = this is FieldValues.Classes
? "nullableIntValue"
: nameof(WithSimpleProperties.NullableIntValue);
this.CopyMethod(source, target, excluded: excluded);
Assert.AreEqual(1, source.IntValue);
Assert.AreEqual(1, target.IntValue);
Assert.AreEqual(2, source.NullableIntValue);
Assert.AreEqual(4, target.NullableIntValue);
Assert.AreEqual("3", source.StringValue);
Assert.AreEqual("3", target.StringValue);
Assert.AreEqual(StringSplitOptions.RemoveEmptyEntries, source.EnumValue);
Assert.AreEqual(StringSplitOptions.RemoveEmptyEntries, target.EnumValue);
}
}
}
| |
//
// Mono.Xml.XmlFilterReader.cs
//
// Author:
// Atsushi Enomoto <[email protected]>
//
// Copyright (c) 2004 Novell Inc. All rights reserved
//
// 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.
//
//
// Similar to SAX DefaultHandler
//
#if NET_2_0
using System;
using System.Collections.Generic;
using Mono.System.Xml;
using Mono.System.Xml.Schema;
namespace Mono.Xml
{
internal class XmlFilterReader : XmlReader, IXmlLineInfo, IXmlNamespaceResolver
{
XmlReader reader;
XmlReaderSettings settings;
IXmlLineInfo lineInfo;
public XmlFilterReader (XmlReader reader, XmlReaderSettings settings)
{
this.reader = reader;
this.settings = settings.Clone ();
this.lineInfo = reader as IXmlLineInfo;
}
#region Properties
#if NET_2_0
public override bool CanReadBinaryContent {
get { return reader.CanReadBinaryContent; }
}
public override bool CanReadValueChunk {
get { return reader.CanReadValueChunk; }
}
#endif
// This is the only one non-overriden property.
public XmlReader Reader {
get { return reader; }
}
public int LineNumber {
get { return lineInfo != null ? lineInfo.LineNumber : 0; }
}
public int LinePosition {
get { return lineInfo != null ? lineInfo.LinePosition : 0; }
}
public override XmlNodeType NodeType
{
get { return reader.NodeType; }
}
public override string Name {
get { return reader.Name; }
}
public override string LocalName {
get { return reader.LocalName; }
}
public override string NamespaceURI {
get { return reader.NamespaceURI; }
}
public override string Prefix {
get { return reader.Prefix; }
}
public override bool HasValue {
get { return reader.HasValue; }
}
public override int Depth {
get { return reader.Depth; }
}
public override string Value {
get { return reader.Value; }
}
public override string BaseURI {
get { return reader.BaseURI; }
}
public override bool IsEmptyElement {
get { return reader.IsEmptyElement; }
}
public override bool IsDefault {
get { return reader.IsDefault; }
}
public override char QuoteChar {
get { return reader.QuoteChar; }
}
public override string XmlLang {
get { return reader.XmlLang; }
}
public override XmlSpace XmlSpace {
get { return reader.XmlSpace; }
}
public override int AttributeCount {
get { return reader.AttributeCount; }
}
public override string this [int i] {
get { return reader [i]; }
}
public override string this [string name] {
get { return reader [name]; }
}
public override string this [string localName, string namespaceURI] {
get { return reader [localName, namespaceURI]; }
}
public override bool EOF {
get { return reader.EOF; }
}
public override ReadState ReadState {
get { return reader.ReadState; }
}
public override XmlNameTable NameTable {
get { return reader.NameTable; }
}
#if !NET_2_1
public override IXmlSchemaInfo SchemaInfo {
get { return reader.SchemaInfo; }
}
#endif
public override XmlReaderSettings Settings {
get { return settings; }
}
#endregion
#region Methods
public override string GetAttribute (string name)
{
return reader.GetAttribute (name);
}
public override string GetAttribute (string localName, string namespaceURI)
{
return reader.GetAttribute (localName, namespaceURI);
}
public override string GetAttribute (int i)
{
return reader.GetAttribute (i);
}
public bool HasLineInfo ()
{
return lineInfo != null ? lineInfo.HasLineInfo () : false;
}
public override bool MoveToAttribute (string name)
{
return reader.MoveToAttribute (name);
}
public override bool MoveToAttribute (string localName, string namespaceURI)
{
return reader.MoveToAttribute (localName, namespaceURI);
}
public override void MoveToAttribute (int i)
{
reader.MoveToAttribute (i);
}
public override bool MoveToFirstAttribute ()
{
return reader.MoveToFirstAttribute ();
}
public override bool MoveToNextAttribute ()
{
return reader.MoveToNextAttribute ();
}
public override bool MoveToElement ()
{
return reader.MoveToElement ();
}
public override void Close ()
{
if (settings.CloseInput)
reader.Close ();
}
public override bool Read ()
{
if (!reader.Read ())
return false;
if (reader.NodeType == XmlNodeType.DocumentType && settings.ProhibitDtd)
throw new XmlException ("Document Type Definition (DTD) is prohibited in this XML reader.");
if (reader.NodeType == XmlNodeType.Whitespace &&
settings.IgnoreWhitespace)
return Read ();
if (reader.NodeType == XmlNodeType.ProcessingInstruction &&
settings.IgnoreProcessingInstructions)
return Read ();
if (reader.NodeType == XmlNodeType.Comment &&
settings.IgnoreComments)
return Read ();
return true;
}
public override string ReadString ()
{
return reader.ReadString ();
}
public override string LookupNamespace (string prefix)
{
return reader.LookupNamespace (prefix);
}
public override void ResolveEntity ()
{
reader.ResolveEntity ();
}
public override bool ReadAttributeValue () {
return reader.ReadAttributeValue ();
}
string IXmlNamespaceResolver.LookupPrefix (string ns)
{
return ((IXmlNamespaceResolver) reader).LookupPrefix (ns);
}
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope (XmlNamespaceScope scope)
{
return ((IXmlNamespaceResolver) reader).GetNamespacesInScope (scope);
}
#endregion
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
namespace Orleans.Runtime
{
public class TelemetryManager : ITelemetryProducer, IDisposable
{
internal const string ObsoleteMessageTelemetry = "This method might be removed in the future in favor of a non Orleans-owned abstraction for APMs.";
private List<ITelemetryConsumer> consumers = new List<ITelemetryConsumer>();
private List<IMetricTelemetryConsumer> metricTelemetryConsumers = new List<IMetricTelemetryConsumer>();
private List<ITraceTelemetryConsumer> traceTelemetryConsumers = new List<ITraceTelemetryConsumer>();
public IEnumerable<ITelemetryConsumer> TelemetryConsumers => this.consumers;
public TelemetryManager(IServiceProvider serviceProvider, IOptions<TelemetryOptions> options)
{
var newConsumers = new List<ITelemetryConsumer>(options.Value.Consumers.Count);
foreach (var consumerType in options.Value.Consumers)
{
var consumer = GetTelemetryConsumer(serviceProvider, consumerType);
newConsumers.Add(consumer);
}
this.AddConsumers(newConsumers);
}
public void AddConsumers(IEnumerable<ITelemetryConsumer> newConsumers)
{
this.consumers = new List<ITelemetryConsumer>(this.consumers.Union(newConsumers));
this.metricTelemetryConsumers = this.consumers.OfType<IMetricTelemetryConsumer>().ToList();
this.traceTelemetryConsumers = this.consumers.OfType<ITraceTelemetryConsumer>().ToList();
}
private static ITelemetryConsumer GetTelemetryConsumer(IServiceProvider serviceProvider, Type consumerType)
{
ITelemetryConsumer consumer = null;
// first check whether it is registered in the container already
consumer = (ITelemetryConsumer)serviceProvider.GetService(consumerType);
if (consumer == null)
{
consumer = (ITelemetryConsumer)ActivatorUtilities.CreateInstance(serviceProvider, consumerType);
}
return consumer;
}
public void TrackMetric(string name, double value, IDictionary<string, string> properties = null)
{
foreach (var tc in this.metricTelemetryConsumers)
{
tc.TrackMetric(name, value, properties);
}
}
public void TrackMetric(string name, TimeSpan value, IDictionary<string, string> properties = null)
{
foreach (var tc in this.metricTelemetryConsumers)
{
tc.TrackMetric(name, value, properties);
}
}
public void IncrementMetric(string name)
{
foreach (var tc in this.metricTelemetryConsumers)
{
tc.IncrementMetric(name);
}
}
public void IncrementMetric(string name, double value)
{
foreach (var tc in this.metricTelemetryConsumers)
{
tc.IncrementMetric(name, value);
}
}
public void DecrementMetric(string name)
{
foreach (var tc in this.metricTelemetryConsumers)
{
tc.DecrementMetric(name);
}
}
public void DecrementMetric(string name, double value)
{
foreach (var tc in this.metricTelemetryConsumers)
{
tc.DecrementMetric(name, value);
}
}
public void TrackDependency(string name, string commandName, DateTimeOffset startTime, TimeSpan duration, bool success)
{
foreach (var tc in this.consumers.OfType<IDependencyTelemetryConsumer>())
{
tc.TrackDependency(name, commandName, startTime, duration, success);
}
}
public void TrackEvent(string name, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null)
{
foreach (var tc in this.consumers.OfType<IEventTelemetryConsumer>())
{
tc.TrackEvent(name, properties, metrics);
}
}
public void TrackRequest(string name, DateTimeOffset startTime, TimeSpan duration, string responseCode, bool success)
{
foreach (var tc in this.consumers.OfType<IRequestTelemetryConsumer>())
{
tc.TrackRequest(name, startTime, duration, responseCode, success);
}
}
public void TrackException(Exception exception, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null)
{
foreach (var tc in this.consumers.OfType<IExceptionTelemetryConsumer>())
{
tc.TrackException(exception, properties, metrics);
}
}
public void TrackTrace(string message)
{
foreach (var tc in this.traceTelemetryConsumers)
{
tc.TrackTrace(message);
}
}
public void TrackTrace(string message, Severity severity)
{
foreach (var tc in this.traceTelemetryConsumers)
{
tc.TrackTrace(message, severity);
}
}
public void TrackTrace(string message, Severity severity, IDictionary<string, string> properties)
{
foreach (var tc in this.traceTelemetryConsumers)
{
tc.TrackTrace(message, severity, properties);
}
}
public void TrackTrace(string message, IDictionary<string, string> properties)
{
foreach (var tc in this.traceTelemetryConsumers)
{
tc.TrackTrace(message, properties);
}
}
public void Flush()
{
List<Exception> exceptions = null;
var all = this.consumers;
foreach (var tc in all)
{
try
{
tc.Flush();
}
catch (Exception ex)
{
(exceptions ?? (exceptions = new List<Exception>())).Add(ex);
}
}
if (exceptions?.Count > 0)
{
throw new AggregateException(exceptions);
}
}
public void Close()
{
List<Exception> exceptions = null;
var all = this.consumers;
this.consumers = new List<ITelemetryConsumer>();
this.metricTelemetryConsumers = new List<IMetricTelemetryConsumer>();
this.traceTelemetryConsumers = new List<ITraceTelemetryConsumer>();
foreach (var tc in all)
{
try
{
tc.Close();
}
catch (Exception ex)
{
(exceptions ?? (exceptions = new List<Exception>())).Add(ex);
}
try
{
(tc as IDisposable)?.Dispose();
}
catch (Exception ex)
{
(exceptions ?? (exceptions = new List<Exception>())).Add(ex);
}
}
if (exceptions?.Count > 0)
{
throw new AggregateException(exceptions);
}
}
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
this.Close();
}
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~TelemetryManager() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_WEBSS
{
using System.Web.Services.Protocols;
using System.Xml;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// The adapter's implementation
/// </summary>
public partial class MS_WEBSSAdapter : ManagedAdapterBase, IMS_WEBSSAdapter
{
/// <summary>
/// SOAP service.
/// </summary>
private WebsSoap service;
#region Initialize TestSuite
/// <summary>
/// Initializes the services of MS-WEBSS with the specified transport type, soap version and user authentication provided by the test case.
/// </summary>
/// <param name="transportType">The type of the connection</param>
/// <param name="soapVersion">The soap version of the protocol message</param>
/// <param name="userAuthentication">a user authenticated</param>
/// <param name="serverRelativeUrl"> a Server related URL</param>
public void InitializeService(TransportProtocol transportType, SoapProtocolVersion soapVersion, UserAuthentication userAuthentication, string serverRelativeUrl)
{
this.service = Proxy.CreateProxy<WebsSoap>(this.Site);
this.service.SoapVersion = soapVersion;
// select transport protocol
switch (transportType)
{
case TransportProtocol.HTTP:
this.service.Url = serverRelativeUrl;
break;
default:
this.service.Url = serverRelativeUrl;
// when request URL include HTTPS prefix, avoid closing base connection.
// local client will accept all certificate after execute this function.
Common.AcceptServerCertificate();
break;
}
this.service.Credentials = AdapterHelper.ConfigureCredential(userAuthentication);
// Configure the service timeout.
int soapTimeOut = Common.GetConfigurationPropertyValue<int>("ServiceTimeOut", this.Site);
// 60000 means the configure SOAP Timeout is in minute.
this.service.Timeout = soapTimeOut * 60000;
}
/// <summary>
/// Initialize the services of WEBSS with the specified transport type, soap version and user authentication provided by the test case.
/// </summary>
/// <param name="userAuthentication">a user authenticated</param>
public void InitializeService(UserAuthentication userAuthentication)
{
SoapVersion soapVersion = Common.GetConfigurationPropertyValue<SoapVersion>("SoapVersion", this.Site);
switch (soapVersion)
{
case SoapVersion.SOAP11:
{
this.InitializeService(AdapterHelper.GetTransportType(), SoapProtocolVersion.Soap11, userAuthentication, Common.GetConfigurationPropertyValue("TargetServiceUrl", this.Site));
break;
}
default:
{
this.InitializeService(AdapterHelper.GetTransportType(), SoapProtocolVersion.Soap12, userAuthentication, Common.GetConfigurationPropertyValue("TargetServiceUrl", this.Site));
break;
}
}
}
/// <summary>
/// Overrides IAdapter's Initialize() and sets default protocol short name of the testSite.
/// </summary>
/// <param name="testSite">Transfer ITestSite into adapter, make adapter use ITestSite's function.</param>
public override void Initialize(ITestSite testSite)
{
base.Initialize(testSite);
testSite.DefaultProtocolDocShortName = "MS-WEBSS";
AdapterHelper.Initialize(testSite);
// Merge the common configuration
string conmmonConfigFileName = Common.GetConfigurationPropertyValue("CommonConfigurationFileName", this.Site);
Common.MergeGlobalConfig(conmmonConfigFileName, this.Site);
Common.CheckCommonProperties(this.Site, true);
// Merge SHOULD/MAY configuration
Common.MergeSHOULDMAYConfig(this.Site);
}
#endregion
/// <summary>
/// This operation obtains properties of the object referenced by the specified URL.
/// </summary>
/// <param name="objectUrl">The URL of the object to retrieve information.</param>
/// <returns>The Object Id of GetObjectIdFromUrl.</returns>
public GetObjectIdFromUrlResponseGetObjectIdFromUrlResult GetObjectIdFromUrl(string objectUrl)
{
GetObjectIdFromUrlResponseGetObjectIdFromUrlResult getObjectIdFromUrlResult = null;
getObjectIdFromUrlResult = this.service.GetObjectIdFromUrl(objectUrl);
this.ValidateGetObjectIdFromUrl(getObjectIdFromUrlResult);
this.CaptureTransportRelatedRequirements();
return getObjectIdFromUrlResult;
}
/// <summary>
/// This operation is used to create a new content type on the context site
/// </summary>
/// <param name="displayName">displayName means the XML encoded name of content type to be created.</param>
/// <param name="parentType">parentType is used to indicate the ID of a content type from which the content type to be created will inherit.</param>
/// <param name="newFields">newFields is the container for a list of existing fields to be included in the content type.</param>
/// <param name="contentTypeProperties">contentTypeProperties is the container for properties to set on the content type.</param>
/// <returns>The ID of Created ContentType.</returns>
public string CreateContentType(string displayName, string parentType, AddOrUpdateFieldsDefinition newFields, CreateContentTypeContentTypeProperties contentTypeProperties)
{
string contentTypeId = this.service.CreateContentType(displayName, parentType, newFields, contentTypeProperties);
this.ValidateCreateContentType();
this.CaptureTransportRelatedRequirements();
return contentTypeId;
}
/// <summary>
/// This operation is used to enable customization of the specified cascading style sheet (CSS) for the context site.
/// </summary>
/// <param name="cssFile">cssFile specifies the name of one of the CSS files that resides in the default, central location on the server.</param>
public void CustomizeCss(string cssFile)
{
try
{
this.service.CustomizeCss(cssFile);
this.CaptureTransportRelatedRequirements();
this.ValidateCustomizeCss();
}
catch (SoapException exp)
{
// Capture requirements of detail complex type.
this.ValidateDetail(exp.Detail);
this.CaptureTransportRelatedRequirements();
throw;
}
}
/// <summary>
/// This operation is used to remove a given content type from the site.
/// </summary>
/// <param name="contentTypeId">contentTypeId is the content type ID of the content type that is to be removed from the site.</param>
/// <returns>The result of DeleteContentType.</returns>
public DeleteContentTypeResponseDeleteContentTypeResult DeleteContentType(string contentTypeId)
{
DeleteContentTypeResponseDeleteContentTypeResult result = new DeleteContentTypeResponseDeleteContentTypeResult();
result = this.service.DeleteContentType(contentTypeId);
this.ValidateDeleteContentType();
this.CaptureTransportRelatedRequirements();
return result;
}
/// <summary>
/// This operation is used to get a list of activated features on the site and on the parent site collection.
/// </summary>
/// <returns>The result of GetActivedFeatures.</returns>
public string GetActivatedFeatures()
{
string result = string.Empty;
try
{
result = this.service.GetActivatedFeatures();
// Capture requirements of GetActivatedFeatures operation.
this.ValidateGetActivatedFeatures();
this.CaptureTransportRelatedRequirements();
return result;
}
catch (SoapException exp)
{
// Capture requirements of detail complex type.
this.ValidateDetail(exp.Detail);
this.CaptureTransportRelatedRequirements();
throw;
}
}
/// <summary>
/// This operation is used to get a list of the titles and URLs of all sites in the site collection.
/// </summary>
/// <returns>The result of GetAllSubWebCollection.</returns>
public GetAllSubWebCollectionResponseGetAllSubWebCollectionResult GetAllSubWebCollection()
{
GetAllSubWebCollectionResponseGetAllSubWebCollectionResult result = new GetAllSubWebCollectionResponseGetAllSubWebCollectionResult();
try
{
result = this.service.GetAllSubWebCollection();
// Capture requirements of WebDefinition complex type.
if (result.Webs.Length > 0)
{
this.ValidateWebDefinitionForSubWebCollection();
}
// Capture requirements of GetAllSubWebCollection operation.
this.ValidateGetAllSubWebCollection(result);
this.CaptureTransportRelatedRequirements();
return result;
}
catch (SoapException exp)
{
// Capture requirements of detail complex type.
this.ValidateDetail(exp.Detail);
this.CaptureTransportRelatedRequirements();
throw;
}
}
/// <summary>
/// This operation is used to get the collection of column definitions for all the columns available on the context site.
/// </summary>
/// <returns>The result of GetColumns.</returns>
public GetColumnsResponseGetColumnsResult GetColumns()
{
GetColumnsResponseGetColumnsResult getColumnsResponseGetColumnsResult = null;
getColumnsResponseGetColumnsResult = this.service.GetColumns();
this.CaptureTransportRelatedRequirements();
return getColumnsResponseGetColumnsResult;
}
/// <summary>
/// This operation is used to get the collection of column definitions for all the columns available on the context site.
/// </summary>
/// <param name="contentTypeId">contentTypeId is the ID of the content type to be returned.</param>
/// <returns>The result of GetContentType.</returns>
public GetContentTypeResponseGetContentTypeResult GetContentType(string contentTypeId)
{
GetContentTypeResponseGetContentTypeResult result = new GetContentTypeResponseGetContentTypeResult();
result = this.service.GetContentType(contentTypeId);
this.CaptureTransportRelatedRequirements();
return result;
}
/// <summary>
/// This method retrieves all content types for a given context site.
/// </summary>
/// <returns>The result of GetContentTypes.</returns>
public GetContentTypesResponseGetContentTypesResult GetContentTypes()
{
GetContentTypesResponseGetContentTypesResult result = new GetContentTypesResponseGetContentTypesResult();
result = this.service.GetContentTypes();
this.ValidateGetContentTypes();
this.CaptureTransportRelatedRequirements();
return result;
}
/// <summary>
/// This operation is used to get the customization status (also known as the ghosted status) of the specified page or file.
/// </summary>
/// <param name="fileUrl">fileUrl is the URL of a page or file on the protocol server.</param>
/// <returns>The result of GetCustomizedPageStatus.</returns>
public CustomizedPageStatus GetCustomizedPageStatus(string fileUrl)
{
CustomizedPageStatus customizedPageStatus = CustomizedPageStatus.None;
customizedPageStatus = this.service.GetCustomizedPageStatus(fileUrl);
this.ValidateGetCustomizedPageStatus(customizedPageStatus);
this.CaptureTransportRelatedRequirements();
return customizedPageStatus;
}
/// <summary>
/// This operation is used to get the collection of list template definitions for the context site.
/// </summary>
/// <returns>The result of GetListTemplates.</returns>
public GetListTemplatesResponseGetListTemplatesResult GetListTemplates()
{
GetListTemplatesResponseGetListTemplatesResult result = null;
result = this.service.GetListTemplates();
this.ValidateGetListTemplates();
this.CaptureTransportRelatedRequirements();
return result;
}
/// <summary>
/// This operation is used to get the Title, URL, Description, Language, and theme properties of the specified site.
/// </summary>
/// <param name="webUrl">WebUrl is a string that contains the absolute URL of the site.</param>
/// <returns>The result of GetWeb.</returns>
public GetWebResponseGetWebResult GetWeb(string webUrl)
{
GetWebResponseGetWebResult getWebResult = new GetWebResponseGetWebResult();
try
{
getWebResult = this.service.GetWeb(webUrl);
// Capture requirements of WebDefinition complex type.
if (getWebResult.Web != null)
{
this.ValidateWebDefinition(getWebResult.Web);
}
// Capture requirements of GetWeb operation.
this.ValidateGetWeb(getWebResult);
this.CaptureTransportRelatedRequirements();
return getWebResult;
}
catch (SoapException exp)
{
// Capture requirements of detail complex type.
this.ValidateDetail(exp.Detail);
this.CaptureTransportRelatedRequirements();
throw;
}
}
/// <summary>
/// This operation is used to get the Title and URL properties of all immediate child sites of the context site.
/// </summary>
/// <returns>The result of GetWebCollection.</returns>
public GetWebCollectionResponseGetWebCollectionResult GetWebCollection()
{
GetWebCollectionResponseGetWebCollectionResult result = new GetWebCollectionResponseGetWebCollectionResult();
try
{
result = this.service.GetWebCollection();
// Capture requirements of WebDefinition complex type.
if (result.Webs.Length > 0)
{
this.ValidateWebDefinitionForSubWebCollection();
}
this.ValidateGetWebCollection();
this.CaptureTransportRelatedRequirements();
}
catch (SoapException exp)
{
// Capture requirements of detail complex type.
this.ValidateDetail(exp.Detail);
this.CaptureTransportRelatedRequirements();
throw;
}
return result;
}
/// <summary>
/// This operation is used to remove an XML document in the XML document collection of a site content type.
/// </summary>
/// <param name="contentTypeId">contentTypeID is the content type ID of the site content type to be modified</param>
/// <param name="documentUri">documentUri is the namespace URI of the XML document of the site content type to remove</param>
/// <returns>The result of RemoveContentTypeXmlDocument.</returns>
public RemoveContentTypeXmlDocumentResponseRemoveContentTypeXmlDocumentResult RemoveContentTypeXmlDocument(string contentTypeId, string documentUri)
{
RemoveContentTypeXmlDocumentResponseRemoveContentTypeXmlDocumentResult result = new RemoveContentTypeXmlDocumentResponseRemoveContentTypeXmlDocumentResult();
result = this.service.RemoveContentTypeXmlDocument(contentTypeId, documentUri);
this.ValidateRemoveContentTypeXmlDocument();
this.CaptureTransportRelatedRequirements();
return result;
}
/// <summary>
/// This operation is used to revert all pages within the context site to their original states.
/// </summary>
public void RevertAllFileContentStreams()
{
this.service.RevertAllFileContentStreams();
this.ValidateRevertAllFileContentStreams();
this.CaptureTransportRelatedRequirements();
}
/// <summary>
/// This operation is used to revert the customizations of the context site defined by the given CSS file and return those customizations to the default style.
/// </summary>
/// <param name="cssFile">cssFile specifies the name of one of the CSS files that resides in the default.</param>
public void RevertCss(string cssFile)
{
try
{
this.service.RevertCss(cssFile);
// Capture requirements of RevertCss operation.
this.ValidateRevertCss();
this.CaptureTransportRelatedRequirements();
}
catch (SoapException exp)
{
// Capture requirements of detail complex type.
this.ValidateDetail(exp.Detail);
this.CaptureTransportRelatedRequirements();
throw;
}
}
/// <summary>
/// This operation is used to revert the specified page within the context site to its original state.
/// </summary>
/// <param name="fileUrl">fileUrl is a string that contains the URL of the page.</param>
public void RevertFileContentStream(string fileUrl)
{
this.service.RevertFileContentStream(fileUrl);
this.ValidateRevertFileContentStream();
this.CaptureTransportRelatedRequirements();
}
/// <summary>
/// This operation is used to perform the following operation on the context site and all child sites within its hierarchy
/// <ul>
/// <li>Adding one or more specified new columns</li>
/// <li>Updating one or more specified existing columns</li>
/// <li>Deleting one or more specified existing columns</li>
/// </ul>
/// </summary>
/// <param name="newFields">newFields is an XML element that represents the collection of columns to be added to the context site and all child sites within its hierarchy.</param>
/// <param name="updateFields">updateFields is an XML element that represents the collection of columns to be updated on the context site and all child sites within its hierarchy</param>
/// <param name="deleteFields">deleteFields is an XML element that represents the collection of columns to be deleted from the context site and all child sites within its hierarchy</param>
/// <returns>The result of UpdateColumns.</returns>
public UpdateColumnsResponseUpdateColumnsResult UpdateColumns(UpdateColumnsMethod[] newFields, UpdateColumnsMethod1[] updateFields, UpdateColumnsMethod2[] deleteFields)
{
UpdateColumnsResponseUpdateColumnsResult updateColumnsResponseUpdateColumnsResult = null;
updateColumnsResponseUpdateColumnsResult = this.service.UpdateColumns(newFields, updateFields, deleteFields);
this.ValidateUpdateColumns();
this.CaptureTransportRelatedRequirements();
return updateColumnsResponseUpdateColumnsResult;
}
/// <summary>
/// This operation is used to update a content type on the context site.
/// </summary>
/// <param name="contentTypeId">contentTypeID is the ID of the content type to be updated.</param>
/// <param name="contentTypeProperties">properties is the container for properties to set on the content type.</param>
/// <param name="newFields">newFields is the container for a list of existing fields to be included in the content type.</param>
/// <param name="updateFields">updateFields is the container for a list of fields to be updated on the content type.</param>
/// <param name="deleteFields">deleteFields is the container for a list of fields to be updated on the content type.</param>
/// <returns>The result of UpdateContentType.</returns>
public UpdateContentTypeResponseUpdateContentTypeResult UpdateContentType(string contentTypeId, UpdateContentTypeContentTypeProperties contentTypeProperties, AddOrUpdateFieldsDefinition newFields, AddOrUpdateFieldsDefinition updateFields, DeleteFieldsDefinition deleteFields)
{
UpdateContentTypeResponseUpdateContentTypeResult result = new UpdateContentTypeResponseUpdateContentTypeResult();
result = this.service.UpdateContentType(contentTypeId, contentTypeProperties, newFields, updateFields, deleteFields);
this.ValidateUpdateContentType();
this.CaptureTransportRelatedRequirements();
return result;
}
/// <summary>
/// This operation is used to add or update an XML document in the XML Document collection of a site content type.
/// </summary>
/// <param name="contentTypeId">contentTypeID is the content type ID of the site content type to be modified.</param>
/// <param name="newDocument">newDocument is the XML document to be added to the site content type XML document collection.</param>
/// <returns>The result of UpdateContentTypeXmlDocument.</returns>
public UpdateContentTypeXmlDocumentResponseUpdateContentTypeXmlDocumentResult UpdateContentTypeXmlDocument(string contentTypeId, XmlElement newDocument)
{
UpdateContentTypeXmlDocumentResponseUpdateContentTypeXmlDocumentResult result = new UpdateContentTypeXmlDocumentResponseUpdateContentTypeXmlDocumentResult();
result = this.service.UpdateContentTypeXmlDocument(contentTypeId, newDocument);
this.ValidateUpdateContentTypeXmlDocument();
this.CaptureTransportRelatedRequirements();
return result;
}
/// <summary>
/// This operation is used to get the URL of the parent site of the specified URL.
/// </summary>
/// <param name="pageUrl">PageUrl is a URL use to get its parent page URL.</param>
/// <returns>The result of WebUrlFromPageUrl.</returns>
public string WebUrlFromPageUrl(string pageUrl)
{
string webUrlFromPageUrl = this.service.WebUrlFromPageUrl(pageUrl).ToLower();
this.ValidateWebUrlFromPageUrl();
this.CaptureTransportRelatedRequirements();
return webUrlFromPageUrl;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Samples.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace DataMovementSamples
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.DataMovement;
using Microsoft.WindowsAzure.Storage.File;
public class Samples
{
public static void Main(string[] args)
{
try
{
// Single object transfer samples
Console.WriteLine("Data movement upload sample.");
BlobUploadSample().Wait();
// Uncomment the following statement if the account supports Azure File Storage.
// Note that Azure File Storage are not supported on Azure Storage Emulator.
// FileUploadSample().Wait();
// Azure Blob Storage are used in following copy and download samples. You can replace the
// source/destination object with CloudFile to transfer data from/to Azure File Storage as well.
Console.WriteLine();
Console.WriteLine("Data movement copy sample.");
BlobCopySample().Wait();
Console.WriteLine();
Console.WriteLine("Data movement download sample.");
BlobDownloadSample().Wait();
// Directory transfer samples
Console.WriteLine();
Console.WriteLine("Data movement directory upload sample");
BlobDirectoryUploadSample().Wait();
Console.WriteLine();
Console.WriteLine("Data movement directory copy sample.");
BlobDirectoryCopySample().Wait();
}
finally
{
Console.WriteLine();
Console.WriteLine("Cleanup generated data.");
Cleanup();
}
}
/// <summary>
/// Container name used in this sample.
/// </summary>
private const string ContainerName = "samplecontainer";
/// <summary>
/// Share name used in this sample.
/// </summary>
private const string ShareName = "sampleshare";
/// <summary>
/// Upload a local picture to azure storage.
/// 1. Upload a local picture as a block blob.
/// 2. Set its content type to "image/png".
/// </summary>
private static async Task BlobUploadSample()
{
string sourceFileName = "azure.png";
string destinationBlobName = "azure_blockblob.png";
// Create the destination CloudBlob instance
CloudBlob destinationBlob = Util.GetCloudBlob(ContainerName, destinationBlobName, BlobType.BlockBlob);
// Use UploadOptions to set ContentType of destination CloudBlob
UploadOptions options = new UploadOptions();
options.ContentType = "image/png";
// Start the upload
await TransferManager.UploadAsync(sourceFileName, destinationBlob, options, null /* context */);
Console.WriteLine("File {0} is uploaded to {1} successfully.", sourceFileName, destinationBlob.Uri.ToString());
}
/// <summary>
/// Upload a local picture to azure storage as a cloud file.
/// </summary>
private static async Task FileUploadSample()
{
string sourceFileName = "azure.png";
string destinationFileName = "azure_cloudfile.png";
// Create the destination CloudFile instance
CloudFile destinationFile = Util.GetCloudFile(ShareName, destinationFileName);
// Start the upload
await TransferManager.UploadAsync(sourceFileName, destinationFile);
Console.WriteLine("File {0} is uploaded to {1} successfully.", sourceFileName, destinationFile.Uri.ToString());
}
/// <summary>
/// Copy data between Azure storage.
/// 1. Copy a CloudBlob
/// 2. Cancel the transfer before it finishes with a CancellationToken
/// 3. Store the transfer checkpoint after transfer being cancelled
/// 4. Resume the transfer with the stored checkpoint
/// </summary>
private static async Task BlobCopySample()
{
string sourceBlobName = "azure_blockblob.png";
string destinationBlobName = "azure_blockblob2.png";
// Create the source CloudBlob instance
CloudBlob sourceBlob = Util.GetCloudBlob(ContainerName, sourceBlobName, BlobType.BlockBlob);
// Create the destination CloudBlob instance
CloudBlob destinationBlob = Util.GetCloudBlob(ContainerName, destinationBlobName, BlobType.BlockBlob);
// Create CancellationTokenSource used to cancel the transfer
CancellationTokenSource cancellationSource = new CancellationTokenSource();
TransferCheckpoint checkpoint = null;
TransferContext context = new TransferContext();
// Start the transfer
try
{
Task task = TransferManager.CopyAsync(sourceBlob, destinationBlob, false /* isServiceCopy */, null /* options */, context, cancellationSource.Token);
// Sleep for 1 seconds and cancel the transfer.
// It may fail to cancel the transfer if transfer is done in 1 second. If so, no file will tranferred after resume.
Thread.Sleep(1000);
Console.WriteLine("Cancel the transfer.");
cancellationSource.Cancel();
await task;
}
catch (Exception e)
{
Console.WriteLine("The transfer is cancelled: {0}", e.Message);
}
// Store the transfer checkpoint
checkpoint = context.LastCheckpoint;
// Create a new TransferContext with the store checkpoint
TransferContext resumeContext = new TransferContext(checkpoint);
// Resume transfer from the stored checkpoint
Console.WriteLine("Resume the cancelled transfer.");
await TransferManager.CopyAsync(sourceBlob, destinationBlob, false /* isServiceCopy */, null /* options */, resumeContext);
Console.WriteLine("CloudBlob {0} is copied to {1} successfully.", sourceBlob.Uri.ToString(), destinationBlob.Uri.ToString());
}
/// <summary>
/// Download data from Azure storage.
/// 1. Download a CloudBlob to an exsiting local file
/// 2. Query the user to overwrite the local file or not in the OverwriteCallback
/// 3. Download another CloudBlob to local with content MD5 validation disabled
/// 4. Show the overall progress of both transfers
/// </summary>
private static async Task BlobDownloadSample()
{
string sourceBlobName1 = "azure_blockblob.png";
string sourceBlobName2 = "azure_blockblob2.png";
string destinationFileName1 = "azure.png";
string destinationFileName2 = "azure_new.png";
// Create the source CloudBlob instances
CloudBlob sourceBlob1 = Util.GetCloudBlob(ContainerName, sourceBlobName1, BlobType.BlockBlob);
CloudBlob sourceBlob2 = Util.GetCloudBlob(ContainerName, sourceBlobName2, BlobType.BlockBlob);
// Create a TransferContext shared by both transfers
TransferContext sharedTransferContext = new TransferContext();
// Show overwrite prompt in console when OverwriteCallback is triggered
sharedTransferContext.OverwriteCallback = (source, destination) =>
{
Console.WriteLine("{0} already exists. Do you want to overwrite it with {1}? (Y/N)", destination, source);
while (true)
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
char key = keyInfo.KeyChar;
if (key == 'y' || key == 'Y')
{
Console.WriteLine("User choose to overwrite the destination.");
return true;
}
else if (key == 'n' || key == 'N')
{
Console.WriteLine("User choose NOT to overwrite the destination.");
return false;
}
Console.WriteLine("Please press 'y' or 'n'.");
}
};
// Record the overall progress
ProgressRecorder recorder = new ProgressRecorder();
sharedTransferContext.ProgressHandler = recorder;
// Start the blob download
Task task1 = TransferManager.DownloadAsync(sourceBlob1, destinationFileName1, null /* options */, sharedTransferContext);
// Create a DownloadOptions to disable md5 check after data is downloaded. Otherwise, data movement
// library will check the md5 checksum stored in the ContentMD5 property of the source CloudFile/CloudBlob
// You can uncomment following codes, enable ContentMD5Validation and have a try.
// sourceBlob2.Properties.ContentMD5 = "WrongMD5";
// sourceBlob2.SetProperties();
DownloadOptions options = new DownloadOptions();
options.DisableContentMD5Validation = true;
// Start the download
Task task2 = TransferManager.DownloadAsync(sourceBlob2, destinationFileName2, options, sharedTransferContext);
// Wait for both transfers to finish
try
{
await task1;
}
catch(Exception e)
{
// Data movement library will throw a TransferException when user choose to not overwrite the existing destination
Console.WriteLine(e.Message);
}
await task2;
// Print out the final transfer state
Console.WriteLine("Final transfer state: {0}", recorder.ToString());
}
/// <summary>
/// Upload local pictures to azure storage.
/// 1. Upload png files starting with "azure" in the source directory as block blobs, not including the sub-directory
/// 2. Set their content type to "image/png".
/// </summary>
private static async Task BlobDirectoryUploadSample()
{
string sourceDirPath = ".";
CloudBlobDirectory destDir = Util.GetCloudBlobDirectory(ContainerName, "blobdir");
// SearchPattern and Recuresive can be used to determine the files to be transferred from the source directory. The behavior of
// SearchPattern and Recuresive varies for different source directory types.
// See https://azure.github.io/azure-storage-net-data-movement for more details.
//
// When source is local directory, data movement library matches source files against the SearchPattern as standard wildcards. If
// recuresive is set to false, only files directly under the source directory will be matched. Otherwise, all files in the
// sub-directory will be matched as well.
//
// In the following case, data movement library will upload png files starting with "azure" in the source directory as block blobs,
// not including the sub-directory.
UploadDirectoryOptions options = new UploadDirectoryOptions()
{
SearchPattern = "azure*.png",
Recursive = false,
BlobType = BlobType.BlockBlob,
ContentType = "image/png",
};
// Register for transfer event. It's optional and also applicable to single object transfer after v0.2.0.
TransferContext context = new TransferContext();
context.FileTransferred += FileTransferredCallback;
context.FileFailed +=FileFailedCallback;
context.FileSkipped += FileSkippedCallback;
// Start the upload
await TransferManager.UploadDirectoryAsync(sourceDirPath, destDir, options, context);
Console.WriteLine("Files in directory {0} is uploaded to {1} successfully.", sourceDirPath, destDir.Uri.ToString());
}
/// <summary>
/// Copy data between Azure storage.
/// 1. Copy a CloudBlobDirectory
/// 2. Cancel the transfer before it finishes with a CancellationToken
/// 3. Store the transfer checkpoint into a file after transfer being cancelled
/// 4. Reload checkpoint from the file
/// 4. Resume the transfer with the loaded checkpoint
/// </summary>
private static async Task BlobDirectoryCopySample()
{
CloudBlobDirectory sourceBlobDir = Util.GetCloudBlobDirectory(ContainerName, "blobdir");
CloudBlobDirectory destBlobDir = Util.GetCloudBlobDirectory(ContainerName, "blobdir2");
// When source is CloudBlobDirectory:
// 1. If recursive is set to true, data movement library matches the source blob name against SearchPattern as prefix.
// 2. Otherwise, data movement library matches the blob with the exact name specified by SearchPattern.
//
// You can also replace the source directory with a CloudFileDirectory instance to copy data from Azure File Storage. If so:
// 1. If recursive is set to true, SearchPattern is not supported. Data movement library simply transfer all azure files
// under the source CloudFileDirectory and its sub-directories.
// 2. Otherwise, data movement library matches the azure file with the exact name specified by SearchPattern.
//
// In the following case, data movement library will copy all blobs with the prefix "azure" in source blob directory.
CopyDirectoryOptions options = new CopyDirectoryOptions()
{
SearchPattern = "azure",
Recursive = true,
};
TransferContext context = new TransferContext();
context.FileTransferred += FileTransferredCallback;
context.FileFailed += FileFailedCallback;
context.FileSkipped += FileSkippedCallback;
// Create CancellationTokenSource used to cancel the transfer
CancellationTokenSource cancellationSource = new CancellationTokenSource();
TransferCheckpoint checkpoint = null;
try
{
Task task = TransferManager.CopyDirectoryAsync(sourceBlobDir, destBlobDir, false /* isServiceCopy */, options, context, cancellationSource.Token);
// Sleep for 1 seconds and cancel the transfer.
// It may fail to cancel the transfer if transfer is done in 1 second. If so, no file will be copied after resume.
Thread.Sleep(1000);
Console.WriteLine("Cancel the transfer.");
cancellationSource.Cancel();
await task;
}
catch (Exception e)
{
Console.WriteLine("The transfer is cancelled: {0}", e.Message);
}
// Store the transfer checkpoint
checkpoint = context.LastCheckpoint;
// Serialize the checkpoint into a file
IFormatter formatter = new BinaryFormatter();
string tempFileName = Guid.NewGuid().ToString();
using (var stream = new FileStream(tempFileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
formatter.Serialize(stream, checkpoint);
}
// Deserialize the checkpoint from the file
using (var stream = new FileStream(tempFileName, FileMode.Open, FileAccess.Read, FileShare.None))
{
checkpoint = formatter.Deserialize(stream) as TransferCheckpoint;
}
File.Delete(tempFileName);
// Create a new TransferContext with the store checkpoint
TransferContext resumeContext = new TransferContext(checkpoint);
resumeContext.FileTransferred += FileTransferredCallback;
resumeContext.FileFailed += FileFailedCallback;
resumeContext.FileSkipped += FileSkippedCallback;
// Record the overall progress
ProgressRecorder recorder = new ProgressRecorder();
resumeContext.ProgressHandler = recorder;
// Resume transfer from the stored checkpoint
Console.WriteLine("Resume the cancelled transfer.");
await TransferManager.CopyDirectoryAsync(sourceBlobDir, destBlobDir, false /* isServiceCopy */, options, resumeContext);
// Print out the final transfer state
Console.WriteLine("Final transfer state: {0}", recorder.ToString());
}
private static void FileTransferredCallback(object sender, TransferEventArgs e)
{
Console.WriteLine("Transfer Succeeds. {0} -> {1}.", e.Source, e.Destination);
}
private static void FileFailedCallback(object sender, TransferEventArgs e)
{
Console.WriteLine("Transfer fails. {0} -> {1}. Error message:{2}", e.Source, e.Destination, e.Exception.Message);
}
private static void FileSkippedCallback(object sender, TransferEventArgs e)
{
Console.WriteLine("Transfer skips. {0} -> {1}.", e.Source, e.Destination);
}
/// <summary>
/// Cleanup all data generated by this sample.
/// </summary>
private static void Cleanup()
{
Console.Write("Deleting container...");
Util.DeleteContainer(ContainerName);
Console.WriteLine("Done");
// Uncomment the following statements if the account supports Azure File Storage.
// Console.Write("Deleting share...");
// Util.DeleteShare(ShareName);
// Console.WriteLine("Done");
// Delete the local file generated by download sample.
Console.Write("Deleting local file...");
File.Delete("azure_new.png");
Console.WriteLine("Done");
}
/// <summary>
/// A helper class to record progress reported by data movement library.
/// </summary>
class ProgressRecorder : IProgress<TransferProgress>
{
private long latestBytesTransferred;
private long latestNumberOfFilesTransferred;
private long latestNumberOfFilesSkipped;
private long latestNumberOfFilesFailed;
public void Report(TransferProgress progress)
{
this.latestBytesTransferred = progress.BytesTransferred;
this.latestNumberOfFilesTransferred = progress.NumberOfFilesTransferred;
this.latestNumberOfFilesSkipped = progress.NumberOfFilesSkipped;
this.latestNumberOfFilesFailed = progress.NumberOfFilesFailed;
}
public override string ToString()
{
return string.Format("Transferred bytes: {0}; Transfered: {1}; Skipped: {2}, Failed: {3}",
this.latestBytesTransferred,
this.latestNumberOfFilesTransferred,
this.latestNumberOfFilesSkipped,
this.latestNumberOfFilesFailed);
}
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel;
using Csla.Validation;
namespace Northwind.CSLA.Library
{
/// <summary>
/// OrderOrderDetail Generated by MyGeneration using the CSLA Object Mapping template
/// </summary>
[Serializable()]
[TypeConverter(typeof(OrderOrderDetailConverter))]
public partial class OrderOrderDetail : BusinessBase<OrderOrderDetail>, IVEHasBrokenRules
{
#region Business Methods
private string _ErrorMessage = string.Empty;
public string ErrorMessage
{
get { return _ErrorMessage; }
}
private int _ProductID;
[System.ComponentModel.DataObjectField(true, true)]
public int ProductID
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MyProduct != null) _ProductID = _MyProduct.ProductID;
return _ProductID;
}
}
private Product _MyProduct;
[System.ComponentModel.DataObjectField(true, true)]
public Product MyProduct
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if (_MyProduct == null && _ProductID != 0) _MyProduct = Product.Get(_ProductID);
return _MyProduct;
}
}
private decimal _UnitPrice;
public decimal UnitPrice
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _UnitPrice;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (_UnitPrice != value)
{
_UnitPrice = value;
PropertyHasChanged();
}
}
}
private Int16 _Quantity;
public Int16 Quantity
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Quantity;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (_Quantity != value)
{
_Quantity = value;
PropertyHasChanged();
}
}
}
private float _Discount;
public float Discount
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Discount;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (_Discount != value)
{
_Discount = value;
PropertyHasChanged();
}
}
}
private string _Product_ProductName = string.Empty;
public string Product_ProductName
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Product_ProductName;
}
}
private int? _Product_SupplierID;
public int? Product_SupplierID
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Product_SupplierID;
}
}
private int? _Product_CategoryID;
public int? Product_CategoryID
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Product_CategoryID;
}
}
private string _Product_QuantityPerUnit = string.Empty;
public string Product_QuantityPerUnit
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Product_QuantityPerUnit;
}
}
private decimal? _Product_UnitPrice;
public decimal? Product_UnitPrice
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Product_UnitPrice;
}
}
private Int16? _Product_UnitsInStock;
public Int16? Product_UnitsInStock
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Product_UnitsInStock;
}
}
private Int16? _Product_UnitsOnOrder;
public Int16? Product_UnitsOnOrder
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Product_UnitsOnOrder;
}
}
private Int16? _Product_ReorderLevel;
public Int16? Product_ReorderLevel
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Product_ReorderLevel;
}
}
private bool _Product_Discontinued;
public bool Product_Discontinued
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _Product_Discontinued;
}
}
// TODO: Check OrderOrderDetail.GetIdValue to assure that the ID returned is unique
/// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary>
/// <returns>A Unique ID for the current OrderOrderDetail</returns>
protected override object GetIdValue()
{
return _ProductID;
}
// TODO: Replace base OrderOrderDetail.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current OrderOrderDetail</returns>
//public override string ToString()
//{
// return base.ToString();
//}
#endregion
#region ValidationRules
[NonSerialized]
private bool _CheckingBrokenRules=false;
public IVEHasBrokenRules HasBrokenRules
{
get
{
if(_CheckingBrokenRules)return null;
if (BrokenRulesCollection.Count > 0) return this;
try
{
_CheckingBrokenRules=true;
IVEHasBrokenRules hasBrokenRules = null;
return hasBrokenRules;
}
finally
{
_CheckingBrokenRules=false;
}
}
}
public BrokenRulesCollection BrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null);
}
}
protected override void AddBusinessRules()
{
// TODO: Add other validation rules
}
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion
#region Authorization Rules
protected override void AddAuthorizationRules()
{
//TODO: Who can read/write which fields
//AuthorizationRules.AllowRead(ProductID, "<Role(s)>");
//AuthorizationRules.AllowRead(UnitPrice, "<Role(s)>");
//AuthorizationRules.AllowWrite(UnitPrice, "<Role(s)>");
//AuthorizationRules.AllowRead(Quantity, "<Role(s)>");
//AuthorizationRules.AllowWrite(Quantity, "<Role(s)>");
//AuthorizationRules.AllowRead(Discount, "<Role(s)>");
//AuthorizationRules.AllowWrite(Discount, "<Role(s)>");
}
public static bool CanAddObject()
{
// TODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// TODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// TODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// TODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion
#region Factory Methods
public int CurrentEditLevel
{ get { return EditLevel; } }
internal static OrderOrderDetail New(Product myProduct)
{
return new OrderOrderDetail(myProduct);
}
internal static OrderOrderDetail Get(SafeDataReader dr)
{
return new OrderOrderDetail(dr);
}
public OrderOrderDetail()
{
MarkAsChild();
_UnitPrice = _OrderOrderDetailExtension.DefaultUnitPrice;
_Quantity = _OrderOrderDetailExtension.DefaultQuantity;
_Discount = _OrderOrderDetailExtension.DefaultDiscount;
ValidationRules.CheckRules();
}
private OrderOrderDetail(Product myProduct)
{
MarkAsChild();
// TODO: Add any initialization & defaults
_UnitPrice = _OrderOrderDetailExtension.DefaultUnitPrice;
_Quantity = _OrderOrderDetailExtension.DefaultQuantity;
_Discount = _OrderOrderDetailExtension.DefaultDiscount;
_MyProduct = myProduct;
ValidationRules.CheckRules();
}
internal OrderOrderDetail(SafeDataReader dr)
{
MarkAsChild();
Fetch(dr);
}
#endregion
#region Data Access Portal
private void Fetch(SafeDataReader dr)
{
Database.LogInfo("OrderOrderDetail.FetchDR", GetHashCode());
try
{
_ProductID = dr.GetInt32("ProductID");
_UnitPrice = dr.GetDecimal("UnitPrice");
_Quantity = dr.GetInt16("Quantity");
_Discount = dr.GetFloat("Discount");
_Product_ProductName = dr.GetString("Product_ProductName");
_Product_SupplierID = (int?)dr.GetValue("Product_SupplierID");
_Product_CategoryID = (int?)dr.GetValue("Product_CategoryID");
_Product_QuantityPerUnit = dr.GetString("Product_QuantityPerUnit");
_Product_UnitPrice = (decimal?)dr.GetValue("Product_UnitPrice");
_Product_UnitsInStock = (Int16?)dr.GetValue("Product_UnitsInStock");
_Product_UnitsOnOrder = (Int16?)dr.GetValue("Product_UnitsOnOrder");
_Product_ReorderLevel = (Int16?)dr.GetValue("Product_ReorderLevel");
_Product_Discontinued = dr.GetBoolean("Product_Discontinued");
}
catch (Exception ex) // FKItem Fetch
{
Database.LogException("OrderOrderDetail.FetchDR", ex);
throw new DbCslaException("OrderOrderDetail.Fetch", ex);
}
MarkOld();
}
internal void Insert(Order myOrder)
{
// if we're not dirty then don't update the database
if (!this.IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
OrderDetail.Add(cn, myOrder, _MyProduct, _UnitPrice, _Quantity, _Discount);
MarkOld();
}
internal void Update(Order myOrder)
{
// if we're not dirty then don't update the database
if (!this.IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
OrderDetail.Update(cn, myOrder, _MyProduct, _UnitPrice, _Quantity, _Discount);
MarkOld();
}
internal void DeleteSelf(Order myOrder)
{
// if we're not dirty then don't update the database
if (!this.IsDirty) return;
// if we're new then don't update the database
if (this.IsNew) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
OrderDetail.Remove(cn, myOrder.OrderID, _ProductID);
MarkNew();
}
#endregion
// Standard Default Code
#region extension
OrderOrderDetailExtension _OrderOrderDetailExtension = new OrderOrderDetailExtension();
[Serializable()]
partial class OrderOrderDetailExtension : extensionBase
{
}
[Serializable()]
class extensionBase
{
// Default Values
public virtual decimal DefaultUnitPrice
{
get { return 0; }
}
public virtual Int16 DefaultQuantity
{
get { return 1; }
}
public virtual float DefaultDiscount
{
get { return 0; }
}
// Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{
// Needs to be overriden to add new authorization rules
}
// Instance Authorization Rules
public virtual void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
{
// Needs to be overriden to add new authorization rules
}
// Validation Rules
public virtual void AddValidationRules(Csla.Validation.ValidationRules rules)
{
// Needs to be overriden to add new validation rules
}
// InstanceValidation Rules
public virtual void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
{
// Needs to be overriden to add new validation rules
}
}
#endregion
} // Class
#region Converter
internal class OrderOrderDetailConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is OrderOrderDetail)
{
// Return the ToString value
return ((OrderOrderDetail)value).ToString();
}
return base.ConvertTo(context, culture, value, destType);
}
}
#endregion
} // Namespace
//// The following is a sample Extension File. You can use it to create OrderOrderDetailExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace Northwind.CSLA.Library
//{
// public partial class OrderOrderDetail
// {
// partial class OrderOrderDetailExtension : extensionBase
// {
// // TODO: Override automatic defaults
// public virtual decimal DefaultUnitPrice
// {
// get { return 0; }
// }
// public virtual Int16 DefaultQuantity
// {
// get { return 1; }
// }
// public virtual float DefaultDiscount
// {
// get { return 0; }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crestron.SimplSharp;
using Crestron.ThirdPartyCommon.Class;
using Crestron.ThirdPartyCommon.ComponentInterfaces;
using Crestron.ThirdPartyCommon.Interfaces;
using Crestron.ThirdPartyCommon.StandardCommands;
using Crestron.ThirdPartyCommon.Transports;
using VTPro.Objects;
using VTPro.SmartObjects;
using myNamespace.Drivers;
using myNamespace.Constants;
namespace myNamespace.Methods
{
public class __AM_FM_MainVTButtons
{
public __AM_FM_MainVTButtons(Panel Panel)
{
this.Panel = Panel;
}
/*
private bool BaseSanityCheck
{
get
{
if (Bluray != ControlSystem.GetSystem._blurayPlayer)
{
Bluray = ControlSystem.GetSystem._blurayPlayer;
}
return Bluray != null;
}
}
*/
public void Button(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Button_1(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Multi_Mode_Button(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Multi_Mode_Button_3(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Multi_Mode_Button_4(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Multi_Mode_Button_5(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Multi_Mode_Button_6(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Multi_Mode_Button_7(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Multi_Mode_Button_8(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_1(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_10(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_11(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_12(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_13(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_14(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_15(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_2(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_3(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_4(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_5(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_6(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_7(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_8(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public void Simple_Button_9(VTButton Button, bool IsPressed)
{
if (IsPressed)
{
//press function here
throw new NotImplementedException();
}
}
public IBasicBlurayPlayer Bluray;
private Panel Panel;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using oAuthX.Areas.HelpPage.ModelDescriptions;
using oAuthX.Areas.HelpPage.Models;
namespace oAuthX.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using AjMessages.Configuration;
using AjMessages.Channels;
namespace AjMessages
{
public class Server
{
private Dictionary<string,Host> hosts = new Dictionary<string,Host>();
private Dictionary<string,Application> applications = new Dictionary<string,Application>();
private Random rnd = new Random();
private AjMessagesConfig configuration;
private static XmlSerializer sercnf;
private bool started;
private IChannelFactory channelfactory;
public IChannelFactory ChannelFactory
{
get { return channelfactory; }
set { channelfactory = value; }
}
static Server()
{
sercnf = new XmlSerializer(typeof(AjMessagesConfig));
}
public void Configure(string filename)
{
FileStream file = new FileStream(filename,FileMode.Open,FileAccess.Read);
AjMessagesConfig config = (AjMessagesConfig)sercnf.Deserialize(file);
file.Close();
Configure(config);
}
public void Configure(TextReader reader)
{
AjMessagesConfig conf = (AjMessagesConfig)sercnf.Deserialize(reader);
Configure(conf);
}
public void Configure(AjMessagesConfig config)
{
configuration = config;
foreach (ApplicationConfig appconfig in configuration.Applications) {
Application app = appconfig.GetApplication();
app.Server = this;
applications[app.Name] = app;
}
List<string> activehosts = new List<string>();
foreach (HostConfig hostconfig in configuration.Hosts)
if (hostconfig.Activate)
activehosts.Add(hostconfig.Name);
if (activehosts.Count > 0)
{
CreateHosts(activehosts);
Start();
}
}
internal void Reconfigure(AjMessagesConfig conf)
{
foreach (ApplicationConfig appconfig in conf.Applications)
{
Application app = appconfig.GetApplication();
app.Server = this;
applications[app.Name] = app;
}
foreach (HostConfig hostconfig in conf.Hosts)
{
// If there is a previous host with same name, stop it
if (hosts.ContainsKey(hostconfig.Name)) {
Host oldhost = hosts[hostconfig.Name];
oldhost.Stop();
hosts.Remove(hostconfig.Name);
}
List<HostConfig> toremove = new List<HostConfig>();
// Remove host from previous configuration
foreach (HostConfig hc in configuration.Hosts)
{
if (hc.Name == hostconfig.Name)
toremove.Add(hc);
}
foreach (HostConfig hc in toremove)
configuration.Hosts.Remove(hc);
// If the host has no applications, discard it
if (hostconfig.Applications.Count == 0)
continue;
// Add to current configuration host list
configuration.Hosts.Add(hostconfig);
// Activate the local or remote host
Host host;
if (hostconfig.Activate == false)
{
host = CreateRemoteHost(hostconfig);
}
else
{
host = CreateLocalHost(hostconfig);
}
hosts[host.Name] = host;
host.Start();
}
}
internal void Reconfigure(XmlReader reader)
{
AjMessagesConfig conf = (AjMessagesConfig) sercnf.Deserialize(reader);
Reconfigure(conf);
}
internal void Reconfigure(TextReader reader)
{
AjMessagesConfig conf = (AjMessagesConfig) sercnf.Deserialize(reader);
Reconfigure(conf);
}
public void Post(Message msg)
{
string nodefullname = MessageUtilities.GetNodeFullName(msg);
List<Host> hostsToPost = new List<Host>();
foreach (Host host in hosts.Values)
if (host.HasNode(nodefullname))
{
hostsToPost.Add(host);
}
if (hostsToPost.Count == 0)
return;
if (hostsToPost.Count == 1)
{
hostsToPost[0].Post(msg);
return;
}
hostsToPost[rnd.Next(hostsToPost.Count)].Post(msg);
}
public void Start()
{
if (started)
return;
foreach (Host host in hosts.Values)
host.Start();
started = true;
}
public void Stop()
{
if (!started)
return;
foreach (Host host in hosts.Values)
host.Stop();
started = false;
}
IOutputChannel CreateOutputChannel(string address)
{
if (channelfactory == null)
return null;
if (address == null)
return null;
return channelfactory.CreateOutputChannel(address);
}
IInputChannel CreateInputChannel(string address, IMessageConsumer consumer)
{
if (channelfactory == null)
return null;
if (address == null)
return null;
return channelfactory.CreateInputChannel(address, consumer);
}
Host CreateLocalHost(HostConfig hostconfig)
{
LocalHost host = new LocalHost();
host.Name = hostconfig.Name;
host.Port = hostconfig.Port;
host.Address = hostconfig.Address;
host.InputChannel = CreateInputChannel(host.Address, host);
foreach (HostedApplicationConfig hostedapp in hostconfig.Applications)
{
Application app = applications[hostedapp.Name];
foreach (HostedNodeConfig hostednode in hostedapp.Nodes)
{
Node node = app.GetNode(hostednode.Name);
host.RegisterNode(node);
}
}
return host;
}
Host CreateRemoteHost(HostConfig hostconfig)
{
RemoteHost host = new RemoteHost();
host.Name = hostconfig.Name;
host.Port = hostconfig.Port;
host.Address = hostconfig.Address;
host.OutputChannel = CreateOutputChannel(host.Address);
foreach (HostedApplicationConfig hostedapp in hostconfig.Applications)
{
Application app = new Application();
app.Name = hostedapp.Name;
foreach (HostedNodeConfig hostednode in hostedapp.Nodes)
{
Node node = new Node();
node.Application = app;
node.Name = hostednode.Name;
host.RegisterNode(node);
}
}
return host;
}
public void CreateHosts(List<string> hostnames)
{
foreach (HostConfig hostconfig in configuration.Hosts)
{
Host host;
if (hostnames.Contains(hostconfig.Name))
host = CreateLocalHost(hostconfig);
else
host = CreateRemoteHost(hostconfig);
hosts[host.Name] = host;
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.Extensions.Logging;
using Orleans.CodeGenerator.Model;
using Orleans.CodeGenerator.Utilities;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using ITypeSymbol = Microsoft.CodeAnalysis.ITypeSymbol;
namespace Orleans.CodeGenerator.Generators
{
/// <summary>
/// Code generator which generates serializers.
/// Sample of generated serializer:
/// [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Orleans-CodeGenerator", "2.0.0.0"), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute, global::Orleans.CodeGeneration.SerializerAttribute(typeof(global::MyType))]
/// internal sealed class OrleansCodeGenUnitTests_GrainInterfaces_MyTypeSerializer
/// {
/// private readonly global::System.Func<global::MyType, global::System.Int32> getField0;
/// private readonly global::System.Action<global::MyType, global::System.Int32> setField0;
/// public OrleansCodeGenUnitTests_GrainInterfaces_MyTypeSerializer(global::Orleans.Serialization.IFieldUtils fieldUtils)
/// {
/// [...]
/// }
/// [global::Orleans.CodeGeneration.CopierMethodAttribute]
/// public global::System.Object DeepCopier(global::System.Object original, global::Orleans.Serialization.ICopyContext context)
/// {
/// [...]
/// }
/// [global::Orleans.CodeGeneration.SerializerMethodAttribute]
/// public void Serializer(global::System.Object untypedInput, global::Orleans.Serialization.ISerializationContext context, global::System.Type expected)
/// {
/// [...]
/// }
/// [global::Orleans.CodeGeneration.DeserializerMethodAttribute]
/// public global::System.Object Deserializer(global::System.Type expected, global::Orleans.Serialization.IDeserializationContext context)
/// {
/// [...]
/// }
///}
/// </summary>
internal class SerializerGenerator
{
/// <summary>
/// The suffix appended to the name of generated classes.
/// </summary>
private const string ClassSuffix = "Serializer";
private readonly CodeGeneratorOptions options;
private readonly WellKnownTypes wellKnownTypes;
public SerializerGenerator(CodeGeneratorOptions options, WellKnownTypes wellKnownTypes)
{
this.options = options;
this.wellKnownTypes = wellKnownTypes;
}
private readonly ConcurrentDictionary<ITypeSymbol, bool> ShallowCopyableTypes = new ConcurrentDictionary<ITypeSymbol, bool>();
/// <summary>
/// Returns the name of the generated class for the provided type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The name of the generated class for the provided type.</returns>
internal string GetGeneratedClassName(INamedTypeSymbol type)
{
var parts = type.ToDisplayParts(SymbolDisplayFormat.FullyQualifiedFormat
.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted)
.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.None)
.WithGenericsOptions(SymbolDisplayGenericsOptions.None)
.WithKindOptions(SymbolDisplayKindOptions.None)
.WithLocalOptions(SymbolDisplayLocalOptions.None)
.WithMemberOptions(SymbolDisplayMemberOptions.None)
.WithParameterOptions(SymbolDisplayParameterOptions.None));
var b = new StringBuilder();
foreach (var part in parts)
{
// Add the class prefix after the type name.
switch (part.Kind)
{
case SymbolDisplayPartKind.Punctuation:
b.Append('_');
break;
case SymbolDisplayPartKind.ClassName:
case SymbolDisplayPartKind.InterfaceName:
case SymbolDisplayPartKind.StructName:
b.Append(part.ToString().TrimStart('@'));
b.Append(ClassSuffix);
break;
default:
b.Append(part.ToString().TrimStart('@'));
break;
}
}
return CodeGenerator.ToolName + b;
}
/// <summary>
/// Generates the non serializer class for the provided grain types.
/// </summary>
internal (TypeDeclarationSyntax, TypeSyntax) GenerateClass(SemanticModel model, SerializerTypeDescription description, ILogger logger)
{
var className = GetGeneratedClassName(description.Target);
var type = description.Target;
var genericTypes = type.GetHierarchyTypeParameters().Select(_ => TypeParameter(_.ToString())).ToArray();
var attributes = new List<AttributeSyntax>
{
GeneratedCodeAttributeGenerator.GetGeneratedCodeAttributeSyntax(wellKnownTypes),
Attribute(wellKnownTypes.ExcludeFromCodeCoverageAttribute.ToNameSyntax()),
Attribute(wellKnownTypes.SerializerAttribute.ToNameSyntax())
.AddArgumentListArguments(
AttributeArgument(TypeOfExpression(type.WithoutTypeParameters().ToTypeSyntax())))
};
var fields = GetFields(model, type, logger);
var members = new List<MemberDeclarationSyntax>(GenerateFields(fields))
{
GenerateConstructor(className, fields),
GenerateDeepCopierMethod(type, fields, model),
GenerateSerializerMethod(type, fields, model),
GenerateDeserializerMethod(type, fields, model),
};
var classDeclaration =
ClassDeclaration(className)
.AddModifiers(Token(SyntaxKind.InternalKeyword))
.AddModifiers(Token(SyntaxKind.SealedKeyword))
.AddAttributeLists(AttributeList().AddAttributes(attributes.ToArray()))
.AddMembers(members.ToArray())
.AddConstraintClauses(type.GetTypeConstraintSyntax());
if (genericTypes.Length > 0)
{
classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes);
}
if (this.options.DebuggerStepThrough)
{
var debuggerStepThroughAttribute = Attribute(this.wellKnownTypes.DebuggerStepThroughAttribute.ToNameSyntax());
classDeclaration = classDeclaration.AddAttributeLists(AttributeList().AddAttributes(debuggerStepThroughAttribute));
}
return (classDeclaration, ParseTypeName(type.GetParsableReplacementName(className)));
}
private MemberDeclarationSyntax GenerateConstructor(string className, List<FieldInfoMember> fields)
{
var body = new List<StatementSyntax>();
// Expressions for specifying binding flags.
var bindingFlags = SymbolSyntaxExtensions.GetBindingFlagsParenthesizedExpressionSyntax(
SyntaxKind.BitwiseOrExpression,
BindingFlags.Instance,
BindingFlags.NonPublic,
BindingFlags.Public);
var fieldUtils = IdentifierName("fieldUtils");
foreach (var field in fields)
{
// Get the field
var fieldInfoField = IdentifierName(field.InfoFieldName);
var fieldInfo =
InvocationExpression(TypeOfExpression(field.Field.ContainingType.ToTypeSyntax()).Member("GetField"))
.AddArgumentListArguments(
Argument(field.Field.Name.ToLiteralExpression()),
Argument(bindingFlags));
var fieldInfoVariable =
VariableDeclarator(field.InfoFieldName).WithInitializer(EqualsValueClause(fieldInfo));
if (!field.IsGettableProperty || !field.IsSettableProperty)
{
body.Add(LocalDeclarationStatement(
VariableDeclaration(wellKnownTypes.FieldInfo.ToTypeSyntax()).AddVariables(fieldInfoVariable)));
}
// Set the getter/setter of the field
if (!field.IsGettableProperty)
{
var getterType = wellKnownTypes.Func_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax();
var getterInvoke = CastExpression(
getterType,
InvocationExpression(fieldUtils.Member("GetGetter")).AddArgumentListArguments(Argument(fieldInfoField)));
body.Add(ExpressionStatement(
AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(field.GetterFieldName), getterInvoke)));
}
if (!field.IsSettableProperty)
{
if (field.Field.ContainingType != null && field.Field.ContainingType.IsValueType)
{
var setterType = wellKnownTypes.ValueTypeSetter_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax();
var getValueSetterInvoke = CastExpression(
setterType,
InvocationExpression(fieldUtils.Member("GetValueSetter"))
.AddArgumentListArguments(Argument(fieldInfoField)));
body.Add(ExpressionStatement(
AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(field.SetterFieldName), getValueSetterInvoke)));
}
else
{
var setterType = wellKnownTypes.Action_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax();
var getReferenceSetterInvoke = CastExpression(
setterType,
InvocationExpression(fieldUtils.Member("GetReferenceSetter"))
.AddArgumentListArguments(Argument(fieldInfoField)));
body.Add(ExpressionStatement(
AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, IdentifierName(field.SetterFieldName), getReferenceSetterInvoke)));
}
}
}
return
ConstructorDeclaration(className)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(
Parameter(fieldUtils.Identifier).WithType(wellKnownTypes.IFieldUtils.ToTypeSyntax()))
.AddBodyStatements(body.ToArray());
}
/// <summary>
/// Returns syntax for the deserializer method.
/// </summary>
private MemberDeclarationSyntax GenerateDeserializerMethod(INamedTypeSymbol type, List<FieldInfoMember> fields, SemanticModel model)
{
var contextParameter = IdentifierName("context");
var resultDeclaration =
LocalDeclarationStatement(
VariableDeclaration(type.ToTypeSyntax())
.AddVariables(
VariableDeclarator("result")
.WithInitializer(EqualsValueClause(GetObjectCreationExpressionSyntax(type, model)))));
var resultVariable = IdentifierName("result");
var body = new List<StatementSyntax> { resultDeclaration };
// Value types cannot be referenced, only copied, so there is no need to box & record instances of value types.
if (!type.IsValueType)
{
// Record the result for cyclic deserialization.
var currentSerializationContext = contextParameter;
body.Add(
ExpressionStatement(
InvocationExpression(currentSerializationContext.Member("RecordObject"))
.AddArgumentListArguments(Argument(resultVariable))));
}
// Deserialize all fields.
foreach (var field in fields)
{
var deserialized =
InvocationExpression(contextParameter.Member("DeserializeInner"))
.AddArgumentListArguments(
Argument(TypeOfExpression(field.Type)));
body.Add(
ExpressionStatement(
field.GetSetter(
resultVariable,
CastExpression(field.Type, deserialized))));
}
// If the type implements the internal IOnDeserialized lifecycle method, invoke it's method now.
if (type.HasInterface(wellKnownTypes.IOnDeserialized))
{
// C#: ((IOnDeserialized)result).OnDeserialized(context);
var typedResult = ParenthesizedExpression(CastExpression(wellKnownTypes.IOnDeserialized.ToTypeSyntax(), resultVariable));
var invokeOnDeserialized = InvocationExpression(typedResult.Member("OnDeserialized"))
.AddArgumentListArguments(Argument(contextParameter));
body.Add(ExpressionStatement(invokeOnDeserialized));
}
body.Add(ReturnStatement(CastExpression(type.ToTypeSyntax(), resultVariable)));
return
MethodDeclaration(wellKnownTypes.Object.ToTypeSyntax(), "Deserializer")
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(
Parameter(Identifier("expected")).WithType(wellKnownTypes.Type.ToTypeSyntax()),
Parameter(Identifier("context")).WithType(wellKnownTypes.IDeserializationContext.ToTypeSyntax()))
.AddBodyStatements(body.ToArray())
.AddAttributeLists(
AttributeList()
.AddAttributes(Attribute(wellKnownTypes.DeserializerMethodAttribute.ToNameSyntax())));
}
private MemberDeclarationSyntax GenerateSerializerMethod(INamedTypeSymbol type, List<FieldInfoMember> fields, SemanticModel model)
{
var contextParameter = IdentifierName("context");
var body = new List<StatementSyntax>
{
LocalDeclarationStatement(
VariableDeclaration(type.ToTypeSyntax())
.AddVariables(
VariableDeclarator("input")
.WithInitializer(
EqualsValueClause(
CastExpression(type.ToTypeSyntax(), IdentifierName("untypedInput"))))))
};
var inputExpression = IdentifierName("input");
// Serialize all members.
foreach (var field in fields)
{
body.Add(
ExpressionStatement(
InvocationExpression(contextParameter.Member("SerializeInner"))
.AddArgumentListArguments(
Argument(field.GetGetter(inputExpression, forceAvoidCopy: true)),
Argument(TypeOfExpression(field.Type)))));
}
return
MethodDeclaration(wellKnownTypes.Void.ToTypeSyntax(), "Serializer")
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(
Parameter(Identifier("untypedInput")).WithType(wellKnownTypes.Object.ToTypeSyntax()),
Parameter(Identifier("context")).WithType(wellKnownTypes.ISerializationContext.ToTypeSyntax()),
Parameter(Identifier("expected")).WithType(wellKnownTypes.Type.ToTypeSyntax()))
.AddBodyStatements(body.ToArray())
.AddAttributeLists(
AttributeList()
.AddAttributes(Attribute(wellKnownTypes.SerializerMethodAttribute.ToNameSyntax())));
}
/// <summary>
/// Returns syntax for the deep copy method.
/// </summary>
private MemberDeclarationSyntax GenerateDeepCopierMethod(INamedTypeSymbol type, List<FieldInfoMember> fields, SemanticModel model)
{
var originalVariable = IdentifierName("original");
var body = new List<StatementSyntax>();
if (type.HasAttribute(wellKnownTypes.ImmutableAttribute)
|| SymbolEqualityComparer.Default.Equals(wellKnownTypes.Immutable_1, type))
{
// Immutable types do not require copying.
var typeName = type.ToDisplayString();
var comment = Comment($"// No deep copy required since {typeName} is marked with the [Immutable] attribute.");
body.Add(ReturnStatement(originalVariable).WithLeadingTrivia(comment));
}
else
{
var inputVariable = IdentifierName("input");
body.Add(
LocalDeclarationStatement(
VariableDeclaration(type.ToTypeSyntax())
.AddVariables(
VariableDeclarator("input")
.WithInitializer(
EqualsValueClause(
ParenthesizedExpression(
CastExpression(type.ToTypeSyntax(), originalVariable)))))));
if (IsOrleansShallowCopyable(type))
{
var comment = Comment($"// {type.ToDisplayString()} needs only a shallow copy.");
body.Add(ReturnStatement(inputVariable).WithLeadingTrivia(comment));
}
else
{
var resultVariable = IdentifierName("result");
body.Add(
LocalDeclarationStatement(
VariableDeclaration(type.ToTypeSyntax())
.AddVariables(
VariableDeclarator("result")
.WithInitializer(EqualsValueClause(GetObjectCreationExpressionSyntax(type, model))))));
var context = IdentifierName("context");
if (!type.IsValueType)
{
// Record this serialization.
body.Add(
ExpressionStatement(
InvocationExpression(context.Member("RecordCopy"))
.AddArgumentListArguments(Argument(originalVariable), Argument(resultVariable))));
}
// Copy all members from the input to the result.
foreach (var field in fields)
{
body.Add(ExpressionStatement(field.GetSetter(resultVariable, field.GetGetter(inputVariable, context))));
}
body.Add(ReturnStatement(resultVariable));
}
}
return
MethodDeclaration(wellKnownTypes.Object.ToTypeSyntax(), "DeepCopier")
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(
Parameter(Identifier("original")).WithType(wellKnownTypes.Object.ToTypeSyntax()),
Parameter(Identifier("context")).WithType(wellKnownTypes.ICopyContext.ToTypeSyntax()))
.AddBodyStatements(body.ToArray())
.AddAttributeLists(
AttributeList().AddAttributes(Attribute(wellKnownTypes.CopierMethodAttribute.ToNameSyntax())));
}
/// <summary>
/// Returns syntax for the fields of the serializer class.
/// </summary>
private MemberDeclarationSyntax[] GenerateFields(List<FieldInfoMember> fields)
{
var result = new List<MemberDeclarationSyntax>();
// Add each field and initialize it.
foreach (var field in fields)
{
// Declare the getter for this field.
if (!field.IsGettableProperty)
{
var getterType = wellKnownTypes.Func_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax();
var fieldGetterVariable = VariableDeclarator(field.GetterFieldName);
result.Add(
FieldDeclaration(VariableDeclaration(getterType).AddVariables(fieldGetterVariable))
.AddModifiers(
Token(SyntaxKind.PrivateKeyword),
Token(SyntaxKind.ReadOnlyKeyword)));
}
if (!field.IsSettableProperty)
{
if (field.Field.ContainingType != null && field.Field.ContainingType.IsValueType)
{
var setterType = wellKnownTypes.ValueTypeSetter_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax();
var fieldSetterVariable = VariableDeclarator(field.SetterFieldName);
result.Add(
FieldDeclaration(VariableDeclaration(setterType).AddVariables(fieldSetterVariable))
.AddModifiers(
Token(SyntaxKind.PrivateKeyword),
Token(SyntaxKind.ReadOnlyKeyword)));
}
else
{
var setterType = wellKnownTypes.Action_2.Construct(field.Field.ContainingType, field.SafeType).ToTypeSyntax();
var fieldSetterVariable = VariableDeclarator(field.SetterFieldName);
result.Add(
FieldDeclaration(VariableDeclaration(setterType).AddVariables(fieldSetterVariable))
.AddModifiers(
Token(SyntaxKind.PrivateKeyword),
Token(SyntaxKind.ReadOnlyKeyword)));
}
}
}
return result.ToArray();
}
/// <summary>
/// Returns syntax for initializing a new instance of the provided type.
/// </summary>
private ExpressionSyntax GetObjectCreationExpressionSyntax(INamedTypeSymbol type, SemanticModel model)
{
ExpressionSyntax result;
if (type.IsValueType)
{
// Use the default value.
result = DefaultExpression(type.ToTypeSyntax());
}
else if (GetEmptyConstructor(type, model) != null)
{
// Use the default constructor.
result = ObjectCreationExpression(type.ToTypeSyntax()).AddArgumentListArguments();
}
else
{
// Create an unformatted object.
result = CastExpression(
type.ToTypeSyntax(),
InvocationExpression(wellKnownTypes.FormatterServices.ToTypeSyntax().Member("GetUninitializedObject"))
.AddArgumentListArguments(
Argument(TypeOfExpression(type.ToTypeSyntax()))));
}
return result;
}
/// <summary>
/// Return the default constructor on <paramref name="type"/> if found or null if not found.
/// </summary>
private IMethodSymbol GetEmptyConstructor(INamedTypeSymbol type, SemanticModel model)
{
return type.GetDeclaredInstanceMembers<IMethodSymbol>()
.FirstOrDefault(method => method.MethodKind == MethodKind.Constructor && method.Parameters.Length == 0 && model.IsAccessible(0, method));
}
/// <summary>
/// Returns a sorted list of the fields of the provided type.
/// </summary>
private List<FieldInfoMember> GetFields(SemanticModel model, INamedTypeSymbol type, ILogger logger)
{
var result = new List<FieldInfoMember>();
foreach (var field in type.GetDeclaredInstanceMembers<IFieldSymbol>())
{
if (ShouldSerializeField(field))
{
result.Add(new FieldInfoMember(this, model, type, field, result.Count));
}
}
if (type.TypeKind == TypeKind.Class)
{
// Some reference assemblies are compiled without private fields.
// Warn the user if they are inheriting from a type in one of these assemblies using a heuristic:
// If the type inherits from a type in a reference assembly and there are no fields declared on those
// base types, emit a warning.
var hasUnsupportedRefAsmBase = false;
var referenceAssemblyHasFields = false;
var baseType = type.BaseType;
while (baseType != null &&
!SymbolEqualityComparer.Default.Equals(baseType, wellKnownTypes.Object) &&
!SymbolEqualityComparer.Default.Equals(baseType, wellKnownTypes.Attribute))
{
if (!hasUnsupportedRefAsmBase
&& baseType.ContainingAssembly.HasAttribute("ReferenceAssemblyAttribute")
&& !IsSupportedRefAsmType(baseType))
{
hasUnsupportedRefAsmBase = true;
}
foreach (var field in baseType.GetDeclaredInstanceMembers<IFieldSymbol>())
{
if (hasUnsupportedRefAsmBase) referenceAssemblyHasFields = true;
if (ShouldSerializeField(field))
{
result.Add(new FieldInfoMember(this, model, type, field, result.Count));
}
}
baseType = baseType.BaseType;
}
if (hasUnsupportedRefAsmBase && !referenceAssemblyHasFields)
{
var fileLocation = string.Empty;
var declaration = type.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() as ClassDeclarationSyntax;
if (declaration != null)
{
var location = declaration.Identifier.GetLocation();
if (location.IsInSource)
{
var pos = location.GetLineSpan();
fileLocation = string.Format(
"{0}({1},{2},{3},{4}): ",
pos.Path,
pos.StartLinePosition.Line + 1,
pos.StartLinePosition.Character + 1,
pos.EndLinePosition.Line + 1,
pos.EndLinePosition.Character + 1);
}
}
logger.LogWarning(
$"{fileLocation}warning ORL1001: Type {type} has a base type which belongs to a reference assembly."
+ " Serializer generation for this type may not include important base type fields.");
}
bool IsSupportedRefAsmType(INamedTypeSymbol t)
{
INamedTypeSymbol baseDefinition;
if (t.IsGenericType && !t.IsUnboundGenericType)
{
baseDefinition = t.ConstructUnboundGenericType().OriginalDefinition;
}
else
{
baseDefinition = t.OriginalDefinition;
}
foreach (var refAsmType in wellKnownTypes.SupportedRefAsmBaseTypes)
{
if (SymbolEqualityComparer.Default.Equals(baseDefinition, refAsmType)) return true;
}
return false;
}
}
result.Sort(FieldInfoMember.Comparer.Instance);
return result;
}
/// <summary>
/// Returns <see langowrd="true"/> if the provided field should be serialized, <see langword="false"/> otherwise.
/// </summary>
public bool ShouldSerializeField(IFieldSymbol symbol)
{
if (symbol.IsStatic) return false;
if (symbol.HasAttribute(wellKnownTypes.NonSerializedAttribute)) return false;
ITypeSymbol fieldType = symbol.Type;
if (fieldType.TypeKind == TypeKind.Pointer) return false;
if (fieldType.TypeKind == TypeKind.Delegate) return false;
if (fieldType.SpecialType == SpecialType.System_IntPtr) return false;
if (fieldType.SpecialType == SpecialType.System_UIntPtr) return false;
if (symbol.ContainingType.HasBaseType(wellKnownTypes.MarshalByRefObject)) return false;
return true;
}
internal bool IsOrleansShallowCopyable(ITypeSymbol type)
{
switch (type.SpecialType)
{
case SpecialType.System_Boolean:
case SpecialType.System_Char:
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_Decimal:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_String:
case SpecialType.System_DateTime:
return true;
}
if (SymbolEqualityComparer.Default.Equals(wellKnownTypes.TimeSpan, type)
|| SymbolEqualityComparer.Default.Equals(wellKnownTypes.IPAddress, type)
|| SymbolEqualityComparer.Default.Equals(wellKnownTypes.IPEndPoint, type)
|| SymbolEqualityComparer.Default.Equals(wellKnownTypes.SiloAddress, type)
|| SymbolEqualityComparer.Default.Equals(wellKnownTypes.GrainId, type)
|| SymbolEqualityComparer.Default.Equals(wellKnownTypes.ActivationId, type)
|| SymbolEqualityComparer.Default.Equals(wellKnownTypes.ActivationAddress, type)
|| wellKnownTypes.CorrelationId is WellKnownTypes.Some correlationIdType && SymbolEqualityComparer.Default.Equals(correlationIdType.Value, type)
|| SymbolEqualityComparer.Default.Equals(wellKnownTypes.CancellationToken, type)
|| SymbolEqualityComparer.Default.Equals(wellKnownTypes.Type, type)) return true;
if (ShallowCopyableTypes.TryGetValue(type, out var result)) return result;
if (type.HasAttribute(wellKnownTypes.ImmutableAttribute))
{
return ShallowCopyableTypes[type] = true;
}
if (type.HasBaseType(wellKnownTypes.Exception))
{
return ShallowCopyableTypes[type] = true;
}
if (!(type is INamedTypeSymbol namedType))
{
return ShallowCopyableTypes[type] = false;
}
if (namedType.IsTupleType)
{
return ShallowCopyableTypes[type] = namedType.TupleElements.All(f => IsOrleansShallowCopyable(f.Type));
}
else if (namedType.IsGenericType)
{
var def = namedType.ConstructedFrom;
if (def.SpecialType == SpecialType.System_Nullable_T)
{
return ShallowCopyableTypes[type] = IsOrleansShallowCopyable(namedType.TypeArguments.Single());
}
if (SymbolEqualityComparer.Default.Equals(wellKnownTypes.Immutable_1, def))
{
return ShallowCopyableTypes[type] = true;
}
if (wellKnownTypes.TupleTypes.Any(t => SymbolEqualityComparer.Default.Equals(t, def)))
{
return ShallowCopyableTypes[type] = namedType.TypeArguments.All(IsOrleansShallowCopyable);
}
}
else
{
if (type.TypeKind == TypeKind.Enum)
{
return ShallowCopyableTypes[type] = true;
}
if (type.TypeKind == TypeKind.Struct && !namedType.IsUnboundGenericType)
{
return ShallowCopyableTypes[type] = IsValueTypeFieldsShallowCopyable(type);
}
}
return ShallowCopyableTypes[type] = false;
}
private bool IsValueTypeFieldsShallowCopyable(ITypeSymbol type)
{
foreach (var field in type.GetInstanceMembers<IFieldSymbol>())
{
if (field.IsStatic) continue;
if (!(field.Type is INamedTypeSymbol fieldType))
{
return false;
}
if (SymbolEqualityComparer.Default.Equals(type, fieldType)) return false;
if (!IsOrleansShallowCopyable(fieldType)) return false;
}
return true;
}
/// <summary>
/// Represents a field.
/// </summary>
private class FieldInfoMember
{
private readonly SerializerGenerator generator;
private readonly SemanticModel model;
private readonly WellKnownTypes wellKnownTypes;
private readonly INamedTypeSymbol targetType;
private IPropertySymbol property;
/// <summary>
/// The ordinal assigned to this field.
/// </summary>
private readonly int ordinal;
public FieldInfoMember(SerializerGenerator generator, SemanticModel model, INamedTypeSymbol targetType, IFieldSymbol field, int ordinal)
{
this.generator = generator;
this.wellKnownTypes = generator.wellKnownTypes;
this.model = model;
this.targetType = targetType;
this.Field = field;
this.ordinal = ordinal;
}
/// <summary>
/// Gets the underlying <see cref="Field"/> instance.
/// </summary>
public IFieldSymbol Field { get; }
/// <summary>
/// Gets a usable representation of the field type.
/// </summary>
/// <remarks>
/// If the field is of type 'dynamic', we represent it as 'object' because 'dynamic' cannot appear in typeof expressions.
/// </remarks>
public ITypeSymbol SafeType => this.Field.Type.TypeKind == TypeKind.Dynamic
? this.wellKnownTypes.Object
: this.Field.Type;
/// <summary>
/// Gets the name of the field info field.
/// </summary>
public string InfoFieldName => "field" + this.ordinal;
/// <summary>
/// Gets the name of the getter field.
/// </summary>
public string GetterFieldName => "getField" + this.ordinal;
/// <summary>
/// Gets the name of the setter field.
/// </summary>
public string SetterFieldName => "setField" + this.ordinal;
/// <summary>
/// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete getter.
/// </summary>
public bool IsGettableProperty => this.Property?.GetMethod != null && this.model.IsAccessible(0, this.Property.GetMethod) && !this.IsObsolete;
/// <summary>
/// Gets a value indicating whether or not this field represents a property with an accessible, non-obsolete setter.
/// </summary>
public bool IsSettableProperty => this.Property?.SetMethod != null && this.model.IsAccessible(0, this.Property.SetMethod) && !this.IsObsolete;
/// <summary>
/// Gets syntax representing the type of this field.
/// </summary>
public TypeSyntax Type => this.SafeType.ToTypeSyntax();
/// <summary>
/// Gets the <see cref="Property"/> which this field is the backing property for, or
/// <see langword="null" /> if this is not the backing field of an auto-property.
/// </summary>
private IPropertySymbol Property
{
get
{
if (this.property != null)
{
return this.property;
}
var propertyName = Regex.Match(this.Field.Name, "^<([^>]+)>.*$");
if (!propertyName.Success || this.Field.ContainingType == null) return null;
var name = propertyName.Groups[1].Value;
var candidates = this.targetType
.GetInstanceMembers<IPropertySymbol>()
.Where(p => string.Equals(name, p.Name, StringComparison.Ordinal) && !p.IsAbstract)
.ToArray();
if (candidates.Length > 1) return null;
if (!SymbolEqualityComparer.Default.Equals(this.SafeType, candidates[0].Type)) return null;
return this.property = candidates[0];
}
}
/// <summary>
/// Gets a value indicating whether or not this field is obsolete.
/// </summary>
private bool IsObsolete => this.Field.HasAttribute(this.wellKnownTypes.ObsoleteAttribute) ||
this.Property != null && this.Property.HasAttribute(this.wellKnownTypes.ObsoleteAttribute);
/// <summary>
/// Returns syntax for retrieving the value of this field, deep copying it if necessary.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <param name="serializationContextExpression">The expression used to retrieve the serialization context.</param>
/// <param name="forceAvoidCopy">Whether or not to ensure that no copy of the field is made.</param>
/// <returns>Syntax for retrieving the value of this field.</returns>
public ExpressionSyntax GetGetter(ExpressionSyntax instance, ExpressionSyntax serializationContextExpression = null, bool forceAvoidCopy = false)
{
// Retrieve the value of the field.
var getValueExpression = this.GetValueExpression(instance);
// Avoid deep-copying the field if possible.
if (forceAvoidCopy || generator.IsOrleansShallowCopyable(this.SafeType))
{
// Return the value without deep-copying it.
return getValueExpression;
}
// Addressable arguments must be converted to references before passing.
// IGrainObserver instances cannot be directly converted to references, therefore they are not included.
ExpressionSyntax deepCopyValueExpression;
if (this.SafeType.HasInterface(this.wellKnownTypes.IAddressable) &&
this.SafeType.TypeKind == TypeKind.Interface &&
!this.SafeType.HasInterface(this.wellKnownTypes.IGrainObserver))
{
var getAsReference = getValueExpression.Member("AsReference".ToGenericName().AddTypeArgumentListArguments(this.Type));
// If the value is not a GrainReference, convert it to a strongly-typed GrainReference.
// C#: (value == null || value is GrainReference) ? value : value.AsReference<TInterface>()
deepCopyValueExpression =
ConditionalExpression(
ParenthesizedExpression(
BinaryExpression(
SyntaxKind.LogicalOrExpression,
BinaryExpression(
SyntaxKind.EqualsExpression,
getValueExpression,
LiteralExpression(SyntaxKind.NullLiteralExpression)),
BinaryExpression(
SyntaxKind.IsExpression,
getValueExpression,
this.wellKnownTypes.GrainReference.ToTypeSyntax()))),
getValueExpression,
InvocationExpression(getAsReference));
}
else
{
deepCopyValueExpression = getValueExpression;
}
// Deep-copy the value.
return CastExpression(
this.Type,
InvocationExpression(serializationContextExpression.Member("DeepCopyInner"))
.AddArgumentListArguments(
Argument(deepCopyValueExpression)));
}
/// <summary>
/// Returns syntax for setting the value of this field.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <param name="value">Syntax for the new value.</param>
/// <returns>Syntax for setting the value of this field.</returns>
public ExpressionSyntax GetSetter(ExpressionSyntax instance, ExpressionSyntax value)
{
// If the field is the backing field for an accessible auto-property use the property directly.
if (this.IsSettableProperty)
{
return AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
instance.Member(this.Property.Name),
value);
}
var instanceArg = Argument(instance);
if (this.Field.ContainingType != null && this.Field.ContainingType.IsValueType)
{
instanceArg = instanceArg.WithRefOrOutKeyword(Token(SyntaxKind.RefKeyword));
}
return
InvocationExpression(IdentifierName(this.SetterFieldName))
.AddArgumentListArguments(instanceArg, Argument(value));
}
/// <summary>
/// Returns syntax for retrieving the value of this field.
/// </summary>
/// <param name="instance">The instance of the containing type.</param>
/// <returns>Syntax for retrieving the value of this field.</returns>
private ExpressionSyntax GetValueExpression(ExpressionSyntax instance)
{
// If the field is the backing field for an accessible auto-property use the property directly.
ExpressionSyntax result;
if (this.IsGettableProperty)
{
result = instance.Member(this.Property.Name);
}
else
{
// Retrieve the field using the generated getter.
result =
InvocationExpression(IdentifierName(this.GetterFieldName))
.AddArgumentListArguments(Argument(instance));
}
return result;
}
/// <summary>
/// A comparer for <see cref="FieldInfoMember"/> which compares by name.
/// </summary>
public class Comparer : IComparer<FieldInfoMember>
{
/// <summary>
/// Gets the singleton instance of this class.
/// </summary>
public static Comparer Instance { get; } = new Comparer();
public int Compare(FieldInfoMember x, FieldInfoMember y)
{
return string.Compare(x?.Field.Name, y?.Field.Name, StringComparison.Ordinal);
}
}
}
}
}
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
using System;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using IronScheme.Editor.ComponentModel;
using IronScheme.Editor.Collections;
using IronScheme.Editor.Controls.Design;
using IServiceProvider = System.IServiceProvider;
using LSharp;
namespace IronScheme.Editor.Controls
{
class GridDocument : Document
{
public GridDocument()
: base(new Grid())
{
AdvancedTextBox atb = new AdvancedTextBox();
atb.EditorLanguage = "LSharp";
AddView(atb);
}
protected override void SwitchView(IDocument newview, IDocument oldview)
{
if (newview is AdvancedTextBox)
{
AdvancedTextBox atb = newview as AdvancedTextBox;
Grid g = oldview as Grid;
StringWriter w = new StringWriter();
g.Save(w);
StringReader r = new StringReader(w.ToString());
atb.Buffer.Load(r);
}
else
{
AdvancedTextBox atb = oldview as AdvancedTextBox;
Grid g = newview as Grid;
StringWriter w = new StringWriter();
atb.Buffer.Save(w);
StringReader r = new StringReader(w.ToString());
g.Open(r);
}
}
}
/// <summary>
/// Summary description for Grid.
/// </summary>
[Name("Grid")]
class Grid : Control, IServiceProvider, IWindowsFormsEditorService, IEdit, IFile, INavigate, IHasUndo
{
#region Fields
private System.ComponentModel.IContainer components = null;
StringFormat sf = new StringFormat(StringFormatFlags.NoWrap);
Hashtable cellstore = new Hashtable();
Hashtable formatstore = new Hashtable();
readonly LSharp.Environment environment = new LSharp.Environment(TopLoop.Environment);
Pen borderpen = SystemPens.WindowFrame;
Brush selbrush;
static BinaryFormatter bf = new BinaryFormatter();
static Regex txtparse = new Regex(@"
(?<real>^-?(\d*\.\d+)$)|
(?<int>^-?\d+$) |
(?<creation>^\w+(\.\w+)*:.*$) |
(?<text>^.+$)",
RegexOptions.ExplicitCapture |
RegexOptions.Compiled |
RegexOptions.IgnorePatternWhitespace);
int padding = 2;
int w = 150;
int h;
Pen selpen;
Size size;
Cell topleft = new Cell(0,0);
Cell fareast = new Cell(0,0);
Cell farsouth = new Cell(0,0);
bool isediting = false;
TextBox editingbox = new TextBox();
private System.Windows.Forms.ErrorProvider errorProvider1;
Range selrange = new Range( new Cell(0,0), new Cell(0,0));
readonly ITypeDescriptorContext context;
#endregion
#region Events
public event EventHandler CornerClick;
protected void OnCornerClick(object sender, EventArgs e)
{
if (CornerClick != null)
CornerClick(this, e);
}
public delegate void CellEditorHandler(object sender, ref object obj);
public event CellEditorHandler CellEdit;
#endregion
#region UI Handling
protected override void OnResize(EventArgs e)
{
base.OnResize (e);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion
#region Cell Service
object IServiceProvider.GetService(Type serviceType)
{
if (serviceType == typeof(IWindowsFormsEditorService))
{
return this;
}
return null;
}
Panel editorpanel = new Panel();
Control uieditor;
void IWindowsFormsEditorService.DropDownControl(Control uieditor)
{
if (this.uieditor != null)
{
((IWindowsFormsEditorService)this).CloseDropDown();
}
this.uieditor = uieditor;
uieditor.Tag = selrange.InitialCell;
//normally these editors are not font friendly, so keep it default,
//if they wanna change they can change from with in that control.
//control.Font = g.Font;
Rectangle rf = rf = GetInitialCell();
editorpanel.Location = new Point(rf.X, rf.Bottom);
editorpanel.Width = rf.Width > uieditor.Width ? rf.Width : uieditor.Width;
editorpanel.Height = uieditor.Height;
uieditor.Dock = DockStyle.Fill;
uieditor.KeyDown +=new KeyEventHandler(uieditor_KeyDown);
editorpanel.Controls.Add(uieditor);
Controls.Add(editorpanel);
editorpanel.Visible = true;
uieditor.Select();
while (editorpanel.Visible)
{
Application.DoEvents();
Runtime.user32.MsgWaitForMultipleObjects(1, 0, true, 250, 0xff);
}
}
void IWindowsFormsEditorService.CloseDropDown()
{
editorpanel.Visible = false;
editorpanel.Controls.Remove(uieditor);
Controls.Remove(editorpanel);
uieditor = null;
Invalidate(true);
}
DialogResult IWindowsFormsEditorService.ShowDialog(Form dialog)
{
return 0;
}
void uieditor_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
e.Handled = true;
((IWindowsFormsEditorService)this).CloseDropDown();
}
else
if (e.Alt && e.KeyCode == Keys.Enter)
{
e.Handled = true;
((IWindowsFormsEditorService)this).CloseDropDown();
}
}
#endregion
#region Cell / Range
public Rectangle GetInitialCell()
{
return GetCell(selrange.InitialCell);
}
[Serializable]
internal struct Cell : IComparable
{
int row;
int col;
public int Row
{
get { return row; }
set
{
if (value >= 0)
row = value; }
}
public int Col
{
get { return col; }
set { if (value >= 0) col = value; }
}
public Cell(int row, int col)
{
this.row = row >= 0 ? row : 0;
this.col = col >= 0 ? col : 0;
}
public Cell(string v)
{
row = col = 0;
int i = 0;
while (i < v.Length && Char.IsLetter(v[i]))
{
col *= 26;
col += Char.ToLower(v[i]) - 'a';
i++;
}
while (i < v.Length && Char.IsDigit(v[i]))
{
row *= 10;
row += v[i] - '0';
i++;
}
row--;
}
public static Cell operator ++(Cell c)
{
c.row++;
return c;
}
public static Cell operator --(Cell c)
{
c.row--;
return c;
}
public static Cell operator <<(Cell c, int i)
{
c.col -= i;
return c;
}
public static Cell operator >>(Cell c, int i)
{
c.col += i;
return c;
}
#if DEBUG
public string DebugInfo
{
get {return ToString();}
}
#endif
public override string ToString()
{
return string.Format("{0}{1}", (char) (col + 'a'), row + 1);
}
public int CompareTo(object o)
{
if (!(o is Cell))
{
return 1;
}
Cell a = (Cell) o;
if (a.col == col)
{
return row.CompareTo(a.row);
}
return col.CompareTo(a.col);
}
}
[Serializable]
internal struct Range : IEnumerable
{
internal Cell start;
internal Cell finish;
public Range(Cell start, Cell finish)
{
this.start = start;
this.finish = finish;
}
public Range(string v)
{
string[] tokens = v.Split('.');
start = new Cell(tokens[0]);
finish = new Cell(tokens[2]);
}
#if DEBUG
public string DebugInfo
{
get {return ToString();}
}
#endif
public bool Contains(Cell cell)
{
return (TopLeft.Col >= cell.Col && cell.Col <= BottomRight.Col) &&
(TopLeft.Row >= cell.Row && cell.Row <= BottomRight.Row);
}
public Cell InitialCell
{
get {return start;}
}
public Cell TopLeft
{
get
{
return new Cell(start.Row > finish.Row ? finish.Row : start.Row ,
start.Col > finish.Col ? finish.Col : start.Col) ; }
}
public Cell BottomRight
{
get
{
return new Cell(start.Row < finish.Row ? finish.Row : start.Row ,
start.Col < finish.Col ? finish.Col : start.Col) ; }
}
public int Width
{
get {return System.Math.Abs(finish.Col - start.Col) + 1;}
}
public int Height
{
get {return System.Math.Abs(finish.Row - start.Row) + 1;}
}
public int Count
{
get {return Height * Width;}
}
public override string ToString()
{
return String.Format("{0}..{1}", TopLeft, BottomRight);
}
public IEnumerator GetEnumerator()
{
ArrayList enu = new ArrayList();
for (int c = TopLeft.Col; c <= BottomRight.Col; c++)
{
for (int r = TopLeft.Row; r <= BottomRight.Row; r++)
{
enu.Add(new Cell(r,c));
}
}
return enu.GetEnumerator();
}
}
#endregion
#region IFile Members
int lastsavelevel = 0;
public bool IsDirty
{
get
{
return undo.CurrentLevel != lastsavelevel;;
}
}
void IDocument.Close()
{
}
string IDocument.Info
{
get
{
if (selrange.Count > 1)
{
return selrange.ToString();
}
else
{
return selrange.InitialCell + " : " + Printer.WriteToString(this[selrange.InitialCell]);
}
}
}
#endregion
#region Clipboard
readonly static Hashtable clipboard = new Hashtable();
bool recording = true;
readonly UndoRedoStack undo;
/// <summary>
/// Undo the last action. The state is as if you never had the action at all.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>The behaviour is recursive.</item>
/// <item>CanUndo is called from within function.</item>
/// </list>
/// </remarks>
public void Undo()
{
if (CanUndo)
{
recording = false;
undo.Pop().CallUndo();
recording = true;
Invalidate();
}
}
/// <summary>
/// Redo the last undo action. The state is as if you never had the undo action at all.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>The behaviour is recursive.</item>
/// <item>CanRedo is called from within function.</item>
/// </list>
/// </remarks>
public void Redo()
{
if (CanRedo)
{
undo.CurrentLevel++;
if (undo.Top != null)
{
recording = false;
undo.Top.CallRedo();
recording = true;
Invalidate();
}
}
}
/// <summary>
/// Checks if the TextBuffer can be undone to a previous state.
/// </summary>
/// <value>
/// Returns true if possible.
/// </value>
public bool CanUndo
{
get {return undo.CanUndo;}
}
/// <summary>
/// Checks if the TextBuffer can be redone to a previously undone state.
/// </summary>
/// <value>
/// Returns true if possible.
/// </value>
public bool CanRedo
{
get {return undo.CanRedo;}
}
/// <summary>
/// Clears the undo stack.
/// </summary>
public void ClearUndo()
{
undo.Clear();
}
object IHasUndo.GetUndoState()
{
return selrange;
}
void IHasUndo.RestoreUndoState(object state)
{
//selrange = (Range)state;
}
sealed class SetCellsOperation : Operation
{
Grid g;
Range r;
object[,] newvalue, oldvalue;
public SetCellsOperation(Grid g, Range r, object[,] newvalue, object[,] oldvalue) :
base(null, null)
{
this.g = g;
this.r = r;
this.newvalue = newvalue;
this.oldvalue = oldvalue;
}
protected override void Redo()
{
g.selrange = r;
g.SelectedObjects = newvalue;
}
protected override void Undo()
{
g.selrange = r;
g.SelectedObjects = oldvalue;
}
}
sealed class SetCellOperation : Operation
{
Grid g;
Cell c;
object newvalue, oldvalue;
public SetCellOperation(Grid g, Cell c, object newvalue, object oldvalue) :
base(null, null)
{
this.g = g;
this.c = c;
this.newvalue = newvalue;
this.oldvalue = oldvalue;
}
protected override void Redo()
{
g[c] = newvalue;
}
protected override void Undo()
{
g[c] = oldvalue;
}
}
[Serializable]
class CellClip
{
public string value;
public string typeconv;
}
[Serializable]
class Reference
{
public Guid key = Guid.NewGuid();
}
[ClassInterface(ClassInterfaceType.None)]
class CellDataObject : IDataObject
{
readonly Hashtable data = new Hashtable();
public CellDataObject(Grid g)
{
object o = g.SelectedObject;
if (g.SelectedObjects.Length > 1)
{
Reference r = new Reference();
clipboard.Add(r.key, g.SelectedObjects);
data[DataFormats.Serializable] = r;
}
else
{
CellClip cc = new CellClip();
TypeConverter tc = TypeDescriptor.GetConverter(o);
cc.typeconv = tc.GetType().AssemblyQualifiedName;
if (tc is LSharpConverter)
{
cc.value = Printer.WriteToString(o);
}
else
{
cc.value = tc.ConvertToString(o);
}
data[DataFormats.Text] = cc.value;
data[DataFormats.Serializable] = cc;
}
}
public bool GetDataPresent(Type format)
{
return (format == typeof(string));
}
public bool GetDataPresent(string format)
{
return GetDataPresent(format, false);
}
public bool GetDataPresent(string format, bool autoConvert)
{
return data.ContainsKey(format);
}
public object GetData(Type format)
{
if (format == typeof(string))
{
return data[DataFormats.Text];
}
return null;
}
public object GetData(string format)
{
return GetData(format, false);
}
public object GetData(string format, bool autoConvert)
{
return data[format];
}
static string[] formats = { DataFormats.Text, DataFormats.Rtf, DataFormats.Html };
public string[] GetFormats()
{
return GetFormats(false);
}
public string[] GetFormats(bool autoConvert)
{
return formats;
}
public void SetData(object data)
{
if (data is string)
{
this.data[DataFormats.Text] = data;
}
}
public void SetData(Type format, object data)
{
if (format == typeof(string))
{
this.data[DataFormats.Text] = data;
}
}
public void SetData(string format, object data)
{
SetData(format, false, data);
}
public void SetData(string format, bool autoConvert, object data)
{
this.data[format] = data;
}
}
public void Cut()
{
Clipboard.SetDataObject( new CellDataObject(this), false);
DeleteSelected();
}
public void Copy()
{
Clipboard.SetDataObject( new CellDataObject(this), false);
}
public void Paste()
{
IDataObject cdo = Clipboard.GetDataObject();
if (cdo != null)
{
object o = cdo.GetData(DataFormats.Serializable);
if (o is CellClip)
{
CellClip cc = o as CellClip;
Type t = Type.GetType(cc.typeconv);
TypeConverter tc = Activator.CreateInstance(t) as TypeConverter;
SelectedObject = tc.ConvertFrom(cc.value);
LSharpUIEditor.conshistory[SelectedObject] = cc.value;
}
else if (o is Reference)
{
Reference r = o as Reference;
object[,] so = clipboard[r.key] as object[,];
SelectedObjects = so;
}
Invalidate();
}
}
public void DeleteSelected()
{
SelectedObjects = new object[selrange.Width,selrange.Height];
Invalidate();
}
void IEdit.SelectAll()
{
// TODO: Add Grid.SelectAll implementation
}
#endregion
#region Initialization/Dispose
public Grid()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
errorProvider1.ContainerControl = FindForm();
editingbox.BorderStyle = BorderStyle.Fixed3D;
editingbox.AutoSize = false;
editingbox.Font = Font;
editingbox.VisibleChanged+=new EventHandler(editingbox_VisibleChanged);
editorpanel.BorderStyle = BorderStyle.FixedSingle;
editorpanel.Visible = false;
editingbox.KeyDown +=new KeyEventHandler(tb_KeyUp);
Color selcolor = SystemColors.Highlight;
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
sf.Trimming = StringTrimming.EllipsisWord;
selpen = new Pen(selcolor, 1f);
selpen.Alignment = PenAlignment.Outset;
selpen.LineJoin = LineJoin.Round;
selbrush = new SolidBrush(Color.FromArgb(40, selcolor));
SetStyle( ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.StandardClick |
ControlStyles.StandardClick | ControlStyles.ContainerControl |
ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint |
ControlStyles.Selectable , true);
h = Font.Height + padding * 2;
using (Graphics g = CreateGraphics())
size = Size.Ceiling(g.MeasureString("000", Font));
context = new GridContext(this);
undo = new UndoRedoStack(this);
environment.SymbolAssigned +=new EnvironmentEventHandler(environment_SymbolAssigned);
environment.SymbolChanged +=new EnvironmentEventHandler(environment_SymbolChanged);
environment.SymbolRemoved +=new EnvironmentEventHandler(environment_SymbolRemoved);
}
#endregion
#region ITypeDescriptorContext
class GridContext : ITypeDescriptorContext
{
readonly Grid grid;
public GridContext(Grid g)
{
grid = g;
}
public void OnComponentChanged()
{
}
public IContainer Container
{
get { return null; }
}
public bool OnComponentChanging()
{
return false;
}
public object Instance
{
get { return grid; }
}
public PropertyDescriptor PropertyDescriptor
{
get {return null;}
}
public object GetService(Type serviceType)
{
return ((IServiceProvider)grid).GetService(serviceType);
}
}
internal LSharp.Environment Environment
{
get {return environment;}
}
#endregion
#region Grid Painting
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawRules(e.Graphics);
}
void DrawRules(Graphics g)
{
//g.CompositingQuality = CompositingQuality.HighQuality;
//g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//g.PixelOffsetMode = PixelOffsetMode.HighQuality;
//g.SmoothingMode = SmoothingMode.HighSpeed;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
sf.Alignment = StringAlignment.Center;
//vertical band
g.FillRectangle(SystemBrushes.Control, 0, 0, size.Width, Height);
//horizontal band
g.FillRectangle(SystemBrushes.Control, 0, 0, Width, h);
Rectangle cell = CurrentSelection;
//vertical selection
g.FillRectangle(Brushes.DarkGray, 0, cell.Y, size.Width, cell.Height);
//horizontal selection
g.FillRectangle(Brushes.DarkGray, cell.X, 0, cell.Width, h);
//horizontal lines ====
int i = topleft.Row;
for (float height = 0; height < Height; height += h, i++)
{
g.DrawLine(SystemPens.ControlDark, 0, height, Width, height);
if (i != (topleft.Row))
{
RectangleF r = new RectangleF(0, height, size.Width, h);
g.DrawString(i.ToString(), Font, SystemBrushes.ControlText, r, sf);
}
}
//vertical lines ||||||
char row = (char)(topleft.Col + 'A');
for (float width = size.Width; width < Width; width += w, row++)
{
g.DrawLine(SystemPens.ControlDark, width, 0, width, Height);
RectangleF r = new RectangleF(width, 0, w , h);
g.DrawString(row.ToString(), Font, SystemBrushes.ControlText, r, sf);
}
//draw selected cell/range
Rectangle sr = GetCell(selrange.InitialCell);
cell = CurrentSelection;
foreach (DictionaryEntry de in cellstore)
{
Cell c = (Cell)de.Key;
Rectangle r = GetCell(c);
UITypeEditor uieditor = TypeDescriptor.GetEditor(de.Value, typeof(UITypeEditor)) as UITypeEditor;
TypeConverter typeconv = TypeDescriptor.GetConverter(de.Value);
r.Inflate(-2,-2);
int rh = r.Height;
if (rh < 19)
{
rh = 19;
}
Rectangle rr = new Rectangle(r.X + rh, r.Y, r.Width - rh, r.Height);
Rectangle rrr = new Rectangle(r.X, r.Y, rh, r.Height);
//do the custom rendering process here, albeit call it
if (typeconv.CanConvertTo(context, typeof(double)))
{
sf.Alignment = StringAlignment.Far;
}
else
{
sf.Alignment = StringAlignment.Near;
}
if (de.Value == null)
{
sf.Alignment = StringAlignment.Center;
g.DrawString("Press F2 or double-click to edit", Font, Drawing.Factory.SolidBrush(SystemColors.GrayText), r, sf);
}
else
{
string sv = typeconv.ConvertTo(context, null, de.Value, typeof(string)) as string;
if (de.Value is Cons || de.Value is Symbol)
{
object v = typeconv.ConvertTo(context, null, de.Value, typeof(object));
if (v != null)
{
if (TypeDescriptor.GetConverter(v).CanConvertTo(context, typeof(double)))
{
sf.Alignment = StringAlignment.Far;
}
else
{
sf.Alignment = StringAlignment.Near;
}
}
}
if (uieditor != null && uieditor.GetPaintValueSupported())
{
// uieditor.PaintValue(de.Value, g, rrr);
// g.DrawRectangle(SystemPens.WindowFrame, rrr);
// g.DrawString(sv, Font, SystemBrushes.ControlText, rr, sf);
Rectangle r2 = r;
r2.Inflate(1,1);
r2.Height++;
r2.Width++;
g.FillRectangle(SystemBrushes.Info, r2);
g.DrawString(sv, Font, SystemBrushes.ControlText, r, sf);
}
else
{
g.DrawString(sv, Font, SystemBrushes.ControlText, r, sf);
}
}
}
Drawing.Utils.PaintLineHighlight(selbrush, selpen, g, cell.X-1, cell.Y-1, cell.Width+2, cell.Height+2, true);
}
#endregion
#region Key Handling
protected override void OnControlAdded(ControlEventArgs e)
{
if (e.Control == editingbox)
{
ServiceHost.State &= ~ApplicationState.Navigate;
}
base.OnControlAdded (e);
}
protected override void OnControlRemoved(ControlEventArgs e)
{
if (e.Control == editingbox)
{
ServiceHost.State |= ApplicationState.Navigate;
}
base.OnControlRemoved (e);
}
public void NavigateUp()
{
if (shift)
{
selrange.finish.Row--;
}
else
{
selrange.start.Row--;
selrange.finish = selrange.start;
}
Invalidate();
}
public void NavigateDown()
{
if (shift)
{
selrange.finish.Row++;
}
else
{
selrange.start.Row++;
selrange.finish = selrange.start;
}
Invalidate();
}
public void NavigateLeft()
{
if (shift)
{
selrange.finish.Col--;
}
else
{
selrange.start.Col--;
selrange.finish = selrange.start;
}
Invalidate();
}
public void NavigateRight()
{
if (shift)
{
selrange.finish.Col++;
}
else
{
selrange.start.Col++;
selrange.finish = selrange.start;
}
Invalidate();
}
public void NavigateHome()
{
Invalidate();
}
public void NavigateEnd()
{
Invalidate();
}
public void NavigatePageUp()
{
Invalidate();
}
public void NavigatePageDown()
{
Invalidate();
}
bool shift = false;
protected override void OnKeyDown(KeyEventArgs e)
{
shift = e.Shift;
switch (e.KeyCode)
{
case Keys.Right:
if (e.Alt)
{
object p = SelectedObject;
if (p == null)
{
p = Symbol.FromName(selrange.InitialCell.ToString());
}
OnCellEdit( ref p);
e.Handled = true;
}
break;
case Keys.Escape:
if (editorpanel.Visible)
{
((IWindowsFormsEditorService)this).CloseDropDown();
}
else
{
selrange.finish = selrange.InitialCell;
}
e.Handled = true;
Invalidate();
break;
case Keys.F2:
object o = this[selrange.InitialCell];
OnCellEdit( ref o);
e.Handled = true;
break;
case Keys.Delete:
DeleteSelected();
e.Handled = true;
break;
}
base.OnKeyDown (e);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar >= ' ' && e.KeyChar != '=')
{
object o = e.KeyChar.ToString();
OnCellEdit(ref o);
}
base.OnKeyPress (e);
}
protected override void OnKeyUp(KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.ShiftKey:
shift = false;
break;
}
base.OnKeyUp (e);
}
private void tb_KeyUp(object sender, KeyEventArgs e)
{
Cell origcell = selrange.InitialCell;
switch (e.KeyCode)
{
case Keys.Up:
selrange.start.Row--;
selrange.finish = selrange.start;
goto case Keys.Enter;
case Keys.Down:
selrange.start.Row++;
selrange.finish = selrange.start;
goto case Keys.Enter;
case Keys.Enter:
bool error = false;
TextBox tb = sender as TextBox;
Match m = txtparse.Match(tb.Text);
object o = null;
if (m.Groups["creation"].Success)
{
string[] tokens = tb.Text.Split(':');
if (tokens.Length == 2 || tokens.Length == 1)
{
string typename = tokens[0].Trim();
Type t = Type.GetType(typename, false, true);
if (t == null)
{
bool found = false;
CaseInsensitiveComparer cic = new CaseInsensitiveComparer();
foreach(Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
{
if (found)
break;
if (ass is System.Reflection.Emit.AssemblyBuilder)
continue;
foreach (Type asst in ass.GetExportedTypes())
{
if (cic.Compare(typename,asst.Name) == 0)
{
t = asst;
found = true;
break;
}
}
}
}
// force the exception assume the user is an idiot at all times
if (t != null && !t.IsAbstract && !t.IsInterface)
{
try
{
string s = tokens.Length < 2 ? "0" : tokens[1];
s = s.Trim();
TypeConverter tc = TypeDescriptor.GetConverter(t);
if (tc != null && tc.CanConvertFrom(typeof(string)))
{
if (s.Length == 0)
s = "0"; //default value
o = tc.ConvertFromString(s);
}
else
{
o = Activator.CreateInstance(t);
}
}
catch (Exception ex)
{
errorProvider1.SetError(tb, ex.Message);
error = true;
}
}
else
{
errorProvider1.SetError(tb, String.Format("Type: '{0}' was not found", typename));
error = true;
}
}
}
else if (m.Groups["int"].Success)
{
o = Convert.ToInt32(tb.Text);
}
else if (m.Groups["real"].Success)
{
o = Convert.ToSingle(tb.Text);
}
else if (m.Groups["text"].Success)
{
o = tb.Text;
}
else
{
if (tb.Text.Trim().Length > 0)
{
//throw new FormatException("Insano user error!");
errorProvider1.SetError(tb, String.Format("Formatting error"));
error = true;
}
}
if (o != null)
this[origcell] = o;
if (!error)
{
Controls.Remove(tb);
isediting = false;
}
Invalidate();
e.Handled = true;
break;
case Keys.Escape:
Controls.Remove(sender as Control);
isediting = false;
e.Handled = true;
break;
}
}
#endregion
#region Mouse Handling
void editingbox_VisibleChanged(object sender, EventArgs e)
{
if (!editingbox.Visible)
{
errorProvider1.SetError(editingbox, "");
}
}
protected override void OnDoubleClick(EventArgs e)
{
base.OnDoubleClick(e);
object o = this[selrange.InitialCell];
Capture = false; // HOLY MOSES!!!
OnCellEdit(ref o);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (mousedown)
{
selrange.finish = GetCellAt(e.X, e.Y);
Invalidate();
}
}
base.OnMouseMove (e);
}
protected override void OnMouseWheel(MouseEventArgs e)
{
base.OnMouseWheel (e);
}
ContextMenuStrip contextmenu;
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus (e);
if (contextmenu == null)
{
contextmenu = new ContextMenuStrip();
ToolStripMenuItem mi = ServiceHost.Menu["Edit"];
Hashtable attrmap = (ServiceHost.Menu as MenuService).GetAttributeMap(mi);
foreach (ToolStripItem m in mi.DropDownItems)
{
ToolStripMenuItem pmi = m as ToolStripMenuItem;
if (pmi != null)
{
MenuItemAttribute mia = attrmap[pmi] as MenuItemAttribute;
if (mia == null)
{
}
else
if ((mia.State & (ApplicationState.Edit)) != 0)
{
contextmenu.Items.Add(pmi.Clone());
}
}
else
{
contextmenu.Items.Add("-");
}
}
ContextMenuStrip = contextmenu;
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mousedown = false;
selrange.finish = GetCellAt(e.X, e.Y);
Invalidate();
}
base.OnMouseUp (e);
}
volatile bool mousedown = false;
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown (e);
if (editorpanel.Visible)
{
((IWindowsFormsEditorService)this).CloseDropDown();
}
if (!Focused)
{
Focus();
}
if (e.Button == MouseButtons.Left)
{
if (isediting)
{
bool error = false;
TextBox tb = editingbox as TextBox;
if (tb.Text.Length == 0)
{
Controls.Remove(tb);
isediting = false;
}
else
{
Match m = txtparse.Match(tb.Text);
object o = null;
if (m.Groups["creation"].Success)
{
string[] tokens = tb.Text.Split(':');
if (tokens.Length == 2 || tokens.Length == 1)
{
string typename = tokens[0].Trim();
Type t = Type.GetType(typename, false, true);
if (t == null)
{
bool found = false;
CaseInsensitiveComparer cic = new CaseInsensitiveComparer();
foreach(Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
{
if (found)
break;
if (ass is System.Reflection.Emit.AssemblyBuilder)
continue;
foreach (Type asst in ass.GetExportedTypes())
{
if (cic.Compare(typename,asst.Name) == 0)
{
t = asst;
found = true;
break;
}
}
}
}
// force the exception assume the user is an idiot at all times
if (t != null && !t.IsAbstract && !t.IsInterface)
{
try
{
string s = tokens.Length < 2 ? "0" : tokens[1];
s = s.Trim();
TypeConverter tc = TypeDescriptor.GetConverter(t);
if (tc != null && tc.CanConvertFrom(typeof(string)))
{
if (s.Length == 0)
s = "0"; //default value
o = tc.ConvertFromString(s);
}
else
{
o = Activator.CreateInstance(t);
}
}
catch (Exception ex)
{
errorProvider1.SetError(tb, ex.Message);
error = true;
}
}
else
{
errorProvider1.SetError(tb, String.Format("Type: '{0}' was not found", typename));
error = true;
}
}
}
else if (m.Groups["int"].Success)
{
o = Convert.ToInt32(tb.Text);
}
else if (m.Groups["real"].Success)
{
o = Convert.ToSingle(tb.Text);
}
else if (m.Groups["text"].Success)
{
o = tb.Text;
}
else
{
if (tb.Text.Trim().Length > 0)
{
//throw new FormatException("Insano user error!");
errorProvider1.SetError(tb, String.Format("Formatting error"));
error = true;
}
}
if (o != null)
this[selrange.InitialCell] = o;
if (!error)
{
Controls.Remove(tb);
isediting = false;
}
}
}
mousedown = true;
if (shift)
{
selrange.finish = GetCellAt(e.X, e.Y);
}
else
{
selrange.start = GetCellAt(e.X, e.Y);
selrange.finish = selrange.start;
}
Invalidate();
}
}
#endregion
#region Cell Metrics
public int CellHeight
{
get {return h;}
set {h = value;}
}
public int CellWidth
{
get {return w;}
set {w = value;}
}
public int VisibleColumns
{
get {return (int)(ClientSize.Width - size.Width)/(int)w ;}
}
public int VisibleRows
{
get {return (int)(ClientSize.Height - h - size.Height)/(int)h ;}
}
Rectangle GetRange(Range r)
{
return new Rectangle(size.Width + w * (r.TopLeft.Col - topleft.Col),
h * (r.TopLeft.Row - topleft.Row + 1), w * r.Width, h * r.Height);
}
Rectangle GetCell(Cell r)
{
return new Rectangle(size.Width + w * (r.Col - topleft.Col), h * (r.Row - topleft.Row + 1), w, h);
}
Rectangle SelectedCell
{
get {return GetCell(selrange.start);}
}
Rectangle CurrentSelection
{
get {return GetRange(selrange);}
}
void UpdateFar(Cell newmax)
{
UpdateFarEast(newmax);
UpdateFarSouth(newmax);
}
void UpdateFarEast(Cell newmax)
{
if ( newmax.Col > fareast.Col)
fareast = newmax;
}
void UpdateFarSouth(Cell newmax)
{
if ( newmax.Row > farsouth.Row)
farsouth = newmax;
}
Cell FarSouthEast
{
get {return new Cell(farsouth.Row, fareast.Col);}
}
Cell BottomLeft
{
get {return new Cell(topleft.Row + VisibleRows, topleft.Col + VisibleColumns);}
}
Cell GetCellAt(int x, int y)
{
return new Cell((int)((y - h)/h) + topleft.Row, (int)((x - size.Width)/w) + topleft.Col);
}
#endregion
#region Load/Save
public void Save(TextWriter w)
{
w.WriteLine("(=");
ArrayList keys = new ArrayList(cellstore.Keys);
keys.Sort();
foreach (Cell c in keys)
{
object v = cellstore[c];
if (v is Symbol || v is Cons)
{
w.WriteLine(" {0,-4} '{1}", c, Printer.WriteToString(v));
}
else
{
w.WriteLine(" {0,-4} {1}", c, Printer.WriteToString(v));
}
}
w.WriteLine(")");
}
public void Save(string filename)
{
SuspendLayout();
Stream s = File.Create(filename);
TextWriter w = new StreamWriter(s);
Save(w);
lastsavelevel = undo.CurrentLevel;
w.Flush();
w.Close();
}
public void Open(TextReader r)
{
string t = r.ReadToEnd();
recording = false;
object res = LSharp.Runtime.EvalString(t, environment);
recording = true;
selrange = new Range("a1..a1");
foreach (Cell c in cellstore.Keys)
{
UpdateFar(c);
}
ResumeLayout();
Invalidate();
}
public void Open(string filename)
{
if (!File.Exists(filename))
{
System.Diagnostics.Trace.WriteLine("File does not exist: " + filename);
return;
}
Stream s = null;
try
{
s = File.OpenRead(filename);
TextReader r = new StreamReader(s);
Open(r);
s.Close();
s = null;
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex);
if (s != null)
s.Close();
}
}
#endregion
#region External Cell Access
public object this[string c]
{
get {return this[new Cell(c)];}
set{this[new Cell(c)] = value;}
}
public int SelectedObjectCount
{
get {return selrange.Count;}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public object SelectedObject
{
get {return this[selrange.InitialCell];}
set {this[selrange.InitialCell] = value;}
}
public object[,] SelectedObjects
{
get
{
//make this the enumerator
object[,] so = new object[selrange.Width, selrange.Height];
for (int x = 0; x < selrange.Width; x++)
{
for (int y = 0; y < selrange.Height; y++)
{
Cell c = new Cell( selrange.TopLeft.Row + y, selrange.TopLeft.Col + x);
so[x,y] = this[c];
}
}
return so;
}
set
{
object[,] so = value;
Cell c = selrange.TopLeft;
Cell end = new Cell(c.Row + so.GetLength(1) - 1, c.Col + so.GetLength(0) - 1);
selrange = new Range(c, end);
object[,] old = SelectedObjects;
for (int j = 0; j < so.GetLength(0); j++, c = selrange.TopLeft >> j)
{
for (int i = 0; i < so.GetLength(1); i++, c++)
{
object ov = cellstore[c];
object nv = so[j,i];
if (!object.Equals(ov, nv))
{
if (nv == null && ov != null)
{
cellstore.Remove(c);
}
else
{
cellstore[c] = nv;
}
}
environment.AssignLocal(Symbol.FromName(c.ToString()), nv);
}
}
if (recording)
{
undo.Push( new SetCellsOperation(this, selrange , so, old));
}
}
}
#if DEBUG
public Hashtable WTF
{
get {return cellstore;}
}
#endif
#endregion
#region Cell Editing
void environment_SymbolAssigned(object sender, EnvironmentEventArgs e)
{
this[e.SymbolName] = e.NewValue;
Invalidate();
}
void environment_SymbolChanged(object sender, EnvironmentEventArgs e)
{
this[e.SymbolName] = e.NewValue;
Invalidate();
}
void environment_SymbolRemoved(object sender, EnvironmentEventArgs e)
{
this[e.SymbolName] = e.NewValue;
Invalidate();
}
public object this[int col, int row]
{
get {return this[new Cell(row, col)];}
set {this[new Cell(row, col)] = value;}
}
public event EventHandler CellValueChanged;
object this[Cell c]
{
get {return cellstore[c];}
set
{
object ov = cellstore[c];
if (!object.Equals(ov, value))
{
if (value == null && ov != null)
{
cellstore.Remove(c);
}
else
{
cellstore[c] = value;
}
environment.AssignLocal(Symbol.FromName(c.ToString()), value);
if (CellValueChanged != null)
{
CellValueChanged(this, EventArgs.Empty);
}
if (recording)
{
undo.Push( new SetCellOperation(this, c, value, ov));
}
Invalidate();
}
}
}
protected void OnCellEdit(ref object obj)
{
//check object type etc
if (obj == null)
{
//popup lame object creation dialog ..... maybe.....
isediting = true;
Rectangle cc = GetCell(selrange.InitialCell);
cc.Inflate(1,1);
cc.Height++;
cc.Width++;
editingbox.Text = "";
editingbox.Bounds = cc;
Controls.Add(editingbox);
editingbox.Focus();
editingbox.Select(editingbox.TextLength, 0);
}
else
{
Type type = obj.GetType();
object uied = TypeDescriptor.GetEditor(type, typeof(UITypeEditor));
TypeConverter tc = TypeDescriptor.GetConverter(obj);
if (uied == null)
{
if (typeof(Enum).IsAssignableFrom(type))
{
if (type.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
{
uied = new FlaggedEnumEditor();
}
else
{
uied = new EnumEditor();
}
}
else if (tc != null && tc.GetStandardValuesSupported())
{
uied = new SupportedValuesEditor();
}
}
if (uied != null)
{
UITypeEditor uie = uied as UITypeEditor;
this[selrange.InitialCell] = uie.EditValue(context, this, obj);
return;
}
if (tc != null)
{
if (tc.CanConvertFrom(typeof(string)) && tc.CanConvertTo(typeof(string)))
{
//display textbox;
isediting = true;
Rectangle cc = GetCell(selrange.InitialCell);
cc.Inflate(1,1);
cc.Height++;
cc.Width++;
editingbox.Text = tc.ConvertTo(obj, typeof(string)) as string;
editingbox.Tag = tc;
editingbox.Bounds = cc;
Controls.Add(editingbox);
editingbox.Focus();
editingbox.Select(editingbox.TextLength, 0);
}
}
else if (CellEdit != null)
{
CellEdit(this, ref obj);
}
}
}
#endregion
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.errorProvider1 = new System.Windows.Forms.ErrorProvider();
//
// Grid
//
this.BackColor = System.Drawing.SystemColors.Window;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.Font = SystemInformation.MenuFont;
this.Size = new System.Drawing.Size(448, 416);
}
#endregion
#region IEdit Members
void IEdit.DeleteCurrentLine()
{
// do nothing for now
}
#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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareGreaterThanOrEqualOrderedScalarSingle()
{
var test = new BooleanComparisonOpTest__CompareGreaterThanOrEqualOrderedScalarSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanComparisonOpTest__CompareGreaterThanOrEqualOrderedScalarSingle
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[ElementCount];
private static Single[] _data2 = new Single[ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private BooleanComparisonOpTest__DataTable<Single> _dataTable;
static BooleanComparisonOpTest__CompareGreaterThanOrEqualOrderedScalarSingle()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
}
public BooleanComparisonOpTest__CompareGreaterThanOrEqualOrderedScalarSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
_dataTable = new BooleanComparisonOpTest__DataTable<Single>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse.CompareGreaterThanOrEqualOrderedScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse.CompareGreaterThanOrEqualOrderedScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse.CompareGreaterThanOrEqualOrderedScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThanOrEqualOrderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThanOrEqualOrderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThanOrEqualOrderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
var result = Sse.CompareGreaterThanOrEqualOrderedScalar(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareGreaterThanOrEqualOrderedScalar(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareGreaterThanOrEqualOrderedScalar(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareGreaterThanOrEqualOrderedScalar(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanComparisonOpTest__CompareGreaterThanOrEqualOrderedScalarSingle();
var result = Sse.CompareGreaterThanOrEqualOrderedScalar(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse.CompareGreaterThanOrEqualOrderedScalar(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Single[] left, Single[] right, bool result, [CallerMemberName] string method = "")
{
if ((left[0] >= right[0]) != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareGreaterThanOrEqualOrderedScalar)}<Single>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace NuGet
{
public static class PathResolver
{
/// <summary>
/// Returns a collection of files from the source that matches the wildcard.
/// </summary>
/// <param name="source">The collection of files to match.</param>
/// <param name="getPath">Function that returns the path to filter a package file </param>
/// <param name="wildcards">The wildcards to apply to match the path with.</param>
/// <returns></returns>
public static IEnumerable<T> GetMatches<T>(IEnumerable<T> source, Func<T, string> getPath, IEnumerable<string> wildcards)
{
var filters = wildcards.Select(WildcardToRegex);
return source.Where(item =>
{
string path = getPath(item);
return filters.Any(f => f.IsMatch(path));
});
}
/// <summary>
/// Removes files from the source that match any wildcard.
/// </summary>
public static void FilterPackageFiles<T>(ICollection<T> source, Func<T, string> getPath, IEnumerable<string> wildcards)
{
var matchedFiles = new HashSet<T>(GetMatches(source, getPath, wildcards));
source.RemoveAll(matchedFiles.Contains);
}
public static string NormalizeWildcard(string basePath, string wildcard)
{
basePath = NormalizeBasePath(basePath, ref wildcard);
return Path.Combine(basePath, wildcard);
}
private static Regex WildcardToRegex(string wildcard)
{
var pattern = Regex.Escape(wildcard);
if (Path.DirectorySeparatorChar == '/')
{
// regex wildcard adjustments for *nix-style file systems
pattern = pattern
.Replace(@"\*\*/", ".*") //For recursive wildcards /**/, include the current directory.
.Replace(@"\*\*", ".*") // For recursive wildcards that don't end in a slash e.g. **.txt would be treated as a .txt file at any depth
.Replace(@"\*", @"[^/]*(/)?") // For non recursive searches, limit it any character that is not a directory separator
.Replace(@"\?", "."); // ? translates to a single any character
}
else
{
// regex wildcard adjustments for Windows-style file systems
pattern = pattern
.Replace("/", @"\\") // On Windows, / is treated the same as \.
.Replace(@"\*\*\\", ".*") //For recursive wildcards \**\, include the current directory.
.Replace(@"\*\*", ".*") // For recursive wildcards that don't end in a slash e.g. **.txt would be treated as a .txt file at any depth
.Replace(@"\*", @"[^\\]*(\\)?") // For non recursive searches, limit it any character that is not a directory separator
.Replace(@"\?", "."); // ? translates to a single any character
}
return new Regex('^' + pattern + '$', RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
}
internal static IEnumerable<PhysicalPackageFile> ResolveSearchPattern(string basePath, string searchPath, string targetPath, bool includeEmptyDirectories)
{
string normalizedBasePath;
IEnumerable<SearchPathResult> searchResults = PerformWildcardSearchInternal(basePath, searchPath, includeEmptyDirectories, out normalizedBasePath);
return searchResults.Select(result =>
result.IsFile
? new PhysicalPackageFile
{
SourcePath = result.Path,
TargetPath = ResolvePackagePath(normalizedBasePath, searchPath, result.Path, targetPath)
}
: new EmptyFrameworkFolderFile(ResolvePackagePath(normalizedBasePath, searchPath, result.Path, targetPath))
{
SourcePath = result.Path
}
);
}
public static IEnumerable<string> PerformWildcardSearch(string basePath, string searchPath)
{
string normalizedBasePath;
var searchResults = PerformWildcardSearchInternal(basePath, searchPath, includeEmptyDirectories: false, normalizedBasePath: out normalizedBasePath);
return searchResults.Select(s => s.Path);
}
private static IEnumerable<SearchPathResult> PerformWildcardSearchInternal(string basePath, string searchPath, bool includeEmptyDirectories, out string normalizedBasePath)
{
if (!searchPath.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase))
{
// If we aren't dealing with network paths, trim the leading slash.
searchPath = searchPath.TrimStart(Path.DirectorySeparatorChar);
}
bool searchDirectory = false;
// If the searchPath ends with \ or /, we treat searchPath as a directory,
// and will include everything under it, recursively
if (IsDirectoryPath(searchPath))
{
searchPath = searchPath + "**" + Path.DirectorySeparatorChar + "*";
searchDirectory = true;
}
basePath = NormalizeBasePath(basePath, ref searchPath);
normalizedBasePath = GetPathToEnumerateFrom(basePath, searchPath);
// Append the basePath to searchPattern and get the search regex. We need to do this because the search regex is matched from line start.
Regex searchRegex = WildcardToRegex(Path.Combine(basePath, searchPath));
// This is a hack to prevent enumerating over the entire directory tree if the only wildcard characters are the ones in the file name.
// If the path portion of the search path does not contain any wildcard characters only iterate over the TopDirectory.
SearchOption searchOption = SearchOption.AllDirectories;
// (a) Path is not recursive search
bool isRecursiveSearch = searchPath.IndexOf("**", StringComparison.OrdinalIgnoreCase) != -1;
// (b) Path does not have any wildcards.
bool isWildcardPath = Path.GetDirectoryName(searchPath).Contains('*');
if (!isRecursiveSearch && !isWildcardPath)
{
searchOption = SearchOption.TopDirectoryOnly;
}
// Starting from the base path, enumerate over all files and match it using the wildcard expression provided by the user.
// Note: We use Directory.GetFiles() instead of Directory.EnumerateFiles() here to support Mono
var matchedFiles = from file in Directory.GetFiles(normalizedBasePath, "*.*", searchOption)
where searchRegex.IsMatch(file)
select new SearchPathResult(file, isFile: true);
if (!includeEmptyDirectories)
{
return matchedFiles;
}
// retrieve empty directories
// Note: We use Directory.GetDirectories() instead of Directory.EnumerateDirectories() here to support Mono
var matchedDirectories = from directory in Directory.GetDirectories(normalizedBasePath, "*.*", searchOption)
where searchRegex.IsMatch(directory) && IsEmptyDirectory(directory)
select new SearchPathResult(directory, isFile: false);
if (searchDirectory && IsEmptyDirectory(normalizedBasePath))
{
matchedDirectories = matchedDirectories.Concat(new [] { new SearchPathResult(normalizedBasePath, isFile: false) });
}
return matchedFiles.Concat(matchedDirectories);
}
internal static string GetPathToEnumerateFrom(string basePath, string searchPath)
{
string basePathToEnumerate;
int wildcardIndex = searchPath.IndexOf('*');
if (wildcardIndex == -1)
{
// For paths without wildcard, we could either have base relative paths (such as lib\foo.dll) or paths outside the base path
// (such as basePath: C:\packages and searchPath: D:\packages\foo.dll)
// In this case, Path.Combine would pick up the right root to enumerate from.
var searchRoot = Path.GetDirectoryName(searchPath);
basePathToEnumerate = Path.Combine(basePath, searchRoot);
}
else
{
// If not, find the first directory separator and use the path to the left of it as the base path to enumerate from.
int directorySeparatoryIndex = searchPath.LastIndexOf(Path.DirectorySeparatorChar, wildcardIndex);
if (directorySeparatoryIndex == -1)
{
// We're looking at a path like "NuGet*.dll", NuGet*\bin\release\*.dll
// In this case, the basePath would continue to be the path to begin enumeration from.
basePathToEnumerate = basePath;
}
else
{
string nonWildcardPortion = searchPath.Substring(0, directorySeparatoryIndex);
basePathToEnumerate = Path.Combine(basePath, nonWildcardPortion);
}
}
return basePathToEnumerate;
}
/// <summary>
/// Determins the path of the file inside a package.
/// For recursive wildcard paths, we preserve the path portion beginning with the wildcard.
/// For non-recursive wildcard paths, we use the file name from the actual file path on disk.
/// </summary>
internal static string ResolvePackagePath(string searchDirectory, string searchPattern, string fullPath, string targetPath)
{
string packagePath;
bool isDirectorySearch = IsDirectoryPath(searchPattern);
bool isWildcardSearch = IsWildcardSearch(searchPattern);
bool isRecursiveWildcardSearch = isWildcardSearch && searchPattern.IndexOf("**", StringComparison.OrdinalIgnoreCase) != -1;
if ((isRecursiveWildcardSearch || isDirectorySearch) && fullPath.StartsWith(searchDirectory, StringComparison.OrdinalIgnoreCase))
{
// The search pattern is recursive. Preserve the non-wildcard portion of the path.
// e.g. Search: X:\foo\**\*.cs results in SearchDirectory: X:\foo and a file path of X:\foo\bar\biz\boz.cs
// Truncating X:\foo\ would result in the package path.
packagePath = fullPath.Substring(searchDirectory.Length).TrimStart(Path.DirectorySeparatorChar);
}
else if (!isWildcardSearch && Path.GetExtension(searchPattern).Equals(Path.GetExtension(targetPath), StringComparison.OrdinalIgnoreCase))
{
// If the search does not contain wild cards, and the target path shares the same extension, copy it
// e.g. <file src="ie\css\style.css" target="Content\css\ie.css" /> --> Content\css\ie.css
return targetPath;
}
else
{
packagePath = Path.GetFileName(fullPath);
}
return Path.Combine(targetPath ?? String.Empty, packagePath);
}
internal static string NormalizeBasePath(string basePath, ref string searchPath)
{
const string relativePath = @"..\";
// If no base path is provided, use the current directory.
basePath = String.IsNullOrEmpty(basePath) ? @".\" : basePath;
// If the search path is relative, transfer the ..\ portion to the base path.
// This needs to be done because the base path determines the root for our enumeration.
while (searchPath.StartsWith(relativePath, StringComparison.OrdinalIgnoreCase))
{
basePath = Path.Combine(basePath, relativePath);
searchPath = searchPath.Substring(relativePath.Length);
}
return Path.GetFullPath(basePath);
}
/// <summary>
/// Returns true if the path contains any wildcard characters.
/// </summary>
internal static bool IsWildcardSearch(string filter)
{
return filter.IndexOf('*') != -1;
}
internal static bool IsDirectoryPath(string path)
{
return path != null && path.Length > 1 &&
(path[path.Length - 1] == Path.DirectorySeparatorChar ||
path[path.Length - 1] == Path.AltDirectorySeparatorChar);
}
private static bool IsEmptyDirectory(string directory)
{
return !Directory.EnumerateFileSystemEntries(directory).Any();
}
private struct SearchPathResult
{
private readonly string _path;
private readonly bool _isFile;
public string Path
{
get
{
return _path;
}
}
public bool IsFile
{
get
{
return _isFile;
}
}
public SearchPathResult(string path, bool isFile)
{
_path = path;
_isFile = isFile;
}
}
}
}
| |
//
// AddinStore.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Reflection;
using System.Diagnostics;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Mono.Addins;
using Mono.Addins.Setup.ProgressMonitoring;
using Mono.Addins.Description;
using Mono.Addins.Serialization;
using System.Collections.Generic;
using System.Linq;
namespace Mono.Addins.Setup
{
internal class AddinStore
{
SetupService service;
public AddinStore (SetupService service)
{
this.service = service;
}
internal void ResetCachedData ()
{
}
public AddinRegistry Registry {
get { return service.Registry; }
}
public bool Install (IProgressStatus statusMonitor, params string[] files)
{
Package[] packages = new Package [files.Length];
for (int n=0; n<files.Length; n++)
packages [n] = AddinPackage.FromFile (files [n]);
return Install (statusMonitor, packages);
}
public bool Install (IProgressStatus statusMonitor, params AddinRepositoryEntry[] addins)
{
Package[] packages = new Package [addins.Length];
for (int n=0; n<addins.Length; n++)
packages [n] = AddinPackage.FromRepository (addins [n]);
return Install (statusMonitor, packages);
}
internal bool Install (IProgressStatus monitor, params Package[] packages)
{
PackageCollection packs = new PackageCollection ();
packs.AddRange (packages);
return Install (monitor, packs);
}
internal bool Install (IProgressStatus statusMonitor, PackageCollection packs)
{
// Make sure the registry is up to date
service.Registry.Update (statusMonitor);
IProgressMonitor monitor = ProgressStatusMonitor.GetProgressMonitor (statusMonitor);
PackageCollection toUninstall;
DependencyCollection unresolved;
if (!ResolveDependencies (monitor, packs, out toUninstall, out unresolved)) {
monitor.ReportError ("Not all dependencies could be resolved.", null);
return false;
}
ArrayList prepared = new ArrayList ();
ArrayList uninstallPrepared = new ArrayList ();
bool rollback = false;
monitor.BeginTask ("Installing add-ins...", 100);
// Prepare install
monitor.BeginStepTask ("Initializing installation", toUninstall.Count + packs.Count + 1, 75);
foreach (Package mpack in toUninstall) {
try {
mpack.PrepareUninstall (monitor, this);
uninstallPrepared.Add (mpack);
if (monitor.IsCancelRequested)
throw new InstallException ("Installation cancelled.");
monitor.Step (1);
} catch (Exception ex) {
ReportException (monitor, ex);
rollback = true;
break;
}
}
monitor.Step (1);
foreach (Package mpack in packs) {
try {
mpack.PrepareInstall (monitor, this);
if (monitor.IsCancelRequested)
throw new InstallException ("Installation cancelled.");
prepared.Add (mpack);
monitor.Step (1);
} catch (Exception ex) {
ReportException (monitor, ex);
rollback = true;
break;
}
}
monitor.EndTask ();
monitor.BeginStepTask ("Installing", toUninstall.Count + packs.Count + 1, 20);
// Commit install
if (!rollback) {
foreach (Package mpack in toUninstall) {
try {
mpack.CommitUninstall (monitor, this);
if (monitor.IsCancelRequested)
throw new InstallException ("Installation cancelled.");
monitor.Step (1);
} catch (Exception ex) {
ReportException (monitor, ex);
rollback = true;
break;
}
}
}
monitor.Step (1);
if (!rollback) {
foreach (Package mpack in packs) {
try {
mpack.CommitInstall (monitor, this);
if (monitor.IsCancelRequested)
throw new InstallException ("Installation cancelled.");
monitor.Step (1);
} catch (Exception ex) {
ReportException (monitor, ex);
rollback = true;
break;
}
}
}
monitor.EndTask ();
// Rollback if failed
if (monitor.IsCancelRequested)
monitor = new NullProgressMonitor ();
if (rollback) {
monitor.BeginStepTask ("Finishing installation", (prepared.Count + uninstallPrepared.Count)*2 + 1, 5);
foreach (Package mpack in prepared) {
try {
mpack.RollbackInstall (monitor, this);
monitor.Step (1);
} catch (Exception ex) {
ReportException (monitor, ex);
}
}
foreach (Package mpack in uninstallPrepared) {
try {
mpack.RollbackUninstall (monitor, this);
monitor.Step (1);
} catch (Exception ex) {
ReportException (monitor, ex);
}
}
} else
monitor.BeginStepTask ("Finishing installation", prepared.Count + uninstallPrepared.Count + 1, 5);
// Cleanup
foreach (Package mpack in prepared) {
try {
mpack.EndInstall (monitor, this);
monitor.Step (1);
} catch (Exception ex) {
monitor.Log.WriteLine (ex);
}
}
monitor.Step (1);
foreach (Package mpack in uninstallPrepared) {
try {
mpack.EndUninstall (monitor, this);
monitor.Step (1);
} catch (Exception ex) {
monitor.Log.WriteLine (ex);
}
}
// Update the extension maps
service.Registry.Update (statusMonitor);
monitor.EndTask ();
monitor.EndTask ();
service.SaveConfiguration ();
ResetCachedData ();
return !rollback;
}
void ReportException (IProgressMonitor statusMonitor, Exception ex)
{
if (ex is InstallException)
statusMonitor.ReportError (ex.Message, null);
else
statusMonitor.ReportError (null, ex);
}
public void Uninstall (IProgressStatus statusMonitor, string id)
{
Uninstall (statusMonitor, new string[] { id });
}
public void Uninstall (IProgressStatus statusMonitor, IEnumerable<string> ids)
{
IProgressMonitor monitor = ProgressStatusMonitor.GetProgressMonitor (statusMonitor);
monitor.BeginTask ("Uninstalling add-ins", ids.Count ());
foreach (string id in ids) {
bool rollback = false;
ArrayList toUninstall = new ArrayList ();
ArrayList uninstallPrepared = new ArrayList ();
Addin ia = service.Registry.GetAddin (id);
if (ia == null)
throw new InstallException ("The add-in '" + id + "' is not installed.");
toUninstall.Add (AddinPackage.FromInstalledAddin (ia));
Addin[] deps = GetDependentAddins (id, true);
foreach (Addin dep in deps)
toUninstall.Add (AddinPackage.FromInstalledAddin (dep));
monitor.BeginTask ("Deleting files", toUninstall.Count*2 + uninstallPrepared.Count + 1);
// Prepare install
foreach (Package mpack in toUninstall) {
try {
mpack.PrepareUninstall (monitor, this);
monitor.Step (1);
uninstallPrepared.Add (mpack);
} catch (Exception ex) {
ReportException (monitor, ex);
rollback = true;
break;
}
}
// Commit install
if (!rollback) {
foreach (Package mpack in toUninstall) {
try {
mpack.CommitUninstall (monitor, this);
monitor.Step (1);
} catch (Exception ex) {
ReportException (monitor, ex);
rollback = true;
break;
}
}
}
// Rollback if failed
if (rollback) {
monitor.BeginTask ("Rolling back uninstall", uninstallPrepared.Count);
foreach (Package mpack in uninstallPrepared) {
try {
mpack.RollbackUninstall (monitor, this);
} catch (Exception ex) {
ReportException (monitor, ex);
}
}
monitor.EndTask ();
}
monitor.Step (1);
// Cleanup
foreach (Package mpack in uninstallPrepared) {
try {
mpack.EndUninstall (monitor, this);
monitor.Step (1);
} catch (Exception ex) {
monitor.Log.WriteLine (ex);
}
}
monitor.EndTask ();
monitor.Step (1);
}
// Update the extension maps
service.Registry.Update (statusMonitor);
monitor.EndTask ();
service.SaveConfiguration ();
ResetCachedData ();
}
public Addin[] GetDependentAddins (string id, bool recursive)
{
ArrayList list = new ArrayList ();
FindDependentAddins (list, id, recursive);
return (Addin[]) list.ToArray (typeof (Addin));
}
void FindDependentAddins (ArrayList list, string id, bool recursive)
{
foreach (Addin iaddin in service.Registry.GetAddins ()) {
if (list.Contains (iaddin))
continue;
foreach (Dependency dep in iaddin.Description.MainModule.Dependencies) {
AddinDependency adep = dep as AddinDependency;
if (adep != null && adep.AddinId == id) {
list.Add (iaddin);
if (recursive)
FindDependentAddins (list, iaddin.Id, true);
}
}
}
}
public bool ResolveDependencies (IProgressStatus statusMonitor, AddinRepositoryEntry[] addins, out PackageCollection resolved, out PackageCollection toUninstall, out DependencyCollection unresolved)
{
resolved = new PackageCollection ();
for (int n=0; n<addins.Length; n++)
resolved.Add (AddinPackage.FromRepository (addins [n]));
return ResolveDependencies (statusMonitor, resolved, out toUninstall, out unresolved);
}
public bool ResolveDependencies (IProgressStatus statusMonitor, PackageCollection packages, out PackageCollection toUninstall, out DependencyCollection unresolved)
{
IProgressMonitor monitor = ProgressStatusMonitor.GetProgressMonitor (statusMonitor);
return ResolveDependencies (monitor, packages, out toUninstall, out unresolved);
}
internal bool ResolveDependencies (IProgressMonitor monitor, PackageCollection packages, out PackageCollection toUninstall, out DependencyCollection unresolved)
{
PackageCollection requested = new PackageCollection();
requested.AddRange (packages);
unresolved = new DependencyCollection ();
toUninstall = new PackageCollection ();
PackageCollection installedRequired = new PackageCollection ();
for (int n=0; n<packages.Count; n++) {
Package p = packages [n];
p.Resolve (monitor, this, packages, toUninstall, installedRequired, unresolved);
}
if (unresolved.Count != 0) {
foreach (Dependency dep in unresolved)
monitor.ReportError (string.Format ("The package '{0}' could not be found in any repository", dep.Name), null);
return false;
}
// Check that we are not uninstalling packages that are required
// by packages being installed.
foreach (Package p in installedRequired) {
if (toUninstall.Contains (p)) {
// Only accept to uninstall this package if we are
// going to install a newer version.
bool foundUpgrade = false;
foreach (Package tbi in packages)
if (tbi.Equals (p) || tbi.IsUpgradeOf (p)) {
foundUpgrade = true;
break;
}
if (!foundUpgrade)
return false;
}
}
// Check that we are not trying to uninstall from a directory from
// which we don't have write permissions
foreach (Package p in toUninstall) {
AddinPackage ap = p as AddinPackage;
if (ap != null) {
Addin ia = service.Registry.GetAddin (ap.Addin.Id);
if (File.Exists (ia.AddinFile) && !HasWriteAccess (ia.AddinFile) && IsUserAddin (ia.AddinFile)) {
monitor.ReportError (GetUninstallErrorNoRoot (ap.Addin), null);
return false;
}
}
}
// Check that we are not installing two versions of the same addin
PackageCollection resolved = new PackageCollection();
resolved.AddRange (packages);
bool error = false;
for (int n=0; n<packages.Count; n++) {
AddinPackage ap = packages [n] as AddinPackage;
if (ap == null) continue;
for (int k=n+1; k<packages.Count; k++) {
AddinPackage otherap = packages [k] as AddinPackage;
if (otherap == null) continue;
if (ap.Addin.Id == otherap.Addin.Id) {
if (ap.IsUpgradeOf (otherap)) {
if (requested.Contains (otherap)) {
monitor.ReportError ("Can't install two versions of the same add-in: '" + ap.Addin.Name + "'.", null);
error = true;
} else {
packages.RemoveAt (k);
}
} else if (otherap.IsUpgradeOf (ap)) {
if (requested.Contains (ap)) {
monitor.ReportError ("Can't install two versions of the same add-in: '" + ap.Addin.Name + "'.", null);
error = true;
} else {
packages.RemoveAt (n);
n--;
}
} else {
error = true;
monitor.ReportError ("Can't install two versions of the same add-in: '" + ap.Addin.Name + "'.", null);
}
break;
}
}
}
// Don't allow installing add-ins which are scheduled for uninstall
foreach (Package p in packages) {
AddinPackage ap = p as AddinPackage;
if (ap != null && Registry.IsRegisteredForUninstall (ap.Addin.Id)) {
error = true;
monitor.ReportError ("The addin " + ap.Addin.Name + " v" + ap.Addin.Version + " is scheduled for uninstallation. Please restart the application before trying to re-install it.", null);
}
}
return !error;
}
internal void ResolveDependency (IProgressMonitor monitor, Dependency dep, AddinPackage parentPackage, PackageCollection toInstall, PackageCollection toUninstall, PackageCollection installedRequired, DependencyCollection unresolved)
{
AddinDependency adep = dep as AddinDependency;
if (adep == null)
return;
string nsid = Addin.GetFullId (parentPackage.Addin.Namespace, adep.AddinId, null);
foreach (Package p in toInstall) {
AddinPackage ap = p as AddinPackage;
if (ap != null) {
if (Addin.GetIdName (ap.Addin.Id) == nsid && ((AddinInfo)ap.Addin).SupportsVersion (adep.Version))
return;
}
}
ArrayList addins = new ArrayList ();
addins.AddRange (service.Registry.GetAddins ());
addins.AddRange (service.Registry.GetAddinRoots ());
foreach (Addin addin in addins) {
if (Addin.GetIdName (addin.Id) == nsid && addin.SupportsVersion (adep.Version)) {
AddinPackage p = AddinPackage.FromInstalledAddin (addin);
if (!installedRequired.Contains (p))
installedRequired.Add (p);
return;
}
}
AddinRepositoryEntry[] avaddins = service.Repositories.GetAvailableAddins ();
foreach (PackageRepositoryEntry avAddin in avaddins) {
if (Addin.GetIdName (avAddin.Addin.Id) == nsid && ((AddinInfo)avAddin.Addin).SupportsVersion (adep.Version)) {
toInstall.Add (AddinPackage.FromRepository (avAddin));
return;
}
}
unresolved.Add (adep);
}
internal string GetAddinDirectory (AddinInfo info)
{
return Path.Combine (service.InstallDirectory, info.Id.Replace (',','.'));
}
internal void RegisterAddin (IProgressMonitor monitor, AddinInfo info, string sourceDir)
{
monitor.Log.WriteLine ("Installing " + info.Name + " v" + info.Version);
string addinDir = GetAddinDirectory (info);
if (!Directory.Exists (addinDir))
Directory.CreateDirectory (addinDir);
CopyDirectory (sourceDir, addinDir);
ResetCachedData ();
}
void CopyDirectory (string src, string dest)
{
CopyDirectory (src, dest, "");
}
void CopyDirectory (string src, string dest, string subdir)
{
string destDir = Path.Combine (dest, subdir);
if (!Directory.Exists (destDir))
Directory.CreateDirectory (destDir);
foreach (string file in Directory.GetFiles (src)) {
if (Path.GetFileName (file) != "addin.info")
File.Copy (file, Path.Combine (destDir, Path.GetFileName (file)), true);
}
foreach (string dir in Directory.GetDirectories (src))
CopyDirectory (dir, dest, Path.Combine (subdir, Path.GetFileName (dir)));
}
internal object DownloadObject (IProgressMonitor monitor, string url, Type type)
{
string file = null;
try {
file = DownloadFile (monitor, url);
return ReadObject (file, type);
} finally {
if (file != null)
File.Delete (file);
}
}
static XmlSerializer GetSerializer (Type type)
{
if (type == typeof(AddinSystemConfiguration))
return new AddinSystemConfigurationSerializer ();
else if (type == typeof(Repository))
return new RepositorySerializer ();
else
return new XmlSerializer (type);
}
internal static object ReadObject (string file, Type type)
{
if (!File.Exists (file))
return null;
StreamReader r = new StreamReader (file);
try {
XmlSerializer ser = GetSerializer (type);
return ser.Deserialize (r);
} catch {
return null;
} finally {
r.Close ();
}
}
internal static void WriteObject (string file, object obj)
{
string dir = Path.GetDirectoryName (file);
if (!Directory.Exists (dir))
Directory.CreateDirectory (dir);
StreamWriter s = new StreamWriter (file);
try {
XmlSerializer ser = GetSerializer (obj.GetType());
ser.Serialize (s, obj);
s.Close ();
} catch {
s.Close ();
if (File.Exists (file))
File.Delete (file);
throw;
}
}
internal string DownloadFile (IProgressMonitor monitor, string url)
{
if (url.StartsWith ("file://")) {
string tmpfile = Path.GetTempFileName ();
string path = new Uri (url).LocalPath;
File.Delete (tmpfile);
File.Copy (path, tmpfile);
return tmpfile;
}
monitor.BeginTask ("Requesting " + url, 2);
HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
req.Headers ["Pragma"] = "no-cache";
HttpWebResponse resp = (HttpWebResponse) req.GetResponse ();
monitor.Step (1);
monitor.BeginTask ("Downloading " + url, (int) resp.ContentLength);
string file = Path.GetTempFileName ();
FileStream fs = null;
Stream s = null;
try {
fs = new FileStream (file, FileMode.Create, FileAccess.Write);
s = req.GetResponse ().GetResponseStream ();
byte[] buffer = new byte [4096];
int n;
while ((n = s.Read (buffer, 0, buffer.Length)) != 0) {
monitor.Step (n);
fs.Write (buffer, 0, n);
if (monitor.IsCancelRequested)
throw new InstallException ("Installation cancelled.");
}
fs.Close ();
s.Close ();
return file;
} catch {
if (fs != null)
fs.Close ();
if (s != null)
s.Close ();
File.Delete (file);
throw;
} finally {
monitor.EndTask ();
monitor.EndTask ();
}
}
internal bool HasWriteAccess (string file)
{
FileInfo f = new FileInfo (file);
return !f.Exists || !f.IsReadOnly;
}
internal bool IsUserAddin (string addinFile)
{
string installPath = service.InstallDirectory;
if (installPath [installPath.Length - 1] != Path.DirectorySeparatorChar)
installPath += Path.DirectorySeparatorChar;
return Path.GetFullPath (addinFile).StartsWith (installPath);
}
internal static string GetUninstallErrorNoRoot (AddinHeader ainfo)
{
return string.Format ("The add-in '{0} v{1}' can't be uninstalled with the current user permissions.", ainfo.Name, ainfo.Version);
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Gallio.Common.Collections;
using Gallio.Common.Reflection;
using Gallio.Runtime.Extensibility;
using MbUnit.Framework;
using System.IO;
using Rhino.Mocks;
using Gallio.Common;
namespace Gallio.Tests.Runtime.Extensibility
{
[TestsOn(typeof(PluginRegistration))]
public class PluginRegistrationTest
{
[Test]
public void Constructor_WhenPluginIdIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() =>
{
new PluginRegistration(null, new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
});
}
[Test]
public void Constructor_WhenPluginTypeNameIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() =>
{
new PluginRegistration("pluginId", null, new DirectoryInfo(@"C:\"));
});
}
[Test]
public void Constructor_WhenBaseDirectoryIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() =>
{
new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), null);
});
}
[Test]
public void PluginId_Accessor_EnforcesConstraints()
{
var registration = new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
Assert.AreEqual("pluginId", registration.PluginId);
Assert.Throws<ArgumentNullException>(() => { registration.PluginId = null; });
registration.PluginId = "differentPluginId";
Assert.AreEqual("differentPluginId", registration.PluginId);
}
[Test]
public void PluginTypeName_Accessor_EnforcesConstraints()
{
var registration = new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
Assert.AreEqual(new TypeName("Plugin, Assembly"), registration.PluginTypeName);
Assert.Throws<ArgumentNullException>(() => { registration.PluginTypeName = null; });
registration.PluginTypeName = new TypeName("DifferentPlugin, Assembly");
Assert.AreEqual(new TypeName("DifferentPlugin, Assembly"), registration.PluginTypeName);
}
[Test]
public void BaseDirectory_Accessor_EnforcesConstraints()
{
var registration = new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
Assert.AreEqual(@"C:\", registration.BaseDirectory.ToString());
Assert.Throws<ArgumentNullException>(() => { registration.BaseDirectory = null; });
registration.BaseDirectory = new DirectoryInfo(@"D:\");
Assert.AreEqual(@"D:\", registration.BaseDirectory.ToString());
}
[Test]
public void PluginProperties_Accessor_EnforcesConstraints()
{
var registration = new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
Assert.IsEmpty(registration.PluginProperties);
Assert.Throws<ArgumentNullException>(() => { registration.PluginProperties = null; });
var differentProperties = new PropertySet();
registration.PluginProperties = differentProperties;
Assert.AreSame(differentProperties, registration.PluginProperties);
}
[Test]
public void TraitsProperties_Accessor_EnforcesConstraints()
{
var registration = new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
Assert.IsEmpty(registration.TraitsProperties);
Assert.Throws<ArgumentNullException>(() => { registration.TraitsProperties = null; });
var differentProperties = new PropertySet();
registration.TraitsProperties = differentProperties;
Assert.AreSame(differentProperties, registration.TraitsProperties);
}
[Test]
public void PluginHandlerFactory_Accessor_EnforcesConstraints()
{
var registration = new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
Assert.IsInstanceOfType<SingletonHandlerFactory>(registration.PluginHandlerFactory);
Assert.Throws<ArgumentNullException>(() => { registration.PluginHandlerFactory = null; });
var differentHandlerFactory = MockRepository.GenerateStub<IHandlerFactory>();
registration.PluginHandlerFactory = differentHandlerFactory;
Assert.AreSame(differentHandlerFactory, registration.PluginHandlerFactory);
}
[Test]
public void AssemblyBindings_Accessor_EnforcesConstraints()
{
var registration = new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
Assert.IsEmpty(registration.AssemblyBindings);
Assert.Throws<ArgumentNullException>(() => { registration.AssemblyBindings = null; });
var differentReferences = new[] { new AssemblyBinding(new AssemblyName("Gallio")) };
registration.AssemblyBindings = differentReferences;
Assert.AreSame(differentReferences, registration.AssemblyBindings);
}
[Test]
public void PluginDependencies_Accessor_EnforcesConstraints()
{
var registration = new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
Assert.IsEmpty(registration.PluginDependencies);
Assert.Throws<ArgumentNullException>(() => { registration.PluginDependencies = null; });
var differentDependencies = new[] { MockRepository.GenerateStub<IPluginDescriptor>() };
registration.PluginDependencies = differentDependencies;
Assert.AreSame(differentDependencies, registration.PluginDependencies);
}
[Test]
public void ProbingPaths_Accessor_EnforcesConstraints()
{
var registration = new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
Assert.IsEmpty(registration.ProbingPaths);
Assert.Throws<ArgumentNullException>(() => { registration.ProbingPaths = null; });
var differentPaths = new[] { "privateBin", "publicBin" };
registration.ProbingPaths = differentPaths;
Assert.AreSame(differentPaths, registration.ProbingPaths);
}
[Test]
public void RecommendedInstallationPath_Accessor_EnforcesConstraints()
{
var registration = new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
Assert.IsNull(registration.RecommendedInstallationPath);
registration.RecommendedInstallationPath = "MyPlugin";
Assert.AreEqual("MyPlugin", registration.RecommendedInstallationPath);
registration.RecommendedInstallationPath = null;
Assert.IsNull(registration.RecommendedInstallationPath);
}
[Test]
public void EnableCondition_Accessor_EnforcesConstraints()
{
var registration = new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
var condition = Condition.Parse("${minFramework:NET35}");
Assert.IsNull(registration.EnableCondition);
registration.EnableCondition = condition;
Assert.AreEqual(condition, registration.EnableCondition);
registration.EnableCondition = null;
Assert.IsNull(registration.EnableCondition);
}
[Test]
public void FilePaths_Accessor_EnforcesConstraints()
{
var registration = new PluginRegistration("pluginId", new TypeName("Plugin, Assembly"), new DirectoryInfo(@"C:\"));
Assert.IsEmpty(registration.FilePaths);
Assert.Throws<ArgumentNullException>(() => { registration.FilePaths = null; });
var differentPaths = new[] { "file1.txt", "file2.dll" };
registration.FilePaths = differentPaths;
Assert.AreSame(differentPaths, registration.FilePaths);
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System.Xml;
using Spring.Context.Support;
using Spring.Core.TypeResolution;
using Spring.Objects;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Xml;
using Spring.Util;
#endregion
namespace Spring.Remoting.Config
{
/// <summary>
/// Implementation of the custom configuration parser for remoting definitions.
/// </summary>
/// <author>Bruno Baia</author>
[
NamespaceParser(
Namespace = "http://www.springframework.net/remoting",
SchemaLocationAssemblyHint = typeof(RemotingNamespaceParser),
SchemaLocation = "/Spring.Remoting.Config/spring-remoting-1.1.xsd")
]
public sealed class RemotingNamespaceParser : ObjectsNamespaceParser
{
private const string RemotingTypePrefix = "remoting: ";
static RemotingNamespaceParser()
{
TypeRegistry.RegisterType(
RemotingTypePrefix + RemotingConfigurerConstants.RemotingConfigurerElement,
typeof(RemotingConfigurer));
TypeRegistry.RegisterType(
RemotingTypePrefix + SaoFactoryObjectConstants.SaoFactoryObjectElement,
typeof(SaoFactoryObject));
TypeRegistry.RegisterType(
RemotingTypePrefix + CaoFactoryObjectConstants.CaoFactoryObjectElement,
typeof(CaoFactoryObject));
TypeRegistry.RegisterType(
RemotingTypePrefix + RemoteObjectFactoryConstants.RemoteObjectFactoryElement,
typeof(RemoteObjectFactory));
TypeRegistry.RegisterType(
RemotingTypePrefix + SaoExporterConstants.SaoExporterElement,
typeof(SaoExporter));
TypeRegistry.RegisterType(
RemotingTypePrefix + CaoExporterConstants.CaoExporterElement,
typeof(CaoExporter));
}
/// <summary>
/// Initializes a new instance of the <see cref="RemotingNamespaceParser"/> class.
/// </summary>
public RemotingNamespaceParser()
{}
/// <summary>
/// Parse the specified element and register any resulting
/// IObjectDefinitions with the IObjectDefinitionRegistry that is
/// embedded in the supplied ParserContext.
/// </summary>
/// <param name="element">The element to be parsed into one or more IObjectDefinitions</param>
/// <param name="parserContext">The object encapsulating the current state of the parsing
/// process.</param>
/// <returns>
/// The primary IObjectDefinition (can be null as explained above)
/// </returns>
/// <remarks>
/// Implementations should return the primary IObjectDefinition
/// that results from the parse phase if they wish to used nested
/// inside (for example) a <code><property></code> tag.
/// <para>Implementations may return null if they will not
/// be used in a nested scenario.
/// </para>
/// </remarks>
public override IObjectDefinition ParseElement(XmlElement element, ParserContext parserContext)
{
string name = element.GetAttribute(ObjectDefinitionConstants.IdAttribute);
IConfigurableObjectDefinition remotingDefinition = ParseRemotingDefinition(element, name, parserContext);
if (!StringUtils.HasText(name))
{
name = ObjectDefinitionReaderUtils.GenerateObjectName(remotingDefinition, parserContext.Registry);
}
parserContext.Registry.RegisterObjectDefinition(name, remotingDefinition);
return null;
}
/// <summary>
/// Parses remoting definitions.
/// </summary>
/// <param name="element">Validator XML element.</param>
/// <param name="name">The name of the object definition.</param>
/// <param name="parserContext">The parser context.</param>
/// <returns>A remoting object definition.</returns>
private IConfigurableObjectDefinition ParseRemotingDefinition(
XmlElement element, string name, ParserContext parserContext)
{
switch (element.LocalName)
{
case RemotingConfigurerConstants.RemotingConfigurerElement:
return ParseRemotingConfigurer(element, name, parserContext);
case SaoFactoryObjectConstants.SaoFactoryObjectElement:
return ParseSaoFactoryObject(element, name, parserContext);
case CaoFactoryObjectConstants.CaoFactoryObjectElement:
return ParseCaoFactoryObject(element, name, parserContext);
case RemoteObjectFactoryConstants.RemoteObjectFactoryElement:
return ParseRemoteObjectFactory(element, name, parserContext);
case SaoExporterConstants.SaoExporterElement:
return ParseSaoExporter(element, name, parserContext);
case CaoExporterConstants.CaoExporterElement:
return ParseCaoExporter(element, name, parserContext);
}
return null;
}
/// <summary>
/// Parses the RemotingConfigurer definition.
/// </summary>
/// <param name="element">The element to parse.</param>
/// <param name="name">The name of the object definition.</param>
/// <param name="parserContext">The parser context.</param>
/// <returns>RemotingConfigurer object definition.</returns>
private IConfigurableObjectDefinition ParseRemotingConfigurer(
XmlElement element, string name, ParserContext parserContext)
{
string typeName = GetTypeName(element);
string filename = element.GetAttribute(RemotingConfigurerConstants.FilenameAttribute);
string useConfigFile = element.GetAttribute(RemotingConfigurerConstants.UseConfigFileAttribute);
string ensureSecurity = element.GetAttribute(RemotingConfigurerConstants.EnsureSecurityAttribute);
MutablePropertyValues properties = new MutablePropertyValues();
if (StringUtils.HasText(filename))
{
properties.Add("Filename", filename);
}
if (StringUtils.HasText(useConfigFile))
{
properties.Add("UseConfigFile", useConfigFile);
}
if (StringUtils.HasText(ensureSecurity))
{
properties.Add("EnsureSecurity", ensureSecurity);
}
IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(
typeName, null, parserContext.ReaderContext.Reader.Domain);
cod.PropertyValues = properties;
return cod;
}
/// <summary>
/// Parses the SaoFactoryObject definition.
/// </summary>
/// <param name="element">The element to parse.</param>
/// <param name="name">The name of the object definition.</param>
/// <param name="parserContext">The parser context.</param>
/// <returns>SaoFactoryObject object definition.</returns>
private IConfigurableObjectDefinition ParseSaoFactoryObject(
XmlElement element, string name, ParserContext parserContext)
{
string typeName = GetTypeName(element);
string serviceInterface = element.GetAttribute(SaoFactoryObjectConstants.ServiceInterfaceAttribute);
string serviceUrl = element.GetAttribute(SaoFactoryObjectConstants.ServiceUrlAttribute);
MutablePropertyValues properties = new MutablePropertyValues();
if (StringUtils.HasText(serviceInterface))
{
properties.Add("ServiceInterface", serviceInterface);
}
if (StringUtils.HasText(serviceUrl))
{
properties.Add("ServiceUrl", serviceUrl);
}
IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(
typeName, null, parserContext.ReaderContext.Reader.Domain);
cod.PropertyValues = properties;
return cod;
}
/// <summary>
/// Parses the CaoFactoryObject definition.
/// </summary>
/// <param name="element">The element to parse.</param>
/// <param name="name">The name of the object definition.</param>
/// <param name="parserContext">The parser context.</param>
/// <returns>CaoFactoryObject object definition.</returns>
private IConfigurableObjectDefinition ParseCaoFactoryObject(
XmlElement element, string name, ParserContext parserContext)
{
string typeName = GetTypeName(element);
string remoteTargetName = element.GetAttribute(CaoFactoryObjectConstants.RemoteTargetNameAttribute);
string serviceUrl = element.GetAttribute(CaoFactoryObjectConstants.ServiceUrlAttribute);
MutablePropertyValues properties = new MutablePropertyValues();
if (StringUtils.HasText(remoteTargetName))
{
properties.Add("RemoteTargetName", remoteTargetName);
}
if (StringUtils.HasText(serviceUrl))
{
properties.Add("ServiceUrl", serviceUrl);
}
foreach (XmlElement child in element.ChildNodes)
{
switch (child.LocalName)
{
case CaoFactoryObjectConstants.ConstructorArgumentsElement:
properties.Add("ConstructorArguments", base.ParseListElement(child, name, parserContext));
break;
}
}
IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(
typeName, null, parserContext.ReaderContext.Reader.Domain);
cod.PropertyValues = properties;
return cod;
}
/// <summary>
/// Parses the RemoteObjectFactory definition.
/// </summary>
/// <param name="element">The element to parse.</param>
/// <param name="name">The name of the object definition.</param>
/// <param name="parserContext">The parser context.</param>
/// <returns>RemoteObjectFactory object definition.</returns>
private IConfigurableObjectDefinition ParseRemoteObjectFactory(
XmlElement element, string name, ParserContext parserContext)
{
string typeName = GetTypeName(element);
string targetName = element.GetAttribute(RemoteObjectFactoryConstants.TargetNameAttribute);
string infinite = element.GetAttribute(RemoteObjectFactoryConstants.InfiniteAttribute);
MutablePropertyValues properties = new MutablePropertyValues();
if (StringUtils.HasText(targetName))
{
properties.Add("Target", targetName);
}
if (StringUtils.HasText(infinite))
{
properties.Add("Infinite", infinite);
}
foreach (XmlElement child in element.ChildNodes)
{
switch (child.LocalName)
{
case LifeTimeConstants.LifeTimeElement:
ParseLifeTime(properties, child, parserContext);
break;
case InterfacesConstants.InterfacesElement:
properties.Add("Interfaces", base.ParseListElement(child, name, parserContext));
break;
}
}
IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(
typeName, null, parserContext.ReaderContext.Reader.Domain);
cod.PropertyValues = properties;
return cod;
}
/// <summary>
/// Parses the SaoExporter definition.
/// </summary>
/// <param name="element">The element to parse.</param>
/// <param name="name">The name of the object definition.</param>
/// <param name="parserContext">The parser context.</param>
/// <returns>SaoExporter object definition.</returns>
private IConfigurableObjectDefinition ParseSaoExporter(
XmlElement element, string name, ParserContext parserContext)
{
string typeName = GetTypeName(element);
string targetName = element.GetAttribute(SaoExporterConstants.TargetNameAttribute);
string applicationName = element.GetAttribute(SaoExporterConstants.ApplicationNameAttribute);
string serviceName = element.GetAttribute(SaoExporterConstants.ServiceNameAttribute);
string infinite = element.GetAttribute(SaoExporterConstants.InfiniteAttribute);
MutablePropertyValues properties = new MutablePropertyValues();
if (StringUtils.HasText(targetName))
{
properties.Add("TargetName", targetName);
}
if (StringUtils.HasText(applicationName))
{
properties.Add("ApplicationName", applicationName);
}
if (StringUtils.HasText(serviceName))
{
properties.Add("ServiceName", serviceName);
}
if (StringUtils.HasText(infinite))
{
properties.Add("Infinite", infinite);
}
foreach (XmlElement child in element.ChildNodes)
{
switch (child.LocalName)
{
case LifeTimeConstants.LifeTimeElement:
ParseLifeTime(properties, child, parserContext);
break;
case InterfacesConstants.InterfacesElement:
properties.Add("Interfaces", base.ParseListElement(child, name, parserContext));
break;
}
}
IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(
typeName, null, parserContext.ReaderContext.Reader.Domain);
cod.PropertyValues = properties;
return cod;
}
/// <summary>
/// Parses the CaoExporter definition.
/// </summary>
/// <param name="element">The element to parse.</param>
/// <param name="name">The name of the object definition.</param>
/// <param name="parserContext">The parser context.</param>
/// <returns>CaoExporter object definition.</returns>
private IConfigurableObjectDefinition ParseCaoExporter(
XmlElement element, string name, ParserContext parserContext)
{
string typeName = GetTypeName(element);
string targetName = element.GetAttribute(CaoExporterConstants.TargetNameAttribute);
string infinite = element.GetAttribute(CaoExporterConstants.InfiniteAttribute);
MutablePropertyValues properties = new MutablePropertyValues();
if (StringUtils.HasText(targetName))
{
properties.Add("TargetName", targetName);
}
if (StringUtils.HasText(infinite))
{
properties.Add("Infinite", infinite);
}
foreach (XmlElement child in element.ChildNodes)
{
switch (child.LocalName)
{
case LifeTimeConstants.LifeTimeElement:
ParseLifeTime(properties, child, parserContext);
break;
case InterfacesConstants.InterfacesElement:
properties.Add("Interfaces", base.ParseListElement(child, name, parserContext));
break;
}
}
IConfigurableObjectDefinition cod = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(
typeName, null, parserContext.ReaderContext.Reader.Domain);
cod.PropertyValues = properties;
return cod;
}
/// <summary>
/// Parses the LifeTime definition.
/// </summary>
private void ParseLifeTime(MutablePropertyValues properties, XmlElement child, ParserContext parserContext)
{
string initialLeaseTime = child.GetAttribute(LifeTimeConstants.InitialLeaseTimeAttribute);
string renewOnCallTime = child.GetAttribute(LifeTimeConstants.RenewOnCallTimeAttribute);
string sponsorshipTimeout = child.GetAttribute(LifeTimeConstants.SponsorshipTimeoutAttribute);
if (StringUtils.HasText(initialLeaseTime))
{
properties.Add("InitialLeaseTime", initialLeaseTime);
}
if (StringUtils.HasText(renewOnCallTime))
{
properties.Add("RenewOnCallTime", renewOnCallTime);
}
if (StringUtils.HasText(sponsorshipTimeout))
{
properties.Add("SponsorshipTimeout", sponsorshipTimeout);
}
}
/// <summary>
/// Gets the name of the object type for the specified element.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>The name of the object type.</returns>
private string GetTypeName(XmlElement element)
{
string typeName = element.GetAttribute(ObjectDefinitionConstants.TypeAttribute);
if (StringUtils.IsNullOrEmpty(typeName))
{
return RemotingTypePrefix + element.LocalName;
}
return typeName;
}
#region Element & Attribute Name Constants
private class RemotingConfigurerConstants
{
public const string RemotingConfigurerElement = "configurer";
public const string FilenameAttribute = "filename";
public const string UseConfigFileAttribute = "useConfigFile";
public const string EnsureSecurityAttribute = "ensureSecurity";
}
private class SaoFactoryObjectConstants
{
public const string SaoFactoryObjectElement = "saoFactory";
public const string ServiceInterfaceAttribute = "serviceInterface";
public const string ServiceUrlAttribute = "serviceUrl";
}
private class CaoFactoryObjectConstants
{
public const string CaoFactoryObjectElement = "caoFactory";
public const string ConstructorArgumentsElement = "constructor-args";
public const string RemoteTargetNameAttribute = "remoteTargetName";
public const string ServiceUrlAttribute = "serviceUrl";
}
private class LifeTimeConstants
{
public const string LifeTimeElement = "lifeTime";
public const string InitialLeaseTimeAttribute = "initialLeaseTime";
public const string RenewOnCallTimeAttribute = "renewOnCallTime";
public const string SponsorshipTimeoutAttribute = "sponsorshipTimeout";
}
private class InterfacesConstants
{
public const string InterfacesElement = "interfaces";
}
private class RemoteObjectFactoryConstants
{
public const string RemoteObjectFactoryElement = "remoteObjectFactory";
public const string TargetNameAttribute = "targetName";
public const string InfiniteAttribute = "infinite";
}
private class SaoExporterConstants
{
public const string SaoExporterElement = "saoExporter";
public const string TargetNameAttribute = "targetName";
public const string ApplicationNameAttribute = "applicationName";
public const string ServiceNameAttribute = "serviceName";
public const string InfiniteAttribute = "infinite";
}
private class CaoExporterConstants
{
public const string CaoExporterElement = "caoExporter";
public const string TargetNameAttribute = "targetName";
public const string InfiniteAttribute = "infinite";
}
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Data.Market;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Logging;
using QuantConnect.Securities;
using QuantConnect.Util;
namespace QuantConnect.Tests.Common.Data.Auxiliary
{
[TestFixture]
public class FactorFileTests
{
[Test]
public void ReadsFactorFileWithoutInfValues()
{
var PermTick = "AAPL";
var Market = "usa";
var _symbol = new Symbol(SecurityIdentifier.GenerateEquity(PermTick, Market), PermTick);
var factorFile = TestGlobals.FactorFileProvider.Get(_symbol);
Assert.AreEqual(41, factorFile.SortedFactorFileData.Count);
Assert.AreEqual(new DateTime(1998, 01, 01), factorFile.FactorFileMinimumDate.Value);
}
[Test]
public void ReadsFactorFileWithExponentialNotation()
{
// Source NEWL factor file at 2019-12-09
var lines = new[]
{
"19980102,0.8116779,1e+07",
"20051108,0.8116779,1e+07",
"20060217,0.8416761,1e+07",
"20060516,0.8644420,1e+07",
"20060814,0.8747766,1e+07",
"20061115,0.8901232,1e+07",
"20070314,0.9082148,1e+07",
"20070522,0.9166239,1e+07",
"20070814,0.9306799,1e+07",
"20071120,0.9534326,1e+07",
"20080520,0.9830510,1e+07",
"20100802,1.0000000,1e+07",
"20131016,1.0000000,1.11111e+06",
"20131205,1.0000000,75188",
"20140305,1.0000000,25000",
"20140514,1.0000000,2500",
"20140714,1.0000000,50",
"20501231,1.0000000,1"
};
DateTime? factorFileMinimumDate;
var factorFile = FactorFileRow.Parse(lines, out factorFileMinimumDate).ToList();
Assert.AreEqual(5, factorFile.Count);
Assert.IsNotNull(factorFileMinimumDate);
Assert.AreEqual(new DateTime(2013, 12, 04), factorFileMinimumDate.Value);
}
[Test]
public void ReadsFactorFileWithInfValues()
{
var lines = new[]
{
"19980102,1.0000000,inf",
"20151211,1.0000000,inf",
"20160330,1.0000000,2500",
"20160915,1.0000000,80",
"20501231,1.0000000,1"
};
DateTime? factorFileMinimumDate;
var factorFile = FactorFileRow.Parse(lines, out factorFileMinimumDate).ToList();
Assert.AreEqual(3, factorFile.Count);
Assert.IsNotNull(factorFileMinimumDate);
Assert.AreEqual(new DateTime(2016, 3, 29), factorFileMinimumDate.Value);
}
[Test]
public void CorrectlyDeterminesTimePriceFactors()
{
var reference = DateTime.Today;
const string symbol = "n/a";
var file = GetTestFactorFile(symbol, reference);
// time price factors should be the price factor * split factor
Assert.AreEqual(1, file.GetPriceScaleFactor(reference));
Assert.AreEqual(1, file.GetPriceScaleFactor(reference.AddDays(-6)));
Assert.AreEqual(.9, file.GetPriceScaleFactor(reference.AddDays(-7)));
Assert.AreEqual(.9, file.GetPriceScaleFactor(reference.AddDays(-13)));
Assert.AreEqual(.8, file.GetPriceScaleFactor(reference.AddDays(-14)));
Assert.AreEqual(.8, file.GetPriceScaleFactor(reference.AddDays(-20)));
Assert.AreEqual(.8m * .5m, file.GetPriceScaleFactor(reference.AddDays(-21)));
Assert.AreEqual(.8m * .5m, file.GetPriceScaleFactor(reference.AddDays(-22)));
Assert.AreEqual(.8m * .5m, file.GetPriceScaleFactor(reference.AddDays(-89)));
Assert.AreEqual(.8m * .25m, file.GetPriceScaleFactor(reference.AddDays(-91)));
}
[Test]
public void HasDividendEventOnNextTradingDay()
{
var reference = DateTime.Today;
const string symbol = "n/a";
decimal priceFactorRatio;
decimal referencePrice;
var file = GetTestFactorFile(symbol, reference);
Assert.IsFalse(file.HasSplitEventOnNextTradingDay(reference, out priceFactorRatio, out referencePrice));
Assert.IsFalse(file.HasDividendEventOnNextTradingDay(reference.AddDays(-6), out priceFactorRatio, out referencePrice));
Assert.IsTrue(file.HasDividendEventOnNextTradingDay(reference.AddDays(-7), out priceFactorRatio, out referencePrice));
Assert.AreEqual(.9m/1m, priceFactorRatio);
Assert.IsFalse(file.HasDividendEventOnNextTradingDay(reference.AddDays(-8), out priceFactorRatio, out referencePrice));
Assert.IsFalse(file.HasDividendEventOnNextTradingDay(reference.AddDays(-13), out priceFactorRatio, out referencePrice));
Assert.IsTrue(file.HasDividendEventOnNextTradingDay(reference.AddDays(-14), out priceFactorRatio, out referencePrice));
Assert.AreEqual(.8m / .9m, priceFactorRatio);
Assert.IsFalse(file.HasDividendEventOnNextTradingDay(reference.AddDays(-15), out priceFactorRatio, out referencePrice));
Assert.IsFalse(file.HasDividendEventOnNextTradingDay(reference.AddDays(-364), out priceFactorRatio, out referencePrice));
Assert.IsTrue(file.HasDividendEventOnNextTradingDay(reference.AddDays(-365), out priceFactorRatio, out referencePrice));
Assert.AreEqual(.7m / .8m, priceFactorRatio);
Assert.IsFalse(file.HasDividendEventOnNextTradingDay(reference.AddDays(-366), out priceFactorRatio, out referencePrice));
Assert.IsNull(file.FactorFileMinimumDate);
}
[Test]
public void HasSplitEventOnNextTradingDay()
{
var reference = DateTime.Today;
const string symbol = "n/a";
decimal splitFactor;
decimal referencePrice;
var file = GetTestFactorFile(symbol, reference);
Assert.IsFalse(file.HasSplitEventOnNextTradingDay(reference, out splitFactor, out referencePrice));
Assert.IsFalse(file.HasSplitEventOnNextTradingDay(reference.AddDays(-20), out splitFactor, out referencePrice));
Assert.IsTrue(file.HasSplitEventOnNextTradingDay(reference.AddDays(-21), out splitFactor, out referencePrice));
Assert.AreEqual(.5, splitFactor);
Assert.IsFalse(file.HasSplitEventOnNextTradingDay(reference.AddDays(-22), out splitFactor, out referencePrice));
Assert.IsFalse(file.HasSplitEventOnNextTradingDay(reference.AddDays(-89), out splitFactor, out referencePrice));
Assert.IsTrue(file.HasSplitEventOnNextTradingDay(reference.AddDays(-90), out splitFactor, out referencePrice));
Assert.AreEqual(.5, splitFactor);
Assert.IsFalse(file.HasSplitEventOnNextTradingDay(reference.AddDays(-91), out splitFactor, out referencePrice));
Assert.IsFalse(file.HasSplitEventOnNextTradingDay(reference.AddDays(-364), out splitFactor, out referencePrice));
Assert.IsTrue(file.HasSplitEventOnNextTradingDay(reference.AddDays(-365), out splitFactor, out referencePrice));
Assert.AreEqual(.5, splitFactor);
Assert.IsFalse(file.HasSplitEventOnNextTradingDay(reference.AddDays(-366), out splitFactor, out referencePrice));
Assert.IsNull(file.FactorFileMinimumDate);
}
[Test]
public void GeneratesCorrectSplitsAndDividends()
{
var reference = new DateTime(2018, 01, 01);
var file = GetTestFactorFile("SPY", reference);
var exchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(QuantConnect.Market.USA, Symbols.SPY, SecurityType.Equity);
var splitsAndDividends = file.GetSplitsAndDividends(Symbols.SPY, exchangeHours);
var dividend = (Dividend)splitsAndDividends.Single(d => d.Time == reference.AddDays(-6));
var distribution = Dividend.ComputeDistribution(100m, .9m / 1m, 2);
Assert.AreEqual(distribution, dividend.Distribution);
dividend = (Dividend) splitsAndDividends.Single(d => d.Time == reference.AddDays(-13));
distribution = Math.Round(Dividend.ComputeDistribution(100m, .8m / .9m, 2), 2);
Assert.AreEqual(distribution, dividend.Distribution);
var split = (Split) splitsAndDividends.Single(d => d.Time == reference.AddDays(-20));
var splitFactor = .5m;
Assert.AreEqual(splitFactor, split.SplitFactor);
split = (Split) splitsAndDividends.Single(d => d.Time == reference.AddDays(-89));
splitFactor = .5m;
Assert.AreEqual(splitFactor, split.SplitFactor);
dividend = splitsAndDividends.OfType<Dividend>().Single(d => d.Time == reference.AddDays(-363));
distribution = Dividend.ComputeDistribution(100m, .7m / .8m, 2);
Assert.AreEqual(distribution, dividend.Distribution);
split = splitsAndDividends.OfType<Split>().Single(d => d.Time == reference.AddDays(-363));
splitFactor = .5m;
Assert.AreEqual(splitFactor, split.SplitFactor);
}
[Test]
public void GetsSplitsAndDividends()
{
var factorFile = GetFactorFile_AAPL2018_05_11();
var exchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(QuantConnect.Market.USA, Symbols.SPY, SecurityType.Equity);
var splitsAndDividends = factorFile.GetSplitsAndDividends(Symbols.AAPL, exchangeHours).ToList();
foreach (var sad in splitsAndDividends)
{
Log.Trace($"{sad.Time.Date:yyyy-MM-dd}: {sad}");
}
var splits = splitsAndDividends.OfType<Split>().ToList();
var dividends = splitsAndDividends.OfType<Dividend>().ToList();
var dividend = dividends.Single(d => d.Time == new DateTime(2018, 05, 11));
Assert.AreEqual(0.73m, dividend.Distribution.RoundToSignificantDigits(6));
var split = splits.Single(d => d.Time == new DateTime(2014, 06, 09));
Assert.AreEqual((1/7m).RoundToSignificantDigits(6), split.SplitFactor);
}
[Test]
public void AppliesDividend()
{
var factorFileBeforeDividend = GetFactorFile_AAPL2018_05_08();
var factorFileAfterDividend = GetFactorFile_AAPL2018_05_11();
var exchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(QuantConnect.Market.USA, Symbols.SPY, SecurityType.Equity);
var dividend = new Dividend(Symbols.AAPL, new DateTime(2018, 05, 11), 0.73m, 190.03m);
var actual = factorFileBeforeDividend.Apply(new List<BaseData> {dividend}, exchangeHours);
Assert.AreEqual(factorFileAfterDividend.Count(), actual.Count());
Assert.True(actual.First().Date == new DateTime(1998, 01, 02),
$"Factor file first row changed from 1998-01-02 to {actual.First().Date:yyyy-MM-dd} after applying new event");
foreach (var item in factorFileAfterDividend.Reverse().Zip(actual.Reverse(), (a,e) => new{actual=a, expected=e}))
{
Log.Trace($"expected: {item.expected} actual: {item.actual} diff: {100* (1 - item.actual.PriceFactor/item.expected.PriceFactor):0.0000}%");
Assert.AreEqual(item.expected.Date, item.actual.Date);
Assert.AreEqual(item.expected.ReferencePrice, item.actual.ReferencePrice);
Assert.AreEqual(item.expected.SplitFactor, item.actual.SplitFactor);
var delta = (double)item.expected.PriceFactor * 1e-5;
Assert.AreEqual((double)item.expected.PriceFactor, (double)item.actual.PriceFactor, delta);
}
}
[Test]
public void AppliesSplit()
{
var factorFileBeforeSplit = GetFactorFile_LODE20191127();
var factorFileAfterSplit = GetFactorFile_LODE20191129();
var exchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(QuantConnect.Market.USA, Symbols.SPY, SecurityType.Equity);
var eventTime = new DateTime(2019, 11, 29);
var split = new Split(Symbols.LODE, eventTime, 0.06m, 5, SplitType.SplitOccurred);
var actual = factorFileBeforeSplit.Apply(new List<BaseData> { split }, exchangeHours);
Assert.AreEqual(factorFileAfterSplit.Count(), actual.Count());
Assert.True(actual.First().Date == new DateTime(1998, 01, 02),
$"Factor file first row changed from 1998-01-02 to {actual.First().Date:yyyy-MM-dd} after applying new event");
Assert.True(actual.First().SplitFactor == 25m, "Factor File split factor is not computed correctly");
foreach (var item in actual.Reverse().Zip(factorFileAfterSplit.Reverse(), (a, e) => new { actual = a, expected = e }))
{
Log.Trace($"expected: {item.expected} actual: {item.actual} diff: {100 * (1 - item.actual.PriceFactor / item.expected.PriceFactor):0.0000}%");
Assert.AreEqual(item.expected.Date, item.actual.Date);
Assert.AreEqual(item.expected.ReferencePrice, item.actual.ReferencePrice);
Assert.AreEqual(item.expected.SplitFactor, item.actual.SplitFactor);
var delta = (double)item.expected.PriceFactor * 1e-5;
Assert.AreEqual((double)item.expected.PriceFactor, (double)item.actual.PriceFactor, delta);
}
}
[Test]
public void CanHandleRepeatedEventsCorrectly()
{
var factorFileBeforeSplit = GetFactorFile_LODE20191127();
var factorFileAfterSplit = GetFactorFile_LODE20191129();
var exchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(QuantConnect.Market.USA, Symbols.SPY, SecurityType.Equity);
var eventTime = new DateTime(2019, 11, 29);
var split = new Split(Symbols.LODE, eventTime, 0.06m, 5, SplitType.SplitOccurred);
var events = new List<BaseData> { split, split, split };
var actual = factorFileBeforeSplit.Apply(events, exchangeHours);
Assert.AreEqual(factorFileAfterSplit.Count(), actual.Count());
Assert.True(actual.First().Date == new DateTime(1998, 01, 02),
$"Factor file first row changed from 1998-01-02 to {actual.First().Date:yyyy-MM-dd} after applying new event");
Assert.True(actual.First().SplitFactor == 25m, "Factor File split factor is not computed correctly");
foreach (var item in actual.Reverse().Zip(factorFileAfterSplit.Reverse(), (a, e) => new { actual = a, expected = e }))
{
Log.Trace($"expected: {item.expected} actual: {item.actual} diff: {100 * (1 - item.actual.PriceFactor / item.expected.PriceFactor):0.0000}%");
Assert.AreEqual(item.expected.Date, item.actual.Date);
Assert.AreEqual(item.expected.ReferencePrice, item.actual.ReferencePrice);
Assert.AreEqual(item.expected.SplitFactor, item.actual.SplitFactor);
var delta = (double)item.expected.PriceFactor * 1e-5;
Assert.AreEqual((double)item.expected.PriceFactor, (double)item.actual.PriceFactor, delta);
}
}
[Test]
public void AppliesSplitAndDividendAtSameTime()
{
var reference = new DateTime(2018, 08, 01);
var exchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(QuantConnect.Market.USA, Symbols.SPY, SecurityType.Equity);
var expected = GetTestFactorFile("AAPL", reference);
// remove the last entry that contains a split and dividend at the same time
var factorFile = new FactorFile("AAPL", expected.SortedFactorFileData.Where(kvp => kvp.Value.PriceFactor >= .8m).Select(kvp => kvp.Value));
var actual = factorFile.Apply(new List<BaseData>
{
new Split(Symbols.AAPL, reference.AddDays(-364), 100m, 1 / 2m, SplitType.SplitOccurred),
new Dividend(Symbols.AAPL, reference.AddDays(-364), 12.5m, 100m)
}, exchangeHours);
foreach (var item in actual.Reverse().Zip(expected.Reverse(), (a, e) => new {actual = a, expected = e}))
{
Log.Trace($"expected: {item.expected} actual: {item.actual} diff: {100 * (1 - item.actual.PriceFactor / item.expected.PriceFactor):0.0000}%");
Assert.AreEqual(item.expected.Date, item.actual.Date);
Assert.AreEqual(item.expected.ReferencePrice, item.actual.ReferencePrice);
Assert.AreEqual(item.expected.SplitFactor, item.actual.SplitFactor);
Assert.AreEqual(item.expected.PriceFactor.RoundToSignificantDigits(4), item.actual.PriceFactor.RoundToSignificantDigits(4));
}
}
[Test]
public void ReadsOldFactorFileFormat()
{
var lines = new[]
{
"19980102,1.0000000,0.5",
"20130828,1.0000000,0.5",
"20501231,1.0000000,1"
};
var factorFile = FactorFile.Parse("bno", lines);
var firstRow = factorFile.SortedFactorFileData[new DateTime(1998, 01, 02)];
Assert.AreEqual(1m, firstRow.PriceFactor);
Assert.AreEqual(0.5m, firstRow.SplitFactor);
Assert.AreEqual(0m, firstRow.ReferencePrice);
var secondRow = factorFile.SortedFactorFileData[new DateTime(2013, 08, 28)];
Assert.AreEqual(1m, secondRow.PriceFactor);
Assert.AreEqual(0.5m, secondRow.SplitFactor);
Assert.AreEqual(0m, firstRow.ReferencePrice);
var thirdRow = factorFile.SortedFactorFileData[Time.EndOfTime];
Assert.AreEqual(1m, thirdRow.PriceFactor);
Assert.AreEqual(1m, thirdRow.SplitFactor);
Assert.AreEqual(0m, firstRow.ReferencePrice);
}
[Test]
public void ResolvesCorrectMostRecentFactorChangeDate()
{
var lines = new[]
{
"19980102,1.0000000,0.5",
"20130828,1.0000000,0.5",
"20501231,1.0000000,1"
};
var factorFile = FactorFile.Parse("bno", lines);
Assert.AreEqual(new DateTime(2013, 08, 28), factorFile.MostRecentFactorChange);
}
[Test]
[TestCase("")]
[TestCase("20501231,1.0000000,1")]
public void EmptyFactorFileReturnsEmptyListForSplitsAndDividends(string contents)
{
var lines = contents.Split('\n').Where(l => !string.IsNullOrWhiteSpace(l));
var factorFile = FactorFile.Parse("bno", lines);
Assert.IsEmpty(factorFile.GetSplitsAndDividends(Symbols.SPY, SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork)));
}
private static FactorFile GetTestFactorFile(string symbol, DateTime reference)
{
var file = new FactorFile(symbol, new List<FactorFileRow>
{
new FactorFileRow(reference, 1, 1),
new FactorFileRow(reference.AddDays(-7), .9m, 1, 100m), // dividend
new FactorFileRow(reference.AddDays(-14), .8m, 1, 100m), // dividend
new FactorFileRow(reference.AddDays(-21), .8m, .5m, 100m), // split
new FactorFileRow(reference.AddDays(-90), .8m, .25m, 100m), // split
new FactorFileRow(reference.AddDays(-365), .7m, .125m, 100m) // split+dividend
});
return file;
}
private static FactorFile GetFactorFile(string permtick)
{
return TestGlobals.FactorFileProvider.Get(permtick);
}
private static FactorFile GetFactorFile_LODE20191127()
{
const string factorFileContents = @"
19980102,1,5,8.5,qq
20171109,1,5,0.12,qq
20501231,1,1,0,qq
";
DateTime? factorFileMinimumDate;
var reader = new StreamReader(factorFileContents.ToStream());
var enumerable = new StreamReaderEnumerable(reader).Where(line => line.Length > 0);
var factorFileRows = FactorFileRow.Parse(enumerable, out factorFileMinimumDate);
return new FactorFile("lode", factorFileRows, factorFileMinimumDate);
}
private static FactorFile GetFactorFile_LODE20191129()
{
const string factorFileContents = @"
19980102,1,25,8.5,qq
20171109,1,25,0.12,qq
20191127,1,5,0.06,qq
20501231,1,1,0,qq
";
DateTime? factorFileMinimumDate;
var reader = new StreamReader(factorFileContents.ToStream());
var enumerable = new StreamReaderEnumerable(reader).Where(line => line.Length > 0);
var factorFileRows = FactorFileRow.Parse(enumerable, out factorFileMinimumDate);
return new FactorFile("lode", factorFileRows, factorFileMinimumDate);
}
private static FactorFile GetFactorFile_AAPL2018_05_11()
{
const string factorFileContents = @"
19980102,0.8893653,0.0357143,16.25
20000620,0.8893653,0.0357143,101
20050225,0.8893653,0.0714286,88.97
20120808,0.8893653,0.142857,619.85
20121106,0.8931837,0.142857,582.85
20130206,0.8972636,0.142857,457.285
20130508,0.9024937,0.142857,463.71
20130807,0.908469,0.142857,464.94
20131105,0.9144679,0.142857,525.58
20140205,0.9198056,0.142857,512.59
20140507,0.9253111,0.142857,592.34
20140606,0.9304792,0.142857,645.57
20140806,0.9304792,1,94.96
20141105,0.9351075,1,108.86
20150204,0.9391624,1,119.55
20150506,0.9428692,1,125.085
20150805,0.9468052,1,115.4
20151104,0.9510909,1,122.01
20160203,0.9551617,1,96.34
20160504,0.9603451,1,94.19
20160803,0.9661922,1,105.8
20161102,0.9714257,1,111.6
20170208,0.9764128,1,132.04
20170510,0.9806461,1,153.26
20170809,0.9846939,1,161.1
20171109,0.9885598,1,175.87
20180208,0.9921138,1,155.16
20180510,0.9961585,1,190.03
20501231,1,1,0
";
DateTime? factorFileMinimumDate;
var reader = new StreamReader(factorFileContents.ToStream());
var enumerable = new StreamReaderEnumerable(reader).Where(line => line.Length > 0);
var factorFileRows = FactorFileRow.Parse(enumerable, out factorFileMinimumDate);
return new FactorFile("aapl", factorFileRows, factorFileMinimumDate);
}
// AAPL experiences a 0.73 dividend distribution on 2018.05.11
private static FactorFile GetFactorFile_AAPL2018_05_08()
{
const string factorFileContents = @"
19980102,0.8927948,0.0357143,16.25
20000620,0.8927948,0.0357143,101
20050225,0.8927948,0.0714286,88.97
20120808,0.8927948,0.142857,619.85
20121106,0.8966279,0.142857,582.85
20130206,0.9007235,0.142857,457.285
20130508,0.9059737,0.142857,463.71
20130807,0.9119721,0.142857,464.94
20131105,0.9179942,0.142857,525.58
20140205,0.9233525,0.142857,512.59
20140507,0.9288793,0.142857,592.34
20140606,0.9340673,0.142857,645.57
20140806,0.9340673,1,94.96
20141105,0.9387135,1,108.86
20150204,0.942784,1,119.55
20150506,0.9465051,1,125.085
20150805,0.9504563,1,115.4
20151104,0.9547586,1,122.01
20160203,0.9588451,1,96.34
20160504,0.9640485,1,94.19
20160803,0.9699181,1,105.8
20161102,0.9751718,1,111.6
20170208,0.9801781,1,132.04
20170510,0.9844278,1,153.26
20170809,0.9884911,1,161.1
20171109,0.992372,1,175.87
20180208,0.9959397,1,155.16
20501231,1,1,0
";
DateTime? factorFileMinimumDate;
var reader = new StreamReader(factorFileContents.ToStream());
var enumerable = new StreamReaderEnumerable(reader).Where(line => line.Length > 0);
var factorFileRows = FactorFileRow.Parse(enumerable, out factorFileMinimumDate);
return new FactorFile("aapl", factorFileRows, factorFileMinimumDate);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.