context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Linq.Expressions;
using Microsoft.Scripting.Ast;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Debugging.CompilerServices;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Interpreter;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Compiler;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Runtime {
/// <summary>
/// Represents a piece of code. This can reference either a CompiledCode
/// object or a Function. The user can explicitly call FunctionCode by
/// passing it into exec or eval.
/// </summary>
[PythonType("code")]
[DebuggerDisplay("{co_name}, FileName = {co_filename}")]
public class FunctionCode : IExpressionSerializable, ICodeFormattable {
internal Delegate _normalDelegate; // the normal delegate - this can be a compiled or interpreted delegate.
private readonly Compiler.Ast.ScopeStatement _lambda; // the original DLR lambda that contains the code
internal readonly string _initialDoc; // the initial doc string
private readonly int _localCount; // the number of local variables in the code
private bool _compilingLight; // true if we're compiling for light exceptions
private int _exceptionCount;
// debugging/tracing support
private LambdaExpression _tracingLambda; // the transformed lambda used for tracing/debugging
internal Delegate _tracingDelegate; // the delegate used for tracing/debugging, if one has been created. This can be interpreted or compiled.
/// <summary>
/// This is both the lock that is held while enumerating the threads or updating the thread accounting
/// information. It's also a marker CodeList which is put in place when we are enumerating the thread
/// list and all additions need to block.
///
/// This lock is also acquired whenever we need to calculate how a function's delegate should be created
/// so that we don't race against sys.settrace/sys.setprofile.
/// </summary>
private static readonly CodeList _CodeCreateAndUpdateDelegateLock = new CodeList();
/// <summary>
/// Constructor used to create a FunctionCode for code that's been serialized to disk.
///
/// Code constructed this way cannot be interpreted or debugged using sys.settrace/sys.setprofile.
///
/// Function codes created this way do support recursion enforcement and are therefore registered in the global function code registry.
/// </summary>
internal FunctionCode(PythonContext context, Delegate code, Compiler.Ast.ScopeStatement scope, string documentation, int localCount) {
_normalDelegate = code;
_lambda = scope;
co_argcount = scope.ArgCount;
co_kwonlyargcount = scope.KwOnlyArgCount;
_initialDoc = documentation;
// need to take this lock to ensure sys.settrace/sys.setprofile is not actively changing
lock (_CodeCreateAndUpdateDelegateLock) {
SetTarget(AddRecursionCheck(context, code));
}
RegisterFunctionCode(context);
}
/// <summary>
/// Constructor to create a FunctionCode at runtime.
///
/// Code constructed this way supports both being interpreted and debugged. When necessary the code will
/// be re-compiled or re-interpreted for that specific purpose.
///
/// Function codes created this way do support recursion enforcement and are therefore registered in the global function code registry.
///
/// the initial delegate provided here should NOT be the actual code. It should always be a delegate which updates our Target lazily.
/// </summary>
internal FunctionCode(PythonContext context, Delegate initialDelegate, Compiler.Ast.ScopeStatement scope, string documentation, bool? tracing, bool register) {
_lambda = scope;
SetTarget(initialDelegate);
_initialDoc = documentation;
_localCount = scope.Variables == null ? 0 : scope.Variables.Count;
co_argcount = scope.ArgCount;
co_kwonlyargcount = scope.KwOnlyArgCount;
if (tracing.HasValue) {
if (tracing.Value) {
_tracingDelegate = initialDelegate;
} else {
_normalDelegate = initialDelegate;
}
}
if (register) {
RegisterFunctionCode(context);
}
}
private static PythonTuple SymbolListToTuple(IList<string> vars) {
if (vars != null && vars.Count != 0) {
object[] tupleData = new object[vars.Count];
for (int i = 0; i < vars.Count; i++) {
tupleData[i] = vars[i];
}
return PythonTuple.MakeTuple(tupleData);
} else {
return PythonTuple.EMPTY;
}
}
private static PythonTuple StringArrayToTuple(string[] closureVars) {
if (closureVars != null && closureVars.Length != 0) {
return PythonTuple.MakeTuple((object[])closureVars);
} else {
return PythonTuple.EMPTY;
}
}
/// <summary>
/// Registers the current function code in our global weak list of all function codes.
///
/// The weak list can be enumerated with GetAllCode().
///
/// Ultimately there are 3 types of threads we care about races with:
/// 1. Other threads which are registering function codes
/// 2. Threads calling sys.settrace which require the world to stop and get updated
/// 3. Threads running cleanup (thread pool thread, or call to gc.collect).
///
/// The 1st two must have perfect synchronization. We cannot have a thread registering
/// a new function which another thread is trying to update all of the functions in the world. Doing
/// so would mean we could miss adding tracing to a thread.
///
/// But the cleanup thread can run in parallel to either registrying or sys.settrace. The only
/// thing it needs to take a lock for is updating our accounting information about the
/// number of code objects are alive.
/// </summary>
private void RegisterFunctionCode(PythonContext context) {
if (_lambda == null) {
return;
}
WeakReference codeRef = new WeakReference(this);
CodeList prevCode;
lock (_CodeCreateAndUpdateDelegateLock) {
Debug.Assert(context._allCodes != _CodeCreateAndUpdateDelegateLock);
// we do an interlocked operation here because this can run in parallel w/ the CodeCleanup thread. The
// lock only prevents us from running in parallel w/ an update to all of the functions in the world which
// needs to be synchronized.
do {
prevCode = context._allCodes;
} while (Interlocked.CompareExchange(ref context._allCodes, new CodeList(codeRef, prevCode), prevCode) != prevCode);
if (context._codeCount++ == context._nextCodeCleanup) {
// run cleanup of codes on another thread
CleanFunctionCodes(context, false);
}
}
}
internal static void CleanFunctionCodes(PythonContext context, bool synchronous) {
if (synchronous) {
CodeCleanup(context);
} else {
ThreadPool.QueueUserWorkItem(CodeCleanup, context);
}
}
internal void SetTarget(Delegate target) {
Target = LightThrowTarget = target;
}
internal void LightThrowCompile(CodeContext/*!*/ context) {
if (++_exceptionCount > 20) {
if (!_compilingLight && (object)Target == (object)LightThrowTarget) {
_compilingLight = true;
if (!IsOnDiskCode) {
ThreadPool.QueueUserWorkItem(x => {
// on mono if the runtime is shutting down, this can throw an InvalidOperationException
try {
var pyCtx = context.LanguageContext;
bool enableTracing;
lock (pyCtx._codeUpdateLock) {
enableTracing = context.LanguageContext.EnableTracing;
}
Delegate target = enableTracing
? ((LambdaExpression)LightExceptions.Rewrite(
GetGeneratorOrNormalLambdaTracing(pyCtx).Reduce())).Compile()
: ((LambdaExpression)LightExceptions.Rewrite(GetGeneratorOrNormalLambda().Reduce()))
.Compile();
lock (pyCtx._codeUpdateLock) {
if (context.LanguageContext.EnableTracing == enableTracing) {
LightThrowTarget = target;
}
}
} catch (InvalidOperationException ex) {
// The InvalidOperationException is thrown with an empty message
if (!string.IsNullOrEmpty(ex.Message)) {
throw;
}
}
});
}
}
}
}
private bool IsOnDiskCode {
get {
if (_lambda is Compiler.Ast.SerializedScopeStatement) {
return true;
}
if (_lambda is Compiler.Ast.PythonAst) {
return ((Compiler.Ast.PythonAst)_lambda).OnDiskProxy;
}
return false;
}
}
/// <summary>
/// Enumerates all function codes for updating the current type of targets we generate.
///
/// While enumerating we hold a lock so that users cannot change sys.settrace/sys.setprofile
/// until the lock is released.
/// </summary>
private static IEnumerable<FunctionCode> GetAllCode(PythonContext context) {
// only a single thread can enumerate the current FunctionCodes at a time.
lock (_CodeCreateAndUpdateDelegateLock) {
CodeList curCodeList = Interlocked.Exchange(ref context._allCodes, _CodeCreateAndUpdateDelegateLock);
Debug.Assert(curCodeList != _CodeCreateAndUpdateDelegateLock);
CodeList initialCode = curCodeList;
try {
while (curCodeList != null) {
WeakReference codeRef = curCodeList.Code;
FunctionCode target = (FunctionCode)codeRef.Target;
if (target != null) {
yield return target;
}
curCodeList = curCodeList.Next;
}
} finally {
Interlocked.Exchange(ref context._allCodes, initialCode);
}
}
}
internal static void UpdateAllCode(PythonContext context) {
foreach (FunctionCode fc in GetAllCode(context)) {
fc.UpdateDelegate(context, false);
}
}
private static void CodeCleanup(object state) {
PythonContext context = (PythonContext)state;
// only allow 1 thread at a time to do cleanup (other threads can continue adding)
lock (context._codeCleanupLock) {
// the bulk of the work is in scanning the list, this proceeeds lock free
int removed = 0, kept = 0;
CodeList prev = null;
CodeList cur = GetRootCodeNoUpdating(context);
while (cur != null) {
if (!cur.Code.IsAlive) {
if (prev == null) {
if (Interlocked.CompareExchange(ref context._allCodes, cur.Next, cur) != cur) {
// someone else snuck in and added a new code entry, spin and try again.
cur = GetRootCodeNoUpdating(context);
continue;
}
cur = cur.Next;
removed++;
continue;
} else {
// remove from the linked list, we're the only one who can change this.
Debug.Assert(prev.Next == cur);
removed++;
cur = prev.Next = cur.Next;
continue;
}
} else {
kept++;
}
prev = cur;
cur = cur.Next;
}
// finally update our bookkeeping statistics which requires locking but is fast.
lock (_CodeCreateAndUpdateDelegateLock) {
// calculate the next cleanup, we want each pass to remove ~50% of all entries
const double removalGoal = .50;
if (context._codeCount == 0) {
// somehow we would have had to queue a bunch of function codes, have 1 thread
// clean them up all up, and a 2nd queued thread waiting to clean them up as well.
// At the same time there would have to be no live functions defined which means
// we're executing top-level code which is causing this to happen.
context._nextCodeCleanup = 200;
return;
}
//Console.WriteLine("Removed {0} entries, {1} remain", removed, context._codeCount);
Debug.Assert(removed <= context._codeCount);
double pctRemoved = (double)removed / (double)context._codeCount; // % of code removed
double targetRatio = pctRemoved / removalGoal; // how we need to adjust our last goal
// update the total and next node cleanup
int newCount = Interlocked.Add(ref context._codeCount, -removed);
Debug.Assert(newCount >= 0);
// set the new target for cleanup
int nextCleanup = targetRatio != 0 ? newCount + (int)(context._nextCodeCleanup / targetRatio) : -1;
if (nextCleanup > 0) {
// we're making good progress, use the newly calculated next cleanup point
context._nextCodeCleanup = nextCleanup;
} else {
// none or very small amount cleaned up, just schedule a cleanup for sometime in the future.
context._nextCodeCleanup += 500;
}
Debug.Assert(context._nextCodeCleanup >= context._codeCount, String.Format("{0} vs {1} ({2})", context._nextCodeCleanup, context._codeCount, targetRatio));
}
}
}
private static CodeList GetRootCodeNoUpdating(PythonContext context) {
CodeList cur = context._allCodes;
if (cur == _CodeCreateAndUpdateDelegateLock) {
lock (_CodeCreateAndUpdateDelegateLock) {
// wait until enumerating thread is done, but it's alright
// if we got cur and then an enumeration started (because we'll
// just clear entries out)
cur = context._allCodes;
Debug.Assert(cur != _CodeCreateAndUpdateDelegateLock);
}
}
return cur;
}
public SourceSpan Span {
[PythonHidden]
get {
return _lambda.Span;
}
}
internal string[] ArgNames {
get {
return _lambda.ParameterNames;
}
}
internal FunctionAttributes Flags {
get {
return _lambda.Flags;
}
}
internal bool IsModule {
get {
return _lambda is Compiler.Ast.PythonAst;
}
}
#region Public constructors
/*
/// <summary>
/// Standard python siganture
/// </summary>
/// <param name="argcount"></param>
/// <param name="nlocals"></param>
/// <param name="stacksize"></param>
/// <param name="flags"></param>
/// <param name="codestring"></param>
/// <param name="constants"></param>
/// <param name="names"></param>
/// <param name="varnames"></param>
/// <param name="filename"></param>
/// <param name="name"></param>
/// <param name="firstlineno"></param>
/// <param name="nlotab"></param>
/// <param name="freevars"></param>
/// <param name="callvars"></param>
public FunctionCode(int argcount, int nlocals, int stacksize, int flags, string codestring, object constants, Tuple names, Tuple varnames, string filename, string name, int firstlineno, object nlotab, object freevars=null, object callvars=null) {
}*/
#endregion
#region Public Python API Surface
public PythonTuple co_varnames {
get {
return SymbolListToTuple(_lambda.GetVarNames());
}
}
public int co_argcount { get; }
public int co_kwonlyargcount { get; }
/// <summary>
/// Returns a list of variable names which are accessed from nested functions.
/// </summary>
public PythonTuple co_cellvars {
get {
return SymbolListToTuple(_lambda.CellVariables != null ? ArrayUtils.ToArray(_lambda.CellVariables) : null);
}
}
/// <summary>
/// Returns the byte code. IronPython does not implement this and always
/// returns an empty string for byte code.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public object co_code {
get {
return String.Empty;
}
}
/// <summary>
/// Returns a list of constants used by the function.
///
/// The first constant is the doc string, or None if no doc string is provided.
///
/// IronPython currently does not include any other constants than the doc string.
/// </summary>
public PythonTuple co_consts {
get {
if (_initialDoc != null) {
return PythonTuple.MakeTuple(_initialDoc, null);
}
return PythonTuple.MakeTuple((object)null);
}
}
/// <summary>
/// Returns the filename that the code object was defined in.
/// </summary>
public string co_filename {
get {
return _lambda.Filename;
}
}
/// <summary>
/// Returns the 1st line number of the code object.
/// </summary>
public int co_firstlineno {
get {
return Span.Start.Line;
}
}
/// <summary>
/// Returns a set of flags for the function.
///
/// 0x04 is set if the function used *args
/// 0x08 is set if the function used **args
/// 0x20 is set if the function is a generator
/// </summary>
public int co_flags {
get {
return (int)Flags;
}
}
/// <summary>
/// Returns a list of free variables (variables accessed
/// from an outer scope). This does not include variables
/// accessed in the global scope.
/// </summary>
public PythonTuple co_freevars {
get {
return SymbolListToTuple(_lambda.FreeVariables != null ? CollectionUtils.ConvertAll(_lambda.FreeVariables, x => x.Name) : null);
}
}
/// <summary>
/// Returns a mapping between byte code and line numbers. IronPython does
/// not implement this because byte code is not available.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public object co_lnotab {
get {
throw PythonOps.NotImplementedError("");
}
}
/// <summary>
/// Returns the name of the code (function name, class name, or <module>).
/// </summary>
public string co_name {
get {
return _lambda.Name;
}
}
/// <summary>
/// Returns a list of global variable names accessed by the code.
/// </summary>
public PythonTuple co_names {
get {
return SymbolListToTuple(_lambda.GlobalVariables);
}
}
/// <summary>
/// Returns the number of local varaibles defined in the function.
/// </summary>
public object co_nlocals {
get {
return _localCount;
}
}
/// <summary>
/// Returns the stack size. IronPython does not implement this
/// because byte code is not supported.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public object co_stacksize {
get {
throw PythonOps.NotImplementedError("");
}
}
#endregion
#region ICodeFormattable Members
public string/*!*/ __repr__(CodeContext/*!*/ context) {
return string.Format(
"<code object {0} at {1}, file {2}, line {3}>",
co_name,
PythonOps.HexId(this),
!string.IsNullOrEmpty(co_filename) ? string.Format("\"{0}\"", co_filename) : "???",
co_firstlineno != 0 ? co_firstlineno : -1);
}
#endregion
#region Internal API Surface
internal LightLambdaExpression Code {
get {
return _lambda.GetLambda();
}
}
internal Compiler.Ast.ScopeStatement PythonCode {
get {
return (Compiler.Ast.ScopeStatement)_lambda;
}
}
/// <summary>
/// The current target for the function. This can change based upon adaptive compilation, recursion enforcement, and tracing.
/// </summary>
internal Delegate Target { get; private set; }
internal Delegate LightThrowTarget { get; private set; }
internal object Call(CodeContext/*!*/ context) {
if (co_freevars != PythonTuple.EMPTY) {
throw PythonOps.TypeError("cannot exec code object that contains free variables: {0}", co_freevars.__repr__(context));
}
if (Target == null || (Target.GetMethodInfo() != null && Target.GetMethodInfo().DeclaringType == typeof(PythonCallTargets))) {
UpdateDelegate(context.LanguageContext, true);
}
if (Target is Func<CodeContext, CodeContext> classTarget) {
return classTarget(context);
}
if (Target is LookupCompilationDelegate moduleCode) {
return moduleCode(context, this);
}
if (Target is Func<FunctionCode, object> optimizedModuleCode) {
return optimizedModuleCode(this);
}
var func = new PythonFunction(context, this, null, ArrayUtils.EmptyObjects, null, null, new MutableTuple<object>());
CallSite<Func<CallSite, CodeContext, PythonFunction, object>> site = context.LanguageContext.FunctionCallSite;
return site.Target(site, context, func);
}
/// <summary>
/// Creates a FunctionCode object for exec/eval/execfile'd/compile'd code.
///
/// The code is then executed in a specific CodeContext by calling the .Call method.
///
/// If the code is being used for compile (vs. exec/eval/execfile) then it needs to be
/// registered in case our tracing mode changes.
/// </summary>
internal static FunctionCode FromSourceUnit(SourceUnit sourceUnit, PythonCompilerOptions options, bool register) {
var code = PythonContext.CompilePythonCode(sourceUnit, options, ThrowingErrorSink.Default);
if (sourceUnit.CodeProperties == ScriptCodeParseResult.Empty) {
// source span is made up
throw new SyntaxErrorException("unexpected EOF while parsing",
sourceUnit, new SourceSpan(new SourceLocation(0, 1, 1), new SourceLocation(0, 1, 1)), 0, Severity.Error);
}
return ((RunnableScriptCode)code).GetFunctionCode(register);
}
#endregion
#region Private helper functions
private void ExpandArgsTuple(List<string> names, PythonTuple toExpand) {
for (int i = 0; i < toExpand.__len__(); i++) {
if (toExpand[i] is PythonTuple) {
ExpandArgsTuple(names, toExpand[i] as PythonTuple);
} else {
names.Add(toExpand[i] as string);
}
}
}
#endregion
public override bool Equals(object obj) {
// overridden because CPython defines this on code objects
return base.Equals(obj);
}
public override int GetHashCode() {
// overridden because CPython defines this on code objects
return base.GetHashCode();
}
[return: MaybeNotImplemented]
public NotImplementedType __gt__(CodeContext context, object other) => NotImplementedType.Value;
[return: MaybeNotImplemented]
public NotImplementedType __lt__(CodeContext context, object other) => NotImplementedType.Value;
[return: MaybeNotImplemented]
public NotImplementedType __ge__(CodeContext context, object other) => NotImplementedType.Value;
[return: MaybeNotImplemented]
public NotImplementedType __le__(CodeContext context, object other) => NotImplementedType.Value;
/// <summary>
/// Called the 1st time a function is invoked by our OriginalCallTarget* methods
/// over in PythonCallTargets. This computes the real delegate which needs to be
/// created for the function. Usually this means starting off interpretering. It
/// also involves adding the wrapper function for recursion enforcement.
///
/// Because this can race against sys.settrace/setprofile we need to take our
/// _ThreadIsEnumeratingAndAccountingLock to ensure no one is actively changing all
/// of the live functions.
/// </summary>
internal void LazyCompileFirstTarget(PythonFunction function) {
lock (_CodeCreateAndUpdateDelegateLock) {
UpdateDelegate(function.Context.LanguageContext, true);
}
}
/// <summary>
/// Updates the delegate based upon current Python context settings for recursion enforcement
/// and for tracing.
/// </summary>
internal void UpdateDelegate(PythonContext context, bool forceCreation) {
Delegate finalTarget;
if (context.EnableTracing && _lambda != null) {
if (_tracingLambda == null) {
if (!forceCreation) {
if (_lambda is Compiler.Ast.ClassDefinition) return; // ClassDefinition does not have the same signature as call targets
// the user just called sys.settrace(), don't force re-compilation of every method in the system. Instead
// we'll just re-compile them as they're invoked.
PythonCallTargets.GetPythonTargetType(_lambda.ParameterNames.Length > PythonCallTargets.MaxArgs, _lambda.ParameterNames.Length, out Delegate target);
SetTarget(target);
return;
}
_tracingLambda = GetGeneratorOrNormalLambdaTracing(context);
}
if (_tracingDelegate == null) {
_tracingDelegate = CompileLambda(_tracingLambda, new TargetUpdaterForCompilation(context, this).SetCompiledTargetTracing);
}
finalTarget = _tracingDelegate;
} else {
if (_normalDelegate == null) {
if (!forceCreation) {
// we cannot create the delegate when forceCreation is false because we hold the
// _CodeCreateAndUpdateDelegateLock and compiling the delegate may create a FunctionCode
// object which requires the lock.
PythonCallTargets.GetPythonTargetType(_lambda.ParameterNames.Length > PythonCallTargets.MaxArgs, _lambda.ParameterNames.Length, out Delegate target);
SetTarget(target);
return;
}
_normalDelegate = CompileLambda(GetGeneratorOrNormalLambda(), new TargetUpdaterForCompilation(context, this).SetCompiledTarget);
}
finalTarget = _normalDelegate;
}
finalTarget = AddRecursionCheck(context, finalTarget);
SetTarget(finalTarget);
}
/// <summary>
/// Called to set the initial target delegate when the user has passed -X:Debug to enable
/// .NET style debugging.
/// </summary>
internal void SetDebugTarget(PythonContext context, Delegate target) {
_normalDelegate = target;
SetTarget(AddRecursionCheck(context, target));
}
/// <summary>
/// Gets the LambdaExpression for tracing.
///
/// If this is a generator function code then the lambda gets tranformed into the correct generator code.
/// </summary>
private LambdaExpression GetGeneratorOrNormalLambdaTracing(PythonContext context) {
var debugProperties = new PythonDebuggingPayload(this);
var debugInfo = new DebugLambdaInfo(
null, // IDebugCompilerSupport
null, // lambda alias
false, // optimize for leaf frames
null, // hidden variables
null, // variable aliases
debugProperties // custom payload
);
if ((Flags & FunctionAttributes.Generator) == 0) {
return context.DebugContext.TransformLambda((LambdaExpression)Compiler.Ast.Node.RemoveFrame(_lambda.GetLambda()), debugInfo);
}
return Expression.Lambda(
Code.Type,
new GeneratorRewriter(
_lambda.Name,
Compiler.Ast.Node.RemoveFrame(Code.Body)
).Reduce(
_lambda.ShouldInterpret,
_lambda.EmitDebugSymbols,
context.Options.CompilationThreshold,
Code.Parameters,
x => (Expression<Func<MutableTuple, object>>)context.DebugContext.TransformLambda(x, debugInfo)
),
Code.Name,
Code.Parameters
);
}
/// <summary>
/// Gets the correct final LambdaExpression for this piece of code.
///
/// This is either just _lambda or _lambda re-written to be a generator expression.
/// </summary>
private LightLambdaExpression GetGeneratorOrNormalLambda() {
LightLambdaExpression finalCode;
if ((Flags & FunctionAttributes.Generator) == 0) {
finalCode = Code;
} else {
finalCode = Code.ToGenerator(
_lambda.ShouldInterpret,
_lambda.EmitDebugSymbols,
_lambda.GlobalParent.PyContext.Options.CompilationThreshold
);
}
return finalCode;
}
private Delegate CompileLambda(LightLambdaExpression code, EventHandler<LightLambdaCompileEventArgs> handler) {
#if EMIT_PDB
if (_lambda.EmitDebugSymbols) {
return CompilerHelpers.CompileToMethod((LambdaExpression)code.Reduce(), DebugInfoGenerator.CreatePdbGenerator(), true);
}
#endif
if (_lambda.ShouldInterpret) {
Delegate result = code.Compile(_lambda.GlobalParent.PyContext.Options.CompilationThreshold);
// If the adaptive compiler decides to compile this function, we
// want to store the new compiled target. This saves us from going
// through the interpreter stub every call.
if (result.Target is LightLambda lightLambda) {
lightLambda.Compile += handler;
}
return result;
}
return code.Compile();
}
private Delegate CompileLambda(LambdaExpression code, EventHandler<LightLambdaCompileEventArgs> handler) {
#if EMIT_PDB
if (_lambda.EmitDebugSymbols) {
return CompilerHelpers.CompileToMethod(code, DebugInfoGenerator.CreatePdbGenerator(), true);
}
#endif
if (_lambda.ShouldInterpret) {
Delegate result = CompilerHelpers.LightCompile(code, _lambda.GlobalParent.PyContext.Options.CompilationThreshold);
// If the adaptive compiler decides to compile this function, we
// want to store the new compiled target. This saves us from going
// through the interpreter stub every call.
if (result.Target is LightLambda lightLambda) {
lightLambda.Compile += handler;
}
return result;
}
return code.Compile();
}
internal Delegate AddRecursionCheck(PythonContext context, Delegate finalTarget) {
if (context.RecursionLimit != Int32.MaxValue) {
if (finalTarget is Func<CodeContext, CodeContext> ||
finalTarget is Func<FunctionCode, object> ||
finalTarget is LookupCompilationDelegate) {
// no recursion enforcement on classes or modules
return finalTarget;
}
switch (_lambda.ParameterNames.Length) {
#region Generated Python Recursion Delegate Switch
// *** BEGIN GENERATED CODE ***
// generated by function: gen_recursion_delegate_switch from: generate_calls.py
case 0:
finalTarget = new Func<PythonFunction, object>(new PythonFunctionRecursionCheck0((Func<PythonFunction, object>)finalTarget).CallTarget);
break;
case 1:
finalTarget = new Func<PythonFunction, object, object>(new PythonFunctionRecursionCheck1((Func<PythonFunction, object, object>)finalTarget).CallTarget);
break;
case 2:
finalTarget = new Func<PythonFunction, object, object, object>(new PythonFunctionRecursionCheck2((Func<PythonFunction, object, object, object>)finalTarget).CallTarget);
break;
case 3:
finalTarget = new Func<PythonFunction, object, object, object, object>(new PythonFunctionRecursionCheck3((Func<PythonFunction, object, object, object, object>)finalTarget).CallTarget);
break;
case 4:
finalTarget = new Func<PythonFunction, object, object, object, object, object>(new PythonFunctionRecursionCheck4((Func<PythonFunction, object, object, object, object, object>)finalTarget).CallTarget);
break;
case 5:
finalTarget = new Func<PythonFunction, object, object, object, object, object, object>(new PythonFunctionRecursionCheck5((Func<PythonFunction, object, object, object, object, object, object>)finalTarget).CallTarget);
break;
case 6:
finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck6((Func<PythonFunction, object, object, object, object, object, object, object>)finalTarget).CallTarget);
break;
case 7:
finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck7((Func<PythonFunction, object, object, object, object, object, object, object, object>)finalTarget).CallTarget);
break;
case 8:
finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck8((Func<PythonFunction, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget);
break;
case 9:
finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck9((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget);
break;
case 10:
finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck10((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget);
break;
case 11:
finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck11((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget);
break;
case 12:
finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck12((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget);
break;
case 13:
finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck13((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget);
break;
case 14:
finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck14((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget);
break;
case 15:
finalTarget = new Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>(new PythonFunctionRecursionCheck15((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)finalTarget).CallTarget);
break;
// *** END GENERATED CODE ***
#endregion
default:
finalTarget = new Func<PythonFunction, object[], object>(new PythonFunctionRecursionCheckN((Func<PythonFunction, object[], object>)finalTarget).CallTarget);
break;
}
}
return finalTarget;
}
private class TargetUpdaterForCompilation {
private readonly PythonContext _context;
private readonly FunctionCode _code;
public TargetUpdaterForCompilation(PythonContext context, FunctionCode code) {
_code = code;
_context = context;
}
public void SetCompiledTarget(object sender, LightLambdaCompileEventArgs e) {
_code.SetTarget(_code.AddRecursionCheck(_context, _code._normalDelegate = e.Compiled));
}
public void SetCompiledTargetTracing(object sender, LightLambdaCompileEventArgs e) {
_code.SetTarget(_code.AddRecursionCheck(_context, _code._tracingDelegate = e.Compiled));
}
}
#region IExpressionSerializable Members
Expression IExpressionSerializable.CreateExpression() {
return Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.MakeFunctionCode)),
Compiler.Ast.PythonAst._globalContext,
Expression.Constant(_lambda.Name),
Expression.Constant(_initialDoc, typeof(string)),
Expression.NewArrayInit(
typeof(string),
ArrayUtils.ConvertAll(_lambda.ParameterNames, (x) => Expression.Constant(x))
),
Expression.Constant(_lambda.ArgCount),
Expression.Constant(Flags),
Expression.Constant(_lambda.IndexSpan.Start),
Expression.Constant(_lambda.IndexSpan.End),
Expression.Constant(_lambda.Filename),
GetGeneratorOrNormalLambda(),
TupleToStringArray(co_freevars),
TupleToStringArray(co_names),
TupleToStringArray(co_cellvars),
TupleToStringArray(co_varnames),
Expression.Constant(_localCount)
);
}
private static Expression TupleToStringArray(PythonTuple tuple) {
return tuple.Count > 0 ?
(Expression)Expression.NewArrayInit(
typeof(string),
ArrayUtils.ConvertAll(tuple._data, (x) => Expression.Constant(x))
) :
(Expression)Expression.Constant(null, typeof(string[]));
}
#endregion
/// <summary>
/// Extremely light weight linked list of weak references used for tracking
/// all of the FunctionCode objects which get created and need to be updated
/// for purposes of recursion enforcement or tracing.
/// </summary>
internal class CodeList {
public readonly WeakReference Code;
public CodeList Next;
public CodeList() { }
public CodeList(WeakReference code, CodeList next) {
Code = code;
Next = next;
}
}
}
internal class PythonDebuggingPayload {
public FunctionCode Code;
private Dictionary<int, bool> _handlerLocations;
private Dictionary<int, Dictionary<int, bool>> _loopAndFinallyLocations;
public PythonDebuggingPayload(FunctionCode code) {
Code = code;
}
public Dictionary<int, bool> HandlerLocations {
get {
if (_handlerLocations == null) {
GatherLocations();
}
return _handlerLocations;
}
}
public Dictionary<int, Dictionary<int, bool>> LoopAndFinallyLocations {
get {
if (_loopAndFinallyLocations == null) {
GatherLocations();
}
return _loopAndFinallyLocations;
}
}
private void GatherLocations() {
var walker = new TracingWalker();
Code.PythonCode.Walk(walker);
_loopAndFinallyLocations = walker.LoopAndFinallyLocations;
_handlerLocations = walker.HandlerLocations;
}
private class TracingWalker : Compiler.Ast.PythonWalker {
private bool _inLoop, _inFinally;
private int _loopId;
public Dictionary<int, bool> HandlerLocations = new Dictionary<int, bool>();
public Dictionary<int, Dictionary<int, bool>> LoopAndFinallyLocations = new Dictionary<int, Dictionary<int, bool>>();
private Dictionary<int, bool> _loopIds = new Dictionary<int, bool>();
public override bool Walk(Compiler.Ast.ForStatement node) {
UpdateLoops(node);
WalkLoopBody(node.Body, false);
if (node.Else != null) {
node.Else.Walk(this);
}
return false;
}
private void WalkLoopBody(IronPython.Compiler.Ast.Statement body, bool isFinally) {
bool inLoop = _inLoop;
bool inFinally = _inFinally;
int loopId = ++_loopId;
_inFinally = false;
_inLoop = true;
_loopIds.Add(loopId, isFinally);
body.Walk(this);
_inLoop = inLoop;
_inFinally = inFinally;
LoopOrFinallyIds.Remove(loopId);
}
public override bool Walk(Compiler.Ast.WhileStatement node) {
UpdateLoops(node);
WalkLoopBody(node.Body, false);
node.ElseStatement?.Walk(this);
return false;
}
public override bool Walk(Compiler.Ast.TryStatement node) {
UpdateLoops(node);
node.Body.Walk(this);
foreach (var handler in node.Handlers) {
HandlerLocations[handler.Span.Start.Line] = false;
handler.Body.Walk(this);
}
if (node.Finally != null) {
WalkLoopBody(node.Finally, true);
}
return false;
}
public override bool Walk(Compiler.Ast.AssertStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.AssignmentStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.AugmentedAssignStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.BreakStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.ClassDefinition node) {
UpdateLoops(node);
return false;
}
public override bool Walk(Compiler.Ast.ContinueStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override void PostWalk(Compiler.Ast.EmptyStatement node) {
UpdateLoops(node);
base.PostWalk(node);
}
public override bool Walk(Compiler.Ast.DelStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.EmptyStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.GlobalStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.FromImportStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.ExpressionStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.FunctionDefinition node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.IfStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.ImportStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.RaiseStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
public override bool Walk(Compiler.Ast.WithStatement node) {
UpdateLoops(node);
return base.Walk(node);
}
private void UpdateLoops(Compiler.Ast.Statement stmt) {
if (_inFinally || _inLoop) {
if (!LoopAndFinallyLocations.ContainsKey(stmt.Span.Start.Line)) {
LoopAndFinallyLocations.Add(stmt.Span.Start.Line, new Dictionary<int, bool>(LoopOrFinallyIds));
}
}
}
public Dictionary<int, bool> LoopOrFinallyIds {
get {
if (_loopIds == null) {
_loopIds = new Dictionary<int, bool>();
}
return _loopIds;
}
}
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Activities.Presentation
{
using System.Activities.Presentation.Model;
using System.Activities.Core.Presentation;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Xml;
using System.Xml.Linq;
using System.ServiceModel.Description;
using System.Runtime;
partial class MessageQueryEditor
{
public static readonly DependencyProperty TypeCollectionProperty = DependencyProperty.Register(
"TypeCollection",
typeof(IList<KeyValuePair<string, Type>>),
typeof(MessageQueryEditor),
new UIPropertyMetadata(null, OnTypeCollectionChanged));
static readonly DependencyPropertyKey QueryPropertyKey = DependencyProperty.RegisterReadOnly(
"Query",
typeof(XPathMessageQuery),
typeof(MessageQueryEditor),
new UIPropertyMetadata(null));
static readonly DependencyProperty ActivityProperty = DependencyProperty.Register(
"Activity",
typeof(ModelItem),
typeof(MessageQueryEditor),
new UIPropertyMetadata(null));
public static readonly DependencyProperty QueryProperty = QueryPropertyKey.DependencyProperty;
public static readonly RoutedEvent XPathCreatedEvent = EventManager.RegisterRoutedEvent(
"XPathCreated",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(MessageQueryEditor));
public MessageQueryEditor()
{
InitializeComponent();
}
//a collection of name and type (argument name + argument type) to expand
public IList<KeyValuePair<string, Type>> TypeCollection
{
get { return (IList<KeyValuePair<string, Type>>)GetValue(TypeCollectionProperty); }
set { SetValue(TypeCollectionProperty, value); }
}
public XPathMessageQuery Query
{
get { return (XPathMessageQuery)GetValue(QueryProperty); }
private set { SetValue(QueryPropertyKey, value); }
}
internal ModelItem Activity
{
get { return (ModelItem)GetValue(ActivityProperty); }
set { SetValue(ActivityProperty, value); }
}
//event raised whenever user creates a xpath
public event RoutedEventHandler XPathCreated
{
add { this.AddHandler(XPathCreatedEvent, value); }
remove { this.RemoveHandler(XPathCreatedEvent, value); }
}
//override default combo box item with my own implementation and style
protected override DependencyObject GetContainerForItemOverride()
{
return new MessageQueryComboBoxItem() { Style = (Style)this.FindResource("comboBoxStyle") };
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Enter && Keyboard.Modifiers == ModifierKeys.None)
{
e.Handled = true;
if (!this.IsDropDownOpen && !string.IsNullOrEmpty(this.Text))
{
this.Query = new XPathMessageQuery(this.Text);
this.RaiseEvent(new RoutedEventArgs(XPathCreatedEvent, this));
}
}
base.OnKeyDown(e);
}
//user double clicked on the expanded type, create a xpath
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Propagating exceptions might lead to VS crash.")]
[SuppressMessage("Reliability", "Reliability108:IsFatalRule",
Justification = "Propagating exceptions might lead to VS crash.")]
void OnTypeSelectionChanged(object sender, RoutedEventArgs e)
{
var contentCorrelationDesigner = (ContentCorrelationTypeExpander)sender;
//is selection valid (valid type or property)
if (contentCorrelationDesigner.IsSelectionValid)
{
var path = contentCorrelationDesigner.GetMemberPath();
var type = contentCorrelationDesigner.GetSelectedType();
try
{
XmlNamespaceManager namespaceManager = null;
string xpathQuery = string.Empty;
var content = this.Activity.Properties["Content"].Value;
if (content.IsAssignableFrom<ReceiveMessageContent>() || content.IsAssignableFrom<SendMessageContent>())
{
//generating xpath for message content
xpathQuery = XPathQueryGenerator.CreateFromDataContractSerializer(type, path, out namespaceManager);
}
else
{
//generating xpath for parameter content
XName serviceContractName = null;
string operationName = null;
string parameterName = contentCorrelationDesigner.SelectedTypeEntry.Name;
bool isReply = this.Activity.IsAssignableFrom<SendReply>() || this.Activity.IsAssignableFrom<ReceiveReply>();
if (isReply)
{
operationName = (string)this.Activity.Properties["Request"].Value.Properties["OperationName"].ComputedValue;
serviceContractName = (XName)this.Activity.Properties["Request"].Value.Properties["ServiceContractName"].ComputedValue;
if (string.IsNullOrEmpty(operationName) || null == serviceContractName)
{
ModelItem requestDisplayName;
this.Activity.TryGetPropertyValue(out requestDisplayName, "Request", "DisplayName");
throw FxTrace.Exception.AsError(new InvalidOperationException(
string.Format(CultureInfo.CurrentUICulture, (string)this.FindResource("parametersRequiredText"), requestDisplayName.GetCurrentValue())));
}
}
else
{
operationName = (string)this.Activity.Properties["OperationName"].ComputedValue;
serviceContractName = (XName)this.Activity.Properties["ServiceContractName"].ComputedValue;
if (string.IsNullOrEmpty(operationName) || null == serviceContractName)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(
string.Format(CultureInfo.CurrentUICulture, (string)this.FindResource("parametersRequiredText"), this.Activity.Properties["DisplayName"].ComputedValue)));
}
}
xpathQuery = ParameterXPathQueryGenerator.CreateFromDataContractSerializer(serviceContractName, operationName, parameterName, isReply, type, path, out namespaceManager);
}
//use CDF api to build a xpath out of type and its properties
string xpath = string.Format(CultureInfo.InvariantCulture, "sm:body(){0}", xpathQuery);
//get the context
//We need to copy over the namespaces from the manager's table 1 by 1. According to MSDN:
//If you specify an existing name table, any namespaces in the name table are not automatically added to XmlNamespaceManager.
//You must use AddNamespace and RemoveNamespace to add or remove namespaces.
XPathMessageContext messageContext = new XPathMessageContext();
foreach (string prefix in namespaceManager)
{
if (!string.IsNullOrEmpty(prefix) && !messageContext.HasNamespace(prefix) && prefix != "xmlns")
{
messageContext.AddNamespace(prefix, namespaceManager.LookupNamespace(prefix));
}
}
var typeEntry = (ExpanderTypeEntry)contentCorrelationDesigner.Tag;
//construct xpath
XPathMessageQuery query = new XPathMessageQuery(xpath, messageContext);
//store the xpath in the Tag property; this combo's selectedValue is bound to i
typeEntry.Tag = query;
this.SelectedIndex = 0;
this.IsDropDownOpen = false;
this.Query = query;
this.RaiseEvent(new RoutedEventArgs(XPathCreatedEvent, this));
}
catch (Exception err)
{
MessageBox.Show(
err.Message,
(string)this.Resources["controlTitle"],
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
void OnTypeCollectionChanged()
{
//user provided a list of types to expand
var items = new List<ExpanderTypeEntry>();
if (null != this.TypeCollection)
{
StringBuilder text = new StringBuilder((string)this.FindResource("selectedDisplayText"));
bool addComma = false;
//copy all of then into ExpanderTypeEntry
foreach (var entry in this.TypeCollection)
{
if (addComma)
{
text.Append(", ");
}
items.Add(new ExpanderTypeEntry() { TypeToExpand = entry.Value, Name = entry.Key });
text.Append(entry.Key);
addComma = true;
}
//requirement of combo box is that data source must be enumerable, so provide one elemnt array
this.ItemsSource = new object[] { new TypeEntryContainer() { Items = items, DisplayText = text.ToString() } };
}
else
{
this.ItemsSource = null;
}
}
static void OnTypeCollectionChanged(object sender, DependencyPropertyChangedEventArgs e)
{
((MessageQueryEditor)sender).OnTypeCollectionChanged();
}
//ComboBox item subclass
sealed class MessageQueryComboBoxItem : ComboBoxItem
{
public MessageQueryComboBoxItem()
{
//i don't want it to be focusable - its conent is
this.Focusable = false;
}
//do not notify parent ComboBox about mouse down & up events - i don't want to close popup too early
//i handle closing myself
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
}
}
}
}
| |
using System;
namespace Ensurance.Attributes
{
public partial class Is
{
#region Nested type: Not
/// <summary>
///
/// </summary>
public class Not
{
#region Nested type: Empty
/// <summary>
///
/// </summary>
public class Empty : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="Empty"/> class.
/// </summary>
public Empty()
{
_constraint = SyntaxHelpers.Is.Not.Empty;
}
}
#endregion
#region Nested type: False
/// <summary>
///
/// </summary>
public class False : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="False"/> class.
/// </summary>
public False()
{
_constraint = SyntaxHelpers.Is.Not.False;
}
}
#endregion
#region Nested type: NaN
/// <summary>
///
/// </summary>
public class NaN : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="NaN"/> class.
/// </summary>
public NaN()
{
_constraint = SyntaxHelpers.Is.Not.NaN;
}
/// <summary>
/// Initializes a new instance of the <see cref="NaN"/> class.
/// </summary>
/// <param name="tolerance">The tolerance.</param>
public NaN( object tolerance )
: this()
{
_constraint.Tolerance = tolerance;
}
}
#endregion
#region Nested type: Null
/// <summary>
///
/// </summary>
public class Null : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="Null"/> class.
/// </summary>
public Null()
{
_constraint = SyntaxHelpers.Is.Not.Null;
}
}
#endregion
#region Nested type: True
/// <summary>
///
/// </summary>
public class True : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="True"/> class.
/// </summary>
public True()
{
_constraint = SyntaxHelpers.Is.Not.True;
}
}
#endregion
#region Nested type: Unique
/// <summary>
///
/// </summary>
public class Unique : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="Unique"/> class.
/// </summary>
public Unique()
{
_constraint = SyntaxHelpers.Is.Not.Unique;
}
}
#region Comparison Constraints
#region Nested type: AtLeast
/// <summary>
///
/// </summary>
public class AtLeast : GreaterThanOrEqualTo
{
/// <summary>
/// Initializes a new instance of the <see cref="AtLeast"/> class.
/// </summary>
/// <param name="expected">The expected.</param>
public AtLeast( IComparable expected )
: base( expected )
{
}
}
#endregion
#region Nested type: AtMost
/// <summary>
///
/// </summary>
public class AtMost : LessThanOrEqualTo
{
/// <summary>
/// Initializes a new instance of the <see cref="AtMost"/> class.
/// </summary>
/// <param name="expected">The expected.</param>
public AtMost( IComparable expected )
: base( expected )
{
}
}
#endregion
#region Nested type: GreaterThan
/// <summary>
///
/// </summary>
public class GreaterThan : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="GreaterThan"/> class.
/// </summary>
/// <param name="expected">The expected.</param>
public GreaterThan( IComparable expected )
{
_constraint = SyntaxHelpers.Is.Not.GreaterThan( expected );
}
}
#endregion
#region Nested type: GreaterThanOrEqualTo
/// <summary>
///
/// </summary>
public class GreaterThanOrEqualTo : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="GreaterThanOrEqualTo"/> class.
/// </summary>
/// <param name="expected">The expected.</param>
public GreaterThanOrEqualTo( IComparable expected )
{
_constraint = SyntaxHelpers.Is.Not.GreaterThanOrEqualTo( expected );
}
}
#endregion
#region Nested type: LessThan
/// <summary>
///
/// </summary>
public class LessThan : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="LessThan"/> class.
/// </summary>
/// <param name="expected">The expected.</param>
public LessThan( IComparable expected )
{
_constraint = SyntaxHelpers.Is.Not.LessThan( expected );
}
}
#endregion
#region Nested type: LessThanOrEqualTo
/// <summary>
///
/// </summary>
public class LessThanOrEqualTo : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="LessThanOrEqualTo"/> class.
/// </summary>
/// <param name="expected">The expected.</param>
public LessThanOrEqualTo( IComparable expected )
{
_constraint = SyntaxHelpers.Is.Not.LessThanOrEqualTo( expected );
}
}
#endregion
#endregion Comparison Constraints
#region Type Constraints
#region Nested type: AssignableFrom
/// <summary>
///
/// </summary>
public class AssignableFrom : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="AssignableFrom"/> class.
/// </summary>
/// <param name="expected">The expected.</param>
public AssignableFrom( Type expected )
{
_constraint = SyntaxHelpers.Is.Not.AssignableFrom( expected );
}
}
#endregion
#region Nested type: InstanceOfType
/// <summary>
///
/// </summary>
public class InstanceOfType : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="InstanceOfType"/> class.
/// </summary>
/// <param name="expected">The expected.</param>
public InstanceOfType( Type expected )
{
_constraint = SyntaxHelpers.Is.Not.InstanceOfType( expected );
}
}
#endregion
#region Nested type: TypeOf
/// <summary>
///
/// </summary>
public class TypeOf : ConstraintAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="TypeOf"/> class.
/// </summary>
/// <param name="expected">The expected.</param>
public TypeOf( Type expected )
{
_constraint = SyntaxHelpers.Is.Not.TypeOf( expected );
}
}
#endregion
#endregion
#endregion
}
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSLF.Model;
using NPOI.ddf.EscherContainerRecord;
using NPOI.ddf.EscherDgRecord;
using NPOI.ddf.EscherDggRecord;
using NPOI.ddf.EscherSpRecord;
using NPOI.HSLF.record.ColorSchemeAtom;
using NPOI.HSLF.record.Comment2000;
using NPOI.HSLF.record.HeadersFootersContainer;
using NPOI.HSLF.record.Record;
using NPOI.HSLF.record.RecordContainer;
using NPOI.HSLF.record.RecordTypes;
using NPOI.HSLF.record.SlideAtom;
using NPOI.HSLF.record.TextHeaderAtom;
using NPOI.HSLF.record.SlideListWithText.SlideAtomsSet;
/**
* This class represents a slide in a PowerPoint Document. It allows
* access to the text within, and the layout. For now, it only does
* the text side of things though
*
* @author Nick Burch
* @author Yegor Kozlov
*/
public class Slide : Sheet
{
private int _slideNo;
private SlideAtomsSet _atomSet;
private TextRun[] _Runs;
private Notes _notes; // usermodel needs to Set this
/**
* Constructs a Slide from the Slide record, and the SlideAtomsSet
* Containing the text.
* Initialises TextRuns, to provide easier access to the text
*
* @param slide the Slide record we're based on
* @param notes the Notes sheet attached to us
* @param atomSet the SlideAtomsSet to Get the text from
*/
public Slide(NPOI.HSLF.record.Slide slide, Notes notes, SlideAtomsSet atomSet, int slideIdentifier, int slideNumber) {
base(slide, slideIdentifier);
_notes = notes;
_atomSet = atomSet;
_slideNo = slideNumber;
// Grab the TextRuns from the PPDrawing
TextRun[] _otherRuns = FindTextRuns(getPPDrawing());
// For the text coming in from the SlideAtomsSet:
// Build up TextRuns from pairs of TextHeaderAtom and
// one of TextBytesAtom or TextCharsAtom
Vector textRuns = new Vector();
if(_atomSet != null) {
FindTextRuns(_atomSet.GetSlideRecords(),textRuns);
} else {
// No text on the slide, must just be pictures
}
// Build an array, more useful than a vector
_Runs = new TextRun[textRuns.Count+_otherRuns.Length];
// Grab text from SlideListWithTexts entries
int i=0;
for(i=0; i<textRuns.Count; i++) {
_Runs[i] = (TextRun)textRuns.Get(i);
_Runs[i].SetSheet(this);
}
// Grab text from slide's PPDrawing
for(int k=0; k<_otherRuns.Length; i++, k++) {
_Runs[i] = _otherRuns[k];
_Runs[i].SetSheet(this);
}
}
/**
* Create a new Slide instance
* @param sheetNumber The internal number of the sheet, as used by PersistPtrHolder
* @param slideNumber The user facing number of the sheet
*/
public Slide(int sheetNumber, int sheetRefId, int slideNumber){
base(new NPOI.HSLF.record.Slide(), sheetNumber);
_slideNo = slideNumber;
GetSheetContainer().SetSheetId(sheetRefId);
}
/**
* Sets the Notes that are associated with this. Updates the
* references in the records to point to the new ID
*/
public void SetNotes(Notes notes) {
_notes = notes;
// Update the Slide Atom's ID of where to point to
SlideAtom sa = GetSlideRecord().GetSlideAtom();
if(notes == null) {
// Set to 0
sa.SetNotesID(0);
} else {
// Set to the value from the notes' sheet id
sa.SetNotesID(notes._getSheetNumber());
}
}
/**
* Changes the Slide's (external facing) page number.
* @see NPOI.HSLF.usermodel.SlideShow#reorderSlide(int, int)
*/
public void SetSlideNumber(int newSlideNumber) {
_slideNo = newSlideNumber;
}
/**
* Called by SlideShow ater a new slide is Created.
* <p>
* For Slide we need to do the following:
* <li> Set id of the Drawing group.
* <li> Set shapeId for the Container descriptor and background
* </p>
*/
public void onCreate(){
//Initialize Drawing group id
EscherDggRecord dgg = GetSlideShow().GetDocumentRecord().GetPPDrawingGroup().GetEscherDggRecord();
EscherContainerRecord dgContainer = (EscherContainerRecord)getSheetContainer().GetPPDrawing().GetEscherRecords()[0];
EscherDgRecord dg = (EscherDgRecord) Shape.GetEscherChild(dgContainer, EscherDgRecord.RECORD_ID);
int dgId = dgg.GetMaxDrawingGroupId() + 1;
dg.SetOptions((short)(dgId << 4));
dgg.SetDrawingsSaved(dgg.GetDrawingsSaved() + 1);
dgg.SetMaxDrawingGroupId(dgId);
foreach (EscherContainerRecord c in dgContainer.GetChildContainers()) {
EscherSpRecord spr = null;
switch(c.GetRecordId()){
case EscherContainerRecord.SPGR_CONTAINER:
EscherContainerRecord dc = (EscherContainerRecord)c.GetChild(0);
spr = dc.GetChildById(EscherSpRecord.RECORD_ID);
break;
case EscherContainerRecord.SP_CONTAINER:
spr = c.GetChildById(EscherSpRecord.RECORD_ID);
break;
}
if(spr != null) spr.SetShapeId(allocateShapeId());
}
//PPT doen't increment the number of saved shapes for group descriptor and background
dg.SetNumShapes(1);
}
/**
* Create a <code>TextBox</code> object that represents the slide's title.
*
* @return <code>TextBox</code> object that represents the slide's title.
*/
public TextBox AddTitle() {
Placeholder pl = new Placeholder();
pl.SetShapeType(ShapeTypes.Rectangle);
pl.GetTextRun().SetRunType(TextHeaderAtom.TITLE_TYPE);
pl.SetText("Click to edit title");
pl.SetAnchor(new java.awt.Rectangle(54, 48, 612, 90));
AddShape(pl);
return pl;
}
// Complex Accesser methods follow
/**
* Return title of this slide or <code>null</code> if the slide does not have title.
* <p>
* The title is a run of text of type <code>TextHeaderAtom.CENTER_TITLE_TYPE</code> or
* <code>TextHeaderAtom.TITLE_TYPE</code>
* </p>
*
* @see TextHeaderAtom
*
* @return title of this slide
*/
public String GetTitle(){
TextRun[] txt = GetTextRuns();
for (int i = 0; i < txt.Length; i++) {
int type = txt[i].GetRunType();
if (type == TextHeaderAtom.CENTER_TITLE_TYPE ||
type == TextHeaderAtom.TITLE_TYPE ){
String title = txt[i].GetText();
return title;
}
}
return null;
}
// Simple Accesser methods follow
/**
* Returns an array of all the TextRuns found
*/
public TextRun[] GetTextRuns() { return _Runs; }
/**
* Returns the (public facing) page number of this slide
*/
public int GetSlideNumber() { return _slideNo; }
/**
* Returns the underlying slide record
*/
public NPOI.HSLF.record.Slide GetSlideRecord() {
return (NPOI.HSLF.record.Slide)getSheetContainer();
}
/**
* Returns the Notes Sheet for this slide, or null if there isn't one
*/
public Notes GetNotesSheet() { return _notes; }
/**
* @return Set of records inside <code>SlideListWithtext</code> Container
* which hold text data for this slide (typically for placeholders).
*/
protected SlideAtomsSet GetSlideAtomsSet() { return _atomSet; }
/**
* Returns master sheet associated with this slide.
* It can be either SlideMaster or TitleMaster objects.
*
* @return the master sheet associated with this slide.
*/
public MasterSheet GetMasterSheet(){
SlideMaster[] master = GetSlideShow().GetSlidesMasters();
SlideAtom sa = GetSlideRecord().GetSlideAtom();
int masterId = sa.GetMasterID();
MasterSheet sheet = null;
for (int i = 0; i < master.Length; i++) {
if (masterId == master[i]._getSheetNumber()) {
sheet = master[i];
break;
}
}
if (sheet == null){
TitleMaster[] titleMaster = GetSlideShow().GetTitleMasters();
if(titleMaster != null) for (int i = 0; i < titleMaster.Length; i++) {
if (masterId == titleMaster[i]._getSheetNumber()) {
sheet = titleMaster[i];
break;
}
}
}
return sheet;
}
/**
* Change Master of this slide.
*/
public void SetMasterSheet(MasterSheet master){
SlideAtom sa = GetSlideRecord().GetSlideAtom();
int sheetNo = master._getSheetNumber();
sa.SetMasterID(sheetNo);
}
/**
* Sets whether this slide follows master background
*
* @param flag <code>true</code> if the slide follows master,
* <code>false</code> otherwise
*/
public void SetFollowMasterBackground(bool flag){
SlideAtom sa = GetSlideRecord().GetSlideAtom();
sa.SetFollowMasterBackground(flag);
}
/**
* Whether this slide follows master sheet background
*
* @return <code>true</code> if the slide follows master background,
* <code>false</code> otherwise
*/
public bool GetFollowMasterBackground(){
SlideAtom sa = GetSlideRecord().GetSlideAtom();
return sa.GetFollowMasterBackground();
}
/**
* Sets whether this slide Draws master sheet objects
*
* @param flag <code>true</code> if the slide Draws master sheet objects,
* <code>false</code> otherwise
*/
public void SetFollowMasterObjects(bool flag){
SlideAtom sa = GetSlideRecord().GetSlideAtom();
sa.SetFollowMasterObjects(flag);
}
/**
* Whether this slide follows master color scheme
*
* @return <code>true</code> if the slide follows master color scheme,
* <code>false</code> otherwise
*/
public bool GetFollowMasterScheme(){
SlideAtom sa = GetSlideRecord().GetSlideAtom();
return sa.GetFollowMasterScheme();
}
/**
* Sets whether this slide Draws master color scheme
*
* @param flag <code>true</code> if the slide Draws master color scheme,
* <code>false</code> otherwise
*/
public void SetFollowMasterScheme(bool flag){
SlideAtom sa = GetSlideRecord().GetSlideAtom();
sa.SetFollowMasterScheme(flag);
}
/**
* Whether this slide Draws master sheet objects
*
* @return <code>true</code> if the slide Draws master sheet objects,
* <code>false</code> otherwise
*/
public bool GetFollowMasterObjects(){
SlideAtom sa = GetSlideRecord().GetSlideAtom();
return sa.GetFollowMasterObjects();
}
/**
* Background for this slide.
*/
public Background GetBackground() {
if(getFollowMasterBackground()) {
return GetMasterSheet().GetBackground();
}
return super.GetBackground();
}
/**
* Color scheme for this slide.
*/
public ColorSchemeAtom GetColorScheme() {
if(getFollowMasterScheme()){
return GetMasterSheet().GetColorScheme();
}
return super.GetColorScheme();
}
/**
* Get the comment(s) for this slide.
* Note - for now, only works on PPT 2000 and
* PPT 2003 files. Doesn't work for PPT 97
* ones, as they do their comments oddly.
*/
public Comment[] GetComments() {
// If there are any, they're in
// ProgTags -> ProgBinaryTag -> BinaryTagData
RecordContainer progTags = (RecordContainer)
GetSheetContainer().FindFirstOfType(
RecordTypes.ProgTags.typeID
);
if(progTags != null) {
RecordContainer progBinaryTag = (RecordContainer)
progTags.FindFirstOfType(
RecordTypes.ProgBinaryTag.typeID
);
if(progBinaryTag != null) {
RecordContainer binaryTags = (RecordContainer)
progBinaryTag.FindFirstOfType(
RecordTypes.BinaryTagData.typeID
);
if(binaryTags != null) {
// This is where they'll be
int count = 0;
for(int i=0; i<binaryTags.GetChildRecords().Length; i++) {
if(binaryTags.GetChildRecords()[i] is Comment2000) {
count++;
}
}
// Now build
Comment[] comments = new Comment[count];
count = 0;
for(int i=0; i<binaryTags.GetChildRecords().Length; i++) {
if(binaryTags.GetChildRecords()[i] is Comment2000) {
comments[i] = new Comment(
(Comment2000)binaryTags.GetChildRecords()[i]
);
count++;
}
}
return comments;
}
}
}
// None found
return new Comment[0];
}
public void Draw(Graphics2D graphics){
MasterSheet master = GetMasterSheet();
if(getFollowMasterBackground()) master.GetBackground().Draw(graphics);
if(getFollowMasterObjects()){
Shape[] sh = master.GetShapes();
for (int i = 0; i < sh.Length; i++) {
if(MasterSheet.IsPlaceholder(sh[i])) continue;
sh[i].Draw(graphics);
}
}
Shape[] sh = GetShapes();
for (int i = 0; i < sh.Length; i++) {
sh[i].Draw(graphics);
}
}
/**
* Header / Footer Settings for this slide.
*
* @return Header / Footer Settings for this slide
*/
public HeadersFooters GetHeadersFooters(){
HeadersFootersContainer hdd = null;
Record[] ch = GetSheetContainer().GetChildRecords();
bool ppt2007 = false;
for (int i = 0; i < ch.Length; i++) {
if(ch[i] is HeadersFootersContainer){
hdd = (HeadersFootersContainer)ch[i];
} else if (ch[i].GetRecordType() == RecordTypes.RoundTripContentMasterId.typeID){
ppt2007 = true;
}
}
bool newRecord = false;
if(hdd == null && !ppt2007) {
return GetSlideShow().GetSlideHeadersFooters();
}
if(hdd == null) {
hdd = new HeadersFootersContainer(HeadersFootersContainer.SlideHeadersFootersContainer);
newRecord = true;
}
return new HeadersFooters(hdd, this, newRecord, ppt2007);
}
protected void onAddTextShape(TextShape shape) {
TextRun run = shape.GetTextRun();
if(_Runs == null) _Runs = new TextRun[]{Run};
else {
TextRun[] tmp = new TextRun[_Runs.Length + 1];
Array.Copy(_Runs, 0, tmp, 0, _Runs.Length);
tmp[tmp.Length-1] = Run;
_Runs = tmp;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file=".cs" company="sgmunn">
// (c) sgmunn 2012
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of
// the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using MonoKit.Interactivity;
namespace MonoKit.UI
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using MonoKit.DataBinding;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
public abstract class TableViewSectionBase : IEnumerable
{
protected const string DefaultViewReuseIdentifier = "DefaultCell";
private object header;
private object footer;
private readonly List<IViewDefinition> viewDefinitions;
protected TableViewSectionBase(TableViewSource source)
{
this.Source = source;
this.viewDefinitions = new List<IViewDefinition>();
this.Source.Add(this);
}
protected TableViewSectionBase(TableViewSource source, params IViewDefinition[] viewDefinitions)
{
this.Source = source;
this.viewDefinitions = new List<IViewDefinition>(viewDefinitions);
this.Source.Add(this);
}
public static AttachedProperty SectionProperty
{
get
{
return AttachedProperty.Register("Section", typeof(TableViewSectionBase), typeof(TableViewSectionBase));
}
}
public TableViewSource Source
{
get;
private set;
}
public string Header
{
get
{
return this.header as string;
}
set
{
this.header = value;
}
}
public string Footer
{
get
{
return this.footer as string;
}
set
{
this.footer = value;
}
}
public UIView HeaderView
{
get
{
return this.header as UIView;
}
set
{
this.header = value;
}
}
public UIView FooterView
{
get
{
return this.footer as UIView;
}
set
{
this.footer = value;
}
}
public int Count
{
get
{
return this.GetCount();
}
}
public bool AllowMoveItems
{
get;
set;
}
public List<IViewDefinition> ViewDefinitions
{
get
{
return this.viewDefinitions;
}
}
public abstract void Clear();
public abstract UITableViewCell GetCell(int row);
public abstract void RowSelected(NSIndexPath indexPath);
public abstract bool CanEditRow(NSIndexPath indexPath);
public abstract void EditRow(UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath);
public abstract void MoveRow(NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath);
public abstract float GetHeightForRow(NSIndexPath indexPath);
public abstract IEnumerator GetEnumerator();
protected abstract int GetCount();
protected virtual UITableViewCell CreateDefaultView()
{
return new UITableViewCell(UITableViewCellStyle.Default, DefaultViewReuseIdentifier);
}
protected UITableViewCell GetViewForObject(object element)
{
UITableViewCell cell = null;
var viewDef = this.GetViewDefinition(element);
if (viewDef == null)
{
cell = this.GetDefaultView();
// perform a basic bind to the cell so that we can see that something should be in the table
cell.TextLabel.Text = element.ToString();
cell.SetValue(DataContextAttachedProperty.DataContextProperty, element);
return cell;
}
cell = this.GetViewFromDeclaration(viewDef);
// if the element is a wrapper, then bind to the wrapped object instead
var dataContext = element;
if (element is IDataViewWrapper)
{
dataContext = ((IDataViewWrapper)element).Data;
}
cell.SetValue(DataContextAttachedProperty.DataContextProperty, dataContext);
viewDef.Bind(cell, dataContext);
return cell;
}
private static void AttachBehavioursToView (List<Type> behaviours, UITableViewCell cell)
{
foreach (var behaviourType in behaviours)
{
var behaviour = System.Activator.CreateInstance(behaviourType) as Behaviour;
behaviour.AttachedObject = cell;
}
}
private static NSString GetReuseIndentiferForView(Type viewType, UITableViewCellStyle style)
{
return new NSString(viewType.ToString()+"_"+style.ToString());
}
private UITableViewCell GetViewFromDeclaration(IViewDefinition viewDefinition)
{
var style = UITableViewCellStyle.Default;
if (viewDefinition.Param is UITableViewCellStyle)
{
style = (UITableViewCellStyle)viewDefinition.Param;
}
var reuseIndentifer = GetReuseIndentiferForView(viewDefinition.ViewType, style);
var cell = this.Source.TableView.DequeueReusableCell(reuseIndentifer);
if (cell == null)
{
cell = this.CreateView(viewDefinition.ViewType, style, reuseIndentifer);
cell.SetValue(TableViewSection.SectionProperty, this);
AttachBehavioursToView(viewDefinition.Behaviours, cell);
}
return cell;
}
private UITableViewCell GetDefaultView()
{
var cell = this.Source.TableView.DequeueReusableCell(DefaultViewReuseIdentifier);
if (cell == null)
{
cell = this.CreateDefaultView();
cell.SetValue(TableViewSection.SectionProperty, this);
}
return cell;
}
private UITableViewCell CreateView(Type viewType, UITableViewCellStyle style, NSString reuseIndentifer)
{
var cell = System.Activator.CreateInstance(viewType, new object[] {style, reuseIndentifer});
return cell as UITableViewCell;
}
private IViewDefinition GetViewDefinition(object element)
{
if (element is IDataViewWrapper)
{
return ((IDataViewWrapper)element).ViewDefinition;
}
var view = this.viewDefinitions.FirstOrDefault(x => x.Renders(element));
return view;
}
}
}
| |
//
// CGColorSpace.cs: Implements geometry classes
//
// Authors: Mono Team
//
// Copyright 2009 Novell, Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
namespace MonoMac.CoreGraphics {
public enum CGColorRenderingIntent {
Default,
AbsoluteColorimetric,
RelativeColorimetric,
Perceptual,
Saturation
};
public enum CGColorSpaceModel {
Unknown = -1,
Monochrome,
RGB,
CMYK,
Lab,
DeviceN,
Indexed,
Pattern
}
public class CGColorSpace : INativeObject, IDisposable {
internal IntPtr handle;
public static CGColorSpace Null = new CGColorSpace (IntPtr.Zero);
// Invoked by the marshallers, we need to take a ref
public CGColorSpace (IntPtr handle)
{
this.handle = handle;
CGColorSpaceRetain (handle);
}
[Preserve (Conditional=true)]
internal CGColorSpace (IntPtr handle, bool owns)
{
if (!owns)
CGColorSpaceRetain (handle);
this.handle = handle;
}
~CGColorSpace ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGColorSpaceRelease (IntPtr handle);
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGColorSpaceRetain (IntPtr handle);
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CGColorSpaceRelease (handle);
handle = IntPtr.Zero;
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGColorSpaceCreateDeviceGray ();
public static CGColorSpace CreateDeviceGray ()
{
return new CGColorSpace (CGColorSpaceCreateDeviceGray (), true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGColorSpaceCreateDeviceRGB ();
public static CGColorSpace CreateDeviceRGB ()
{
return new CGColorSpace (CGColorSpaceCreateDeviceRGB (), true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGColorSpaceCreateDeviceCMYK ();
public static CGColorSpace CreateDeviceCMYK ()
{
return new CGColorSpace (CGColorSpaceCreateDeviceCMYK (), true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGColorSpaceCreateCalibratedGray (float [] whitepoint, float [] blackpoint, float gamma);
public static CGColorSpace CreateCalibratedGray (float [] whitepoint, float [] blackpoint, float gamma)
{
if (whitepoint.Length != 3)
throw new ArgumentException ("Must have 3 values", "whitepoint");
if (blackpoint.Length != 3)
throw new ArgumentException ("Must have 3 values", "blackpoint");
return new CGColorSpace (CGColorSpaceCreateCalibratedGray (whitepoint, blackpoint, gamma), true);
}
// 3, 3, 3, 9
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGColorSpaceCreateCalibratedRGB (float [] whitePoint, float [] blackPoint, float [] gamma, float [] matrix);
public static CGColorSpace CreateCalibratedRGB (float [] whitepoint, float [] blackpoint, float [] gamma, float [] matrix)
{
if (whitepoint.Length != 3)
throw new ArgumentException ("Must have 3 values", "whitepoint");
if (blackpoint.Length != 3)
throw new ArgumentException ("Must have 3 values", "blackpoint");
if (gamma.Length != 3)
throw new ArgumentException ("Must have 3 values", "gamma");
if (matrix.Length != 9)
throw new ArgumentException ("Must have 9 values", "matrix");
return new CGColorSpace (CGColorSpaceCreateCalibratedRGB (whitepoint, blackpoint, gamma, matrix), true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGColorSpaceCreatePattern (IntPtr baseSpace);
public static CGColorSpace CreatePattern (CGColorSpace baseSpace)
{
return new CGColorSpace (CGColorSpaceCreatePattern (baseSpace == null ? IntPtr.Zero : baseSpace.handle), true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGColorSpaceCreateWithName (IntPtr name);
public static CGColorSpace CreateWithName (string name)
{
if (name == null)
throw new ArgumentNullException ("name");
return new CGColorSpace (CGColorSpaceCreateWithName (new NSString(name).Handle), true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGColorSpaceGetBaseColorSpace (IntPtr space);
public CGColorSpace GetBaseColorSpace ()
{
return new CGColorSpace (CGColorSpaceGetBaseColorSpace (handle), true);
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static CGColorSpaceModel CGColorSpaceGetModel (IntPtr space);
public CGColorSpaceModel Model {
get {
return CGColorSpaceGetModel (handle);
}
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static int CGColorSpaceGetNumberOfComponents (IntPtr space);
public int Components {
get {
return CGColorSpaceGetNumberOfComponents (handle);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
// This abstract class represents a calendar. A calendar reckons time in
// divisions such as weeks, months and years. The number, length and start of
// the divisions vary in each calendar.
//
// Any instant in time can be represented as an n-tuple of numeric values using
// a particular calendar. For example, the next vernal equinox occurs at (0.0, 0
// , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of
// Calendar can map any DateTime value to such an n-tuple and vice versa. The
// DateTimeFormat class can map between such n-tuples and a textual
// representation such as "8:46 AM March 20th 1999 AD".
//
// Most calendars identify a year which begins the current era. There may be any
// number of previous eras. The Calendar class identifies the eras as enumerated
// integers where the current era (CurrentEra) has the value zero.
//
// For consistency, the first unit in each interval, e.g. the first month, is
// assigned the value one.
// The calculation of hour/minute/second is moved to Calendar from GregorianCalendar,
// since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
[Serializable]
public abstract partial class Calendar : ICloneable
{
// Number of 100ns (10E-7 second) ticks per time unit
internal const long TicksPerMillisecond = 10000;
internal const long TicksPerSecond = TicksPerMillisecond * 1000;
internal const long TicksPerMinute = TicksPerSecond * 60;
internal const long TicksPerHour = TicksPerMinute * 60;
internal const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
internal const int MillisPerSecond = 1000;
internal const int MillisPerMinute = MillisPerSecond * 60;
internal const int MillisPerHour = MillisPerMinute * 60;
internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
internal const int DaysPerYear = 365;
// Number of days in 4 years
internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 1/1/10000
internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
private int _currentEraValue = -1;
[OptionalField(VersionAdded = 2)]
private bool _isReadOnly = false;
#if INSIDE_CLR
internal const CalendarId CAL_HEBREW = CalendarId.HEBREW;
internal const CalendarId CAL_HIJRI = CalendarId.HIJRI;
internal const CalendarId CAL_JAPAN = CalendarId.JAPAN;
internal const CalendarId CAL_JULIAN = CalendarId.JULIAN;
internal const CalendarId CAL_TAIWAN = CalendarId.TAIWAN;
internal const CalendarId CAL_UMALQURA = CalendarId.UMALQURA;
internal const CalendarId CAL_PERSIAN = CalendarId.PERSIAN;
#endif
// The minimum supported DateTime range for the calendar.
public virtual DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
// The maximum supported DateTime range for the calendar.
public virtual DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
public virtual CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.Unknown;
}
}
protected Calendar()
{
//Do-nothing constructor.
}
///
// This can not be abstract, otherwise no one can create a subclass of Calendar.
//
internal virtual CalendarId ID
{
get
{
return CalendarId.UNINITIALIZED_VALUE;
}
}
///
// Return the Base calendar ID for calendars that didn't have defined data in calendarData
//
internal virtual CalendarId BaseCalendarID
{
get { return ID; }
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
public bool IsReadOnly
{
get { return (_isReadOnly); }
}
////////////////////////////////////////////////////////////////////////
//
// Clone
//
// Is the implementation of ICloneable.
//
////////////////////////////////////////////////////////////////////////
public virtual object Clone()
{
object o = MemberwiseClone();
((Calendar)o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
public static Calendar ReadOnly(Calendar calendar)
{
if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); }
Contract.EndContractBlock();
if (calendar.IsReadOnly) { return (calendar); }
Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone());
clonedCalendar.SetReadOnlyState(true);
return (clonedCalendar);
}
internal void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
_isReadOnly = readOnly;
}
/*=================================CurrentEraValue==========================
**Action: This is used to convert CurretEra(0) to an appropriate era value.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** The value is from calendar.nlp.
============================================================================*/
internal virtual int CurrentEraValue
{
get
{
// The following code assumes that the current era value can not be -1.
if (_currentEraValue == -1)
{
Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (_currentEraValue);
}
}
// The current era for a calendar.
public const int CurrentEra = 0;
internal int twoDigitYearMax = -1;
internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue)
{
if (ticks < minValue.Ticks || ticks > maxValue.Ticks)
{
throw new ArgumentException(
String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange,
minValue, maxValue)));
}
Contract.EndContractBlock();
}
internal DateTime Add(DateTime time, double value, int scale)
{
// From ECMA CLI spec, Partition III, section 3.27:
//
// If overflow occurs converting a floating-point type to an integer, or if the floating-point value
// being converted to an integer is a NaN, the value returned is unspecified.
//
// Based upon this, this method should be performing the comparison against the double
// before attempting a cast. Otherwise, the result is undefined.
double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5));
if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis)))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue);
}
long millis = (long)tempMillis;
long ticks = time.Ticks + millis * TicksPerMillisecond;
CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// milliseconds to the specified DateTime. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to the specified DateTime. The value
// argument is permitted to be negative.
//
public virtual DateTime AddMilliseconds(DateTime time, double milliseconds)
{
return (Add(time, milliseconds, 1));
}
// Returns the DateTime resulting from adding a fractional number of
// days to the specified DateTime. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddDays(DateTime time, int days)
{
return (Add(time, days, MillisPerDay));
}
// Returns the DateTime resulting from adding a fractional number of
// hours to the specified DateTime. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddHours(DateTime time, int hours)
{
return (Add(time, hours, MillisPerHour));
}
// Returns the DateTime resulting from adding a fractional number of
// minutes to the specified DateTime. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddMinutes(DateTime time, int minutes)
{
return (Add(time, minutes, MillisPerMinute));
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public abstract DateTime AddMonths(DateTime time, int months);
// Returns the DateTime resulting from adding a number of
// seconds to the specified DateTime. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddSeconds(DateTime time, int seconds)
{
return Add(time, seconds, MillisPerSecond);
}
// Returns the DateTime resulting from adding a number of
// weeks to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddWeeks(DateTime time, int weeks)
{
return (AddDays(time, weeks * 7));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public abstract DateTime AddYears(DateTime time, int years);
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public abstract int GetDayOfMonth(DateTime time);
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public abstract DayOfWeek GetDayOfWeek(DateTime time);
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public abstract int GetDayOfYear(DateTime time);
// Returns the number of days in the month given by the year and
// month arguments.
//
public virtual int GetDaysInMonth(int year, int month)
{
return (GetDaysInMonth(year, month, CurrentEra));
}
// Returns the number of days in the month given by the year and
// month arguments for the specified era.
//
public abstract int GetDaysInMonth(int year, int month, int era);
// Returns the number of days in the year given by the year argument for the current era.
//
public virtual int GetDaysInYear(int year)
{
return (GetDaysInYear(year, CurrentEra));
}
// Returns the number of days in the year given by the year argument for the current era.
//
public abstract int GetDaysInYear(int year, int era);
// Returns the era for the specified DateTime value.
public abstract int GetEra(DateTime time);
/*=================================Eras==========================
**Action: Get the list of era values.
**Returns: The int array of the era names supported in this calendar.
** null if era is not used.
**Arguments: None.
**Exceptions: None.
============================================================================*/
public abstract int[] Eras
{
get;
}
// Returns the hour part of the specified DateTime. The returned value is an
// integer between 0 and 23.
//
public virtual int GetHour(DateTime time)
{
return ((int)((time.Ticks / TicksPerHour) % 24));
}
// Returns the millisecond part of the specified DateTime. The returned value
// is an integer between 0 and 999.
//
public virtual double GetMilliseconds(DateTime time)
{
return (double)((time.Ticks / TicksPerMillisecond) % 1000);
}
// Returns the minute part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetMinute(DateTime time)
{
return ((int)((time.Ticks / TicksPerMinute) % 60));
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public abstract int GetMonth(DateTime time);
// Returns the number of months in the specified year in the current era.
public virtual int GetMonthsInYear(int year)
{
return (GetMonthsInYear(year, CurrentEra));
}
// Returns the number of months in the specified year and era.
public abstract int GetMonthsInYear(int year, int era);
// Returns the second part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetSecond(DateTime time)
{
return ((int)((time.Ticks / TicksPerSecond) % 60));
}
/*=================================GetFirstDayWeekOfYear==========================
**Action: Get the week of year using the FirstDay rule.
**Returns: the week of year.
**Arguments:
** time
** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday)
**Notes:
** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year.
** Assume f is the specifed firstDayOfWeek,
** and n is the day of week for January 1 of the specified year.
** Assign offset = n - f;
** Case 1: offset = 0
** E.g.
** f=1
** weekday 0 1 2 3 4 5 6 0 1
** date 1/1
** week# 1 2
** then week of year = (GetDayOfYear(time) - 1) / 7 + 1
**
** Case 2: offset < 0
** e.g.
** n=1 f=3
** weekday 0 1 2 3 4 5 6 0
** date 1/1
** week# 1 2
** This means that the first week actually starts 5 days before 1/1.
** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1
** Case 3: offset > 0
** e.g.
** f=0 n=2
** weekday 0 1 2 3 4 5 6 0 1 2
** date 1/1
** week# 1 2
** This means that the first week actually starts 2 days before 1/1.
** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1
============================================================================*/
internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek)
{
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
// Calculate the day of week for the first day of the year.
// dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays)
{
int dayForJan1;
int offset;
int day;
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
//
// Calculate the number of days between the first day of year (1/1) and the first day of the week.
// This value will be a positive value from 0 ~ 6. We call this value as "offset".
//
// If offset is 0, it means that the 1/1 is the start of the first week.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 12/31 1/1 1/2 1/3 1/4 1/5 1/6
// +--> First week starts here.
//
// If offset is 1, it means that the first day of the week is 1 day ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7
// +--> First week starts here.
//
// If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sat Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8
// +--> First week starts here.
// Day of week is 0-based.
// Get the day of week for 1/1. This can be derived from the day of week of the target day.
// Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset.
dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
// Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value.
offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
if (offset != 0 && offset >= fullDays)
{
//
// If the offset is greater than the value of fullDays, it means that
// the first week of the year starts on the week where Jan/1 falls on.
//
offset -= 7;
}
//
// Calculate the day of year for specified time by taking offset into account.
//
day = dayOfYear - offset;
if (day >= 0)
{
//
// If the day of year value is greater than zero, get the week of year.
//
return (day / 7 + 1);
}
//
// Otherwise, the specified time falls on the week of previous year.
// Call this method again by passing the last day of previous year.
//
// the last day of the previous year may "underflow" to no longer be a valid date time for
// this calendar if we just subtract so we need the subclass to provide us with
// that information
if (time <= MinSupportedDateTime.AddDays(dayOfYear))
{
return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays);
}
return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays));
}
private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek)
{
int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7;
// Calculate the offset (how many days from the start of the year to the start of the week)
int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7;
if (offset == 0 || offset >= minimumDaysInFirstWeek)
{
// First of year falls in the first week of the year
return 1;
}
int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7);
// starting from first day of the year, how many days do you have to go forward
// before getting to the first day of the week?
int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7;
int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek;
if (daysInInitialPartialWeek >= minimumDaysInFirstWeek)
{
// If the offset is greater than the minimum Days in the first week, it means that
// First of year is part of the first week of the year even though it is only a partial week
// add another week
day += 7;
}
return (day / 7 + 1);
}
// it would be nice to make this abstract but we can't since that would break previous implementations
protected virtual int DaysInYearBeforeMinSupportedYear
{
get
{
return 365;
}
}
// Returns the week of year for the specified DateTime. The returned value is an
// integer between 1 and 53.
//
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6)
{
throw new ArgumentOutOfRangeException(
nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range,
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
switch (rule)
{
case CalendarWeekRule.FirstDay:
return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
case CalendarWeekRule.FirstFullWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7));
case CalendarWeekRule.FirstFourDayWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4));
}
throw new ArgumentOutOfRangeException(
nameof(rule), SR.Format(SR.ArgumentOutOfRange_Range,
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public abstract int GetYear(DateTime time);
// Checks whether a given day in the current era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public virtual bool IsLeapDay(int year, int month, int day)
{
return (IsLeapDay(year, month, day, CurrentEra));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public abstract bool IsLeapDay(int year, int month, int day, int era);
// Checks whether a given month in the current era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public virtual bool IsLeapMonth(int year, int month)
{
return (IsLeapMonth(year, month, CurrentEra));
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public abstract bool IsLeapMonth(int year, int month, int era);
// Returns the leap month in a calendar year of the current era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public virtual int GetLeapMonth(int year)
{
return (GetLeapMonth(year, CurrentEra));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public virtual int GetLeapMonth(int year, int era)
{
if (!IsLeapYear(year, era))
return 0;
int monthsCount = GetMonthsInYear(year, era);
for (int month = 1; month <= monthsCount; month++)
{
if (IsLeapMonth(year, month, era))
return month;
}
return 0;
}
// Checks whether a given year in the current era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public virtual bool IsLeapYear(int year)
{
return (IsLeapYear(year, CurrentEra));
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public abstract bool IsLeapYear(int year, int era);
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era);
internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result)
{
result = DateTime.MinValue;
try
{
result = ToDateTime(year, month, day, hour, minute, second, millisecond, era);
return true;
}
catch (ArgumentException)
{
return false;
}
}
internal virtual bool IsValidYear(int year, int era)
{
return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime));
}
internal virtual bool IsValidMonth(int year, int month, int era)
{
return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era));
}
internal virtual bool IsValidDay(int year, int month, int day, int era)
{
return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era));
}
// Returns and assigns the maximum value to represent a two digit year. This
// value is the upper boundary of a 100 year range that allows a two digit year
// to be properly translated to a four digit year. For example, if 2029 is the
// upper boundary, then a two digit value of 30 should be interpreted as 1930
// while a two digit value of 29 should be interpreted as 2029. In this example
// , the 100 year range would be from 1930-2029. See ToFourDigitYear().
public virtual int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
twoDigitYearMax = value;
}
}
// Converts the year value to the appropriate century by using the
// TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029,
// then a two digit value of 30 will get converted to 1930 while a two digit
// value of 29 will get converted to 2029.
public virtual int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year);
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
// Return the tick count corresponding to the given hour, minute, second.
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
String.Format(
CultureInfo.InvariantCulture,
SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)));
}
return InternalGloablizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue)
{
// Call nativeGetTwoDigitYearMax
int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID);
if (twoDigitYearMax < 0)
{
twoDigitYearMax = defaultYearValue;
}
return (twoDigitYearMax);
}
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class ObjectScript : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
private bool mouseDown = false;
private Vector3 startMousePos;
private Vector3 startPos;
private bool restrictX;
private bool restrictY;
private float fakeX;
private float fakeY;
private float myWidth;
private float myHeight;
private RectTransform ParentRT;
public RectTransform MyRect;
private Vector3 player_pos;
private PlayerProperties playerProperties;
private GameObject buttonUtiliser;
private GameObject infoObjets;
public ObjectsType o_type;
[SerializeField]
private Rigidbody o_mushroom;
public bool is_usable = false;
[SerializeField]
private AudioSource m_pickSound;
private bool isUsed = false;
private InventoryManager inventoryManager;
private void Awake()
{
inventoryManager = InventoryManager.Instance.GetComponent<InventoryManager>();
}
void Start()
{
m_pickSound.Play();
ParentRT = (RectTransform)GameObject.Find ("InventoryHUD").transform;
myWidth = (MyRect.rect.width + 5) / 2;
myHeight = (MyRect.rect.height + 5) / 2;
playerProperties = GameObject.FindWithTag("Player").GetComponent<PlayerProperties>();
buttonUtiliser = GameObject.Find("Affichages/HUD/InventoryHUD/ButtonUtiliser");
infoObjets = GameObject.FindWithTag("InfoObjets");
}
void Update ()
{
if (InventoryManager.Instance.bag_open) {
DragNDrop ();
}
}
public void OnCollisionEnter2D(Collision2D collision){
if (collision.gameObject.name == "FallDetector") {
player_pos = GameObject.FindWithTag ("Player").transform.position;
InventoryManager.Instance.GetComponent<InventoryManager>().RemoveObjectOfType (o_type);
Rigidbody clone;
clone = Instantiate(o_mushroom,new Vector3(player_pos.x+20f*(Random.value-0.5f), player_pos.y+10f, player_pos.z+20f*(Random.value-0.5f)) ,Random.rotation) as Rigidbody;
Destroy (this.gameObject);
}
}
public void OnPointerDown(PointerEventData ped)
{
mouseDown = true;
startPos = transform.position;
startMousePos = Input.mousePosition;
}
public void OnPointerUp(PointerEventData ped)
{
mouseDown = false;
//InventoryManager.Instance.ChangePickUpButtonState(false);
HideInfo ();
}
private void DragNDrop(){
if (mouseDown) {
Vector3 currentPos = Input.mousePosition;
Vector3 diff = currentPos - startMousePos;
Vector3 pos = startPos + diff;
transform.position = pos;
if(transform.localPosition.x < 0 - ((ParentRT.rect.width / 2) - myWidth) || transform.localPosition.x > ((ParentRT.rect.width / 2) - myWidth))
restrictX = true;
else
restrictX = false;
if(transform.localPosition.y < 0 - ((ParentRT.rect.height / 2) - myHeight) || transform.localPosition.y > ((ParentRT.rect.height / 2) - myHeight))
restrictY = true;
else
restrictY = false;
if(restrictX)
{
if(transform.localPosition.x < 0)
fakeX = 0 - (ParentRT.rect.width / 2) + myWidth;
else
fakeX = (ParentRT.rect.width / 2) - myWidth;
Vector3 xpos = new Vector3 (fakeX, transform.localPosition.y, 0.0f);
transform.localPosition = xpos;
}
if(restrictY)
{
if(transform.localPosition.y < 0)
fakeY = 0 - (ParentRT.rect.height / 2) + myHeight;
else
fakeY = (ParentRT.rect.height / 2) - myHeight;
Vector3 ypos = new Vector3 (transform.localPosition.x, fakeY, 0.0f);
transform.localPosition = ypos;
}
GetInputs ();
if (is_usable && !isUsed) {
buttonUtiliser.SetActive(true);
ShowInfo (o_type);
}
if(!is_usable)
ShowInfo (o_type);
}
}
private void GetInputs(){
if (Input.GetKeyDown (KeyCode.E) && is_usable) {
UseObject (o_type);
}
}
//Ajouter la verification de si on ets humain pour arc et torche !!!
private void UseObject(ObjectsType o_type){
switch(o_type) {
case ObjectsType.Bow:
if (!InventoryManager.Instance.isTorchEquiped) {
InventoryManager.Instance.isBowEquiped = true;
buttonUtiliser.SetActive(false);
HideInfo ();
inventoryManager.RemoveObjectOfType (o_type);
isUsed = true;
GameObject player = GameObject.FindWithTag("Player");
player.GetComponent<ActionsNew>().EquipWeapon();
GameObject.Find ("SportyGirl/RigAss/RigSpine1/RigSpine2/RigSpine3/RigArmLeftCollarbone/RigArmLeft1/RigArmLeft2/RigArmLeft3/Bow3D").SetActive (true);
Destroy(this.gameObject);
}
break;
case ObjectsType.Fire:
break;
case ObjectsType.Meat:
playerProperties.Eat (30);
buttonUtiliser.SetActive (false);
HideInfo ();
inventoryManager.RemoveObjectOfType (o_type);
isUsed = true;
Destroy(this.gameObject);
break;
case ObjectsType.Mushroom:
playerProperties.Eat(10);
buttonUtiliser.SetActive(false);
HideInfo ();
inventoryManager.RemoveObjectOfType (o_type);
isUsed = true;
Destroy(this.gameObject);
break;
case ObjectsType.Torch:
if (!InventoryManager.Instance.isBowEquiped) {
InventoryManager.Instance.isTorchEquiped = true;
buttonUtiliser.SetActive(false);
HideInfo ();
inventoryManager.RemoveObjectOfType (o_type);
isUsed = true;
GameObject player = GameObject.FindWithTag("Player");
player.GetComponent<ActionsNew>().EquipWeapon();
GameObject.Find ("SportyGirl/RigAss/RigSpine1/RigSpine2/RigSpine3/RigArmRightCollarbone/RigArmRight1/RigArmRight2/RigArmRight3/Torch3D").SetActive (true);
Destroy(this.gameObject);
}
break;
default:
break;
}
}
private void ShowInfo(ObjectsType o_type){
switch (o_type) {
case ObjectsType.Arrow:
infoObjets.transform.Find("Arrow").gameObject.SetActive(true);
break;
case ObjectsType.Mushroom:
infoObjets.transform.Find("Mushroom").gameObject.SetActive(true);
break;
case ObjectsType.Bow:
infoObjets.transform.Find("Bow").gameObject.SetActive(true);
break;
case ObjectsType.Meat:
infoObjets.transform.Find("Meat").gameObject.SetActive(true);
break;
case ObjectsType.Plank:
infoObjets.transform.Find("Plank").gameObject.SetActive(true);
break;
case ObjectsType.Sail:
infoObjets.transform.Find("Sail").gameObject.SetActive(true);
break;
case ObjectsType.Fire:
infoObjets.transform.Find("Bonfire").gameObject.SetActive(true);
break;
case ObjectsType.Raft:
infoObjets.transform.Find("Raft").gameObject.SetActive(true);
break;
case ObjectsType.Wood:
infoObjets.transform.Find("Wood").gameObject.SetActive(true);
break;
case ObjectsType.Rope:
infoObjets.transform.Find("Rope").gameObject.SetActive(true);
break;
case ObjectsType.Flint:
infoObjets.transform.Find("Flint").gameObject.SetActive(true);
break;
case ObjectsType.Torch:
infoObjets.transform.Find("Torch").gameObject.SetActive(true);
break;
}
}
private void HideInfo(){
for (int i = 0; i < infoObjets.transform.childCount; i++)
{
infoObjets.transform.GetChild(i).gameObject.SetActive(false);
}
}
}
| |
/*
* Copyright 2014, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using UnityEngine;
using DeJson;
using System;
using System.Collections.Generic;
namespace HappyFunTimes {
public abstract class NetPlayer
{
public delegate void UntypedCmdEventHandler(Dictionary<string, object> data);
public delegate void TypedCmdEventHandler<T>(T eventArgs);
private class CmdConverter<T>
{
public CmdConverter(TypedCmdEventHandler<T> handler) {
m_handler = handler;
}
public void Callback(Deserializer deserializer, GameServer server, object dict) {
T data = deserializer.Deserialize<T>(dict);
server.QueueEvent(() => {
m_handler((T)data);
});
}
TypedCmdEventHandler<T> m_handler;
}
private class UntypedCmdConverter {
public UntypedCmdConverter(UntypedCmdEventHandler handler) {
m_handler = handler;
}
public void Callback(Deserializer deserializer, GameServer server, object dict) {
Dictionary<string, object> data = (Dictionary<string, object>)dict;
server.QueueEvent(() => {
m_handler(data);
});
}
UntypedCmdEventHandler m_handler;
}
/// <param name="server">This needs the server because messages need to be queued as they need to be delivered on anther thread</param>.
private delegate void CmdEventHandler(Deserializer deserializer, GameServer server, object dict);
public NetPlayer(GameServer server, string name)
{
m_server = server;
m_connected = true;
m_handlers = new Dictionary<string, CmdEventHandler>();
m_internalHandlers = new Dictionary<string, CmdEventHandler>();
m_deserializer = new Deserializer();
m_log = new HFTLog("NetPlayer[" + name + "]");
AddHandlers();
}
/// <summary>
/// Lets you register a command to be called when message comes in from this player.
///
/// The callback you register must have a CmdName attribute. That attibute will determine
/// which event the callback gets dispatched for.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// [CmdName("color")]
/// private class MessageColor : MessageCmdData {
/// public string color = ""; // in CSS format rgb(r,g,b)
/// };
///
/// ...
/// netPlayer.RegisterCmdHandler<MessageColor>(OnColor);
/// ...
/// void OnColor(MessageColor) {
/// Debug.Log("received msg with color: " + color);
/// }
/// ]]>
/// </code>
/// </example>
/// <param name="callback">Typed callback</param>
public void RegisterCmdHandler<T>(TypedCmdEventHandler<T> callback) where T : MessageCmdData {
string name = HFTMessageCmdDataNameDB.GetCmdName(typeof(T));
if (name == null) {
throw new System.InvalidOperationException("no CmdNameAttribute on " + typeof(T).Name);
}
RegisterCmdHandler<T>(name, callback);
}
/// <summary>
/// Lets you register a command to be called when a message comes in from this player.
/// </summary>
/// <example>
/// <code>
/// private class MessageColor {
/// public string color = ""; // in CSS format rgb(r,g,b)
/// };
///
/// ...
/// newPlayer.RegisterCmdHandler("color", OnColor);
/// ...
/// void OnColor(MessageColor) {
/// Debug.Log("received msg with color: " + color);
/// }
/// </code>
/// </example>
/// <param name="name">command to call callback for</param>
/// <param name="callback">Typed callback</param>
public void RegisterCmdHandler<T>(string name, TypedCmdEventHandler<T> callback) {
CmdConverter<T> converter = new CmdConverter<T>(callback);
m_handlers[name] = converter.Callback;
}
private void RegisterInternalCmdHandler<T>(string name, TypedCmdEventHandler<T> callback) {
CmdConverter<T> converter = new CmdConverter<T>(callback);
m_internalHandlers[name] = converter.Callback;
}
/// <summary>
/// Lets you register a command to be called when a message is sent from this player.
///
/// This the most low-level basic version of RegisterCmdHandler. The function registered
/// will be called with a Dictionary<string, object> with whatever data is passed in.
/// You can either pull the data out directly OR you can call Deserializer.Deserilize
/// with a type and have the data extracted for you.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// ...
/// netPlayer.RegisterCmdHandler("color", OnColor);
/// ...
/// void OnColor(Dictionary<string, object> data) {
/// Debug.Log("received msg with color: " + data["color"]);
/// }
/// ]]>
/// </code>
/// or
/// <code>
/// <![CDATA[
/// private class MessageColor {
/// public string color = ""; // in CSS format rgb(r,g,b)
/// };
/// ...
/// gameServer.RegisterCmdHandler("color", OnColor);
/// ...
/// void OnColor(Dictionary<string, object> data) {
/// Deserializer d = new Deserializer();
/// MessageColor msg = d.Deserialize<MessageColor>(data);
/// Debug.Log("received msg with color: " + msg.color);
/// }
/// ]]>
/// </code>
/// </example>
/// <param name="name">command to call callback for</param>
/// <param name="callback">Typed callback</param>
public void RegisterCmdHandler(string name, UntypedCmdEventHandler callback) {
UntypedCmdConverter converter = new UntypedCmdConverter(callback);
m_handlers[name] = converter.Callback;
}
/// <summary>
/// Unregisters the command handler for a given MessageCmdData. Gets the Command name from the MessgeCmdData's
/// CmdData attribute.
/// </summary>
/// <returns>true if there was a command handler, false if not</returns>
public bool UnregisterCmdHandler<T>() where T : MessageCmdData {
string name = HFTMessageCmdDataNameDB.GetCmdName(typeof(T));
return UnregisterCmdHandler(name);
}
/// <summary>
/// Unregisters the command handler for the specified command
/// </summary>
/// <param name="name"></param>
/// <returns>true if there was a command handler, false if not</returns>
public bool UnregisterCmdHandler(string name) {
return m_handlers.Remove(name);
}
/// <summary>
/// Removes all handlers
/// </summary>
public void RemoveAllHandlers() {
OnDisconnect = null;
m_handlers.Clear();
}
void AddHandlers() {
RegisterInternalCmdHandler<HFTMessageLog>("_hft_log_", HandleLogMsg);
}
/// <summary>
/// Sends a message to this player's phone
/// </summary>
/// <param name="data">The message. It must be derived from MessageCmdData and must have a
/// CmdName attribute</param>
/// <example>
/// <code>
/// </code>
/// </example>
public abstract void SendCmd(MessageCmdData data);
public abstract void SendCmd(string cmd, object data);
public void SendCmd(string cmd) {
SendCmd(cmd, null);
}
public virtual void Disconnect()
{
m_connected = false;
EventHandler<EventArgs> handler = OnDisconnect;
if (handler != null) {
handler(this, new EventArgs());
}
RemoveAllHandlers();
}
public abstract void SwitchGame(string gameId, object data);
public void SendUnparsedEvent(object data)
{
if (!m_connected)
{
return;
}
// This is kind of round about. The issue is we queue message
// if there are no handlers as that means no one has had time
// to register any and those message will be lost.
//
// That's great but we can also call RemoveAllHanders. PlayerConnector
// does this. Players that are waiting have all messages disconnected.
// That means if they are waiting for 2-3 mins, with a poorly designed
// controller there could be tons of messages queued up.
//
// So, only allow queuing messages once. After that they're never
// queued.
if (m_handlers.Count > 0) {
m_haveHandlers = true;
}
// If there are no handlers registered then the object using this NetPlayer
// has not been instantiated yet. The issue is the GameSever makes a NetPlayer.
// It then has to queue an event to start that player so that it can be started
// on another thread. But, before that event has triggered other messages might
// come through. So, if there are no handlers then we add an event to run the
// command later. It's the same queue that will birth the object that needs the
// message.
if (!m_haveHandlers) {
m_server.QueueEvent(() => {
SendUnparsedEvent(data);
});
return;
}
try {
HFTMessageCmd cmd = m_deserializer.Deserialize<HFTMessageCmd>(data);
CmdEventHandler handler;
if (!m_handlers.TryGetValue(cmd.cmd, out handler)) {
if (!m_internalHandlers.TryGetValue(cmd.cmd, out handler)) {
m_log.Error("unhandled NetPlayer cmd: " + cmd.cmd);
return;
}
}
handler(m_deserializer, m_server, cmd.data);
} catch (Exception ex) {
m_log.Error(ex);
}
}
private string errorStr = @"error";
void HandleLogMsg(HFTMessageLog data) {
if (errorStr.Equals(data.type, StringComparison.Ordinal)) {
m_log.Error(data.msg);
} else {
m_log.Tell(data.msg);
}
}
public abstract string GetSessionId();
public string Name {
set {
m_log.prefix = "NetPlayer[" + value + "]";
}
}
public event EventHandler<EventArgs> OnDisconnect;
// We need to separate m_internalHandlers because we check if
// m_handlers.count is 0. If it is we assume no one has had
// a chance to add any handlers and we queue the messages
// instead of processing them. If we registered internal handlers
// to m_handlers we'd couldn't check that.
private Dictionary<string, CmdEventHandler> m_handlers; // handlers by command name
private Dictionary<string, CmdEventHandler> m_internalHandlers; // handlers by command name
private Deserializer m_deserializer;
private bool m_connected;
private bool m_haveHandlers = false;
private GameServer m_server;
private HFTLog m_log;
protected Deserializer Deserializer {
get {
return m_deserializer;
}
}
protected bool Connected {
get {
return m_connected;
}
}
protected GameServer Server {
get {
return m_server;
}
}
}
}
| |
/*-------------------------------------------------------------------------
ParserGen.cs -- Generation of the Recursive Descent Parser
Compiler Generator Coco/R,
Copyright (c) 1990, 2004 Hanspeter Moessenboeck, University of Linz
extended by M. Loeberbauer & A. Woess, Univ. of Linz
with improvements by Pat Terry, Rhodes University
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As an exception, it is allowed to write an extension of Coco/R that is
used as a plugin in non-free software.
If not otherwise stated, any source code generated by Coco/R (other than
Coco/R itself) does not fall under the GNU General Public License.
-------------------------------------------------------------------------*/
using System;
using System.IO;
using System.Collections;
using System.Text;
namespace at.jku.ssw.Coco {
public class ParserGen {
const int maxTerm = 3; // sets of size < maxTerm are enumerated
const char CR = '\r';
const char LF = '\n';
const int EOF = -1;
const int tErr = 0; // error codes
const int altErr = 1;
const int syncErr = 2;
public Position usingPos; // "using" definitions from the attributed grammar
int errorNr; // highest parser error number
Symbol curSy; // symbol whose production is currently generated
FileStream fram; // parser frame file
StreamWriter gen; // generated parser source file
StringWriter err; // generated parser error messages
ArrayList symSet = new ArrayList();
Tab tab; // other Coco objects
TextWriter trace;
Errors errors;
Buffer buffer;
void Indent (int n) {
for (int i = 1; i <= n; i++) gen.Write('\t');
}
bool Overlaps(BitArray s1, BitArray s2) {
int len = s1.Count;
for (int i = 0; i < len; ++i) {
if (s1[i] && s2[i]) {
return true;
}
}
return false;
}
// use a switch if more than 5 alternatives and none starts with a resolver
bool UseSwitch (Node p) {
BitArray s1, s2;
if (p.typ != Node.alt) return false;
int nAlts = 0;
s1 = new BitArray(tab.terminals.Count);
while (p != null) {
s2 = tab.Expected0(p.sub, curSy);
// must not optimize with switch statement, if there are ll1 warnings
if (Overlaps(s1, s2)) { return false; }
s1.Or(s2);
++nAlts;
// must not optimize with switch-statement, if alt uses a resolver expression
if (p.sub.typ == Node.rslv) return false;
p = p.down;
}
return nAlts > 5;
}
void CopyFramePart (string stop) {
char startCh = stop[0];
int endOfStopString = stop.Length-1;
int ch = fram.ReadByte();
while (ch != EOF)
if (ch == startCh) {
int i = 0;
do {
if (i == endOfStopString) return; // stop[0..i] found
ch = fram.ReadByte(); i++;
} while (ch == stop[i]);
// stop[0..i-1] found; continue with last read character
gen.Write(stop.Substring(0, i));
} else {
gen.Write((char)ch); ch = fram.ReadByte();
}
throw new FatalError("Incomplete or corrupt parser frame file");
}
void CopySourcePart (Position pos, int indent) {
// Copy text described by pos from atg to gen
int ch, nChars, i;
if (pos != null) {
buffer.Pos = pos.beg; ch = buffer.Read(); nChars = pos.len - 1;
Indent(indent);
while (nChars >= 0) {
while (ch == CR || ch == LF) { // eol is either CR or CRLF or LF
gen.WriteLine(); Indent(indent);
if (ch == CR) { ch = buffer.Read(); nChars--; } // skip CR
if (ch == LF) { ch = buffer.Read(); nChars--; } // skip LF
for (i = 1; i <= pos.col && (ch == ' ' || ch == '\t'); i++) {
// skip blanks at beginning of line
ch = buffer.Read(); nChars--;
}
if (i <= pos.col) pos.col = i - 1; // heading TABs => not enough blanks
if (nChars < 0) goto done;
}
gen.Write((char)ch);
ch = buffer.Read(); nChars--;
}
done:
if (indent > 0) gen.WriteLine();
}
}
void GenErrorMsg (int errTyp, Symbol sym) {
errorNr++;
err.Write("\t\t\tcase " + errorNr + ": s = \"");
switch (errTyp) {
case tErr:
if (sym.name[0] == '"') err.Write(tab.Escape(sym.name) + " expected");
else err.Write(sym.name + " expected");
break;
case altErr: err.Write("invalid " + sym.name); break;
case syncErr: err.Write("this symbol not expected in " + sym.name); break;
}
err.WriteLine("\"; break;");
}
int NewCondSet (BitArray s) {
for (int i = 1; i < symSet.Count; i++) // skip symSet[0] (reserved for union of SYNC sets)
if (Sets.Equals(s, (BitArray)symSet[i])) return i;
symSet.Add(s.Clone());
return symSet.Count - 1;
}
void GenCond (BitArray s, Node p) {
if (p.typ == Node.rslv) CopySourcePart(p.pos, 0);
else {
int n = Sets.Elements(s);
if (n == 0) gen.Write("false"); // should never happen
else if (n <= maxTerm)
foreach (Symbol sym in tab.terminals) {
if (s[sym.n]) {
gen.Write("la.kind == {0}", sym.n);
--n;
if (n > 0) gen.Write(" || ");
}
}
else
gen.Write("StartOf({0})", NewCondSet(s));
/*
if (p.typ == Node.alt) {
// for { ... | IF ... | ... } or [ ... | IF ... | ... ]
// check resolvers in addition to terminal start symbols of alternatives
Node q = p;
while (q != null) {
if (q.sub.typ == Node.rslv) {
gen.Write(" || ");
CopySourcePart(q.sub.pos, 0);
}
q = q.down;
}
}
*/
}
}
void PutCaseLabels (BitArray s) {
foreach (Symbol sym in tab.terminals)
if (s[sym.n]) gen.Write("case {0}: ", sym.n);
}
void GenCode (Node p, int indent, BitArray isChecked) {
Node p2;
BitArray s1, s2;
while (p != null) {
switch (p.typ) {
case Node.nt: {
Indent(indent);
gen.Write(p.sym.name + "(");
CopySourcePart(p.pos, 0);
gen.WriteLine(");");
break;
}
case Node.t: {
Indent(indent);
if (isChecked[p.sym.n]) gen.WriteLine("Get();");
else gen.WriteLine("Expect({0});", p.sym.n);
break;
}
case Node.wt: {
Indent(indent);
s1 = tab.Expected(p.next, curSy);
s1.Or(tab.allSyncSets);
gen.WriteLine("ExpectWeak({0}, {1});", p.sym.n, NewCondSet(s1));
break;
}
case Node.any: {
Indent(indent);
gen.WriteLine("Get();");
break;
}
case Node.eps: break; // nothing
case Node.rslv: break; // nothing
case Node.sem: {
CopySourcePart(p.pos, indent);
break;
}
case Node.sync: {
Indent(indent);
GenErrorMsg(syncErr, curSy);
s1 = (BitArray)p.set.Clone();
gen.Write("while (!("); GenCond(s1, p); gen.Write(")) {");
gen.Write("SynErr({0}); Get();", errorNr); gen.WriteLine("}");
break;
}
case Node.alt: {
s1 = tab.First(p);
bool equal = Sets.Equals(s1, isChecked);
bool useSwitch = UseSwitch(p);
if (useSwitch) { Indent(indent); gen.WriteLine("switch (la.kind) {"); }
p2 = p;
while (p2 != null) {
s1 = tab.Expected(p2.sub, curSy);
Indent(indent);
if (useSwitch) {
PutCaseLabels(s1); gen.WriteLine("{");
} else if (p2 == p) {
gen.Write("if ("); GenCond(s1, p2.sub); gen.WriteLine(") {");
} else if (p2.down == null && equal) { gen.WriteLine("} else {");
} else {
gen.Write("} else if ("); GenCond(s1, p2.sub); gen.WriteLine(") {");
}
s1.Or(isChecked);
//if (p2.sub.typ == Node.rslv) GenCode(p2.sub.next, indent + 1, s1);
//else GenCode(p2.sub, indent + 1, s1);
GenCode(p2.sub, indent + 1, s1);
if (useSwitch) {
Indent(indent); gen.WriteLine("\tbreak;");
Indent(indent); gen.WriteLine("}");
}
p2 = p2.down;
}
Indent(indent);
if (equal) {
gen.WriteLine("}");
} else {
GenErrorMsg(altErr, curSy);
if (useSwitch) {
gen.WriteLine("default: SynErr({0}); break;", errorNr);
Indent(indent); gen.WriteLine("}");
} else {
gen.Write("} "); gen.WriteLine("else SynErr({0});", errorNr);
}
}
break;
}
case Node.iter: {
Indent(indent);
p2 = p.sub;
gen.Write("while (");
if (p2.typ == Node.wt) {
s1 = tab.Expected(p2.next, curSy);
s2 = tab.Expected(p.next, curSy);
gen.Write("WeakSeparator({0},{1},{2}) ", p2.sym.n, NewCondSet(s1), NewCondSet(s2));
s1 = new BitArray(tab.terminals.Count); // for inner structure
if (p2.up || p2.next == null) p2 = null; else p2 = p2.next;
} else {
s1 = tab.First(p2);
GenCond(s1, p2);
}
gen.WriteLine(") {");
GenCode(p2, indent + 1, s1);
Indent(indent); gen.WriteLine("}");
break;
}
case Node.opt:
//if (p.sub.typ == Node.rslv) s1 = tab.First(p.sub.next);
//else s1 = tab.First(p.sub);
s1 = tab.First(p.sub);
Indent(indent);
gen.Write("if ("); GenCond(s1, p.sub); gen.WriteLine(") {");
//if (p.sub.typ == Node.rslv) GenCode(p.sub.next, indent + 1, s1);
//else GenCode(p.sub, indent + 1, s1);
GenCode(p.sub, indent + 1, s1);
Indent(indent); gen.WriteLine("}");
break;
}
if (p.typ != Node.eps && p.typ != Node.sem && p.typ != Node.sync)
isChecked.SetAll(false); // = new BitArray(tab.terminals.Count);
if (p.up) break;
p = p.next;
}
}
void GenTokens() {
foreach (Symbol sym in tab.terminals) {
if (Char.IsLetter(sym.name[0]))
gen.WriteLine("\tpublic const int _{0} = {1};", sym.name, sym.n);
}
}
void GenPragmas() {
foreach (Symbol sym in tab.pragmas) {
gen.WriteLine("\tpublic const int _{0} = {1};", sym.name, sym.n);
}
}
void GenCodePragmas() {
foreach (Symbol sym in tab.pragmas) {
gen.WriteLine("\t\t\t\tif (la.kind == {0}) {{", sym.n);
CopySourcePart(sym.semPos, 4);
gen.WriteLine("\t\t\t\t}");
}
}
void GenProductions() {
foreach (Symbol sym in tab.nonterminals) {
curSy = sym;
gen.Write("\tvoid {0}(", sym.name);
CopySourcePart(sym.attrPos, 0);
gen.WriteLine(") {");
CopySourcePart(sym.semPos, 2);
GenCode(sym.graph, 2, new BitArray(tab.terminals.Count));
gen.WriteLine("\t}"); gen.WriteLine();
}
}
void InitSets() {
for (int i = 0; i < symSet.Count; i++) {
BitArray s = (BitArray)symSet[i];
gen.Write("\t\t{");
int j = 0;
foreach (Symbol sym in tab.terminals) {
if (s[sym.n]) gen.Write("T,"); else gen.Write("x,");
++j;
if (j%4 == 0) gen.Write(" ");
}
if (i == symSet.Count-1) gen.WriteLine("x}"); else gen.WriteLine("x},");
}
}
void OpenGen(bool backUp) { /* pdt */
try {
string fn = Path.Combine(tab.outDir, "Parser.cs"); /* pdt */
if (File.Exists(fn) && backUp) File.Copy(fn, fn + ".old", true);
gen = new StreamWriter(new FileStream(fn, FileMode.Create)); /* pdt */
} catch (IOException) {
throw new FatalError("Cannot generate parser file");
}
}
public void WriteParser () {
int oldPos = buffer.Pos; // Pos is modified by CopySourcePart
symSet.Add(tab.allSyncSets);
string fr = Path.Combine(tab.srcDir, "Parser.frame");
if (!File.Exists(fr)) {
if (tab.frameDir != null) fr = Path.Combine(tab.frameDir.Trim(), "Parser.frame");
if (!File.Exists(fr)) throw new FatalError("Cannot find Parser.frame");
}
try {
fram = new FileStream(fr, FileMode.Open, FileAccess.Read, FileShare.Read);
} catch (IOException) {
throw new FatalError("Cannot open Parser.frame.");
}
OpenGen(true); /* pdt */
err = new StringWriter();
foreach (Symbol sym in tab.terminals) GenErrorMsg(tErr, sym);
CopyFramePart("-->begin");
if (!tab.srcName.ToLower().EndsWith("coco.atg")) {
gen.Close(); OpenGen(false); /* pdt */
}
if (usingPos != null) {CopySourcePart(usingPos, 0); gen.WriteLine();}
CopyFramePart("-->namespace");
/* AW open namespace, if it exists */
if (tab.nsName != null && tab.nsName.Length > 0) {
gen.WriteLine("namespace {0} {{", tab.nsName);
gen.WriteLine();
}
CopyFramePart("-->constants");
GenTokens(); /* ML 2002/09/07 write the token kinds */
gen.WriteLine("\tpublic const int maxT = {0};", tab.terminals.Count-1);
GenPragmas(); /* ML 2005/09/23 write the pragma kinds */
CopyFramePart("-->declarations"); CopySourcePart(tab.semDeclPos, 0);
CopyFramePart("-->pragmas"); GenCodePragmas();
CopyFramePart("-->productions"); GenProductions();
CopyFramePart("-->parseRoot"); gen.WriteLine("\t\t{0}();", tab.gramSy.name);
CopyFramePart("-->initialization"); InitSets();
CopyFramePart("-->errors"); gen.Write(err.ToString());
CopyFramePart("$$$");
/* AW 2002-12-20 close namespace, if it exists */
if (tab.nsName != null && tab.nsName.Length > 0) gen.Write("}");
gen.Close();
buffer.Pos = oldPos;
}
public void WriteStatistics () {
trace.WriteLine();
trace.WriteLine("{0} terminals", tab.terminals.Count);
trace.WriteLine("{0} symbols", tab.terminals.Count + tab.pragmas.Count +
tab.nonterminals.Count);
trace.WriteLine("{0} nodes", tab.nodes.Count);
trace.WriteLine("{0} sets", symSet.Count);
}
public ParserGen (Parser parser) {
tab = parser.tab;
errors = parser.errors;
trace = parser.trace;
buffer = parser.scanner.buffer;
errorNr = -1;
usingPos = null;
}
} // end ParserGen
} // end namespace
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass()]
public partial class Scroller : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Scroller()
{
InitJNI();
}
protected Scroller(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getDuration11875;
public virtual int getDuration()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.Scroller._getDuration11875);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._getDuration11875);
}
internal static global::MonoJavaBridge.MethodId _isFinished11876;
public virtual bool isFinished()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Scroller._isFinished11876);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._isFinished11876);
}
internal static global::MonoJavaBridge.MethodId _forceFinished11877;
public virtual void forceFinished(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.Scroller._forceFinished11877, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._forceFinished11877, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getCurrX11878;
public virtual int getCurrX()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.Scroller._getCurrX11878);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._getCurrX11878);
}
internal static global::MonoJavaBridge.MethodId _getCurrY11879;
public virtual int getCurrY()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.Scroller._getCurrY11879);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._getCurrY11879);
}
internal static global::MonoJavaBridge.MethodId _getStartX11880;
public virtual int getStartX()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.Scroller._getStartX11880);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._getStartX11880);
}
internal static global::MonoJavaBridge.MethodId _getStartY11881;
public virtual int getStartY()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.Scroller._getStartY11881);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._getStartY11881);
}
internal static global::MonoJavaBridge.MethodId _getFinalX11882;
public virtual int getFinalX()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.Scroller._getFinalX11882);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._getFinalX11882);
}
internal static global::MonoJavaBridge.MethodId _getFinalY11883;
public virtual int getFinalY()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.Scroller._getFinalY11883);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._getFinalY11883);
}
internal static global::MonoJavaBridge.MethodId _computeScrollOffset11884;
public virtual bool computeScrollOffset()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.Scroller._computeScrollOffset11884);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._computeScrollOffset11884);
}
internal static global::MonoJavaBridge.MethodId _startScroll11885;
public virtual void startScroll(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.Scroller._startScroll11885, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._startScroll11885, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _startScroll11886;
public virtual void startScroll(int arg0, int arg1, int arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.Scroller._startScroll11886, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._startScroll11886, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _fling11887;
public virtual void fling(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.Scroller._fling11887, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._fling11887, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7));
}
internal static global::MonoJavaBridge.MethodId _abortAnimation11888;
public virtual void abortAnimation()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.Scroller._abortAnimation11888);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._abortAnimation11888);
}
internal static global::MonoJavaBridge.MethodId _extendDuration11889;
public virtual void extendDuration(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.Scroller._extendDuration11889, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._extendDuration11889, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _timePassed11890;
public virtual int timePassed()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.Scroller._timePassed11890);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._timePassed11890);
}
internal static global::MonoJavaBridge.MethodId _setFinalX11891;
public virtual void setFinalX(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.Scroller._setFinalX11891, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._setFinalX11891, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setFinalY11892;
public virtual void setFinalY(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.Scroller._setFinalY11892, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.Scroller.staticClass, global::android.widget.Scroller._setFinalY11892, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _Scroller11893;
public Scroller(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Scroller.staticClass, global::android.widget.Scroller._Scroller11893, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Scroller11894;
public Scroller(android.content.Context arg0, android.view.animation.Interpolator arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.Scroller.staticClass, global::android.widget.Scroller._Scroller11894, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.Scroller.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/Scroller"));
global::android.widget.Scroller._getDuration11875 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "getDuration", "()I");
global::android.widget.Scroller._isFinished11876 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "isFinished", "()Z");
global::android.widget.Scroller._forceFinished11877 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "forceFinished", "(Z)V");
global::android.widget.Scroller._getCurrX11878 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "getCurrX", "()I");
global::android.widget.Scroller._getCurrY11879 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "getCurrY", "()I");
global::android.widget.Scroller._getStartX11880 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "getStartX", "()I");
global::android.widget.Scroller._getStartY11881 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "getStartY", "()I");
global::android.widget.Scroller._getFinalX11882 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "getFinalX", "()I");
global::android.widget.Scroller._getFinalY11883 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "getFinalY", "()I");
global::android.widget.Scroller._computeScrollOffset11884 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "computeScrollOffset", "()Z");
global::android.widget.Scroller._startScroll11885 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "startScroll", "(IIII)V");
global::android.widget.Scroller._startScroll11886 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "startScroll", "(IIIII)V");
global::android.widget.Scroller._fling11887 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "fling", "(IIIIIIII)V");
global::android.widget.Scroller._abortAnimation11888 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "abortAnimation", "()V");
global::android.widget.Scroller._extendDuration11889 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "extendDuration", "(I)V");
global::android.widget.Scroller._timePassed11890 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "timePassed", "()I");
global::android.widget.Scroller._setFinalX11891 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "setFinalX", "(I)V");
global::android.widget.Scroller._setFinalY11892 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "setFinalY", "(I)V");
global::android.widget.Scroller._Scroller11893 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "<init>", "(Landroid/content/Context;)V");
global::android.widget.Scroller._Scroller11894 = @__env.GetMethodIDNoThrow(global::android.widget.Scroller.staticClass, "<init>", "(Landroid/content/Context;Landroid/view/animation/Interpolator;)V");
}
}
}
| |
using System;
using System.IO;
using NUnit.Framework;
using Raksha.Crypto.Modes;
using Raksha.Crypto.Modes.Gcm;
using Raksha.Crypto.Utilities;
using Raksha.Security;
using Raksha.Utilities;
using Raksha.Utilities.Encoders;
namespace Raksha.Tests.Crypto
{
[TestFixture]
public class GcmReorderTest
{
private static readonly byte[] H;
private static readonly SecureRandom random = new SecureRandom();
private static readonly IGcmMultiplier mul = new Tables64kGcmMultiplier();
private static readonly IGcmExponentiator exp = new Tables1kGcmExponentiator();
private static readonly byte[] Empty = new byte[0];
static GcmReorderTest()
{
H = new byte[16];
random.NextBytes(H);
mul.Init(Arrays.Clone(H));
exp.Init(Arrays.Clone(H));
}
[Test]
public void TestCombine()
{
for (int count = 0; count < 10; ++count)
{
byte[] A = randomBytes(1000);
byte[] C = randomBytes(1000);
byte[] ghashA_ = GHASH(A, Empty);
byte[] ghash_C = GHASH(Empty, C);
byte[] ghashAC = GHASH(A, C);
byte[] ghashCombine = combine_GHASH(ghashA_, (long)A.Length * 8, ghash_C, (long)C.Length * 8);
Assert.IsTrue(Arrays.AreEqual(ghashAC, ghashCombine));
}
}
[Test]
public void TestConcatAuth()
{
for (int count = 0; count < 10; ++count)
{
byte[] P = randomBlocks(100);
byte[] A = randomBytes(1000);
byte[] PA = concatArrays(P, A);
byte[] ghashP_ = GHASH(P, Empty);
byte[] ghashA_ = GHASH(A, Empty);
byte[] ghashPA_val = GHASH(PA, Empty);
byte[] ghashConcat = concatAuth_GHASH(ghashP_, (long)P.Length * 8, ghashA_, (long)A.Length * 8);
Assert.IsTrue(Arrays.AreEqual(ghashPA_val, ghashConcat));
}
}
[Test]
public void TestConcatCrypt()
{
for (int count = 0; count < 10; ++count)
{
byte[] P = randomBlocks(100);
byte[] A = randomBytes(1000);
byte[] PA = concatArrays(P, A);
byte[] ghash_P = GHASH(Empty, P);
byte[] ghash_A = GHASH(Empty, A);
byte[] ghash_PA = GHASH(Empty, PA);
byte[] ghashConcat = concatCrypt_GHASH(ghash_P, (long)P.Length * 8, ghash_A, (long)A.Length * 8);
Assert.IsTrue(Arrays.AreEqual(ghash_PA, ghashConcat));
}
}
[Test]
public void TestExp()
{
{
byte[] buf1 = new byte[16];
buf1[0] = 0x80;
byte[] buf2 = new byte[16];
for (int pow = 0; pow != 100; ++pow)
{
exp.ExponentiateX(pow, buf2);
Assert.IsTrue(Arrays.AreEqual(buf1, buf2));
mul.MultiplyH(buf1);
}
}
long[] testPow = new long[]{ 10, 1, 8, 17, 24, 13, 2, 13, 2, 3 };
byte[][] testData = new byte[][]{
Hex.Decode("9185848a877bd87ba071e281f476e8e7"),
Hex.Decode("697ce3052137d80745d524474fb6b290"),
Hex.Decode("2696fc47198bb23b11296e4f88720a17"),
Hex.Decode("01f2f0ead011a4ae0cf3572f1b76dd8e"),
Hex.Decode("a53060694a044e4b7fa1e661c5a7bb6b"),
Hex.Decode("39c0392e8b6b0e04a7565c85394c2c4c"),
Hex.Decode("519c362d502e07f2d8b7597a359a5214"),
Hex.Decode("5a527a393675705e19b2117f67695af4"),
Hex.Decode("27fc0901d1d332a53ba4d4386c2109d2"),
Hex.Decode("93ca9b57174aabedf8220e83366d7df6"),
};
for (int i = 0; i != 10; ++i)
{
long pow = testPow[i];
byte[] data = Arrays.Clone(testData[i]);
byte[] expected = Arrays.Clone(data);
for (int j = 0; j < pow; ++j)
{
mul.MultiplyH(expected);
}
byte[] H_a = new byte[16];
exp.ExponentiateX(pow, H_a);
byte[] actual = multiply(data, H_a);
Assert.IsTrue(Arrays.AreEqual(expected, actual));
}
}
[Test]
public void TestMultiply()
{
byte[] expected = Arrays.Clone(H);
mul.MultiplyH(expected);
Assert.IsTrue(Arrays.AreEqual(expected, multiply(H, H)));
for (int count = 0; count < 10; ++count)
{
byte[] a = new byte[16];
random.NextBytes(a);
byte[] b = new byte[16];
random.NextBytes(b);
expected = Arrays.Clone(a);
mul.MultiplyH(expected);
Assert.IsTrue(Arrays.AreEqual(expected, multiply(a, H)));
Assert.IsTrue(Arrays.AreEqual(expected, multiply(H, a)));
expected = Arrays.Clone(b);
mul.MultiplyH(expected);
Assert.IsTrue(Arrays.AreEqual(expected, multiply(b, H)));
Assert.IsTrue(Arrays.AreEqual(expected, multiply(H, b)));
Assert.IsTrue(Arrays.AreEqual(multiply(a, b), multiply(b, a)));
}
}
private byte[] randomBlocks(int upper)
{
byte[] bs = new byte[16 * random.Next(upper)];
random.NextBytes(bs);
return bs;
}
private byte[] randomBytes(int upper)
{
byte[] bs = new byte[random.Next(upper)];
random.NextBytes(bs);
return bs;
}
private byte[] concatArrays(byte[] P, byte[] A)
{
MemoryStream buf = new MemoryStream();
buf.Write(P, 0, P.Length);
buf.Write(A, 0, A.Length);
return buf.ToArray();
}
private byte[] combine_GHASH(byte[] ghashA_, long bitlenA, byte[] ghash_C, long bitlenC)
{
// Note: bitlenP must be aligned to the block size
long c = (bitlenC + 127) >> 7;
byte[] H_c = new byte[16];
exp.ExponentiateX(c, H_c);
byte[] tmp1 = lengthBlock(bitlenA, 0);
mul.MultiplyH(tmp1);
byte[] ghashAC = Arrays.Clone(ghashA_);
xor(ghashAC, tmp1);
ghashAC = multiply(ghashAC, H_c);
// No need to touch the len(C) part (second 8 bytes)
xor(ghashAC, tmp1);
xor(ghashAC, ghash_C);
return ghashAC;
}
private byte[] concatAuth_GHASH(byte[] ghashP, long bitlenP, byte[] ghashA, long bitlenA)
{
// Note: bitlenP must be aligned to the block size
long a = (bitlenA + 127) >> 7;
byte[] tmp1 = lengthBlock(bitlenP, 0);
mul.MultiplyH(tmp1);
byte[] tmp2 = lengthBlock(bitlenA ^ (bitlenP + bitlenA), 0);
mul.MultiplyH(tmp2);
byte[] H_a = new byte[16];
exp.ExponentiateX(a, H_a);
byte[] ghashC = Arrays.Clone(ghashP);
xor(ghashC, tmp1);
ghashC = multiply(ghashC, H_a);
xor(ghashC, tmp2);
xor(ghashC, ghashA);
return ghashC;
}
private byte[] concatCrypt_GHASH(byte[] ghashP, long bitlenP, byte[] ghashA, long bitlenA)
{
// Note: bitlenP must be aligned to the block size
long a = (bitlenA + 127) >> 7;
byte[] tmp1 = lengthBlock(0, bitlenP);
mul.MultiplyH(tmp1);
byte[] tmp2 = lengthBlock(0, bitlenA ^ (bitlenP + bitlenA));
mul.MultiplyH(tmp2);
byte[] H_a = new byte[16];
exp.ExponentiateX(a, H_a);
byte[] ghashC = Arrays.Clone(ghashP);
xor(ghashC, tmp1);
ghashC = multiply(ghashC, H_a);
xor(ghashC, tmp2);
xor(ghashC, ghashA);
return ghashC;
}
private byte[] GHASH(byte[] A, byte[] C)
{
byte[] X = new byte[16];
{
for (int pos = 0; pos < A.Length; pos += 16)
{
byte[] tmp = new byte[16];
int num = System.Math.Min(A.Length - pos, 16);
Array.Copy(A, pos, tmp, 0, num);
xor(X, tmp);
mul.MultiplyH(X);
}
}
{
for (int pos = 0; pos < C.Length; pos += 16)
{
byte[] tmp = new byte[16];
int num = System.Math.Min(C.Length - pos, 16);
Array.Copy(C, pos, tmp, 0, num);
xor(X, tmp);
mul.MultiplyH(X);
}
}
{
xor(X, lengthBlock((long)A.Length * 8, (long)C.Length * 8));
mul.MultiplyH(X);
}
return X;
}
private static byte[] lengthBlock(long bitlenA, long bitlenC)
{
byte[] tmp = new byte[16];
packLength(bitlenA, tmp, 0);
packLength(bitlenC, tmp, 8);
return tmp;
}
private static void xor(byte[] block, byte[] val)
{
for (int i = 15; i >= 0; --i)
{
block[i] ^= val[i];
}
}
private static void packLength(long count, byte[] bs, int off)
{
UInt32_To_BE((uint)(count >> 32), bs, off);
UInt32_To_BE((uint)count, bs, off + 4);
}
private static void UInt32_To_BE(uint n, byte[] bs, int off)
{
bs[ off] = (byte)(n >> 24);
bs[++off] = (byte)(n >> 16);
bs[++off] = (byte)(n >> 8);
bs[++off] = (byte)(n );
}
private static byte[] multiply(byte[] a, byte[] b)
{
byte[] c = new byte[16];
byte[] tmp = Arrays.Clone(b);
for (int i = 0; i < 16; ++i)
{
byte bits = a[i];
for (int j = 7; j >= 0; --j)
{
if ((bits & (1 << j)) != 0)
{
xor(c, tmp);
}
bool lsb = (tmp[15] & 1) != 0;
shiftRight(tmp);
if (lsb)
{
// R = new byte[]{ 0xe1, ... };
//GcmUtilities.Xor(tmp, R);
tmp[0] ^= (byte)0xe1;
}
}
}
return c;
}
private static void shiftRight(byte[] block)
{
int i = 0;
byte bit = 0;
for (;;)
{
byte b = block[i];
block[i] = (byte)((b >> 1) | bit);
if (++i == 16) break;
bit = (byte)(b << 7);
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.ServiceModel.Description;
using System.ServiceModel.Security.Tokens;
using SR = System.ServiceModel.SR;
namespace System.ServiceModel.Security
{
/// <summary>
/// SecurityTokenManager that enables plugging custom tokens easily.
/// The SecurityTokenManager provides methods to register custom token providers,
/// serializers and authenticators. It can wrap another Token Managers and
/// delegate token operation calls to it if required.
/// </summary>
/// <remarks>
/// Framework use only - this is an implementation adapter class that is used to expose
/// the Framework SecurityTokenHandlers to WCF.
/// </remarks>
sealed class FederatedSecurityTokenManager : ServiceCredentialsSecurityTokenManager
{
static string ListenUriProperty = "http://schemas.microsoft.com/ws/2006/05/servicemodel/securitytokenrequirement/ListenUri";
ExceptionMapper _exceptionMapper;
SecurityTokenResolver _defaultTokenResolver;
SecurityTokenHandlerCollection _securityTokenHandlerCollection;
object _syncObject = new object();
ReadOnlyCollection<CookieTransform> _cookieTransforms;
SessionSecurityTokenCache _tokenCache;
/// <summary>
/// Initializes an instance of <see cref="FederatedSecurityTokenManager"/>.
/// </summary>
/// <param name="parentCredentials">ServiceCredentials that created this instance of TokenManager.</param>
/// <exception cref="ArgumentNullException">The argument 'parentCredentials' is null.</exception>
public FederatedSecurityTokenManager( ServiceCredentials parentCredentials )
: base( parentCredentials )
{
if ( parentCredentials == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "parentCredentials" );
}
if ( parentCredentials.IdentityConfiguration == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "parentCredentials.IdentityConfiguration" );
}
_exceptionMapper = parentCredentials.ExceptionMapper;
_securityTokenHandlerCollection = parentCredentials.IdentityConfiguration.SecurityTokenHandlers;
_tokenCache = _securityTokenHandlerCollection.Configuration.Caches.SessionSecurityTokenCache;
_cookieTransforms = SessionSecurityTokenHandler.DefaultCookieTransforms;
}
/// <summary>
/// Returns the list of SecurityTokenHandlers.
/// </summary>
public SecurityTokenHandlerCollection SecurityTokenHandlers
{
//
//
get { return _securityTokenHandlerCollection; }
}
/// <summary>
/// Gets or sets the ExceptionMapper to be used when throwing exceptions.
/// </summary>
public ExceptionMapper ExceptionMapper
{
get
{
return _exceptionMapper;
}
set
{
if ( value == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "value" );
}
_exceptionMapper = value;
}
}
#region SecurityTokenManager Implementation
/// <summary>
/// Overriden from the base class. Creates the requested Token Authenticator.
/// Looks up the list of Token Handlers registered with the token Manager
/// based on the TokenType Uri in the SecurityTokenRequirement. If none is found,
/// then the call is delegated to the inner Token Manager.
/// </summary>
/// <param name="tokenRequirement">Security Token Requirement for which the Authenticator should be created.</param>
/// <param name="outOfBandTokenResolver">Token resolver that resolves any out-of-band tokens.</param>
/// <returns>Instance of Security Token Authenticator.</returns>
/// <exception cref="ArgumentNullException">'tokenRequirement' parameter is null.</exception>
/// <exception cref="NotSupportedException">No Authenticator is registered for the given token type.</exception>
public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator( SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver )
{
if ( tokenRequirement == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "tokenRequirement" );
}
outOfBandTokenResolver = null;
// Check for a registered authenticator
SecurityTokenAuthenticator securityTokenAuthenticator = null;
string tokenType = tokenRequirement.TokenType;
//
// When the TokenRequirement.TokenType is null, we treat this as a SAML issued token case. It may be SAML 1.1 or SAML 2.0.
//
if ( String.IsNullOrEmpty( tokenType ) )
{
return CreateSamlSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
}
//
// When the TokenType is set, build a token authenticator for the specified token type.
//
SecurityTokenHandler securityTokenHandler = _securityTokenHandlerCollection[tokenType];
if ( ( securityTokenHandler != null ) && ( securityTokenHandler.CanValidateToken ) )
{
outOfBandTokenResolver = GetDefaultOutOfBandTokenResolver();
if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.UserName ) )
{
UserNameSecurityTokenHandler upSecurityTokenHandler = securityTokenHandler as UserNameSecurityTokenHandler;
if ( upSecurityTokenHandler == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( UserNameSecurityTokenHandler ) ) ) );
}
securityTokenAuthenticator = new WrappedUserNameSecurityTokenAuthenticator( upSecurityTokenHandler, _exceptionMapper );
}
else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.Kerberos ) )
{
securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
}
else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.Rsa ) )
{
RsaSecurityTokenHandler rsaSecurityTokenHandler = securityTokenHandler as RsaSecurityTokenHandler;
if ( rsaSecurityTokenHandler == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( RsaSecurityTokenHandler ) ) ) );
}
securityTokenAuthenticator = new WrappedRsaSecurityTokenAuthenticator( rsaSecurityTokenHandler, _exceptionMapper );
}
else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.X509Certificate ) )
{
X509SecurityTokenHandler x509SecurityTokenHandler = securityTokenHandler as X509SecurityTokenHandler;
if ( x509SecurityTokenHandler == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( X509SecurityTokenHandler ) ) ) );
}
securityTokenAuthenticator = new WrappedX509SecurityTokenAuthenticator( x509SecurityTokenHandler, _exceptionMapper );
}
else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.SamlTokenProfile11 ) ||
StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.OasisWssSamlTokenProfile11 ) )
{
SamlSecurityTokenHandler saml11SecurityTokenHandler = securityTokenHandler as SamlSecurityTokenHandler;
if ( saml11SecurityTokenHandler == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( SamlSecurityTokenHandler ) ) ) );
}
if ( saml11SecurityTokenHandler.Configuration == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4274 ) );
}
securityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator( saml11SecurityTokenHandler, _exceptionMapper );
// The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
outOfBandTokenResolver = saml11SecurityTokenHandler.Configuration.ServiceTokenResolver;
}
else if ( StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.Saml2TokenProfile11 ) ||
StringComparer.Ordinal.Equals( tokenType, SecurityTokenTypes.OasisWssSaml2TokenProfile11 ) )
{
Saml2SecurityTokenHandler saml2SecurityTokenHandler = securityTokenHandler as Saml2SecurityTokenHandler;
if ( saml2SecurityTokenHandler == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException( SR.GetString( SR.ID4072, securityTokenHandler.GetType(), tokenType, typeof( Saml2SecurityTokenHandler ) ) ) );
}
if ( saml2SecurityTokenHandler.Configuration == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4274 ) );
}
securityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator( saml2SecurityTokenHandler, _exceptionMapper );
// The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
outOfBandTokenResolver = saml2SecurityTokenHandler.Configuration.ServiceTokenResolver;
}
else if ( StringComparer.Ordinal.Equals( tokenType, ServiceModelSecurityTokenTypes.SecureConversation ) )
{
RecipientServiceModelSecurityTokenRequirement tr = tokenRequirement as RecipientServiceModelSecurityTokenRequirement;
if ( tr == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4240, tokenRequirement.GetType().ToString() ) );
}
securityTokenAuthenticator = SetupSecureConversationWrapper( tr, securityTokenHandler as SessionSecurityTokenHandler, out outOfBandTokenResolver );
}
else
{
securityTokenAuthenticator = new SecurityTokenAuthenticatorAdapter( securityTokenHandler, _exceptionMapper );
}
}
else
{
if ( tokenType == ServiceModelSecurityTokenTypes.SecureConversation
|| tokenType == ServiceModelSecurityTokenTypes.MutualSslnego
|| tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego
|| tokenType == ServiceModelSecurityTokenTypes.SecurityContext
|| tokenType == ServiceModelSecurityTokenTypes.Spnego )
{
RecipientServiceModelSecurityTokenRequirement tr = tokenRequirement as RecipientServiceModelSecurityTokenRequirement;
if ( tr == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4240, tokenRequirement.GetType().ToString() ) );
}
securityTokenAuthenticator = SetupSecureConversationWrapper( tr, null, out outOfBandTokenResolver );
}
else
{
securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
}
}
return securityTokenAuthenticator;
}
/// <summary>
/// Helper method to setup the WrappedSecureConversttion
/// </summary>
SecurityTokenAuthenticator SetupSecureConversationWrapper( RecipientServiceModelSecurityTokenRequirement tokenRequirement, SessionSecurityTokenHandler tokenHandler, out SecurityTokenResolver outOfBandTokenResolver )
{
// This code requires Orcas SP1 to compile.
// WCF expects this securityTokenAuthenticator to support:
// 1. IIssuanceSecurityTokenAuthenticator
// 2. ICommunicationObject is needed for this to work right.
// WCF opens a listener in this STA that handles the nego and uses an internal class for negotiating the
// the bootstrap tokens. We want to handle ValidateToken to return our authorization policies and surface the bootstrap tokens.
// when sp1 is installed, use this one.
//SecurityTokenAuthenticator sta = base.CreateSecureConversationTokenAuthenticator( tokenRequirement as RecipientServiceModelSecurityTokenRequirement, _saveBootstrapTokensInSession, out outOfBandTokenResolver );
// use this code if SP1 is not installed
SecurityTokenAuthenticator sta = base.CreateSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
SessionSecurityTokenHandler sessionTokenHandler = tokenHandler;
//
// If there is no SCT handler here, create one.
//
if ( tokenHandler == null )
{
sessionTokenHandler = new SessionSecurityTokenHandler( _cookieTransforms, SessionSecurityTokenHandler.DefaultTokenLifetime );
sessionTokenHandler.ContainingCollection = _securityTokenHandlerCollection;
sessionTokenHandler.Configuration = _securityTokenHandlerCollection.Configuration;
}
if ( ServiceCredentials != null )
{
sessionTokenHandler.Configuration.MaxClockSkew = ServiceCredentials.IdentityConfiguration.MaxClockSkew;
}
SctClaimsHandler claimsHandler = new SctClaimsHandler(
_securityTokenHandlerCollection,
GetNormalizedEndpointId( tokenRequirement ) );
WrappedSessionSecurityTokenAuthenticator wssta = new WrappedSessionSecurityTokenAuthenticator( sessionTokenHandler, sta,
claimsHandler, _exceptionMapper );
WrappedTokenCache wrappedTokenCache = new WrappedTokenCache( _tokenCache, claimsHandler);
SetWrappedTokenCache( wrappedTokenCache, sta, wssta, claimsHandler );
outOfBandTokenResolver = wrappedTokenCache;
return wssta;
}
/// <summary>
/// The purpose of this method is to set our WrappedTokenCache as the token cache for SCT's.
/// And to set our OnIssuedToken callback when in cookie mode.
/// We have to use reflection here as this is a private method.
/// </summary>
static void SetWrappedTokenCache(
WrappedTokenCache wrappedTokenCache,
SecurityTokenAuthenticator sta,
WrappedSessionSecurityTokenAuthenticator wssta,
SctClaimsHandler claimsHandler )
{
if ( sta is SecuritySessionSecurityTokenAuthenticator )
{
( sta as SecuritySessionSecurityTokenAuthenticator ).IssuedTokenCache = wrappedTokenCache;
}
else if ( sta is AcceleratedTokenAuthenticator )
{
( sta as AcceleratedTokenAuthenticator ).IssuedTokenCache = wrappedTokenCache;
}
else if ( sta is SpnegoTokenAuthenticator )
{
( sta as SpnegoTokenAuthenticator ).IssuedTokenCache = wrappedTokenCache;
}
else if ( sta is TlsnegoTokenAuthenticator )
{
( sta as TlsnegoTokenAuthenticator ).IssuedTokenCache = wrappedTokenCache;
}
// we need to special case this as the OnTokenIssued callback is not hooked up in the cookie mode case.
IIssuanceSecurityTokenAuthenticator issuanceTokenAuthenticator = sta as IIssuanceSecurityTokenAuthenticator;
if ( issuanceTokenAuthenticator != null )
{
issuanceTokenAuthenticator.IssuedSecurityTokenHandler = claimsHandler.OnTokenIssued;
issuanceTokenAuthenticator.RenewedSecurityTokenHandler = claimsHandler.OnTokenRenewed;
}
}
/// <summary>
/// Overriden from the base class. Creates the requested Token Serializer.
/// Returns a Security Token Serializer that is wraps the list of token
/// hanlders registerd and also the serializers from the inner token manager.
/// </summary>
/// <param name="version">SecurityTokenVersion of the serializer to be created.</param>
/// <returns>Instance of SecurityTokenSerializer.</returns>
/// <exception cref="ArgumentNullException">Input parameter is null.</exception>
public override SecurityTokenSerializer CreateSecurityTokenSerializer( SecurityTokenVersion version )
{
if ( version == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "version" );
}
TrustVersion trustVersion = null;
SecureConversationVersion scVersion = null;
foreach ( string securitySpecification in version.GetSecuritySpecifications() )
{
if ( StringComparer.Ordinal.Equals( securitySpecification, WSTrustFeb2005Constants.NamespaceURI ) )
{
trustVersion = TrustVersion.WSTrustFeb2005;
}
else if ( StringComparer.Ordinal.Equals( securitySpecification, WSTrust13Constants.NamespaceURI ) )
{
trustVersion = TrustVersion.WSTrust13;
}
else if ( StringComparer.Ordinal.Equals( securitySpecification, WSSecureConversationFeb2005Constants.Namespace ) )
{
scVersion = SecureConversationVersion.WSSecureConversationFeb2005;
}
else if ( StringComparer.Ordinal.Equals( securitySpecification, WSSecureConversation13Constants.Namespace ) )
{
scVersion = SecureConversationVersion.WSSecureConversation13;
}
if ( trustVersion != null && scVersion != null )
{
break;
}
}
if ( trustVersion == null )
{
trustVersion = TrustVersion.WSTrust13;
}
if ( scVersion == null )
{
scVersion = SecureConversationVersion.WSSecureConversation13;
}
WsSecurityTokenSerializerAdapter adapter = new WsSecurityTokenSerializerAdapter( _securityTokenHandlerCollection,
GetSecurityVersion( version ), trustVersion, scVersion, false, this.ServiceCredentials.IssuedTokenAuthentication.SamlSerializer,
this.ServiceCredentials.SecureConversationAuthentication.SecurityStateEncoder,
this.ServiceCredentials.SecureConversationAuthentication.SecurityContextClaimTypes );
adapter.MapExceptionsToSoapFaults = true;
adapter.ExceptionMapper = _exceptionMapper;
return adapter;
}
/// <summary>
/// The out-of-band token resolver to be used if the authenticator does
/// not provide another.
/// </summary>
/// <remarks>By default this will create the resolver with the service certificate and
/// know certificates collections specified in the service credentials when the STS is
/// hosted inside WCF.</remarks>
SecurityTokenResolver GetDefaultOutOfBandTokenResolver()
{
if ( _defaultTokenResolver == null )
{
lock ( _syncObject )
{
if ( _defaultTokenResolver == null )
{
//
// Create default Out-Of-Band SecurityResolver.
//
List<SecurityToken> outOfBandTokens = new List<SecurityToken>();
if ( base.ServiceCredentials.ServiceCertificate.Certificate != null )
{
outOfBandTokens.Add( new X509SecurityToken( base.ServiceCredentials.ServiceCertificate.Certificate ) );
}
if ( ( base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates != null ) && ( base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates.Count > 0 ) )
{
for ( int i = 0; i < base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates.Count; ++i )
{
outOfBandTokens.Add( new X509SecurityToken( base.ServiceCredentials.IssuedTokenAuthentication.KnownCertificates[i]));
}
}
_defaultTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( outOfBandTokens.AsReadOnly(), false );
}
}
}
return _defaultTokenResolver;
}
/// <summary>
/// There is a bug in WCF where the version obtained from the public SecurityTokenVersion strings is wrong.
/// The internal MessageSecurityTokenVersion has the right version.
/// </summary>
internal static SecurityVersion GetSecurityVersion( SecurityTokenVersion tokenVersion )
{
if ( tokenVersion == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "tokenVersion" );
}
//
// Workaround for WCF bug.
// In .NET 3.5 WCF returns the wrong Token Specification. We need to reflect on the
// internal code so we can access the SecurityVersion directly instead of depending
// on the security specification.
//
if ( tokenVersion is MessageSecurityTokenVersion )
{
SecurityVersion sv = ( tokenVersion as MessageSecurityTokenVersion ).SecurityVersion;
if ( sv != null )
{
return sv;
}
}
else
{
if ( tokenVersion.GetSecuritySpecifications().Contains( WSSecurity11Constants.Namespace ) )
{
return SecurityVersion.WSSecurity11;
}
else if ( tokenVersion.GetSecuritySpecifications().Contains( WSSecurity10Constants.Namespace ) )
{
return SecurityVersion.WSSecurity10;
}
}
return SecurityVersion.WSSecurity11;
}
#endregion // SecurityTokenManager Implementation
/// <summary>
/// This method creates the inner security token authenticator from the base class.
/// The wrapped token cache is initialized with this authenticator.
/// </summary>
SecurityTokenAuthenticator CreateInnerSecurityTokenAuthenticator( SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver )
{
SecurityTokenAuthenticator securityTokenAuthenticator = base.CreateSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
SctClaimsHandler claimsHandler = new SctClaimsHandler(
_securityTokenHandlerCollection,
GetNormalizedEndpointId( tokenRequirement ) );
SetWrappedTokenCache( new WrappedTokenCache( _tokenCache, claimsHandler ), securityTokenAuthenticator, null, claimsHandler );
return securityTokenAuthenticator;
}
/// <summary>
/// This method creates a SAML security token authenticator when token type is null.
/// It wraps the SAML 1.1 and the SAML 2.0 token handlers that are configured.
/// If no token handler was found, then the inner token manager is created.
/// </summary>
SecurityTokenAuthenticator CreateSamlSecurityTokenAuthenticator( SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver )
{
outOfBandTokenResolver = null;
SecurityTokenAuthenticator securityTokenAuthenticator = null;
SamlSecurityTokenHandler saml11SecurityTokenHandler = _securityTokenHandlerCollection[SecurityTokenTypes.SamlTokenProfile11] as SamlSecurityTokenHandler;
Saml2SecurityTokenHandler saml2SecurityTokenHandler = _securityTokenHandlerCollection[SecurityTokenTypes.Saml2TokenProfile11] as Saml2SecurityTokenHandler;
if ( saml11SecurityTokenHandler != null && saml11SecurityTokenHandler.Configuration == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4274 ) );
}
if ( saml2SecurityTokenHandler != null && saml2SecurityTokenHandler.Configuration == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4274 ) );
}
if ( saml11SecurityTokenHandler != null && saml2SecurityTokenHandler != null )
{
//
// Both SAML 1.1 and SAML 2.0 token handlers have been configured.
//
WrappedSaml11SecurityTokenAuthenticator wrappedSaml11SecurityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator( saml11SecurityTokenHandler, _exceptionMapper );
WrappedSaml2SecurityTokenAuthenticator wrappedSaml2SecurityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator( saml2SecurityTokenHandler, _exceptionMapper );
securityTokenAuthenticator = new WrappedSamlSecurityTokenAuthenticator( wrappedSaml11SecurityTokenAuthenticator, wrappedSaml2SecurityTokenAuthenticator );
// The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
List<SecurityTokenResolver> resolvers = new List<SecurityTokenResolver>();
resolvers.Add( saml11SecurityTokenHandler.Configuration.ServiceTokenResolver );
resolvers.Add( saml2SecurityTokenHandler.Configuration.ServiceTokenResolver );
outOfBandTokenResolver = new AggregateTokenResolver( resolvers );
}
else if ( saml11SecurityTokenHandler == null && saml2SecurityTokenHandler != null )
{
//
// SAML 1.1 token handler is not present but SAML 2.0 is. Set the token type to SAML 2.0
//
securityTokenAuthenticator = new WrappedSaml2SecurityTokenAuthenticator( saml2SecurityTokenHandler, _exceptionMapper );
// The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
outOfBandTokenResolver = saml2SecurityTokenHandler.Configuration.ServiceTokenResolver;
}
else if ( saml11SecurityTokenHandler != null && saml2SecurityTokenHandler == null )
{
//
// SAML 1.1 token handler is present but SAML 2.0 is not. Set the token type to SAML 1.1
//
securityTokenAuthenticator = new WrappedSaml11SecurityTokenAuthenticator( saml11SecurityTokenHandler, _exceptionMapper );
// The out-of-band token resolver will be used by WCF to decrypt any encrypted SAML tokens.
outOfBandTokenResolver = saml11SecurityTokenHandler.Configuration.ServiceTokenResolver;
}
else
{
securityTokenAuthenticator = CreateInnerSecurityTokenAuthenticator( tokenRequirement, out outOfBandTokenResolver );
}
return securityTokenAuthenticator;
}
/// <summary>
/// Converts the ListenUri in the <see cref="SecurityTokenRequirement"/> to a normalized string.
/// The method preserves the Uri scheme, port and absolute path and replaces the host name
/// with the string 'NormalizedHostName'.
/// </summary>
/// <param name="tokenRequirement">The <see cref="SecurityTokenRequirement"/> which contains the 'ListenUri' property.</param>
/// <returns>A string representing the Normalized URI string.</returns>
public static string GetNormalizedEndpointId( SecurityTokenRequirement tokenRequirement )
{
if ( tokenRequirement == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "tokenRequirement" );
}
Uri listenUri = null;
if ( tokenRequirement.Properties.ContainsKey( ListenUriProperty ) )
{
listenUri = tokenRequirement.Properties[ListenUriProperty] as Uri;
}
if ( listenUri == null )
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperInvalidOperation( SR.GetString( SR.ID4287, tokenRequirement ) );
}
if ( listenUri.IsDefaultPort )
{
return String.Format( CultureInfo.InvariantCulture, "{0}://NormalizedHostName{1}", listenUri.Scheme, listenUri.AbsolutePath );
}
else
{
return String.Format( CultureInfo.InvariantCulture, "{0}://NormalizedHostName:{1}{2}", listenUri.Scheme, listenUri.Port, listenUri.AbsolutePath );
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Nohros.Resources;
namespace Nohros
{
/// <summary>
/// Logical representation of a pointer, but in fact a byte array reference and a position in it. This
/// is used to read logical units (bytes, shorts, integers, domain names etc.) from a byte array, keeping
/// the pointer updated and positioning to the next record. This type of pointer can be considered the logical
/// equivalent of an (unsigned char*) in C++;
/// </summary>
public class Pointer : IPointer
{
/// <summary>
/// The pointer message.
/// </summary>
protected byte[] message_;
/// <summary>
/// The message length.
/// </summary>
protected int length_;
/// <summary>
/// An index within the [message] representing the current pointer position.
/// </summary>
protected int position_;
#region .ctor
/// <summary>
/// Initializes a new instance_ of the Pointer class by using the specified message and position.
/// </summary>
/// <param name="message">An sequence of bytes that represents/contains the pointer.</param>
/// <param name="position">An index within the <paramref name="message"/> the is the begging of the pointer.</param>
public Pointer(byte[] message, int position) {
if (message == null)
throw new ArgumentNullException("message");
if (position < 0 || position >= message.Length)
throw new IndexOutOfRangeException(StringResources.Arg_IndexOutOfRange);
message_ = message;
position_ = position;
length_ = message_.Length;
}
#endregion
/// <summary>
/// Creates and returns an identical copy of the current pointer object.
/// </summary>
/// <returns>A copy of the current pointer.</returns>
public virtual Pointer Copy() {
return new Pointer(message_, position_);
}
/// <summary>
/// Overloads the + operator to allow advancing the pointer by so many bytes.
/// </summary>
/// <param name="pointer">the initial pointer.</param>
/// <param name="offset">the offset to add to the pointer in bytes.</param>
/// <returns>a reference to a new pointer moved forward by offset bytes.</returns>
/// <exception cref="IndexOutOfRangeException">Advancing the pointer by <paramref name="offset"/> bytes
/// past the related message array bounds.</exception>
public static Pointer operator +(Pointer pointer, int offset) {
int position = pointer.position_ + offset;
if (position < 0 || position >= pointer.message_.Length)
throw new IndexOutOfRangeException(StringResources.Arg_IndexOutOfRange);
pointer.position_ = position;
return pointer;
}
/// <summary>
/// Overloads the ++ operator to allow pointer increment.
/// </summary>
/// <param name="pointer">the initial pointer.</param>
/// <returns>a reference to a new pointer moved backward by one byte.</returns>
/// <exception cref="IndexOutOfRangeException">Advancing the pointer by <paramref name="offset"/> bytes
/// past the related message array bounds.</exception>
public static Pointer operator ++(Pointer pointer) {
return (pointer + 1);
}
/// <summary>
/// Overloads the - operator to allow advancing the pointer by so many bytes.
/// </summary>
/// <param name="pointer">the initial pointer.</param>
/// <param name="offset">the offset to add to the pointer in bytes.</param>
/// <returns>a reference to a new pointer moved forward by offset bytes.</returns>
/// <exception cref="IndexOutOfRangeException">Advancing the pointer by <paramref name="offset"/> bytes
/// past the related message array bounds.</exception>
public static Pointer operator -(Pointer pointer, int offset) {
int position = pointer.position_ - offset;
if (position < 0 || position >= pointer.message_.Length)
throw new IndexOutOfRangeException(StringResources.Arg_IndexOutOfRange);
pointer.position_ = position;
return pointer;
}
/// <summary>
/// Overloads the -- operator to allow pointer decrement.
/// </summary>
/// <param name="pointer">the initial pointer.</param>
/// <returns>a reference to a new pointer moved backward by one byte.</returns>
/// <exception cref="ArgumentOutOfRangeException">Moving the pointer by one byte
/// back past the related message array bounds.</exception>
public static Pointer operator --(Pointer pointer) {
return (pointer - 1);
}
/// <summary>
/// Converts the underlying message to its equivalent System.String representation encoded with base 64 digits.
/// </summary>
/// <param name="pointer">A <see cref="Pointer"/>object.</param>
/// <returns>The string representation, in base 64, of the underlying message.</returns>
/// <remarks>
/// The bytes of the underlying message ate taken as a numeric value and converted to a string representation that
/// is encoded with base-64 digits.
/// <para>
/// The base-64 digits in ascending order from zero are the upercase characters "A" to "Z", the lowercase characters
/// "a" to "z", the numerals "0" to "9", and the symbols "+" and "/". The valueless character "=", is used for tailing
/// padding.
/// </para>
/// </remarks>
public static string ToBase64String(Pointer pointer) {
byte[] message = pointer.message_;
int message_length = message.Length;
byte[] pre_encoded_message = new byte[message_length + 4];
Buffer.BlockCopy(message, 0, pre_encoded_message, 0, message_length);
// the last four bytes of the pre encoded array will be filled with
// the current pointer position.
pre_encoded_message[message_length] = (byte)(pointer.position_ & 0xf000);
pre_encoded_message[message_length + 1] = (byte)(pointer.position_ & 0xf00);
pre_encoded_message[message_length + 2] = (byte)(pointer.position_ & 0xf0);
pre_encoded_message[message_length + 3] = (byte)(pointer.position_ & 0xf);
return Convert.ToBase64String(pre_encoded_message);
}
/// <summary>
/// Converts the specified string, which encodes a Pointer object as base-64 digits, to an
/// equivalent Pointer object.
/// </summary>
/// <param name="s">The string representation of a pointer object to convert.</param>
/// <returns>A pointer object that is equivalent to <paramref name="s"/></returns>
/// <exception cref="ArgumentNullException"><paramref name="s"/> is null.</exception>
/// <exception cref="FormatException">The length of <paramref name="s"/>, ignoring white-space characters, is not zero or
/// a multiple of 4. -or- The format of <paramref name="s"/> is invalid. <paramref name="s"/> contains a non-base-64 character
/// , more than two padding characters, or a non-white space-cheracter among the padding characters.</exception>
/// <remarks>
/// <paramref name="s"/> is composed of base-64 digits, white-space characters, and trailing padding characters.
/// The base-64 digits in ascending order from zero are the upercase characters "A" to "Z", the lowercase characters
/// "a" to "z", the numerals "0" to "9", and the symbols "+" and "/".
/// <para>
/// The white-space character, and their Unicode names and hexadecimal code points, are tab(CHARACTER TABULATION, U+0009),
/// newline(LINE FEED, U+000A), carriage return(CARRIAGE RETURN, U+000D), and blank(SPACE, U+0020). An arbitrary number
/// of white spaces characters can appear in <paramref name="s"/> because all white-space characters are ignored.
/// </para>
/// <para>
/// The valueless character "=", is used for tailing padding. The end of <paramref name="s"/> can consist of zero, one,
/// or two padding characters.
/// </para>
/// </remarks>
public static Pointer FromBase64String(string s) {
// let the Convert function do the checks for us.
byte[] pre_decoded_message = Convert.FromBase64String(s);
// the last four bytes represents the position of the pointer
// when it was encoded.
int message_len = pre_decoded_message.Length - 4;
byte[] message = new byte[message_len];
// separate the wheat(message) from the chaff(pointer position)
int position = (ushort)((pre_decoded_message[message_len] << 8 | pre_decoded_message[message_len + 1]) << 16) |
(ushort)(pre_decoded_message[message_len + 2] << 8 | pre_decoded_message[message_len + 3]);
Buffer.BlockCopy(pre_decoded_message, 0, message, 0, message_len);
return new Pointer(message, position);
}
/// <summary>
/// Reads a single byte at the current position, advancing the pointer.
/// </summary>
/// <returns>the byte at the current position.</returns>
/// <remarks>If the current position is the end of the message array, the pointer will not be advanced and
/// the last byte will be returned.</remarks>
/// <exception cref="IndexOutOfRangeException">Advancing the pointer past the bounds of the underlying message
/// array.</exception>
public byte GetByte() {
// let the .NET framework do the bound checks and exception throwing for us.
return message_[position_++];
}
/// <summary>
/// Reads a single short(2 bytes) at the current position, advancing pointer.
/// </summary>
/// <returns>the short at the current position</returns>
/// <exception cref="IndexOutOfRangeException">Advancing the pointer past the bounds of the underlying message
/// array.</exception>
public short GetShort() {
return (short)(GetByte() << 8 | GetByte());
}
/// <summary>
/// Reads a single int(4 bytes) from the current position, advancing the pointer.
/// </summary>
/// <returns>the int at the current position.</returns>
/// <exception cref="IndexOutOfRangeException">Advancing the pointer past the bounds of the underlying message
/// array.</exception>
public int GetInt() {
return (ushort)GetShort() << 16 | (ushort)GetShort();
}
/// <summary>
/// Reads a single byte as a char at the current position, advancing the pointer.
/// </summary>
/// <returns>the char at the current position.</returns>
/// <exception cref="IndexOutOfRangeException">Advancing the pointer past the bounds of the underlying message
/// array.</exception>
public char GetChar() {
return (char)GetByte();
}
/// <summary>
/// Reads a single byte at the current pointer, does not advance pointer
/// </summary>
/// <returns>the byte at the current position.</returns>
public byte Peek() {
return this[position_];
}
/// <summary>
/// Reads a single byte at the specified position, does not advance the pointer.
/// </summary>
/// <param name="position"></param>
/// <returns>The byte at the specified position.</returns>
///<exception cref="IndexOutOfRangeException">The specified position is outside the bounds of the underlying message array.</exception>
public byte this[int position] {
get {
if (position < 0 || position > length_)
throw new IndexOutOfRangeException(StringResources.Arg_IndexOutOfRange);
return message_[position];
}
}
/// <summary>
/// Gets the current pointer position.
/// </summary>
public int Position {
get { return position_; }
}
/// <summary>
/// Gets the underlying message as a byte array.
/// </summary>
public byte[] Message {
get { return message_; }
}
}
}
| |
// 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 is used internally to create best fit behavior as per the original windows best fit behavior.
//
namespace System.Text
{
using System;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
[Serializable]
internal sealed class InternalDecoderBestFitFallback : DecoderFallback
{
// Our variables
internal Encoding encoding = null;
internal char[] arrayBestFit = null;
internal char cReplacement = '?';
internal InternalDecoderBestFitFallback(Encoding encoding)
{
// Need to load our replacement characters table.
this.encoding = encoding;
this.bIsMicrosoftBestFitFallback = true;
}
public override DecoderFallbackBuffer CreateFallbackBuffer()
{
return new InternalDecoderBestFitFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return 1;
}
}
public override bool Equals(Object value)
{
InternalDecoderBestFitFallback that = value as InternalDecoderBestFitFallback;
if (that != null)
{
return (this.encoding.CodePage == that.encoding.CodePage);
}
return (false);
}
public override int GetHashCode()
{
return this.encoding.CodePage;
}
}
internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer
{
// Our variables
internal char cBestFit = '\0';
internal int iCount = -1;
internal int iSize;
private InternalDecoderBestFitFallback oFallback;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
private static Object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Constructor
public InternalDecoderBestFitFallbackBuffer(InternalDecoderBestFitFallback fallback)
{
this.oFallback = fallback;
if (oFallback.arrayBestFit == null)
{
// Lock so we don't confuse ourselves.
lock(InternalSyncObject)
{
// Double check before we do it again.
if (oFallback.arrayBestFit == null)
oFallback.arrayBestFit = fallback.encoding.GetBestFitBytesToUnicodeData();
}
}
}
// Fallback methods
public override bool Fallback(byte[] bytesUnknown, int index)
{
// We expect no previous fallback in our buffer
Debug.Assert(iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer");
cBestFit = TryBestFit(bytesUnknown);
if (cBestFit == '\0')
cBestFit = oFallback.cReplacement;
iCount = iSize = 1;
return true;
}
// Default version is overridden in DecoderReplacementFallback.cs
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
iCount--;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (iCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (iCount == int.MaxValue)
{
iCount = -1;
return '\0';
}
// Return the best fit character
return cBestFit;
}
public override bool MovePrevious()
{
// Exception fallback doesn't have anywhere to back up to.
if (iCount >= 0)
iCount++;
// Return true if we could do it.
return (iCount >= 0 && iCount <= iSize);
}
// How many characters left to output?
public override int Remaining
{
get
{
return (iCount > 0) ? iCount : 0;
}
}
// Clear the buffer
public override unsafe void Reset()
{
iCount = -1;
byteStart = null;
}
// This version just counts the fallback and doesn't actually copy anything.
internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
{
// return our replacement string Length (always 1 for InternalDecoderBestFitFallback, either
// a best fit char or ?
return 1;
}
// private helper methods
private char TryBestFit(byte[] bytesCheck)
{
// Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array
int lowBound = 0;
int highBound = oFallback.arrayBestFit.Length;
int index;
char cCheck;
// Check trivial case first (no best fit)
if (highBound == 0)
return '\0';
// If our array is too small or too big we can't check
if (bytesCheck.Length == 0 || bytesCheck.Length > 2)
return '\0';
if (bytesCheck.Length == 1)
cCheck = unchecked((char)bytesCheck[0]);
else
cCheck = unchecked((char)((bytesCheck[0] << 8) + bytesCheck[1]));
// Check trivial out of range case
if (cCheck < oFallback.arrayBestFit[0] || cCheck > oFallback.arrayBestFit[highBound - 2])
return '\0';
// Binary search the array
int iDiff;
while ((iDiff = (highBound - lowBound)) > 6)
{
// Look in the middle, which is complicated by the fact that we have 2 #s for each pair,
// so we don't want index to be odd because it must be word aligned.
// Also note that index can never == highBound (because diff is rounded down)
index = ((iDiff / 2) + lowBound) & 0xFFFE;
char cTest = oFallback.arrayBestFit[index];
if (cTest == cCheck)
{
// We found it
Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
else if (cTest < cCheck)
{
// We weren't high enough
lowBound = index;
}
else
{
// We weren't low enough
highBound = index;
}
}
for (index = lowBound; index < highBound; index += 2)
{
if (oFallback.arrayBestFit[index] == cCheck)
{
// We found it
Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
}
// Char wasn't in our table
return '\0';
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.Text;
using Encog.MathUtil;
using Encog.Neural.Networks.Layers;
using Encog.Util;
namespace Encog.Neural.Networks.Structure
{
/// <summary>
/// Allows the weights and bias values of the neural network to be analyzed.
/// </summary>
///
public class AnalyzeNetwork
{
/// <summary>
/// All of the values in the neural network.
/// </summary>
///
private readonly double[] _allValues;
/// <summary>
/// The ranges of the bias values.
/// </summary>
///
private readonly NumericRange _bias;
/// <summary>
/// The bias values in the neural network.
/// </summary>
///
private readonly double[] _biasValues;
/// <summary>
/// The number of disabled connections.
/// </summary>
///
private readonly int _disabledConnections;
/// <summary>
/// The total number of connections.
/// </summary>
///
private readonly int _totalConnections;
/// <summary>
/// The weight values in the neural network.
/// </summary>
///
private readonly double[] _weightValues;
/// <summary>
/// The ranges of the weights.
/// </summary>
///
private readonly NumericRange _weights;
/// <summary>
/// The ranges of both the weights and biases.
/// </summary>
///
private readonly NumericRange _weightsAndBias;
/// <summary>
/// Construct a network analyze class. Analyze the specified network.
/// </summary>
///
/// <param name="network">The network to analyze.</param>
public AnalyzeNetwork(BasicNetwork network)
{
int assignDisabled = 0;
int assignedTotal = 0;
IList<Double> biasList = new List<Double>();
IList<Double> weightList = new List<Double>();
IList<Double> allList = new List<Double>();
for (int layerNumber = 0; layerNumber < network.LayerCount - 1; layerNumber++)
{
int fromCount = network.GetLayerNeuronCount(layerNumber);
int fromBiasCount = network
.GetLayerTotalNeuronCount(layerNumber);
int toCount = network.GetLayerNeuronCount(layerNumber + 1);
// weights
for (int fromNeuron = 0; fromNeuron < fromCount; fromNeuron++)
{
for (int toNeuron = 0; toNeuron < toCount; toNeuron++)
{
double v = network.GetWeight(layerNumber, fromNeuron,
toNeuron);
if (network.Structure.ConnectionLimited )
{
if (Math.Abs(v) < network.Structure.ConnectionLimit )
{
assignDisabled++;
}
}
weightList.Add(v);
allList.Add(v);
assignedTotal++;
}
}
// bias
if (fromCount != fromBiasCount)
{
int biasNeuron = fromCount;
for (int toNeuron = 0; toNeuron < toCount; toNeuron++)
{
double v = network.GetWeight(layerNumber, biasNeuron,
toNeuron);
if (network.Structure.ConnectionLimited)
{
if (Math.Abs(v) < network.Structure.ConnectionLimit)
{
assignDisabled++;
}
}
biasList.Add(v);
allList.Add(v);
assignedTotal++;
}
}
}
_disabledConnections = assignDisabled;
_totalConnections = assignedTotal;
_weights = new NumericRange(weightList);
_bias = new NumericRange(biasList);
_weightsAndBias = new NumericRange(allList);
_weightValues = EngineArray.ListToDouble(weightList);
_allValues = EngineArray.ListToDouble(allList);
_biasValues = EngineArray.ListToDouble(biasList);
}
/// <value>All of the values in the neural network.</value>
public double[] AllValues
{
get { return _allValues; }
}
/// <value>The numeric range of the bias values.</value>
public NumericRange Bias
{
get { return _bias; }
}
/// <value>The bias values in the neural network.</value>
public double[] BiasValues
{
get { return _biasValues; }
}
/// <value>The number of disabled connections in the network.</value>
public int DisabledConnections
{
get { return _disabledConnections; }
}
/// <value>The total number of connections in the network.</value>
public int TotalConnections
{
get { return _totalConnections; }
}
/// <value>The numeric range of the weights values.</value>
public NumericRange Weights
{
get { return _weights; }
}
/// <value>The numeric range of the weights and bias values.</value>
public NumericRange WeightsAndBias
{
get { return _weightsAndBias; }
}
/// <value>The weight values in the neural network.</value>
public double[] WeightValues
{
get { return _weightValues; }
}
/// <inheritdoc/>
public override sealed String ToString()
{
var result = new StringBuilder();
result.Append("All Values : ");
result.Append((_weightsAndBias.ToString()));
result.Append("\n");
result.Append("Bias : ");
result.Append((_bias.ToString()));
result.Append("\n");
result.Append("Weights : ");
result.Append((_weights.ToString()));
result.Append("\n");
result.Append("Disabled : ");
result.Append(Format.FormatInteger(_disabledConnections));
result.Append("\n");
return result.ToString();
}
}
}
| |
/*=================================\
* PlotterControl\Form_editvector.cs
*
* The Coestaris licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
*
* Created: 27.11.2017 14:04
* Last Edited: 27.11.2017 14:04:46
*=================================*/
using CWA_Resources.Properties;
using CWA;
using CWA.Vectors;
using CWA.Vectors.Document;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace CnC_WFA
{
public partial class Form_EditVector : Form
{
char[] num = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ',' ,'.'};
private int tc;
private Bitmap samplecolorprobe;
private int datacount;
private Color remember_text_color;
private string remember_text_name;
private float remember_text_angle;
private bool cntr_pressed;
private Point scrpoint;
public bool globalsel;
private Point realpos;
private Point pos;
public float zoom;
public Document main;
private float SampleX, SampleY, SampleW, SampleH;
private string l1, l2, l3, l4;
private Bitmap prbitmap;
int mode;
Point lp;
public Form_EditVector()
{
InitializeComponent();
}
public Form_EditVector(string Filename)
{
InitializeComponent();
main = Document.Load(Filename);
if (main == null)
{
return;
}
if (main.CreatedVersion < new Version(GlobalOptions.Ver))
{
var h = MessageBox.Show(TB.L.Message["VectorEditor.OldPCVdocVersion"], TB.L.Phrase["VectorEditor.Word.Warning"], MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (h == DialogResult.Yes)
{
main.CreatedVersion = new Version(GlobalOptions.Ver);
main.Save(Filename);
}
}
labelHint.Visible = false;
for (int i = 0; i <= main.Items.Count - 1; i++) main.Items[i].PreRender();
UpdateListbox();
Render();
panel_zoom.Enabled = true;
panel_newdoc.Visible = false;
toolStripButton_save.Enabled = true;
button_dideprop.Enabled = true;
button_dideprop.Size = new Size(63, 23);
panel_properties.Visible = true;
button_dideprop.Text = TB.L.Phrase["VectorEditor.Word.Hide"];
button_hidezoom.Enabled = true;
Form_editvector_SizeChanged(null, null);
toolStripStatusLabel1.Text = TB.L.Phrase["VectorEditor.Word.Name"] + ": " + main.Name;
toolStripStatusLabel3.Text = string.Format("| "+ TB.L.Phrase["VectorEditor.Word.Resolution"] + ": {0}x{1}", main.Size.Width, main.Size.Height);
Form_editvector_SizeChanged(null, null);
panel_zoom.Visible = true;
statusStrip1.Visible = true;
button_dideprop.Visible = true;
button_hidezoom.Visible = true;
toolStripButton_docopts_.Enabled = true;
toolStripButton_render_.Enabled = true;
toolStripButton_save_.Enabled = true;
toolStripSplitButton_additems.Enabled = true;
toolStripStatusLabel_fileversion.Text = "| "+ TB.L.Phrase["VectorEditor.UsedDocumentVersion"] + ": " + main.CreatedVersion.ToString();
trackBar1_Scroll(null, null);
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
label_zoom.Text = (trackBar_zoom.Value - 50).ToString() + '%';
zoom = (trackBar_zoom.Value - 50f) / 100f;
pos = new Point((int)(realpos.X * zoom), (int)(realpos.Y * zoom));
pictureBox2.Location = pos;
if (!globalsel) Render();
else RenderEX(Color.Magenta, (GraphicsPath)main.Items[listBox1.SelectedIndex].GrPath.Clone());
RenderSample();
}
public static Image resizeImage(Image imgToResize, Size size)
{
return (new Bitmap(imgToResize, size));
}
private void RenderSample()
{
switch (mode)
{
case 0:
RenderSampleText();
break;
case 1:
RenderSampleData();
break;
}
}
private void RenderSampleData()
{
if (main != null)
{
Pen p = new Pen(Color.Black, 1);
p.DashStyle = DashStyle.Dash;
Rectangle rec = new Rectangle(0, 0, (int)((SampleW - 1) * zoom), (int)((SampleH - 1) * zoom));
pictureBox2.Size = new Size((int)(SampleW * zoom), (int)(SampleH * zoom));
Bitmap bmp = new Bitmap((int)(SampleW * zoom) + 1, (int)(SampleH * zoom) + 1);
using (Graphics gr = Graphics.FromImage(bmp))
{
gr.DrawImage(prbitmap, rec);
gr.DrawRectangle(p, rec);
}
Image img = pictureBox2.Image;
pictureBox2.Image = bmp;
if (img != null) img.Dispose();
}
}
private void RenderSampleText()
{
if (main != null)
{
string text = richTextBox_texteditor_text.Text;
Pen p = new Pen(Color.Black, 1);
p.DashStyle = DashStyle.Dash;
Rectangle rec = new Rectangle(0, 0, (int)((SampleW - 1) * zoom), (int)((SampleH - 1) * zoom));
Bitmap bmp = new Bitmap((int)(SampleW * zoom) + 1, (int)(SampleH * zoom) + 1);
Font ff = fontDialog1.Font;
Font f = new Font(ff.FontFamily, ff.Size * zoom, FontStyle.Regular, GraphicsUnit.Pixel, ff.GdiCharSet, ff.GdiVerticalFont);
using (Graphics gr = Graphics.FromImage(bmp))
{
gr.DrawString(text, f, Brushes.Black, new PointF(0, 0));
gr.DrawRectangle(p, rec);
}
//panel2.BackColor = Color.FromArgb(25, Color);
pictureBox2.Size = new Size((int)(SampleW * zoom), (int)(SampleH * zoom));
Image img = pictureBox2.Image;
pictureBox2.Image = bmp;
if (img != null) img.Dispose();
}
}
public void RenderEX(Color c, GraphicsPath gr)
{
Bitmap im;
main.RenderEX(zoom, out im, c, gr);
Image img = pictureBox1.Image;
pictureBox1.Image = im;
if (img != null) img.Dispose();
}
public void Render()
{
Bitmap im;
main.Render(zoom, out im);
Image img = pictureBox1.Image;
pictureBox1.Image = im;
if (img != null) img.Dispose();
}
private void Form_editvector_Load(object sender, EventArgs e)
{
//toolStripButton_theme.PerformClick();
comboBox_bordstyle.Items.AddRange(Enum.GetNames(typeof(DocumentBorderStyle)));
MouseWheel += new MouseEventHandler(Form4_MouseWheel);
pictureBox1.MouseWheel += new MouseEventHandler(Form4_MouseWheel);
zoom = 1;
SampleW = 200;
SampleH = 150;
textBox_text_height.Text = "150";
textBox_text_posy.Text = "0";
textBox_text_xpos.Text = "0";
textBox_text_width.Text = "200";
panel4.AutoScroll = true;
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBox1.Controls.Add(pictureBox2);
pictureBox2.Location = new Point(0, 0);
pictureBox2.BackColor = Color.Transparent;
label_zoom.Text = (trackBar_zoom.Value - 50).ToString() + '%';
zoom = (trackBar_zoom.Value - 50) / 100;
radioButton_newdoc_usesize.Checked = true;
button_dideprop.Size = new Size(27, 30);
button_dideprop.Text = "";
Form_editvector_SizeChanged(null, null);
}
private void Form4_MouseWheel(object sender, MouseEventArgs e)
{
if(cntr_pressed)
{
trackBar_zoom.Value += e.Delta/50;
trackBar1_Scroll(null, null);
panel4.AutoScrollPosition = scrpoint;
}
}
private void textToolStripMenuItem_Click(object sender, EventArgs e)
{
mode = 0;
RenderSample();
pictureBox2.Visible = true;
panel_text.Visible = true;
}
private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
lp = new Point(PointToClient(MousePosition).X, PointToClient(MousePosition).Y);
}
private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point temp = Control.MousePosition;
Point rs = new Point(lp.X - temp.X, lp.Y - temp.Y);
int x = pictureBox2.Location.X - rs.X;
int y = pictureBox2.Location.Y - rs.Y;
//int maxx = pictureBox1.Image.Width;
//int maxy = pictureBox1.Image.Height;
if(x < 0) x = 0;
//else if(x + (int)SampleW > maxx) x = maxx - (int)SampleW;
if (y < 0) y = 0;
//else if (y + (int)SampleH > maxy) y = maxy - (int)SampleH;
pictureBox2.Location = new Point(x,y);
realpos = pictureBox2.Location;
if (mode == 0)
{
textBox_text_xpos.Text = (pictureBox2.Location.X / zoom).ToString(CultureInfo.InvariantCulture);
textBox_text_posy.Text = (pictureBox2.Location.Y / zoom).ToString(CultureInfo.InvariantCulture);
} else
if( mode == 1)
{
textBox_loaddata_x.Text = (pictureBox2.Location.X / zoom).ToString(CultureInfo.InvariantCulture);
textBox_loaddata_y.Text = (pictureBox2.Location.Y / zoom).ToString(CultureInfo.InvariantCulture);
}
lp = temp;
}
if(mode == 1)
{
toolStripStatusLabel4.Text = string.Format("| X: {0:0.##}", e.X / zoom);
toolStripStatusLabel5.Text = string.Format("| Y: {0:0.##}", e.Y / zoom);
}
}
private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
lp = MousePosition;
}
}
private void button_hidezoom_Click(object sender, EventArgs e)
{
if (panel_zoom.Visible)
{
panel_zoom.Visible = false;
button_hidezoom.Size = new Size(27, 30);
button_hidezoom.Text = "";
}
else
{
panel_zoom.Visible = true;
button_hidezoom.Size = new Size(83, 30);
button_hidezoom.Text = TB.L.Phrase["VectorEditor.Word.Hide"];
}
Form_editvector_SizeChanged(null, null);
}
private void textBox_text_xpos_TextChanged(object sender, EventArgs e)
{
bool err = false;
foreach (char a in textBox_text_xpos.Text)
{
if (!num.Contains(a))
{
MessageBox.Show(string.Format(TB.L.Error["VectorEditor.FloatInputError"], a), TB.L.Phrase["VectorEditor.Word.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error);
textBox_text_xpos.Text = l1;
err = true;
return;
}
}
if(!err)
{
l1 = textBox_text_xpos.Text;
try { SampleX = float.Parse(l1, CultureInfo.InvariantCulture); }
catch { SampleX = 0; }
if (mode == 0) RenderSampleText();
//pictureBox2.Location = new Point((int)(SampleX * zoom), (int)(SampleY * zoom));
}
}
private void textBox_text_width_TextChanged(object sender, EventArgs e)
{
bool err = false;
foreach (char a in textBox_text_width.Text)
{
if (!num.Contains(a))
{
MessageBox.Show(string.Format(TB.L.Error["VectorEditor.FloatInputError"], a), TB.L.Phrase["VectorEditor.Word.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error);
textBox_text_width.Text = l3;
err = true;
return;
}
}
if (!err)
{
l3 = textBox_text_width.Text;
try { SampleW = float.Parse(l3, CultureInfo.InvariantCulture); }
catch { SampleW = 1; }
if (SampleW == 0) SampleW = 1;
if(mode==0) RenderSampleText();
}
}
private void textBox_text_posy_TextChanged(object sender, EventArgs e)
{
bool err = false;
foreach (char a in textBox_text_posy.Text)
{
if (!num.Contains(a))
{
MessageBox.Show(string.Format(TB.L.Error["VectorEditor.FloatInputError"], a), TB.L.Phrase["VectorEditor.Word.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error);
textBox_text_posy.Text = l2;
err = true;
return;
}
}
if (!err)
{
l2 = textBox_text_posy.Text;
try { SampleY = float.Parse(l2, CultureInfo.InvariantCulture); }
catch { SampleY = 0; }
if (mode == 0) RenderSampleText();
//pictureBox2.Location = new Point((int)(SampleX * zoom), (int)(SampleY * zoom));
}
}
private void textBox_text_height_TextChanged(object sender, EventArgs e)
{
bool err = false;
foreach (char a in textBox_text_height.Text)
{
if (!num.Contains(a))
{
MessageBox.Show(string.Format(TB.L.Error["VectorEditor.FloatInputError"], a), TB.L.Phrase["VectorEditor.Word.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error);
textBox_text_height.Text = l4;
err = true;
return;
}
}
if (!err)
{
l4 = textBox_text_height.Text;
try { SampleH = float.Parse(l4, CultureInfo.InvariantCulture); }
catch { SampleH = 1; }
if (SampleH == 0) SampleH = 1;
if (mode == 0) RenderSampleText();
}
}
private void button_break_Click(object sender, EventArgs e)
{
SampleW = 200;
SampleH = 150;
textBox_text_height.Text = "150";
textBox_text_posy.Text = "0";
textBox_text_xpos.Text = "0";
textBox_text_width.Text = "200";
pictureBox2.Visible = false;
panel_text.ResetText();
panel_text.Visible = false;
pictureBox2.Location = new Point(3, 3);
}
private void toolStripButton_new_Click(object sender, EventArgs e)
{
panel_newdoc.Visible = true;
labelHint.Visible = false;
}
private void radioButton_newdoc_usesize_CheckedChanged(object sender, EventArgs e)
{
bool a = radioButton_newdoc_usesize.Checked;
textBox_newdoc_height.Enabled = a;
textBox_newdoc_width.Enabled = a;
label_newdoc_height.Enabled = a;
label_newdoc_width.Enabled = a;
button_newdoc_brouse.Enabled = !a;
label_newdoc_path.Enabled = !a;
}
private void button_newdoc_cancel_Click(object sender, EventArgs e)
{
if(main == null) labelHint.Visible = true;
panel_newdoc.Visible = false;
}
private void button_newdoc_ok_Click(object sender, EventArgs e)
{
globalsel = false;
if(textBox_newdoc_name.Text.Trim() == "")
{
MessageBox.Show(TB.L.Message["VectorEditor.EnterTheNameOfDocument"], TB.L.Phrase["VectorEditor.Word.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (radioButton_newdoc_usesize.Checked)
{
int width, height;
if (!int.TryParse(textBox_newdoc_width.Text, out width))
{
MessageBox.Show(TB.L.Error["VectorEditor.WrongWidthValue"], TB.L.Phrase["VectorEditor.Word.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!int.TryParse(textBox_newdoc_height.Text, out height))
{
MessageBox.Show(TB.L.Error["VectorEditor.WrongHeightValue"], TB.L.Phrase["VectorEditor.Word.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
main = new Document(new SizeF(width, height));
main.Name = textBox_newdoc_name.Text;
Render();
panel_zoom.Enabled = true;
panel_newdoc.Visible = false;
toolStripButton_save.Enabled = true;
button_dideprop.Enabled = true;
button_dideprop.Size = new Size(83, 30);
panel_properties.Visible = true;
button_dideprop.Text = TB.L.Phrase["VectorEditor.Word.Hide"];
button_hidezoom.Enabled = true;
}
else
{
tmpv = new Vector(path);
main = new Document(new SizeF((float)tmpv.Header.Width,( float) tmpv.Header.Height));
main.Name = textBox_newdoc_name.Text;
panel_zoom.Enabled = true;
panel_newdoc.Visible = false;
toolStripButton_save.Enabled = true;
button_dideprop.Enabled = true;
button_dideprop.Size = new Size(83, 30);
panel_properties.Visible = true;
button_dideprop.Text = TB.L.Phrase["VectorEditor.Word.Hide"];
button_hidezoom.Enabled = true;
prbitmap = tmpv.ToBitmap(Color.White, Color.Black);
pictureBox_loaddata_preview.Image = prbitmap;
panel_dataload.Visible = true;
pictureBox2.Visible = true;
mode = 1;
label_loaddata_path.Text = TB.L.Phrase["VectorEditor.Word.Path"] + ':' + new FileInfo(openFileDialog1.FileName).Directory.Name + '\\' + new FileInfo(openFileDialog1.FileName).Name;
label_loaddata_resolution.Text = string.Format("{2}: {0}x{1}", tmpv.Header.Width, tmpv.Header.Height, TB.L.Phrase["VectorEditor.Word.Resolution"]);
label_loaddata_cont.Text = string.Format("{2}: {0}, {3}: {1}", tmpv.RawData.Length, tmpv.Points, TB.L.Phrase["VectorEditor.Word.Contours"], TB.L.Phrase["VectorEditor.Word.Points"]);
SampleH = (int)tmpv.Header.Height;
SampleW = (int)tmpv.Header.Width;
RenderSampleData();
Render();
}
button_hidezoom.Visible = true;
button_dideprop.Visible = true;
listBox1.Items.Clear();
Form_editvector_SizeChanged(null, null);
toolStripStatusLabel1.Text = TB.L.Phrase["VectorEditor.Word.Name"] + ": " + main.Name;
toolStripStatusLabel3.Text = string.Format("| {2}: {0}x{1}", main.Size.Width, main.Size.Height, TB.L.Phrase["VectorEditor.Word.Resolution"]);
toolStripButton_docopts_.Enabled = true;
toolStripButton_render_.Enabled = true;
toolStripButton_save_.Enabled = true;
panel_zoom.Visible = true;
statusStrip1.Visible = true;
toolStripSplitButton_additems.Enabled = true;
toolStripStatusLabel_fileversion.Text = "| "+ TB.L.Phrase["VectorEditor.UsedDocumentVersion"] + ": " + main.CreatedVersion.ToString();
}
private void button_done_Click(object sender, EventArgs e)
{
if (remember_text_name != "")
{
panel_properties.Enabled = true;
main.AddItem(new DocumentText(new PointF(float.Parse(textBox_text_xpos.Text, CultureInfo.InvariantCulture),
float.Parse(textBox_text_posy.Text, CultureInfo.InvariantCulture)),
new SizeF(float.Parse(textBox_text_width.Text, CultureInfo.InvariantCulture), float.Parse(textBox_text_height.Text, CultureInfo.InvariantCulture)),
richTextBox_texteditor_text.Text, fontDialog1.Font),
remember_text_name);
button_break_Click(null, null);
UpdateListbox();
main.Items[main.Items.Count - 1].DispColor = remember_text_color;
main.Items[main.Items.Count - 1].Angle = remember_text_angle;
main.Items[main.Items.Count - 1].PreRender();
Matrix m = new Matrix();
m.RotateAt(remember_text_angle, new PointF(main.Items[main.Items.Count - 1].Size.Width / 2 + main.Items[main.Items.Count - 1].Position.X, main.Items[main.Items.Count - 1].Size.Height / 2 + main.Items[main.Items.Count - 1].Position.Y));
main.Items[main.Items.Count - 1].GrPath.Transform(m);
Render();
globalsel = false;
remember_text_name = "";
remember_text_angle = 0;
}
else
{
main.AddItem(new DocumentText(new PointF(float.Parse(textBox_text_xpos.Text, CultureInfo.InvariantCulture),
float.Parse(textBox_text_posy.Text, CultureInfo.InvariantCulture)),
new SizeF(float.Parse(textBox_text_width.Text, CultureInfo.InvariantCulture), float.Parse(textBox_text_height.Text, CultureInfo.InvariantCulture)),
richTextBox_texteditor_text.Text, fontDialog1.Font),
"text0" + (++tc).ToString());
button_break_Click(null, null);
UpdateListbox();
main.Items[main.Items.Count - 1].PreRender();
Render();
}
}
private void button_dideprop_Click(object sender, EventArgs e)
{
panel_properties.Visible = !panel_properties.Visible;
if(panel_properties.Visible)
{
button_dideprop.Location = new Point(Width - button_dideprop.Width - 27 - 83 + 15, button_dideprop.Location.Y);
button_dideprop.Size = new Size(83, 30);
button_dideprop.Text = TB.L.Phrase["VectorEditor.Word.Hide"];
}
else
{
button_dideprop.Location = new Point(Width - button_dideprop.Width + 15, button_dideprop.Location.Y);
button_dideprop.Size = new Size(27, 30);
button_dideprop.Text = "";
}
}
private void UpdateListbox()
{
label_obcount.Text = TB.L.Phrase["VectorEditor.Word.Objects"] + ": " + main.Items.Count;
listBox1.Items.Clear();
foreach(var a in main.Items)
{
listBox1.Items.Add(string.Format("{0} - {1}", a.Type, a.Name));
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
DocumentItem selitem = main.Items[listBox1.SelectedIndex];
samplecolorprobe = new Bitmap(55, 23);
Rectangle rec = new Rectangle(0, 0, 55, 23);
var b = new SolidBrush(selitem.DispColor);
using (Graphics gr = Graphics.FromImage(samplecolorprobe))
{
gr.FillRectangle(b, rec);
}
pictureBox_drawcolor.Image = samplecolorprobe;
label_type.Text = TB.L.Phrase["VectorEditor.Word.Type"] + ": " + selitem.Type.ToString();
if (selitem.Type != DocumentItemType.Text)
{
} else
{
label_subtype.Text = TB.L.Phrase["VectorEditor.Word.SubType"] + ": " + TB.L.Phrase["VectorEditor.Word.None"];
}
textBox_editname.Text = selitem.Name;
RenderEX(Color.Magenta, (GraphicsPath) main.Items[listBox1.SelectedIndex].GrPath.Clone());
}
}
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
FormTranslator.Translate(new Form_VectorMaster()).Show();
}
private Vector tmpv;
private void dataToolStripMenuItem_Click(object sender, EventArgs e)
{
var a = openFileDialog1.ShowDialog();
if (a == DialogResult.OK)
{
tmpv = new Vector(openFileDialog1.FileName);
prbitmap = tmpv.ToBitmap(Color.White, Color.Black);
pictureBox_loaddata_preview.Image = prbitmap;
panel_dataload.Visible = true;
pictureBox2.Visible = true;
mode = 1;
label_loaddata_path.Text = TB.L.Phrase["VectorEditor.Word.Path"] + ": " + new FileInfo(openFileDialog1.FileName).Directory.Name + '\\' + new FileInfo(openFileDialog1.FileName).Name;
label_loaddata_resolution.Text = string.Format("{2}: {0}x{1}", tmpv.Header.Width, tmpv.Header.Height, TB.L.Phrase["VectorEditor.Word.Resolution"]);
label_loaddata_cont.Text = string.Format("{2}: {0}, {3}: {1}", tmpv.RawData.Length, tmpv.Points, TB.L.Phrase["VectorEditor.Word.Contours"], TB.L.Phrase["VectorEditor.Word.Points"]);
SampleH = (float)tmpv.Header.Height;
SampleW = (float)tmpv.Header.Width;
RenderSampleData();
}
}
private void button_loaddata_ok_Click(object sender, EventArgs e)
{
main.AddItem(new DocumentData(new PointF(float.Parse(textBox_loaddata_x.Text, CultureInfo.InvariantCulture),
float.Parse(textBox_loaddata_y.Text, CultureInfo.InvariantCulture)), tmpv),
"data0" + (++datacount).ToString());
button_loaddata_break_Click(null, null);
UpdateListbox();
main.Items[main.Items.Count - 1].PreRender();
Render();
}
string path;
private void button_newdoc_brouse_Click(object sender, EventArgs e)
{
saveFileDialog1.InitialDirectory = new FileInfo(Application.ExecutablePath).Directory.FullName + "\\Data\\Vect";
var a = openFileDialog1.ShowDialog();
if(a == DialogResult.OK)
{
label_newdoc_path.Text = TB.L.Phrase["VectorEditor.Word.Path"] + ": " + new FileInfo(openFileDialog1.FileName).Directory.Name + '\\' + new FileInfo(openFileDialog1.FileName).Name;
path = openFileDialog1.FileName;
}
}
/* Sdelyal` do etogo :/*/
private void button_loaddata_break_Click(object sender, EventArgs e)
{
SampleW = 200;
SampleH = 150;
textBox_loaddata_x.Text = "0";
textBox_loaddata_y.Text = "0";
pictureBox2.Visible = false;
panel_dataload.ResetText();
panel_dataload.Visible = false;
pictureBox2.Location = new Point(3, 3);
}
private void button_drcolor_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
colorDialog1.Color = main.Items[listBox1.SelectedIndex].DispColor;
var a = colorDialog1.ShowDialog();
if (a == DialogResult.OK)
{
main.Items[listBox1.SelectedIndex].DispColor = colorDialog1.Color;
main.Items[listBox1.SelectedIndex].UseDispColor = true;
samplecolorprobe = new Bitmap(55, 23);
Rectangle rec = new Rectangle(0, 0, 55, 23);
var b = new SolidBrush(main.Items[listBox1.SelectedIndex].DispColor);
using (Graphics gr = Graphics.FromImage(samplecolorprobe))
{
gr.FillRectangle(b, rec);
}
pictureBox_drawcolor.Image = samplecolorprobe;
Render();
}
}
}
private void Form_editvector_SizeChanged(object sender, EventArgs e)
{
labelHint.Location = new Point(Width / 2 - labelHint.Width / 2, Height / 2 - labelHint.Height / 2 - 60);
panel_newdoc.Location = new Point(Width/2 - panel_newdoc.Width/2, Height/2 - panel_newdoc.Height/2 - 100);
panel_zoom.Location = new Point(Width - panel_zoom.Width - 30, Height - panel_zoom.Height - 75);
panel_properties.Location = new Point(Width - panel_properties.Width - 30, panel_properties.Location.Y);
panel_angle.Location = new Point(panel_angle.Location.X, Height - panel_angle.Height - 80);
panel_dataload.Location = new Point(Width - panel_dataload.Width - 30, 331);
panel_text.Location = new Point(Width - panel_text.Width - 30, panel_text.Location.Y);
if (button_dideprop.Text == "") button_dideprop.Location = new Point(Width - button_dideprop.Width - 39 -2 , button_dideprop.Location.Y);
else button_dideprop.Location = new Point(Width - button_dideprop.Width - 36 - 3, button_dideprop.Location.Y);
if (button_hidezoom.Text == "") button_hidezoom.Location = new Point(Width - button_hidezoom.Width - 39 - 2, Height - button_hidezoom.Height - 80);
else button_hidezoom.Location = new Point(Width - button_hidezoom.Width - 36 - 3, Height - button_hidezoom.Height - 80);
}
private void button_edit_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
if (main.Items[listBox1.SelectedIndex].Type == DocumentItemType.Image)
{
var a = FormTranslator.Translate(new Form_Dialog_Edit(main.Items[listBox1.SelectedIndex]));
a.parent = this;
//if(main.UseDarkTheme) a.ToTheme(Color.FromArgb(45, 45, 48), Color.FromArgb(255, 255, 255), Color.FromArgb(30, 30, 30), Color.FromArgb(30, 30, 30));
//else a.ToTheme(Color.FromKnownColor(KnownColor.Control), Color.FromKnownColor(KnownColor.ControlText), Color.FromKnownColor(KnownColor.Window), Color.FromKnownColor(KnownColor.Control));
a.Show();
}
else
{
panel_properties.Enabled = false;
var a = (DocumentText)main.Items[listBox1.SelectedIndex];
pictureBox2.Visible = true;
textBox_text_height.Text = a.Size.Height.ToString(CultureInfo.InvariantCulture);
textBox_text_width.Text = a.Size.Width.ToString(CultureInfo.InvariantCulture);
pictureBox2.Width = (int)a.Size.Width;
pictureBox2.Height = (int)a.Size.Height;
textBox_text_posy.Text = a.Position.Y.ToString(CultureInfo.InvariantCulture);
textBox_text_xpos.Text = a.Position.X.ToString(CultureInfo.InvariantCulture);
pictureBox2.Location = new Point((int)(a.Position.X*zoom),(int)(a.Position.Y*zoom));
fontDialog1.Font = a.Font;
main.Items.RemoveAt(listBox1.SelectedIndex);
panel_text.Visible = true;
richTextBox_texteditor_text.Text = a.Caption;
remember_text_angle = a.Angle;
remember_text_color = a.DispColor;
remember_text_name = a.Name;
listBox1.SelectedIndex = -1;
Render();
RenderSample();
}
}
}
private void button_rename_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
textBox_editname.ReadOnly = !textBox_editname.ReadOnly;
}
}
private void toolStripButton4_Click(object sender, EventArgs e)
{
saveFileDialog1.InitialDirectory = "Data\\VDocs";
saveFileDialog1.FileName = main.Name + ".pcvdoc";
var a = saveFileDialog1.ShowDialog();
if (a == DialogResult.OK)
{
main.Save(new FileInfo(saveFileDialog1.FileName).Name);
}
}
private void toolStripButton3_Click(object sender, EventArgs e)
{
saveFileDialog1.InitialDirectory = "Data\\VDocs";
var a = openFileDialog2.ShowDialog();
if (a == DialogResult.OK)
{
main = Document.Load(new FileInfo(openFileDialog2.FileName).Name);
if(main == null)
{
return;
}
if(main.CreatedVersion < new Version(GlobalOptions.Ver))
{
var h = MessageBox.Show(TB.L.Message["VectorEditor.OldPCVdocVersion"], TB.L.Phrase["VectorEditor.Word.Warning"], MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if(h == DialogResult.Yes)
{
main.CreatedVersion = new Version(GlobalOptions.Ver);
main.Save(new FileInfo(openFileDialog2.FileName).Name);
}
}
labelHint.Visible = false;
for (int i = 0; i <= main.Items.Count - 1; i++) main.Items[i].PreRender();
UpdateListbox();
Render();
panel_zoom.Enabled = true;
panel_newdoc.Visible = false;
toolStripButton_save.Enabled = true;
button_dideprop.Enabled = true;
button_dideprop.Size = new Size(63, 23);
panel_properties.Visible = true;
button_dideprop.Text = TB.L.Phrase["VectorEditor.Word.Hide"];
button_hidezoom.Enabled = true;
Form_editvector_SizeChanged(null, null);
toolStripStatusLabel1.Text = TB.L.Phrase["VectorEditor.Word.Name"] + ": " + main.Name;
toolStripStatusLabel3.Text = string.Format("| "+ TB.L.Phrase["VectorEditor.Word.Resolution"] + ": {0}x{1}", main.Size.Width, main.Size.Height);
Form_editvector_SizeChanged(null, null);
panel_zoom.Visible = true;
statusStrip1.Visible = true;
button_dideprop.Visible = true;
button_hidezoom.Visible = true;
toolStripButton_docopts_.Enabled = true;
toolStripButton_render_.Enabled = true;
toolStripButton_save_.Enabled = true;
toolStripSplitButton_additems.Enabled = true;
toolStripStatusLabel_fileversion.Text = "| "+ TB.L.Phrase["VectorEditor.UsedDocumentVersion"] + ": " + main.CreatedVersion.ToString();
}
}
private void textBox_editname_TextChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
if (textBox_editname.ReadOnly == false)
{
main.Items[listBox1.SelectedIndex].Name = textBox_editname.Text;
listBox1.Items[listBox1.SelectedIndex] = string.Format("{0} - {1}", main.Items[listBox1.SelectedIndex].Type, textBox_editname.Text);
int c = main.Items.FindAll(p => p.Name == textBox_editname.Text.Trim()).Count;
if (c >= 2)
{
MessageBox.Show(string.Format(TB.L.Error["VectorEditor.FoundObjectWithSameName"], c,textBox_editname.Text), TB.L.Phrase["VectorEditor.Word.Warning"], MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listBox1.SelectedIndex!=-1)
{
main.Items.RemoveAt(listBox1.SelectedIndex);
UpdateListbox();
Render();
}
}
private void pictureBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (main != null)
{
var a = pictureBox1.PointToClient(MousePosition);
Pen p = new Pen(Color.Black, 10);
for (int i = 0; i <= main.Items.Count - 1; i++)
{
if (main.Items[i].GrPath.IsOutlineVisible(a.X / zoom, a.Y / zoom, p))
{
globalsel = false;
button_edit_Click(null, null);
panel_angle.Visible = false;
return;
}
}
if (DocumentBorderRender.Render(main.Border, main.Size).IsOutlineVisible(a.X / zoom, a.Y / zoom, p))
{
textBox_fileinfo.Text = main.FileName;
textBox_fileautor.Text = main.FileAutor;
richTextBox_filediscr.Text = main.FileDescr;
checkBox_useborder.Checked = main.Border.Use;
comboBox_bordstyle.Text = main.Border.Style.ToString();
textBox_bordoffset.Text = main.Border.Offset.ToString(CultureInfo.InvariantCulture);
panel_docsettings.Visible = true;
}
}
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
toolStripStatusLabel4.Text = string.Format("| X: {0:0.##}", e.X / zoom);
toolStripStatusLabel5.Text = string.Format("| Y: {0:0.##}", e.Y / zoom);
}
private void toolStripButton_docopts__Click(object sender, EventArgs e)
{
panel_docsettings.Visible = !panel_docsettings.Visible;
if(panel_docsettings.Visible)
{
textBox_fileinfo.Text = main.FileName;
textBox_fileautor.Text = main.FileAutor;
richTextBox_filediscr.Text = main.FileDescr;
checkBox_useborder.Checked = main.Border.Use;
comboBox_bordstyle.Text = main.Border.Style.ToString();
textBox_bordoffset.Text = main.Border.Offset.ToString(CultureInfo.InvariantCulture);
}
}
private void checkBox_useborder_CheckedChanged(object sender, EventArgs e)
{
comboBox_bordstyle.Enabled = checkBox_useborder.Checked;
textBox_bordoffset.Enabled = checkBox_useborder.Checked;
main.Border.Use = checkBox_useborder.Checked;
Render();
}
private void textBox_fileinfo_TextChanged(object sender, EventArgs e)
{
main.FileName = textBox_fileinfo.Text;
}
private void textBox_fileautor_TextChanged(object sender, EventArgs e)
{
main.FileAutor = textBox_fileautor.Text;
}
private void richTextBox_filediscr_TextChanged(object sender, EventArgs e)
{
main.FileDescr = richTextBox_filediscr.Text;
}
private void textBox_bordoffset_TextChanged(object sender, EventArgs e)
{
float offset = 0.0f;
bool b = float.TryParse(textBox_bordoffset.Text, out offset);
if(!b)
{
MessageBox.Show(TB.L.Error["VectorEditor.WrongBordOffsetInput"]);
return;
}
main.Border.Offset = offset;
Render();
}
private void comboBox_bordstyle_SelectedIndexChanged(object sender, EventArgs e)
{
main.Border.Style = ExOperators.GetEnum<DocumentBorderStyle>(comboBox_bordstyle.Text);
Render();
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
if (main != null)
{
if(remember_text_name != "" && pictureBox2.Visible == true)
{
button_done_Click(null, null);
}
var a = pictureBox1.PointToClient(MousePosition);
Pen p = new Pen(Color.Black, 10);
if (DocumentBorderRender.Render(main.Border, main.Size).IsOutlineVisible(a.X / zoom, a.Y / zoom, p))
{
main.BorderPen = Pens.Magenta;
if (e.Button == MouseButtons.Right)
{
contextMenuStrip_object_edit.Items.Clear();
contextMenuStrip_object_edit.Items.Add(TB.L.Phrase["VectorEditor.Word.Edit"], Resources.edit);
contextMenuStrip_object_edit.Items.Add(TB.L.Phrase["VectorEditor.Word.Delete"], Resources.delete);
for (int ii = 0; ii <= contextMenuStrip_object_edit.Items.Count - 1; ii++)
{
contextMenuStrip_object_edit.Items[ii].ForeColor = Color.FromKnownColor(KnownColor.ControlText);
contextMenuStrip_object_edit.Items[ii].BackColor = Color.FromKnownColor(KnownColor.MenuHighlight);
}
contextMenuStrip_object_edit.Show(pictureBox1, a);
}
Render();
}
else
{
main.BorderPen = Pens.Black;
panel_docsettings.Visible = false;
}
for (int i = 0; i <= main.Items.Count - 1; i++)
{
if (main.Items[i].GrPath.IsOutlineVisible(a.X / zoom, a.Y / zoom, p))
{
globalsel = true;
listBox1.SelectedItem = listBox1.Items[i];
panel_angle.Visible = true;
trackBar_angle.Value = (int)main.Items[i].Angle;
label_text_anglevalue.Text = trackBar_angle.Value.ToString() + ".";
if (e.Button == MouseButtons.Right)
{
contextMenuStrip_object_edit.Items.Clear();
contextMenuStrip_object_edit.Items.Add(TB.L.Phrase["VectorEditor.Word.Edit"], Resources.edit);
contextMenuStrip_object_edit.Items.Add(TB.L.Phrase["VectorEditor.Word.Clone"], Resources.add);
contextMenuStrip_object_edit.Items.Add(TB.L.Phrase["VectorEditor.Word.Delete"], Resources.delete);
for (int ii = 0; ii <= contextMenuStrip_object_edit.Items.Count-1; ii++)
{
contextMenuStrip_object_edit.Items[ii].ForeColor = Color.FromKnownColor(KnownColor.ControlText);
contextMenuStrip_object_edit.Items[ii].BackColor = Color.FromKnownColor(KnownColor.MenuHighlight);
}
contextMenuStrip_object_edit.Show(pictureBox1, a);
}
return;
}
}
panel_angle.Visible = false;
listBox1.SelectedIndex = -1;
if (main != null) Render();
globalsel = false;
}
}
private void contextMenuStrip_object_edit_Click(object sender, EventArgs e)
{
int selindex = -1;
for (int i = 0; i <= contextMenuStrip_object_edit.Items.Count - 1; i++)
{
if(contextMenuStrip_object_edit.Items[i].Selected)
{
selindex = i;
break;
}
}
if (selindex != -1)
{
if (contextMenuStrip_object_edit.Items.Count == 3)
{
switch (selindex)
{
case (0):
button_edit_Click(null, null);
break;
case (1):
break;
case (2):
button1_Click(null, null);
break;
}
}
else
{
switch (selindex)
{
case (0):
textBox_fileinfo.Text = main.FileName;
textBox_fileautor.Text = main.FileAutor;
richTextBox_filediscr.Text = main.FileDescr;
checkBox_useborder.Checked = main.Border.Use;
comboBox_bordstyle.Text = main.Border.Style.ToString();
textBox_bordoffset.Text = main.Border.Offset.ToString(CultureInfo.InvariantCulture);
panel_docsettings.Visible = true;
break;
case (1):
main.Border.Use = false;
Render();
break;
}
}
}
}
private void button_angle_0deg_Click(object sender, EventArgs e)
{
trackBar_angle.Value = 0;
trackBar1_Scroll_1(null, null);
}
private void button_angle_p90deg_Click(object sender, EventArgs e)
{
int a = trackBar_angle.Value;
if (-180 <= a && a < -90) trackBar_angle.Value = -90;
else if (-90 <= a && a < 0) trackBar_angle.Value = 0;
else if (0 <= a && a < 90) trackBar_angle.Value = 90;
else if (90 <= a && a < 180) trackBar_angle.Value = 180;
else if (a == 180) trackBar_angle.Value = -90;
trackBar1_Scroll_1(null, null);
}
private void button_angle_m90deg_Click(object sender, EventArgs e)
{
int a = trackBar_angle.Value;
if (-180 < a && a <= -90) trackBar_angle.Value = -180;
else if (-90 < a && a <= 0) trackBar_angle.Value = -90;
else if (0 < a && a <= 90) trackBar_angle.Value = 0;
else if (90 < a && a <= 180) trackBar_angle.Value = 90;
else if (a == -180) trackBar_angle.Value = 90;
trackBar1_Scroll_1(null, null);
}
private void button_loaddata_load_Click(object sender, EventArgs e)
{
}
private void trackBar1_Scroll_1(object sender, EventArgs e)
{
label_text_anglevalue.Text = trackBar_angle.Value.ToString() + ".";
main.Items[listBox1.SelectedIndex].Angle = trackBar_angle.Value;
main.Items[listBox1.SelectedIndex].PreRender();
Matrix m = new Matrix();
m.RotateAt(main.Items[listBox1.SelectedIndex].Angle/2, new PointF(main.Items[listBox1.SelectedIndex].Size.Width / 2 + main.Items[listBox1.SelectedIndex].Position.X, main.Items[listBox1.SelectedIndex].Size.Height / 2 + main.Items[listBox1.SelectedIndex].Position.Y));
main.Items[listBox1.SelectedIndex].GrPath.Transform(m);
Render();
}
private void Form_editvector_KeyDown(object sender, KeyEventArgs e)
{
cntr_pressed = e.Control;
if (cntr_pressed)
{
scrpoint = panel4.AutoScrollPosition;
}
}
private void Form_editvector_KeyUp(object sender, KeyEventArgs e)
{
cntr_pressed = e.Control;
}
private void richTextBox_texteditor_text_TextChanged(object sender, EventArgs e)
{
SizeF size =Graphics.FromImage(pictureBox1.Image).MeasureString(richTextBox_texteditor_text.Text, fontDialog1.Font);
textBox_text_width.Text = (size.Width*0.75 - 5).ToString(CultureInfo.InvariantCulture);
textBox_text_height.Text = size.Height.ToString(CultureInfo.InvariantCulture);
RenderSampleText();
}
private void button_pickfont_Click(object sender, EventArgs e)
{
var a = fontDialog1.ShowDialog();
if(a == DialogResult.OK)
{
RenderSampleText();
}
}
}
}
| |
// 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.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
#if SRM
namespace System.Reflection.Metadata.Decoding
#else
namespace Roslyn.Reflection.Metadata.Decoding
#endif
{
/// <summary>
/// Decodes signature blobs.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
#if SRM
public
#endif
struct SignatureDecoder<TType>
{
private readonly ISignatureTypeProvider<TType> _provider;
private readonly MetadataReader _metadataReaderOpt;
private readonly SignatureDecoderOptions _options;
/// <summary>
/// Creates a new SignatureDecoder.
/// </summary>
/// <param name="provider">The provider used to obtain type symbols as the signature is decoded.</param>
/// <param name="metadataReader">
/// The metadata reader from which the signature was obtained. It may be null if the given provider allows it.
/// However, if <see cref="SignatureDecoderOptions.DifferentiateClassAndValueTypes"/> is specified, it should
/// be non-null to evaluate WinRT projections from class to value type or vice-versa correctly.
/// </param>
/// <param name="options">Set of optional decoder features to enable.</param>
public SignatureDecoder(
ISignatureTypeProvider<TType> provider,
MetadataReader metadataReader = null,
SignatureDecoderOptions options = SignatureDecoderOptions.None)
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
}
_metadataReaderOpt = metadataReader;
_provider = provider;
_options = options;
}
/// <summary>
/// Decodes a type embedded in a signature and advances the reader past the type.
/// </summary>
/// <param name="blobReader">The blob reader positioned at the leading SignatureTypeCode</param>
/// <param name="allowTypeSpecifications">Allow a <see cref="TypeSpecificationHandle"/> to follow a (CLASS | VALUETYPE) in the signature.
/// At present, the only context where that would be valid is in a LocalConstantSig as defined by the Portable PDB specification.
/// </param>
/// <returns>The decoded type.</returns>
/// <exception cref="System.BadImageFormatException">The reader was not positioned at a valid signature type.</exception>
public TType DecodeType(ref BlobReader blobReader, bool allowTypeSpecifications = false)
{
return DecodeType(ref blobReader, allowTypeSpecifications, blobReader.ReadCompressedInteger());
}
private TType DecodeType(ref BlobReader blobReader, bool allowTypeSpecifications, int typeCode)
{
TType elementType;
int index;
switch (typeCode)
{
case (int)SignatureTypeCode.Boolean:
case (int)SignatureTypeCode.Char:
case (int)SignatureTypeCode.SByte:
case (int)SignatureTypeCode.Byte:
case (int)SignatureTypeCode.Int16:
case (int)SignatureTypeCode.UInt16:
case (int)SignatureTypeCode.Int32:
case (int)SignatureTypeCode.UInt32:
case (int)SignatureTypeCode.Int64:
case (int)SignatureTypeCode.UInt64:
case (int)SignatureTypeCode.Single:
case (int)SignatureTypeCode.Double:
case (int)SignatureTypeCode.IntPtr:
case (int)SignatureTypeCode.UIntPtr:
case (int)SignatureTypeCode.Object:
case (int)SignatureTypeCode.String:
case (int)SignatureTypeCode.Void:
case (int)SignatureTypeCode.TypedReference:
return _provider.GetPrimitiveType((PrimitiveTypeCode)typeCode);
case (int)SignatureTypeCode.Pointer:
elementType = DecodeType(ref blobReader);
return _provider.GetPointerType(elementType);
case (int)SignatureTypeCode.ByReference:
elementType = DecodeType(ref blobReader);
return _provider.GetByReferenceType(elementType);
case (int)SignatureTypeCode.Pinned:
elementType = DecodeType(ref blobReader);
return _provider.GetPinnedType(elementType);
case (int)SignatureTypeCode.SZArray:
elementType = DecodeType(ref blobReader);
return _provider.GetSZArrayType(elementType);
case (int)SignatureTypeCode.FunctionPointer:
MethodSignature<TType> methodSignature = DecodeMethodSignature(ref blobReader);
return _provider.GetFunctionPointerType(methodSignature);
case (int)SignatureTypeCode.Array:
return DecodeArrayType(ref blobReader);
case (int)SignatureTypeCode.RequiredModifier:
return DecodeModifiedType(ref blobReader, isRequired: true);
case (int)SignatureTypeCode.OptionalModifier:
return DecodeModifiedType(ref blobReader, isRequired: false);
case (int)SignatureTypeCode.GenericTypeInstance:
return DecodeGenericTypeInstance(ref blobReader);
case (int)SignatureTypeCode.GenericTypeParameter:
index = blobReader.ReadCompressedInteger();
return _provider.GetGenericTypeParameter(index);
case (int)SignatureTypeCode.GenericMethodParameter:
index = blobReader.ReadCompressedInteger();
return _provider.GetGenericMethodParameter(index);
case (int)SignatureTypeHandleCode.Class:
case (int)SignatureTypeHandleCode.ValueType:
return DecodeTypeHandle(ref blobReader, (SignatureTypeHandleCode)typeCode, allowTypeSpecifications);
default:
#if SRM
throw new BadImageFormatException(SR.Format(SR.UnexpectedSignatureTypeCode, typeCode));
#else
throw new BadImageFormatException();
#endif
}
}
/// <summary>
/// Decodes a list of types, with at least one instance that is preceded by its count as a compressed integer.
/// </summary>
private ImmutableArray<TType> DecodeTypeSequence(ref BlobReader blobReader)
{
int count = blobReader.ReadCompressedInteger();
if (count == 0)
{
// This method is used for Local signatures and method specs, neither of which can have
// 0 elements. Parameter sequences can have 0 elements, but they are handled separately
// to deal with the sentinel/varargs case.
#if SRM
throw new BadImageFormatException(SR.SignatureTypeSequenceMustHaveAtLeastOneElement);
#else
throw new BadImageFormatException();
#endif
}
var types = ImmutableArray.CreateBuilder<TType>(count);
for (int i = 0; i < count; i++)
{
types.Add(DecodeType(ref blobReader));
}
return types.MoveToImmutable();
}
/// <summary>
/// Decodes a method (definition, reference, or standalone) or property signature blob.
/// </summary>
/// <param name="blobReader">BlobReader positioned at a method signature.</param>
/// <returns>The decoded method signature.</returns>
/// <exception cref="System.BadImageFormatException">The method signature is invalid.</exception>
public MethodSignature<TType> DecodeMethodSignature(ref BlobReader blobReader)
{
SignatureHeader header = blobReader.ReadSignatureHeader();
CheckMethodOrPropertyHeader(header);
int genericParameterCount = 0;
if (header.IsGeneric)
{
genericParameterCount = blobReader.ReadCompressedInteger();
}
int parameterCount = blobReader.ReadCompressedInteger();
TType returnType = DecodeType(ref blobReader);
ImmutableArray<TType> parameterTypes;
int requiredParameterCount;
if (parameterCount == 0)
{
requiredParameterCount = 0;
parameterTypes = ImmutableArray<TType>.Empty;
}
else
{
var parameterBuilder = ImmutableArray.CreateBuilder<TType>(parameterCount);
int parameterIndex;
for (parameterIndex = 0; parameterIndex < parameterCount; parameterIndex++)
{
int typeCode = blobReader.ReadCompressedInteger();
if (typeCode == (int)SignatureTypeCode.Sentinel)
{
break;
}
parameterBuilder.Add(DecodeType(ref blobReader, allowTypeSpecifications: false, typeCode: typeCode));
}
requiredParameterCount = parameterIndex;
for (; parameterIndex < parameterCount; parameterIndex++)
{
parameterBuilder.Add(DecodeType(ref blobReader));
}
parameterTypes = parameterBuilder.MoveToImmutable();
}
return new MethodSignature<TType>(header, returnType, requiredParameterCount, genericParameterCount, parameterTypes);
}
/// <summary>
/// Decodes a method specification signature blob and advances the reader past the signature.
/// </summary>
/// <param name="blobReader">A BlobReader positioned at a valid method specification signature.</param>
/// <returns>The types used to instantiate a generic method via the method specification.</returns>
public ImmutableArray<TType> DecodeMethodSpecificationSignature(ref BlobReader blobReader)
{
SignatureHeader header = blobReader.ReadSignatureHeader();
CheckHeader(header, SignatureKind.MethodSpecification);
return DecodeTypeSequence(ref blobReader);
}
/// <summary>
/// Decodes a local variable signature blob and advances the reader past the signature.
/// </summary>
/// <param name="blobReader">The blob reader positioned at a local variable signature.</param>
/// <returns>The local variable types.</returns>
/// <exception cref="System.BadImageFormatException">The local variable signature is invalid.</exception>
public ImmutableArray<TType> DecodeLocalSignature(ref BlobReader blobReader)
{
SignatureHeader header = blobReader.ReadSignatureHeader();
CheckHeader(header, SignatureKind.LocalVariables);
return DecodeTypeSequence(ref blobReader);
}
/// <summary>
/// Decodes a field signature blob and advances the reader past the signature.
/// </summary>
/// <param name="blobReader">The blob reader positioned at a field signature.</param>
/// <returns>The decoded field type.</returns>
public TType DecodeFieldSignature(ref BlobReader blobReader)
{
SignatureHeader header = blobReader.ReadSignatureHeader();
CheckHeader(header, SignatureKind.Field);
return DecodeType(ref blobReader);
}
private TType DecodeArrayType(ref BlobReader blobReader)
{
// PERF_TODO: Cache/reuse common case of small number of all-zero lower-bounds.
TType elementType = DecodeType(ref blobReader);
int rank = blobReader.ReadCompressedInteger();
var sizes = ImmutableArray<int>.Empty;
var lowerBounds = ImmutableArray<int>.Empty;
int sizesCount = blobReader.ReadCompressedInteger();
if (sizesCount > 0)
{
var builder = ImmutableArray.CreateBuilder<int>(sizesCount);
for (int i = 0; i < sizesCount; i++)
{
builder.Add(blobReader.ReadCompressedInteger());
}
sizes = builder.MoveToImmutable();
}
int lowerBoundsCount = blobReader.ReadCompressedInteger();
if (lowerBoundsCount > 0)
{
var builder = ImmutableArray.CreateBuilder<int>(lowerBoundsCount);
for (int i = 0; i < lowerBoundsCount; i++)
{
builder.Add(blobReader.ReadCompressedSignedInteger());
}
lowerBounds = builder.MoveToImmutable();
}
var arrayShape = new ArrayShape(rank, sizes, lowerBounds);
return _provider.GetArrayType(elementType, arrayShape);
}
private TType DecodeGenericTypeInstance(ref BlobReader blobReader)
{
TType genericType = DecodeType(ref blobReader);
ImmutableArray<TType> types = DecodeTypeSequence(ref blobReader);
return _provider.GetGenericInstance(genericType, types);
}
private TType DecodeModifiedType(ref BlobReader blobReader, bool isRequired)
{
TType modifier = DecodeTypeHandle(ref blobReader, SignatureTypeHandleCode.Unresolved, allowTypeSpecifications: true);
TType unmodifiedType = DecodeType(ref blobReader);
return _provider.GetModifiedType(_metadataReaderOpt, isRequired, modifier, unmodifiedType);
}
private TType DecodeTypeHandle(ref BlobReader blobReader, SignatureTypeHandleCode code, bool allowTypeSpecifications)
{
// Force no differentiation of class vs. value type unless the option is enabled.
// Avoids cost of WinRT projection.
if ((_options & SignatureDecoderOptions.DifferentiateClassAndValueTypes) == 0)
{
code = SignatureTypeHandleCode.Unresolved;
}
EntityHandle handle = blobReader.ReadTypeHandle();
if (!handle.IsNil)
{
switch (handle.Kind)
{
case HandleKind.TypeDefinition:
var typeDef = (TypeDefinitionHandle)handle;
return _provider.GetTypeFromDefinition(_metadataReaderOpt, typeDef, code);
case HandleKind.TypeReference:
var typeRef = (TypeReferenceHandle)handle;
if (code != SignatureTypeHandleCode.Unresolved)
{
ProjectClassOrValueType(typeRef, ref code);
}
return _provider.GetTypeFromReference(_metadataReaderOpt, typeRef, code);
case HandleKind.TypeSpecification:
if (!allowTypeSpecifications)
{
#if SRM
// To prevent cycles, the token following (CLASS | VALUETYPE) must not be a type spec.
// https://github.com/dotnet/coreclr/blob/8ff2389204d7c41b17eff0e9536267aea8d6496f/src/md/compiler/mdvalidator.cpp#L6154-L6160
throw new BadImageFormatException(SR.NotTypeDefOrRefHandle);
#else
throw new BadImageFormatException();
#endif
}
if (code != SignatureTypeHandleCode.Unresolved)
{
// TODO: We need more work here in differentiating case because instantiations can project class
// to value type as in IReference<T> -> Nullable<T>. Unblocking Roslyn work where the differentiation
// feature is not used. Note that the use-case of custom-mods will not hit this because there is no
// CLASS | VALUETYPE before the modifier token and so it always comes in unresolved.
code = SignatureTypeHandleCode.Unresolved; // never lie in the meantime.
}
var typeSpec = (TypeSpecificationHandle)handle;
return _provider.GetTypeFromSpecification(_metadataReaderOpt, typeSpec, SignatureTypeHandleCode.Unresolved);
default:
// indicates an error returned from ReadTypeHandle, otherwise unreachable.
Debug.Assert(handle.IsNil); // will fall through to throw in release.
break;
}
}
#if SRM
throw new BadImageFormatException(SR.NotTypeDefOrRefOrSpecHandle);
#else
throw new BadImageFormatException();
#endif
}
private void ProjectClassOrValueType(TypeReferenceHandle handle, ref SignatureTypeHandleCode code)
{
Debug.Assert(code != SignatureTypeHandleCode.Unresolved);
Debug.Assert((_options & SignatureDecoderOptions.DifferentiateClassAndValueTypes) != 0);
if (_metadataReaderOpt == null)
{
// If we're asked to differentiate value types without a reader, then
// return the designation unprojected as it occurs in the signature blob.
return;
}
#if SRM
TypeReference typeRef = _metadataReaderOpt.GetTypeReference(handle);
switch (typeRef.SignatureTreatment)
{
case TypeRefSignatureTreatment.ProjectedToClass:
code = SignatureTypeHandleCode.Class;
break;
case TypeRefSignatureTreatment.ProjectedToValueType:
code = SignatureTypeHandleCode.ValueType;
break;
}
#endif
}
private void CheckHeader(SignatureHeader header, SignatureKind expectedKind)
{
if (header.Kind != expectedKind)
{
#if SRM
throw new BadImageFormatException(SR.Format(SR.UnexpectedSignatureHeader, expectedKind, header.Kind, header.RawValue));
#else
throw new BadImageFormatException();
#endif
}
}
private void CheckMethodOrPropertyHeader(SignatureHeader header)
{
SignatureKind kind = header.Kind;
if (kind != SignatureKind.Method && kind != SignatureKind.Property)
{
#if SRM
throw new BadImageFormatException(SR.Format(SR.UnexpectedSignatureHeader2, SignatureKind.Property, SignatureKind.Method, header.Kind, header.RawValue));
#else
throw new BadImageFormatException();
#endif
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cocos2D;
using tests.Clipping;
using tests.FontTest;
using tests.Extensions;
using tests.classes.tests.Box2DTestBet;
using Box2D.TestBed;
namespace tests
{
public class TestController : CCLayer
{
static int LINE_SPACE = 40;
static CCPoint s_tCurPos = new CCPoint(0.0f, 0.0f);
private CCGamePadButtonDelegate _GamePadButtonDelegate;
private CCGamePadDPadDelegate _GamePadDPadDelegate;
private List<CCMenuItem> _Items = new List<CCMenuItem>();
private int _CurrentItemIndex = 0;
private CCSprite _menuIndicator;
public TestController()
{
// add close menu
var pCloseItem = new CCMenuItemImage(TestResource.s_pPathClose, TestResource.s_pPathClose, closeCallback);
var pMenu = new CCMenu(pCloseItem);
var s = CCDirector.SharedDirector.WinSize;
#if !XBOX && !OUYA
TouchEnabled = true;
#else
GamePadEnabled = true;
KeypadEnabled = true;
#endif
#if WINDOWS || WINDOWSGL || MACOS
GamePadEnabled = true;
#endif
pMenu.Position = CCPoint.Zero;
pCloseItem.Position = new CCPoint(s.Width - 30, s.Height - 30);
#if !PSM && !WINDOWS_PHONE
#if NETFX_CORE
CCLabelTTF versionLabel = new CCLabelTTF("v" + this.GetType().GetAssemblyName().Version.ToString(), "arial", 12);
#else
CCLabelTTF versionLabel = new CCLabelTTF("v" + this.GetType().Assembly.GetName().Version.ToString(), "arial", 12);
#endif
versionLabel.Position = new CCPoint(versionLabel.ContentSizeInPixels.Width/2f, s.Height - 18f);
versionLabel.HorizontalAlignment = CCTextAlignment.Left;
AddChild(versionLabel, 20000);
#endif
// add menu items for tests
m_pItemMenu = new CCMenu();
for (int i = 0; i < (int)(TestCases.TESTS_COUNT); ++i)
{
var label = new CCLabelTTF(Tests.g_aTestNames[i], "arial", 24);
var pMenuItem = new CCMenuItemLabel(label, menuCallback);
pMenuItem.UserData = i;
m_pItemMenu.AddChild(pMenuItem, 10000);
#if XBOX || OUYA
pMenuItem.Position = new CCPoint(s.Width / 2, -(i + 1) * LINE_SPACE);
#else
pMenuItem.Position = new CCPoint(s.Width / 2, (s.Height - (i + 1) * LINE_SPACE));
#endif
_Items.Add(pMenuItem);
}
m_pItemMenu.ContentSize = new CCSize(s.Width, ((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE);
#if XBOX || OUYA
CCSprite sprite = new CCSprite("Images/aButton");
AddChild(sprite, 10001);
_menuIndicator = sprite;
// Center the menu on the first item so that it is
// in the center of the screen
_HomePosition = new CCPoint(0f, s.Height / 2f + LINE_SPACE / 2f);
_LastPosition = new CCPoint(0f, _HomePosition.Y - (_Items.Count - 1) * LINE_SPACE);
#else
_HomePosition = s_tCurPos;
#endif
m_pItemMenu.Position = _HomePosition;
AddChild(m_pItemMenu);
AddChild(pMenu, 1);
_GamePadDPadDelegate = new CCGamePadDPadDelegate(MyOnGamePadDPadUpdate);
_GamePadButtonDelegate = new CCGamePadButtonDelegate(MyOnGamePadButtonUpdate);
// set the first one to have the selection highlight
_CurrentItemIndex = 0;
SelectMenuItem();
}
private CCPoint _HomePosition;
private CCPoint _LastPosition;
private void SelectMenuItem()
{
_Items[_CurrentItemIndex].Selected();
if (_menuIndicator != null)
{
_menuIndicator.Position = new CCPoint(
m_pItemMenu.Position.X + _Items[_CurrentItemIndex].Position.X - _Items[_CurrentItemIndex].ContentSizeInPixels.Width / 2f - _menuIndicator.ContentSizeInPixels.Width / 2f - 5f,
m_pItemMenu.Position.Y + _Items[_CurrentItemIndex].Position.Y
);
}
}
private void NextMenuItem()
{
_Items[_CurrentItemIndex].Unselected();
_CurrentItemIndex = (_CurrentItemIndex + 1) % _Items.Count;
CCSize winSize = CCDirector.SharedDirector.WinSize;
m_pItemMenu.Position = (new CCPoint(0, _HomePosition.Y + _CurrentItemIndex * LINE_SPACE));
s_tCurPos = m_pItemMenu.Position;
SelectMenuItem();
}
private void PreviousMenuItem()
{
_Items[_CurrentItemIndex].Unselected();
_CurrentItemIndex--;
if(_CurrentItemIndex < 0) {
_CurrentItemIndex = _Items.Count - 1;
}
CCSize winSize = CCDirector.SharedDirector.WinSize;
m_pItemMenu.Position = (new CCPoint(0, _HomePosition.Y + _CurrentItemIndex * LINE_SPACE));
s_tCurPos = m_pItemMenu.Position;
SelectMenuItem();
}
public override void OnExit()
{
base.OnExit();
CCApplication.SharedApplication.GamePadDPadUpdate -= _GamePadDPadDelegate;
CCApplication.SharedApplication.GamePadButtonUpdate -= _GamePadButtonDelegate;
}
public override void OnEnter()
{
base.OnEnter();
CCApplication.SharedApplication.GamePadDPadUpdate += _GamePadDPadDelegate;
CCApplication.SharedApplication.GamePadButtonUpdate += _GamePadButtonDelegate;
}
private bool _aButtonWasPressed = false;
private void MyOnGamePadButtonUpdate(CCGamePadButtonStatus backButton, CCGamePadButtonStatus startButton, CCGamePadButtonStatus systemButton, CCGamePadButtonStatus aButton, CCGamePadButtonStatus bButton, CCGamePadButtonStatus xButton, CCGamePadButtonStatus yButton, CCGamePadButtonStatus leftShoulder, CCGamePadButtonStatus rightShoulder, Microsoft.Xna.Framework.PlayerIndex player)
{
if (aButton == CCGamePadButtonStatus.Pressed)
{
_aButtonWasPressed = true;
}
else if (aButton == CCGamePadButtonStatus.Released && _aButtonWasPressed)
{
// Select the menu
_Items[_CurrentItemIndex].Activate();
_Items[_CurrentItemIndex].Unselected();
}
}
private long _FirstTicks;
private bool _bDownPress = false;
private bool _bUpPress = false;
private void MyOnGamePadDPadUpdate(CCGamePadButtonStatus leftButton, CCGamePadButtonStatus upButton, CCGamePadButtonStatus rightButton, CCGamePadButtonStatus downButton, Microsoft.Xna.Framework.PlayerIndex player)
{
// Down and Up only
if (downButton == CCGamePadButtonStatus.Pressed)
{
if (_FirstTicks == 0L)
{
_FirstTicks = DateTime.Now.Ticks;
_bDownPress = true;
}
}
else if (downButton == CCGamePadButtonStatus.Released && _FirstTicks > 0L && _bDownPress)
{
_FirstTicks = 0L;
NextMenuItem();
_bDownPress = false;
}
if (upButton == CCGamePadButtonStatus.Pressed)
{
if (_FirstTicks == 0L)
{
_FirstTicks = DateTime.Now.Ticks;
_bUpPress = true;
}
}
else if (upButton == CCGamePadButtonStatus.Released && _FirstTicks > 0L && _bUpPress)
{
_FirstTicks = 0L;
PreviousMenuItem();
_bUpPress = false;
}
}
~TestController()
{
}
public void menuCallback(object pSender)
{
// get the userdata, it's the index of the menu item clicked
CCMenuItem pMenuItem = (CCMenuItem)(pSender);
int nIdx = (int)pMenuItem.UserData;
// create the test scene and run it
TestScene pScene = CreateTestScene(nIdx);
if (pScene != null)
{
CCApplication.SharedApplication.GamePadDPadUpdate -= _GamePadDPadDelegate;
CCApplication.SharedApplication.GamePadButtonUpdate -= _GamePadButtonDelegate;
pScene.runThisTest();
}
}
public void closeCallback(object pSender)
{
CCDirector.SharedDirector.End();
CCApplication.SharedApplication.Game.Exit();
}
public override void TouchesBegan(List<CCTouch> pTouches)
{
CCTouch touch = pTouches.FirstOrDefault();
m_tBeginPos = touch.Location;
}
public override void TouchesMoved(List<CCTouch> pTouches)
{
CCTouch touch = pTouches.FirstOrDefault();
var touchLocation = touch.Location;
float nMoveY = touchLocation.Y - m_tBeginPos.Y;
CCPoint curPos = m_pItemMenu.Position;
CCPoint nextPos = new CCPoint(curPos.X, curPos.Y + nMoveY);
CCSize winSize = CCDirector.SharedDirector.WinSize;
if (nextPos.Y < 0.0f)
{
m_pItemMenu.Position = new CCPoint(0, 0);
return;
}
if (nextPos.Y > (((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE - winSize.Height))
{
m_pItemMenu.Position = (new CCPoint(0, (((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE - winSize.Height)));
return;
}
m_pItemMenu.Position = nextPos;
m_tBeginPos = touchLocation;
s_tCurPos = nextPos;
}
public static TestScene CreateTestScene(int nIdx)
{
CCDirector.SharedDirector.PurgeCachedData();
TestScene pScene = null;
switch (nIdx)
{
case (int)TestCases.TEST_ACTIONS:
pScene = new ActionsTestScene(); break;
case (int)TestCases.TEST_TRANSITIONS:
pScene = new TransitionsTestScene(); break;
case (int)TestCases.TEST_PROGRESS_ACTIONS:
pScene = new ProgressActionsTestScene(); break;
case (int)TestCases.TEST_EFFECTS:
pScene = new EffectTestScene(); break;
case (int)TestCases.TEST_CLICK_AND_MOVE:
pScene = new ClickAndMoveTest(); break;
case (int)TestCases.TEST_ROTATE_WORLD:
pScene = new RotateWorldTestScene(); break;
case (int)TestCases.TEST_PARTICLE:
pScene = new ParticleTestScene(); break;
case (int)TestCases.TEST_EASE_ACTIONS:
pScene = new EaseActionsTestScene(); break;
case (int)TestCases.TEST_MOTION_STREAK:
pScene = new MotionStreakTestScene(); break;
case (int)TestCases.TEST_DRAW_PRIMITIVES:
pScene = new DrawPrimitivesTestScene(); break;
case (int)TestCases.TEST_COCOSNODE:
pScene = new CocosNodeTestScene(); break;
case (int)TestCases.TEST_TOUCHES:
pScene = new PongScene(); break;
case (int)TestCases.TEST_MENU:
pScene = new MenuTestScene(); break;
case (int)TestCases.TEST_ACTION_MANAGER:
pScene = new ActionManagerTestScene(); break;
case (int)TestCases.TEST_LAYER:
pScene = new LayerTestScene(); break;
case (int)TestCases.TEST_SCENE:
pScene = new SceneTestScene(); break;
case (int)TestCases.TEST_PARALLAX:
pScene = new ParallaxTestScene(); break;
case (int)TestCases.TEST_TILE_MAP:
pScene = new TileMapTestScene(); break;
case (int)TestCases.TEST_INTERVAL:
pScene = new IntervalTestScene(); break;
// case TEST_CHIPMUNK:
//#if (CC_TARGET_PLATFORM != CC_PLATFORM_AIRPLAY)
// pScene = new ChipmunkTestScene(); break;
//#else
//#ifdef AIRPLAYUSECHIPMUNK
//#if (AIRPLAYUSECHIPMUNK == 1)
// pScene = new ChipmunkTestScene(); break;
//#endif
//#endif
//#endif
case (int)TestCases.TEST_LABEL:
pScene = new AtlasTestScene(); break;
case (int)TestCases.TEST_TEXT_INPUT:
pScene = new TextInputTestScene(); break;
case (int)TestCases.TEST_SPRITE:
pScene = new SpriteTestScene(); break;
case (int)TestCases.TEST_SCHEDULER:
pScene = new SchedulerTestScene(); break;
case (int)TestCases.TEST_RENDERTEXTURE:
pScene = new RenderTextureScene(); break;
case (int)TestCases.TEST_TEXTURE2D:
pScene = new TextureTestScene(); break;
case (int)TestCases.TEST_BOX2D:
pScene = new Box2DTestScene(); break;
case (int)TestCases.TEST_BOX2DBED:
pScene = new tests.classes.tests.Box2DTestBet.Box2dTestBedScene(); break;
case (int)TestCases.TEST_BOX2DBED2:
pScene = new Box2D.TestBed.Box2dTestBedScene(); break;
case (int)TestCases.TEST_EFFECT_ADVANCE:
pScene = new EffectAdvanceScene(); break;
case (int)TestCases.TEST_ACCELEROMRTER:
pScene = new AccelerometerTestScene(); break;
// case TEST_KEYPAD:
// pScene = new KeypadTestScene(); break;
case (int)TestCases.TEST_COCOSDENSHION:
pScene = new CocosDenshionTestScene(); break;
case (int)TestCases.TEST_PERFORMANCE:
pScene = new PerformanceTestScene(); break;
case (int)TestCases.TEST_ZWOPTEX:
pScene = new ZwoptexTestScene(); break;
//#if (CC_TARGET_PLATFORM != CC_PLATFORM_AIRPLAY)
// case TEST_CURL:
// pScene = new CurlTestScene(); break;
//case (int)TestCases.TEST_USERDEFAULT:
// pScene = new UserDefaultTestScene(); break;
//#endif
// case TEST_BUGS:
// pScene = new BugsTestScene(); break;
//#if (CC_TARGET_PLATFORM != CC_PLATFORM_AIRPLAY)
case (int)TestCases.TEST_FONTS:
pScene = new FontTestScene(); break;
#if IPHONE || IOS || MACOS || WINDOWSGL || WINDOWS || (ANDROID && !OUYA) || NETFX_CORE
case (int)TestCases.TEST_SYSTEM_FONTS:
pScene = new SystemFontTestScene(); break;
#endif
// case TEST_CURRENT_LANGUAGE:
// pScene = new CurrentLanguageTestScene(); break;
// break;
//#endif
case (int)TestCases.TEST_CLIPPINGNODE:
pScene = new ClippingNodeTestScene();
break;
case (int)TestCases.TEST_EXTENSIONS:
pScene = new ExtensionsTestScene();
break;
case (int)TestCases.TEST_ORIENTATION:
pScene = new OrientationTestScene();
break;
case(int)TestCases.TEST_MULTITOUCH:
pScene = new MultiTouchTestScene();
break;
default:
break;
}
return pScene;
}
private CCPoint m_tBeginPos;
private CCMenu m_pItemMenu;
}
}
| |
/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
using ZXing.Common.ReedSolomon;
namespace ZXing.Aztec.Internal
{
/// <summary>
/// The main class which implements Aztec Code decoding -- as opposed to locating and extracting
/// the Aztec Code from an image.
/// </summary>
/// <author>David Olivier</author>
internal sealed class Decoder
{
private enum Table
{
UPPER,
LOWER,
MIXED,
DIGIT,
PUNCT,
BINARY
}
private static readonly String[] UPPER_TABLE =
{
"CTRL_PS", " ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "CTRL_LL", "CTRL_ML", "CTRL_DL", "CTRL_BS"
};
private static readonly String[] LOWER_TABLE =
{
"CTRL_PS", " ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
"q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "CTRL_US", "CTRL_ML", "CTRL_DL", "CTRL_BS"
};
private static readonly String[] MIXED_TABLE =
{
"CTRL_PS", " ", "\x1", "\x2", "\x3", "\x4", "\x5", "\x6", "\x7", "\b", "\t", "\n",
"\xD", "\f", "\r", "\x21", "\x22", "\x23", "\x24", "\x25", "@", "\\", "^", "_",
"`", "|", "~", "\xB1", "CTRL_LL", "CTRL_UL", "CTRL_PL", "CTRL_BS"
};
private static readonly String[] PUNCT_TABLE =
{
"", "\r", "\r\n", ". ", ", ", ": ", "!", "\"", "#", "$", "%", "&", "'", "(", ")",
"*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "]", "{", "}", "CTRL_UL"
};
private static readonly String[] DIGIT_TABLE =
{
"CTRL_PS", " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", ".", "CTRL_UL", "CTRL_US"
};
private static readonly IDictionary<Table, String[]> codeTables = new Dictionary<Table, String[]>
{
{Table.UPPER, UPPER_TABLE},
{Table.LOWER, LOWER_TABLE},
{Table.MIXED, MIXED_TABLE},
{Table.PUNCT, PUNCT_TABLE},
{Table.DIGIT, DIGIT_TABLE},
{Table.BINARY, null}
};
private static readonly IDictionary<char, Table> codeTableMap = new Dictionary<char, Table>
{
{'U', Table.UPPER},
{'L', Table.LOWER},
{'M', Table.MIXED},
{'P', Table.PUNCT},
{'D', Table.DIGIT},
{'B', Table.BINARY}
};
private AztecDetectorResult ddata;
/// <summary>
/// Decodes the specified detector result.
/// </summary>
/// <param name="detectorResult">The detector result.</param>
/// <returns></returns>
public DecoderResult decode(AztecDetectorResult detectorResult)
{
ddata = detectorResult;
BitMatrix matrix = detectorResult.Bits;
bool[] rawbits = extractBits(matrix);
if (rawbits == null)
return null;
bool[] correctedBits = correctBits(rawbits);
if (correctedBits == null)
return null;
String result = getEncodedData(correctedBits);
if (result == null)
return null;
return new DecoderResult(null, result, null, null);
}
// This method is used for testing the high-level encoder
public static String highLevelDecode(bool[] correctedBits)
{
return getEncodedData(correctedBits);
}
/// <summary>
/// Gets the string encoded in the aztec code bits
/// </summary>
/// <param name="correctedBits">The corrected bits.</param>
/// <returns>the decoded string</returns>
private static String getEncodedData(bool[] correctedBits)
{
var endIndex = correctedBits.Length;
var latchTable = Table.UPPER; // table most recently latched to
var shiftTable = Table.UPPER; // table to use for the next read
var strTable = UPPER_TABLE;
var result = new StringBuilder(20);
var index = 0;
while (index < endIndex)
{
if (shiftTable == Table.BINARY)
{
if (endIndex - index < 5)
{
break;
}
int length = readCode(correctedBits, index, 5);
index += 5;
if (length == 0)
{
if (endIndex - index < 11)
{
break;
}
length = readCode(correctedBits, index, 11) + 31;
index += 11;
}
for (int charCount = 0; charCount < length; charCount++)
{
if (endIndex - index < 8)
{
index = endIndex; // Force outer loop to exit
break;
}
int code = readCode(correctedBits, index, 8);
result.Append((char) code);
index += 8;
}
// Go back to whatever mode we had been in
shiftTable = latchTable;
strTable = codeTables[shiftTable];
}
else
{
int size = shiftTable == Table.DIGIT ? 4 : 5;
if (endIndex - index < size)
{
break;
}
int code = readCode(correctedBits, index, size);
index += size;
String str = getCharacter(strTable, code);
if (str.StartsWith("CTRL_"))
{
// Table changes
shiftTable = getTable(str[5]);
strTable = codeTables[shiftTable];
if (str[6] == 'L')
{
latchTable = shiftTable;
}
}
else
{
result.Append(str);
// Go back to whatever mode we had been in
shiftTable = latchTable;
strTable = codeTables[shiftTable];
}
}
}
return result.ToString();
}
/// <summary>
/// gets the table corresponding to the char passed
/// </summary>
/// <param name="t">The t.</param>
/// <returns></returns>
private static Table getTable(char t)
{
if (!codeTableMap.ContainsKey(t))
return codeTableMap['U'];
return codeTableMap[t];
}
/// <summary>
/// Gets the character (or string) corresponding to the passed code in the given table
/// </summary>
/// <param name="table">the table used</param>
/// <param name="code">the code of the character</param>
/// <returns></returns>
private static String getCharacter(String[] table, int code)
{
return table[code];
}
/// <summary>
///Performs RS error correction on an array of bits.
/// </summary>
/// <param name="rawbits">The rawbits.</param>
/// <returns>the corrected array</returns>
private bool[] correctBits(bool[] rawbits)
{
GenericGF gf;
int codewordSize;
if (ddata.NbLayers <= 2)
{
codewordSize = 6;
gf = GenericGF.AZTEC_DATA_6;
}
else if (ddata.NbLayers <= 8)
{
codewordSize = 8;
gf = GenericGF.AZTEC_DATA_8;
}
else if (ddata.NbLayers <= 22)
{
codewordSize = 10;
gf = GenericGF.AZTEC_DATA_10;
}
else
{
codewordSize = 12;
gf = GenericGF.AZTEC_DATA_12;
}
int numDataCodewords = ddata.NbDatablocks;
int numCodewords = rawbits.Length/codewordSize;
int offset = rawbits.Length%codewordSize;
int numECCodewords = numCodewords - numDataCodewords;
int[] dataWords = new int[numCodewords];
for (int i = 0; i < numCodewords; i++, offset += codewordSize)
{
dataWords[i] = readCode(rawbits, offset, codewordSize);
}
var rsDecoder = new ReedSolomonDecoder(gf);
if (!rsDecoder.decode(dataWords, numECCodewords))
return null;
// Now perform the unstuffing operation.
// First, count how many bits are going to be thrown out as stuffing
int mask = (1 << codewordSize) - 1;
int stuffedBits = 0;
for (int i = 0; i < numDataCodewords; i++)
{
int dataWord = dataWords[i];
if (dataWord == 0 || dataWord == mask)
{
return null;
}
else if (dataWord == 1 || dataWord == mask - 1)
{
stuffedBits++;
}
}
// Now, actually unpack the bits and remove the stuffing
bool[] correctedBits = new bool[numDataCodewords*codewordSize - stuffedBits];
int index = 0;
for (int i = 0; i < numDataCodewords; i++)
{
int dataWord = dataWords[i];
if (dataWord == 1 || dataWord == mask - 1)
{
// next codewordSize-1 bits are all zeros or all ones
SupportClass.Fill(correctedBits, index, index + codewordSize - 1, dataWord > 1);
index += codewordSize - 1;
}
else
{
for (int bit = codewordSize - 1; bit >= 0; --bit)
{
correctedBits[index++] = (dataWord & (1 << bit)) != 0;
}
}
}
if (index != correctedBits.Length)
return null;
return correctedBits;
}
/// <summary>
/// Gets the array of bits from an Aztec Code matrix
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns>the array of bits</returns>
private bool[] extractBits(BitMatrix matrix)
{
bool compact = ddata.Compact;
int layers = ddata.NbLayers;
int baseMatrixSize = compact ? 11 + layers*4 : 14 + layers*4; // not including alignment lines
int[] alignmentMap = new int[baseMatrixSize];
bool[] rawbits = new bool[totalBitsInLayer(layers, compact)];
if (compact)
{
for (int i = 0; i < alignmentMap.Length; i++)
{
alignmentMap[i] = i;
}
}
else
{
int matrixSize = baseMatrixSize + 1 + 2*((baseMatrixSize/2 - 1)/15);
int origCenter = baseMatrixSize/2;
int center = matrixSize/2;
for (int i = 0; i < origCenter; i++)
{
int newOffset = i + i/15;
alignmentMap[origCenter - i - 1] = center - newOffset - 1;
alignmentMap[origCenter + i] = center + newOffset + 1;
}
}
for (int i = 0, rowOffset = 0; i < layers; i++)
{
int rowSize = compact ? (layers - i)*4 + 9 : (layers - i)*4 + 12;
// The top-left most point of this layer is <low, low> (not including alignment lines)
int low = i*2;
// The bottom-right most point of this layer is <high, high> (not including alignment lines)
int high = baseMatrixSize - 1 - low;
// We pull bits from the two 2 x rowSize columns and two rowSize x 2 rows
for (int j = 0; j < rowSize; j++)
{
int columnOffset = j*2;
for (int k = 0; k < 2; k++)
{
// left column
rawbits[rowOffset + columnOffset + k] =
matrix[alignmentMap[low + k], alignmentMap[low + j]];
// bottom row
rawbits[rowOffset + 2*rowSize + columnOffset + k] =
matrix[alignmentMap[low + j], alignmentMap[high - k]];
// right column
rawbits[rowOffset + 4*rowSize + columnOffset + k] =
matrix[alignmentMap[high - k], alignmentMap[high - j]];
// top row
rawbits[rowOffset + 6*rowSize + columnOffset + k] =
matrix[alignmentMap[high - j], alignmentMap[low + k]];
}
}
rowOffset += rowSize*8;
}
return rawbits;
}
/// <summary>
/// Reads a code of given length and at given index in an array of bits
/// </summary>
/// <param name="rawbits">The rawbits.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="length">The length.</param>
/// <returns></returns>
private static int readCode(bool[] rawbits, int startIndex, int length)
{
int res = 0;
for (int i = startIndex; i < startIndex + length; i++)
{
res <<= 1;
if (rawbits[i])
{
res++;
}
}
return res;
}
private static int totalBitsInLayer(int layers, bool compact)
{
return ((compact ? 88 : 112) + 16*layers)*layers;
}
}
}
| |
/* This class has been written by
* Corinna John (Hannover, Germany)
* cj@binary-universe.net
*
* You may do with this code whatever you like,
* except selling it or claiming any rights/ownership.
*
* Please send me a little feedback about what you're
* using this code for and what changes you'd like to
* see in later versions. (And please excuse my bad english.)
*
* WARNING: This is experimental code.
* Please do not expect "Release Quality".
* */
using System;
using System.IO;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace CameraLib.AVI
{
public class AviManager
{
private int aviFile = 0;
private ArrayList streams = new ArrayList();
/// <summary>Open or create an AVI file</summary>
/// <param name="fileName">Name of the AVI file</param>
/// <param name="open">true: Open the file; false: Create or overwrite the file</param>
public AviManager(String fileName, bool open){
Avi.AVIFileInit();
int result;
if(open){ //open existing file
result = Avi.AVIFileOpen(
ref aviFile, fileName,
Avi.OF_READWRITE, 0);
}else{ //create empty file
result = Avi.AVIFileOpen(
ref aviFile, fileName,
Avi.OF_WRITE | Avi.OF_CREATE, 0);
}
if(result != 0) {
throw new Exception("Exception in AVIFileOpen: "+result.ToString());
}
}
private AviManager(int aviFile) {
this.aviFile = aviFile;
}
/// <summary>Get the first video stream - usually there is only one video stream</summary>
/// <returns>VideoStream object for the stream</returns>
public VideoStream GetVideoStream(){
IntPtr aviStream;
int result = Avi.AVIFileGetStream(
aviFile,
out aviStream,
Avi.streamtypeVIDEO, 0);
if(result != 0){
throw new Exception("Exception in AVIFileGetStream: "+result.ToString());
}
VideoStream stream = new VideoStream(aviFile, aviStream);
streams.Add(stream);
return stream;
}
/// <summary>Getthe first wave audio stream</summary>
/// <returns>AudioStream object for the stream</returns>
public AudioStream GetWaveStream(){
IntPtr aviStream;
int result = Avi.AVIFileGetStream(
aviFile,
out aviStream,
Avi.streamtypeAUDIO, 0);
if(result != 0){
throw new Exception("Exception in AVIFileGetStream: "+result.ToString());
}
AudioStream stream = new AudioStream(aviFile, aviStream);
streams.Add(stream);
return stream;
}
/// <summary>Get a stream from the internal list of opened streams</summary>
/// <param name="index">Index of the stream. The streams are not sorted, the first stream is the one that was opened first.</param>
/// <returns>VideoStream at position [index]</returns>
/// <remarks>
/// Use this method after DecompressToNewFile,
/// to get the copied stream from the new AVI file
/// </remarks>
/// <example>
/// //streams cannot be edited - copy to a new file
/// AviManager newManager = aviStream.DecompressToNewFile(@"..\..\testdata\temp.avi", true);
/// //there is only one stream in the new file - get it and add a frame
/// VideoStream aviStream = newManager.GetOpenStream(0);
/// aviStream.AddFrame(bitmap);
/// </example>
public VideoStream GetOpenStream(int index){
return (VideoStream)streams[index];
}
/// <summary>Add an empty video stream to the file</summary>
/// <param name="isCompressed">true: Create a compressed stream before adding frames</param>
/// <param name="frameRate">Frames per second</param>
/// <param name="frameSize">Size of one frame in bytes</param>
/// <param name="width">Width of each image</param>
/// <param name="height">Height of each image</param>
/// <param name="format">PixelFormat of the images</param>
/// <returns>VideoStream object for the new stream</returns>
public VideoStream AddVideoStream(bool isCompressed, double frameRate, int frameSize, int width, int height, PixelFormat format){
VideoStream stream = new VideoStream(aviFile, isCompressed, frameRate, frameSize, width, height, format);
streams.Add(stream);
return stream;
}
/// <summary>Add an empty video stream to the file</summary>
/// <remarks>Compresses the stream without showing the codecs dialog</remarks>
/// <param name="compressOptions">Compression options</param>
/// <param name="frameRate">Frames per second</param>
/// <param name="firstFrame">Image to write into the stream as the first frame</param>
/// <returns>VideoStream object for the new stream</returns>
public VideoStream AddVideoStream(Avi.AVICOMPRESSOPTIONS compressOptions, double frameRate, Bitmap firstFrame) {
VideoStream stream = new VideoStream(aviFile, compressOptions, frameRate, firstFrame);
streams.Add(stream);
return stream;
}
/// <summary>Add an empty video stream to the file</summary>
/// <param name="isCompressed">true: Create a compressed stream before adding frames</param>
/// <param name="frameRate">Frames per second</param>
/// <param name="firstFrame">Image to write into the stream as the first frame</param>
/// <returns>VideoStream object for the new stream</returns>
public VideoStream AddVideoStream(bool isCompressed, double frameRate, Bitmap firstFrame){
VideoStream stream = new VideoStream(aviFile, isCompressed, frameRate, firstFrame);
streams.Add(stream);
return stream;
}
/// <summary>Add a wave audio stream from another file to this file</summary>
/// <param name="waveFileName">Name of the wave file to add</param>
/// <param name="startAtFrameIndex">Index of the video frame at which the sound is going to start</param>
public void AddAudioStream(String waveFileName, int startAtFrameIndex) {
AviManager audioManager = new AviManager(waveFileName, true);
AudioStream newStream = audioManager.GetWaveStream();
AddAudioStream(newStream, startAtFrameIndex);
audioManager.Close();
}
private IntPtr InsertSilence(int countSilentSamples, IntPtr waveData, int lengthWave, ref Avi.AVISTREAMINFO streamInfo) {
//initialize silence
int lengthSilence = countSilentSamples * streamInfo.dwSampleSize;
byte[] silence = new byte[lengthSilence];
//initialize new sound
int lengthNewStream = lengthSilence + lengthWave;
IntPtr newWaveData = Marshal.AllocHGlobal(lengthNewStream);
//copy silence
Marshal.Copy(silence, 0, newWaveData, lengthSilence);
//copy sound
byte[] sound = new byte[lengthWave];
Marshal.Copy(waveData, sound, 0, lengthWave);
IntPtr startOfSound = new IntPtr(newWaveData.ToInt32() + lengthSilence);
Marshal.Copy(sound, 0, startOfSound, lengthWave);
Marshal.FreeHGlobal(newWaveData);
streamInfo.dwLength = lengthNewStream;
return newWaveData;
}
/// <summary>Add an existing wave audio stream to the file</summary>
/// <param name="newStream">The stream to add</param>
/// <param name="startAtFrameIndex">
/// The index of the video frame at which the sound is going to start.
/// '0' inserts the sound at the beginning of the video.
/// </param>
public void AddAudioStream(AudioStream newStream, int startAtFrameIndex) {
Avi.AVISTREAMINFO streamInfo = new Avi.AVISTREAMINFO();
Avi.PCMWAVEFORMAT streamFormat = new Avi.PCMWAVEFORMAT();
int streamLength = 0;
IntPtr rawData = newStream.GetStreamData(ref streamInfo, ref streamFormat, ref streamLength);
IntPtr waveData = rawData;
if (startAtFrameIndex > 0) {
//not supported
//streamInfo.dwStart = startAtFrameIndex;
double framesPerSecond = GetVideoStream().FrameRate;
double samplesPerSecond = newStream.CountSamplesPerSecond;
double startAtSecond = startAtFrameIndex / framesPerSecond;
int startAtSample = (int)(samplesPerSecond * startAtSecond);
waveData = InsertSilence(startAtSample - 1, waveData, streamLength, ref streamInfo);
}
IntPtr aviStream;
int result = Avi.AVIFileCreateStream(aviFile, out aviStream, ref streamInfo);
if(result != 0){
throw new Exception("Exception in AVIFileCreateStream: "+result.ToString());
}
result = Avi.AVIStreamSetFormat(aviStream, 0, ref streamFormat, Marshal.SizeOf(streamFormat));
if(result != 0){
throw new Exception("Exception in AVIStreamSetFormat: "+result.ToString());
}
result = Avi.AVIStreamWrite(aviStream, 0, streamLength, waveData, streamLength, Avi.AVIIF_KEYFRAME, 0, 0);
if(result != 0){
throw new Exception("Exception in AVIStreamWrite: "+result.ToString());
}
result = Avi.AVIStreamRelease(aviStream);
if(result != 0){
throw new Exception("Exception in AVIStreamRelease: "+result.ToString());
}
Marshal.FreeHGlobal(waveData);
}
/// <summary>Add an existing wave audio stream to the file</summary>
/// <param name="waveData">The new stream's data</param>
/// <param name="streamInfo">Header info for the new stream</param>
/// <param name="streamFormat">The new stream' format info</param>
/// <param name="streamLength">Length of the new stream</param>
public void AddAudioStream(IntPtr waveData, Avi.AVISTREAMINFO streamInfo, Avi.PCMWAVEFORMAT streamFormat, int streamLength) {
IntPtr aviStream;
int result = Avi.AVIFileCreateStream(aviFile, out aviStream, ref streamInfo);
if (result != 0) {
throw new Exception("Exception in AVIFileCreateStream: " + result.ToString());
}
result = Avi.AVIStreamSetFormat(aviStream, 0, ref streamFormat, Marshal.SizeOf(streamFormat));
if (result != 0) {
throw new Exception("Exception in AVIStreamSetFormat: " + result.ToString());
}
result = Avi.AVIStreamWrite(aviStream, 0, streamLength, waveData, streamLength, Avi.AVIIF_KEYFRAME, 0, 0);
if (result != 0) {
throw new Exception("Exception in AVIStreamWrite: " + result.ToString());
}
result = Avi.AVIStreamRelease(aviStream);
if (result != 0) {
throw new Exception("Exception in AVIStreamRelease: " + result.ToString());
}
}
/// <summary>Copy a piece of video and wave sound int a new file</summary>
/// <param name="newFileName">File name</param>
/// <param name="startAtSecond">Start copying at second x</param>
/// <param name="stopAtSecond">Stop copying at second y</param>
/// <returns>AviManager for the new video</returns>
public AviManager CopyTo(String newFileName, float startAtSecond, float stopAtSecond) {
AviManager newFile = new AviManager(newFileName, false);
try {
//copy video stream
VideoStream videoStream = GetVideoStream();
int startFrameIndex = (int)(videoStream.FrameRate * startAtSecond);
int stopFrameIndex = (int)(videoStream.FrameRate * stopAtSecond);
videoStream.GetFrameOpen();
Bitmap bmp = videoStream.GetBitmap(startFrameIndex);
VideoStream newStream = newFile.AddVideoStream(false, videoStream.FrameRate, bmp);
for (int n = startFrameIndex + 1; n <= stopFrameIndex; n++) {
bmp = videoStream.GetBitmap(n);
newStream.AddFrame(bmp);
}
videoStream.GetFrameClose();
//copy audio stream
AudioStream waveStream = GetWaveStream();
Avi.AVISTREAMINFO streamInfo = new Avi.AVISTREAMINFO();
Avi.PCMWAVEFORMAT streamFormat = new Avi.PCMWAVEFORMAT();
int streamLength = 0;
IntPtr ptrRawData = waveStream.GetStreamData(
ref streamInfo,
ref streamFormat,
ref streamLength);
int startByteIndex = (int)( startAtSecond * (float)(waveStream.CountSamplesPerSecond * streamFormat.nChannels * waveStream.CountBitsPerSample) / 8);
int stopByteIndex = (int)( stopAtSecond * (float)(waveStream.CountSamplesPerSecond * streamFormat.nChannels * waveStream.CountBitsPerSample) / 8);
IntPtr ptrWavePart = new IntPtr(ptrRawData.ToInt32() + startByteIndex);
byte[] rawData = new byte[stopByteIndex - startByteIndex];
Marshal.Copy(ptrWavePart, rawData, 0, rawData.Length);
Marshal.FreeHGlobal(ptrRawData);
streamInfo.dwLength = rawData.Length;
streamInfo.dwStart = 0;
IntPtr unmanagedRawData = Marshal.AllocHGlobal(rawData.Length);
Marshal.Copy(rawData, 0, unmanagedRawData, rawData.Length);
newFile.AddAudioStream(unmanagedRawData, streamInfo, streamFormat, rawData.Length);
Marshal.FreeHGlobal(unmanagedRawData);
} catch (Exception ex) {
newFile.Close();
throw ex;
}
return newFile;
}
/// <summary>Release all ressources</summary>
public void Close(){
foreach(AviStream stream in streams){
stream.Close();
}
Avi.AVIFileRelease(aviFile);
Avi.AVIFileExit();
}
public static void MakeFileFromStream(String fileName, AviStream stream) {
IntPtr newFile = IntPtr.Zero;
IntPtr streamPointer = stream.StreamPointer;
Avi.AVICOMPRESSOPTIONS_CLASS opts = new Avi.AVICOMPRESSOPTIONS_CLASS();
opts.fccType = (uint)Avi.streamtypeVIDEO;
opts.lpParms = IntPtr.Zero;
opts.lpFormat = IntPtr.Zero;
Avi.AVISaveOptions(IntPtr.Zero, Avi.ICMF_CHOOSE_KEYFRAME | Avi.ICMF_CHOOSE_DATARATE, 1, ref streamPointer, ref opts);
Avi.AVISaveOptionsFree(1, ref opts);
Avi.AVISaveV(fileName, 0, 0, 1, ref streamPointer, ref opts);
}
}
}
| |
using AVDump3Lib.Information.MetaInfo;
using AVDump3Lib.Information.MetaInfo.Core;
using ExtKnot.StringInvariants;
using System.Collections.Immutable;
using System.Text;
using System.Text.RegularExpressions;
namespace AVDump3Lib.Information.InfoProvider;
public class FormatInfoProvider : MetaDataProvider {
public FormatInfoProvider(string filePath) : base("FormatInfoProvider", MediaProvider.MediaProviderType) {
FileExtensionProvider.AddMetaData(this, filePath);
}
public static readonly MetaInfoContainerType FormatInfoProviderType = new("FormatInfoProvider");
}
public interface IMagicBytePattern {
}
public interface IFormatPattern {
}
//TODO: Complete rewrite
public class FileExtensionProvider {
//private static byte[] Conv(string str) => Encoding.ASCII.GetBytes(str);
public static void AddMetaData(MetaDataProvider provider, string path) {
Stream stream = null;
if(File.Exists(path)) {
try {
stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
} catch(FileNotFoundException) { }
}
if(stream == null) return;
var fileTypes = new IFileType[] {
//new MpegAudioFileType(),
//new MpegVideoFileType(),
//new WavFileType(),
new SrtFileType(),
new AssSsaFileType(),
new IdxFileType(),
new SamiFileType(),
new C7zFileType(),
new ZipFileType(),
new RarFileType(),
new RaFileType(),
new FlacFileType(),
new LrcFileType(),
new AviFileType(),
new SubFileType(),
new TmpFileType(),
new PJSFileType(),
new WebvttFileType(),
new JSFileType(),
new RTFileType(),
new SMILFileType(),
new TTSFileType(),
new XSSFileType(),
new ZeroGFileType(),
new SUPFileType(),
new FanSubberFileType(),
new Sasami2kFileType()
};
using(stream) {
int b;
var needMoreBytes = true;
while(needMoreBytes) {
b = stream.ReadByte();
if(b == -1 || stream.Position > 10 << 20) return;
needMoreBytes = false;
foreach(var fileType in fileTypes.Where(f => f.IsCandidate)) {
fileType.CheckMagicByte((byte)b);
needMoreBytes |= fileType.NeedsMoreMagicBytes;
}
}
foreach(var fileType in fileTypes.Where(f => f.IsCandidate)) {
stream.Position = 0;
fileType.ElaborateCheck(stream);
}
}
var exts = fileTypes.Where(f => f.IsCandidate);
if(exts.Count() != 1) {
if(exts.Any(ft => ft.PossibleExtensions[0].InvEquals("zip"))) exts = new List<IFileType>(new IFileType[] { new ZipFileType() });
if(exts.Any(ft => ft.PossibleExtensions[0].InvEquals("7z"))) exts = new List<IFileType>(new IFileType[] { new C7zFileType() });
if(exts.Any(ft => ft.PossibleExtensions[0].InvEquals("rar"))) exts = new List<IFileType>(new IFileType[] { new RarFileType() });
}
string extsStr;
if(fileTypes.Any(f => f.IsCandidate)) {
extsStr = exts.Aggregate<IFileType, IEnumerable<string>>(Array.Empty<string>(), (acc, f) => acc.Concat(f.PossibleExtensions)).Aggregate((acc, str) => acc + " " + str);
} else {
extsStr = null;
}
if(!string.IsNullOrEmpty(extsStr)) provider.Add(MediaProvider.SuggestedFileExtensionType, ImmutableArray.Create(extsStr));
if(exts.Count() == 1) {
exts.Single().AddInfo(provider);
}
}
public FileExtensionProvider() {
//Add(EntryKey.Extension, extsStr, null);
//if(exts.Count() == 1) exts.Single().AddInfo(Add);
}
}
public class MpegAudioFileType : FileType {
//public MpegAudioFileType() : base(new byte[][] { new byte[] { 0xff }, new byte[] { (byte)'I', (byte)'D', (byte)'3' } }) { }
public MpegAudioFileType() : base("") => fileType = MediaProvider.AudioStreamType;
private static readonly int[][] bitRateTable = {
new[] {-1, -1 ,-1, -1, -1},
new[] {32, 32,32,32,8},
new[] {64,48,40,48,16},
new[] {96,56,48,56,24},
new[] {128,64,56,64,32},
new[] {160,80,64,80,40},
new[] {192,96,80,96,48},
new[] {224,112,96,112,56},
new[] {256,128,112,128,64},
new[] {288,160,128,144,80},
new[] {320,192,160,160,96},
new[] {352,224,192,176,112},
new[] {384,256,224,192,128},
new[] {416,320,256,224,144},
new[] {448,384,320,256,160},
new[] {-1, -1 ,-1, -1, -1},
};
private static readonly int[][] samplerateTable = {
new[]{44100,22050,11025},
new[]{48000,24000,12000},
new[]{32000,16000,8000},
new[]{-1,-1,-1},
};
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
if(stream.Length > 10 && stream.ReadByte() == 'I' && stream.ReadByte() == 'D' && stream.ReadByte() == '3') {
stream.Position += 3;
var length = 0;
for(var i = 0; i < 4; i++) {
length += (byte)stream.ReadByte() << (7 * (3 - i));
}
stream.Position = length;
} else {
stream.Position = 0;
}
//stream.Position = Math.Max(stream.Length / 2 , stream.Position);
var counter = 0;
Layer layer = 0;
for(var i = 0; i < 100; i++) if(ReadFrame(stream, out layer) && ReadFrame(stream, out _)) break;
for(var i = 0; i < 10; i++) counter += ReadFrame(stream, out _) ? 1 : 0;
if(counter < 7) { IsCandidate = false; return; }
PossibleExtensions = new string[] { (layer == Layer.Layer1) ? "mp1" : ((layer == Layer.Layer2) ? "mp2" : "mp3") };
}
private static bool ReadFrame(Stream stream, out Layer layer) {
int oldByte = 0, newByte, counter = 0;
while((newByte = stream.ReadByte()) != -1) {
if(oldByte == 0xFF && (newByte & 0xE0) == 0xE0) break;
oldByte = newByte;
counter++;
}
var mpegVer = (MpegVer)newByte & MpegVer.MASK;
layer = (Layer)newByte & Layer.MASK;
if((newByte = stream.ReadByte()) == -1) return false;
var rowIndex = (newByte & 0xF0) >> 4;
var columnIndex = mpegVer == MpegVer.Mpeg1 ? (layer == Layer.Layer1 ? 0 : (layer == Layer.Layer2 ? 1 : 2)) : ((mpegVer == MpegVer.Mpeg2 || mpegVer == MpegVer.Mpeg2_5) ? ((layer == Layer.Layer1) ? 3 : 4) : -1);
if(columnIndex == -1) return false;
var bitrate = bitRateTable[rowIndex][columnIndex];
if(bitrate == -1) return false;
rowIndex = (newByte & 0x0C) >> 2;
columnIndex = mpegVer == MpegVer.Mpeg1 ? 0 : (mpegVer == MpegVer.Mpeg2 ? 1 : 2);
if(columnIndex == -1) return false;
var sampleRate = samplerateTable[rowIndex][columnIndex];
if(sampleRate == -1) return false;
var padding = (newByte & 0x02) != 0;
var frameLength = layer == Layer.Layer1 ? (12 * bitrate / sampleRate + (padding ? 1 : 0)) * 4 : 144000 * bitrate / sampleRate + (padding ? 1 : 0);
//Debug.Print(layer.ToString());
stream.Position += frameLength - 3;
return counter <= 2 && frameLength != 0;
}
private enum MpegVer { Mpeg1 = 24, Mpeg2 = 16, Mpeg2_5 = 0, MASK = 0x18 }
private enum Layer { Layer1 = 6, Layer2 = 4, Layer3 = 2, MASK = 0x06 }
}
public class SrtFileType : FileType {
public SrtFileType() : base("", identifier: "text/srt") { PossibleExtensions = new string[] { "srt" }; fileType = MediaProvider.SubtitleStreamType; }
private static readonly Regex regexParse = new(@"^(?<start>\d{1,4} ?\: ?\d{1,4} ?\: ?\d{1,4} ?[,:.] ?\d{1,4}) ?--\> ?(?<end>\d{1,4} ?\: ?\d{1,4} ?\: ?\d{1,4} ?[,:.] ?\d{1,4})", RegexOptions.Compiled | RegexOptions.ECMAScript);
public override void ElaborateCheck(Stream stream) {
if(stream.Length > 10 * 1024 * 1024) IsCandidate = false;
if(!IsCandidate) return;
//bool accept = false;
var count = 0;
//int lineType = 0, dummy;
using var sr = new StreamReader(stream, Encoding.UTF8, true, 2048, true);
foreach(var line in ReadLines(sr, 1024)) {
if(count == 0 && line.InvContainsOrdCI("webvtt")) break;
if(regexParse.IsMatch(line)) count++;
if(count > 20) break;
/*if(int.TryParse(line, out dummy)) {
lineType = 1;
continue;
}
if(string.IsNullOrEmpty(line)) {
continue;
}
switch(lineType) {
//case 0: IsCandidate = int.TryParse(line, out dummy); break;
case 1: IsCandidate = regexParse.IsMatch(line); break;
case 2: accept = true; break;
}
if(!IsCandidate) return;
lineType++;
count++;
if(count > 20) break;*/
}
if(count == 0) IsCandidate = false;
}
}
public class AssSsaFileType : FileType {
public AssSsaFileType() : base("", identifier: "text/") { PossibleExtensions = new string[] { "ssa", "ass" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
IsCandidate = stream.ReadByte() != 0x1A && stream.ReadByte() != 0x45 && stream.ReadByte() != 0xDF && stream.ReadByte() != 0xA3; //Skip Matroska files
stream.Position = 0;
if(!IsCandidate) return;
using var sr = new StreamReader(stream, Encoding.Default, true, 2048, true);
var chars = new char[2048];
var length = sr.Read(chars, 0, chars.Length);
var str = new string(chars, 0, length).ToInvLower();
//int pos = str.IndexOf("[script info]");
//if(pos < 0) { IsCandidate = false; return; }
var pos = str.InvIndexOfOrdCI(" styles]");
if(pos != -1) {
pos = str.InvIndexOfOrdCI("v4", pos - 4, 10);
if(pos != -1) pos += 2;
}
if(pos == -1) {
pos = str.InvIndexOfOrdCI(" styles]");
if(pos != -1) {
pos = str.InvIndexOfOrdCI("v3", pos - 4, 10);
if(pos != -1) pos += 2;
}
}
if(pos == -1) {
pos = str.InvIndexOfOrdCI("scripttype:");
if(pos < 0) {
IsCandidate = false;
return;
}
if((pos = str.InvIndexOfOrdCI("v4.00", pos, 20)) < 0) {
IsCandidate = false;
return;
}
pos += 5;
}
if(pos == -1) {
pos = str.InvIndexOfOrdCI("scripttype:");
if(pos < 0) {
IsCandidate = false;
return;
}
if((pos = str.InvIndexOfOrdCI("v3.00", pos, 20)) < 0) {
IsCandidate = false;
return;
}
pos += 5;
}
if(pos + 2 < stream.Length) {
PossibleExtensions = new string[] { str[pos] == '+' ? "ass" : "ssa" };
identifier += PossibleExtensions[0];
} else {
IsCandidate = false;
}
}
}
public class IdxFileType : FileType {
private IDX idx;
public IdxFileType() : base(Array.Empty<byte>(), identifier: "text/idx") { PossibleExtensions = new string[] { "idx" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(stream.Length > 10 * 1024 * 1024) IsCandidate = false;
if(!IsCandidate) return;
using var sr = new StreamReader(stream, Encoding.UTF8, true, 2048, true);
var line = ReadLines(sr, 1024).FirstOrDefault() ?? "";
IsCandidate = line.InvContains("VobSub index file, v");
if(IsCandidate) {
stream.Position = 0;
var b = new byte[stream.Length];
stream.Read(b);
var str = Encoding.UTF8.GetString(b).Replace('\0', '#');
sr.DiscardBufferedData();
try {
idx = new IDX(str);
} catch { }
}
}
public override void AddInfo(MetaDataProvider provider) {
if(idx != null) {
for(var i = 0; i < idx.Subtitles.Length; i++) {
if(idx.Subtitles[i].SubtitleCount == 0) continue;
var container = new MetaInfoContainer((ulong)i, fileType);
provider.AddNode(container);
provider.Add(container, MediaStream.ContainerCodecIdType, identifier);
provider.Add(container, MediaStream.LanguageType, !string.IsNullOrEmpty(idx.Subtitles[i].Language) ? idx.Subtitles[i].Language : idx.Subtitles[i].LanguageId);
provider.Add(container, MediaStream.IndexType, idx.Subtitles[i].Index);
}
} else {
base.AddInfo(provider);
}
}
}
public class LrcFileType : FileType { //http://en.wikipedia.org/wiki/LRC_(file_format)
public LrcFileType() : base("", identifier: "text/lyric") { PossibleExtensions = new string[] { "lrc" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
var sr = new StreamReader(stream, Encoding.UTF8, true, 2048);
int i = 0, matches = 0;
var regex = new Regex(@"\[\d\d\:\d\d\.\d\d\].*");
foreach(var line in ReadLines(sr, 1024)) {
//if(line == null) break;
matches += regex.IsMatch(line) ? 1 : 0;
i++;
}
if(matches / (double)i < 0.8 || matches == 0) { IsCandidate = false; return; }
}
}
public class TmpFileType : FileType {
public TmpFileType() : base("", identifier: "text/TMPlayer") { PossibleExtensions = new string[] { "tmp" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
var sr = new StreamReader(stream, Encoding.UTF8, true, 2048);
int i = 0, matches = 0;
var regex = new Regex(@"^\d\d\:\d\d\:\d\d(\.\d)?\:.*");
foreach(var line in ReadLines(sr, 1024)) {
//if(line == null) break;
matches += regex.IsMatch(line) ? 1 : 0;
i++;
}
if(matches / (double)i < 0.8 || matches == 0) { IsCandidate = false; return; }
}
}
public class PJSFileType : FileType {
public PJSFileType() : base("", identifier: "text/PhoenixJapanimationSociety") { PossibleExtensions = new string[] { "pjs" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
var sr = new StreamReader(stream, Encoding.UTF8, true, 2048);
int i = 0, matches = 0;
var regex = new Regex(@"^\s*\d*,\s*\d*," + "\".*\"");
var checkLine = "";
foreach(var line in ReadLines(sr, 1024)) {
checkLine += line;
if(!line.Contains(",\"") || line.EndsWith("\"")) {
matches += regex.IsMatch(checkLine) ? 1 : 0;
checkLine = "";
i++;
}
}
if(matches / (double)i < 0.8 || matches == 0) { IsCandidate = false; return; }
}
}
public class JSFileType : FileType {
public JSFileType() : base("", identifier: "text/JS") { PossibleExtensions = new string[] { "js" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
var sr = new StreamReader(stream, Encoding.UTF8, true, 2048);
int i = 0, matches = 0;
var regex = new Regex(@"^\d*\:\d*\:\d*\.\d*\s*\d*\:\d*\:\d*\.\d*.*");
var hasContinuation = false;
var hasMagicString = false;
foreach(var line in ReadLines(sr, 1024)) {
if(line == null) break;
hasMagicString |= line.ToLowerInvariant().Contains("jaco");
if(line.StartsWith("#") || string.IsNullOrEmpty(line)) continue;
var isStartMatch = regex.IsMatch(line);
matches += hasContinuation || isStartMatch ? 1 : 0;
hasContinuation = (isStartMatch && line.EndsWith("\\")) || (hasContinuation && line.EndsWith("\\"));
i++;
}
var isMatch = matches / (double)i > 0.5 && hasMagicString;
isMatch |= matches / (double)i > 0.8;
if(!isMatch || matches == 0) { IsCandidate = false; return; }
}
}
public class TTSFileType : FileType {
public TTSFileType() : base("", identifier: "text/TTS") { PossibleExtensions = new string[] { "tts" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
var sr = new StreamReader(stream, Encoding.UTF8, true, 2048);
int i = 0, matches = 0;
var regex = new Regex(@"^\d*\:\d*\:\d*\.\d*,\d*\:\d*\:\d*\.\d*,.*");
foreach(var line in ReadLines(sr, 1024).Select(ldLine => ldLine.Trim())) {
//if(line == null) break;
if(line.StartsWith("#") || string.IsNullOrEmpty(line)) continue;
var isMatch = regex.IsMatch(line);
matches += isMatch ? 1 : 0;
if(!isMatch) {
if(!string.IsNullOrEmpty(line) && line.Average(ldChar => char.IsLetter(ldChar) || char.IsWhiteSpace(ldChar) || char.IsPunctuation(ldChar) ? 1 : 0) > 0.8) continue;
}
i++;
}
if(matches / (double)i < 0.8 || matches == 0) { IsCandidate = false; return; }
}
}
public class RTFileType : FileType {
public RTFileType() : base("", identifier: "text/RT") { PossibleExtensions = new string[] { "rt" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
var sr = new StreamReader(stream, Encoding.UTF8, true, 2048);
int i, j = 0, matches = 0;
foreach(var line in ReadLines(sr, 1024).Select(ldLine => ldLine.ToLower())) {
//if(line == null) break;
if(string.IsNullOrEmpty(line) || !line.StartsWith("<")) continue;
j++;
matches += (line.StartsWith("<window") || line.StartsWith("<time begin")) ? 1 : 0;
}
if(matches / (double)j < 0.6 || matches == 0 || j < 10) { IsCandidate = false; return; }
}
}
public class XSSFileType : FileType {
public XSSFileType() : base("", identifier: "text/XombieSub") { PossibleExtensions = new string[] { "xss" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
var sr = new StreamReader(stream, Encoding.UTF8, true, 2048);
var chars = new char[2048];
var length = sr.Read(chars, 0, chars.Length);
var str = new string(chars, 0, length).ToLowerInvariant();
IsCandidate = str.Contains("script=xombiesub");
}
}
public class WebvttFileType : FileType {
public WebvttFileType() : base(new byte[][]{
new byte[] { 0xFE, 0xFF, (byte)'W', (byte)'E', (byte)'B', (byte)'V', (byte)'T', (byte)'T' },
new byte[] { (byte)'W', (byte)'E', (byte)'B', (byte)'V', (byte)'T', (byte)'T' }
}, identifier: "text/vtt") { PossibleExtensions = new string[] { "vtt" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
using var sr = new StreamReader(stream, Encoding.UTF8, true, 2048, true);
int score = 0;
string? line;
while((line = sr.ReadLine()) != null) {
if(line.InvStartsWithOrdCI("region") || line.InvStartsWithOrdCI("style") || line.InvStartsWithOrdCI("note")) {
score += 10;
}
if(line.InvStartsWithOrdCI("-->")) {
score += 1;
}
}
IsCandidate = score > 10;
}
}
public class SUPFileType : FileType {
public SUPFileType() : base("", identifier: "text/SubtitleBitmapFile") { PossibleExtensions = new string[] { "sup" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
var startingBytes = new byte[12];
stream.Read(startingBytes, 0, 12);
IsCandidate &= startingBytes[0] == 0x50;
IsCandidate &= startingBytes[1] == 0x47;
IsCandidate &= startingBytes[10] == 0x16;
IsCandidate &= startingBytes[11] == 0x00;
}
}
public class SMILFileType : FileType {
public SMILFileType() : base("", identifier: "SMIL") { PossibleExtensions = new string[] { "smil" }; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
var sr = new StreamReader(stream, Encoding.UTF8, false, 2048);
int i = 0, matches = 0;
foreach(var line in ReadLines(sr, 1024).Select(ldLine => ldLine.ToLower().Trim())) {
if(line == null) break;
if(line.StartsWith("<smil>")) matches++;
i++;
}
if(matches == 0) { IsCandidate = false; return; }
}
}
public class FanSubberFileType : FileType {
public FanSubberFileType() : base("FanSubber v", identifier: "text/FanSubber") { PossibleExtensions = new string[] { "fsb" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
var sr = new StreamReader(stream, Encoding.UTF8, false, 2048);
var line = ReadLines(sr, 1024).FirstOrDefault() ?? "";
IsCandidate &= Regex.IsMatch(line, @"FanSubber v[0-9]+(\.[0-9]+)?");
}
}
public class Sasami2kFileType : FileType { public Sasami2kFileType() : base("// translated by Sami2Sasami", identifier: "text/Sasami2k") { PossibleExtensions = new string[] { "s2k" }; fileType = MediaProvider.SubtitleStreamType; } }
public class MpegVideoFileType : FileType { public MpegVideoFileType() : base(new byte[] { 0x00, 0x00, 0x01, 0xB3 }) { PossibleExtensions = new string[] { "mpg" }; fileType = MediaProvider.VideoStreamType; } }
public class SamiFileType : FileType {
public SamiFileType() : base("", identifier: "text/sami") { PossibleExtensions = new string[] { "smi" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
var sr = new StreamReader(stream, Encoding.UTF8, true, 2048);
var chars = new char[2048];
var length = sr.Read(chars, 0, chars.Length);
var str = new string(chars, 0, length).ToLowerInvariant();
if(str.IndexOf("<sami>", 0, Math.Min(10, str.Length)) < 0) { IsCandidate = false; return; }
}
}
public class SubFileType : FileType { //http://forum.doom9.org/archive/index.php/t-81059.html
public SubFileType() : base("", identifier: "text/") { PossibleExtensions = new string[] { "sub" }; fileType = MediaProvider.SubtitleStreamType; }
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
if(Subviewer(stream)) identifier += "subviewer";
else if(MicroDVD(stream)) identifier += "microdvd";
else IsCandidate = false;
}
private static bool Subviewer(Stream stream) {
using var sr = new StreamReader(stream, Encoding.UTF8, true, 2048, true);
var chars = new char[1024];
var length = sr.Read(chars, 0, chars.Length);
var str = new string(chars, 0, length).ToUpperInvariant();
var matches = 0;
string[] keys = { "[BEGIN]", "[INFORMATION]", "[TITLE]", "[AUTHOR]", "[SOURCE]", "[PRG]", "[FILEPATH]", "[DELAY]", "[CD TRACK]", "[COMMENT]", "[END INFORMATION]", "[SUBTITLE]", "[COLF]", "[STYLE]", "[SIZE]", "[FONT]" };
foreach(var key in keys) matches += str.InvContains(key) ? 1 : 0;
if(matches < 5) return false;
//identifier += "subviewer";
return true;
}
private static bool MicroDVD(Stream stream) {
if(stream.Length > 10 * 1024 * 1024) return false;
stream.Position = 0;
using var sr = new StreamReader(stream, Encoding.UTF8, true, 2048, true);
int count = 0, matches = 0;
var regex = new Regex(@"^\{\d*\}\{\d*\}.*$");
foreach(var line in ReadLines(sr, 1024).Select(ldLine => ldLine.Trim())) {
if(line.InvEquals("")) continue;
if(regex.IsMatch(line)) matches++;
count++;
if(count > 20) break;
}
return matches / (double)count > 0.8 && count > 4;
}
}
public class ZeroGFileType : FileType {
public ZeroGFileType() : base("", identifier: "text/ZeroG") {
PossibleExtensions = new string[] { "zeg" }; fileType = MediaProvider.SubtitleStreamType;
}
public override void ElaborateCheck(Stream stream) {
if(!IsCandidate) return;
var sr = new StreamReader(stream, Encoding.UTF8, true, 2048);
var chars = new char[2048];
var length = sr.Read(chars, 0, chars.Length);
var str = new string(chars, 0, length).ToLowerInvariant();
if(str.IndexOf("% zerog") < 0) { IsCandidate = false; return; }
}
}
public class C7zFileType : FileType {
public C7zFileType() : base(new byte[] { 0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C }, identifier: "compression/7z") => PossibleExtensions = new string[] { "7z" };
public override void AddInfo(MetaDataProvider provider) {
if(!string.IsNullOrEmpty(identifier)) {
provider.Add(MediaProvider.FileTypeIdentifierType, identifier);
}
}
}
public class ZipFileType : FileType {
public ZipFileType() : base(new byte[][] { new byte[] { 0x50, 0x4b, 0x03, 0x04 }, new byte[] { 0x50, 0x4b, 0x30, 0x30, 0x50, 0x4b } }, identifier: "compression/zip") => PossibleExtensions = new string[] { "zip" };
public override void AddInfo(MetaDataProvider provider) {
if(!string.IsNullOrEmpty(identifier)) {
provider.Add(MediaProvider.FileTypeIdentifierType, identifier);
}
}
}
public class RarFileType : FileType {
public RarFileType() : base(new byte[] { 0x52, 0x61, 0x72, 0x21 }, identifier: "compression/rar") => PossibleExtensions = new string[] { "rar" };
public override void AddInfo(MetaDataProvider provider) {
if(!string.IsNullOrEmpty(identifier)) {
provider.Add(MediaProvider.FileTypeIdentifierType, identifier);
}
}
}
public class RaFileType : FileType { public RaFileType() : base(".ra" + (char)0xfd) { PossibleExtensions = new string[] { "ra" }; fileType = MediaProvider.AudioStreamType; } }
public class FlacFileType : FileType { public FlacFileType() : base("fLaC") { PossibleExtensions = new string[] { "flac" }; fileType = MediaProvider.AudioStreamType; } }
public class AviFileType : FileType { public AviFileType() : base("RIFF") { PossibleExtensions = new string[] { "avi" }; fileType = MediaProvider.VideoStreamType; } public override void ElaborateCheck(Stream stream) => IsCandidate &= Check(stream, 8, "AVI LIST"); }
public class WavFileType : FileType { public WavFileType() : base(new string[] { "RIFX", "RIFF" }) { PossibleExtensions = new string[] { "wav" }; fileType = MediaProvider.AudioStreamType; } public override void ElaborateCheck(Stream stream) => IsCandidate &= Check(stream, 8, "WAVE"); }
public abstract class FileType : IFileType {
private readonly byte[][] magicBytesLst;
private readonly int[] magicBytesPos;
private int offset;
protected string? identifier;
protected MetaInfoContainerType fileType = MediaProvider.MediaStreamType;
public bool NeedsMoreMagicBytes { get; private set; }
public bool IsCandidate { get; protected set; }
public string[] PossibleExtensions { get; protected set; } = Array.Empty<string>();
public FileType(string magicString, int offset = 0, string? identifier = null) : this(new string[] { magicString }, offset, identifier) { }
public FileType(byte[] magicBytes, int offset = 0, string? identifier = null) : this(new byte[][] { magicBytes }, offset, identifier) { }
public FileType(string[] magicStringLst, int offset = 0, string? identifier = null) : this(magicStringLst.Select(magicString => Encoding.ASCII.GetBytes(magicString)).ToArray(), offset, identifier) { }
public FileType(byte[][] magicBytesLst, int offset = 0, string? identifier = null) {
this.magicBytesLst = magicBytesLst;
this.offset = offset;
this.identifier = identifier;
magicBytesPos = new int[magicBytesLst.Length];
IsCandidate = true;
foreach(var magicBytes in magicBytesLst) NeedsMoreMagicBytes |= magicBytes.Length != 0;
}
public void CheckMagicByte(byte b) {
if(!NeedsMoreMagicBytes || offset-- > 0) return;
bool needsMoreMagicBytes = false, isCandidate = false;
for(var i = 0; i < magicBytesLst.Length; i++) {
if(magicBytesLst[i] == null) {
isCandidate = true;
} else if(magicBytesLst[i].Length > magicBytesPos[i]) {
isCandidate |= magicBytesLst[i][magicBytesPos[i]++] == b;
if(magicBytesLst[i].Length == magicBytesPos[i] && isCandidate) magicBytesLst[i] = null;
}
needsMoreMagicBytes |= isCandidate && magicBytesLst[i] != null && magicBytesLst[i].Length != magicBytesPos[i];
}
NeedsMoreMagicBytes &= needsMoreMagicBytes;
IsCandidate &= isCandidate;
}
public virtual void ElaborateCheck(Stream stream) { }
protected static bool Check(Stream stream, int totalOffset, string str) => Check(stream, totalOffset, Encoding.ASCII.GetBytes(str));
protected static bool Check(Stream stream, int totalOffset, byte[] b) {
var isValid = true;
stream.Position = totalOffset;
foreach(var item in b) isValid &= item == stream.ReadByte();
return isValid;
}
protected static bool FindSequence(Stream stream, string sequenceStr, int bytesToCheck) => FindSequence(stream, Encoding.ASCII.GetBytes(sequenceStr), Math.Min(bytesToCheck, 2048));
protected static bool FindSequence(Stream stream, byte[] sequence, int bytesToCheck) {
var sequencePos = 0;
while(stream.Position != stream.Length && bytesToCheck-- != 0 && sequence.Length != sequencePos) if(sequence[sequencePos++] != stream.ReadByte()) sequencePos = 0;
return sequence.Length == sequencePos;
}
public override string ToString() => base.ToString() + " IsCandidate " + IsCandidate;
public virtual void AddInfo(MetaDataProvider provider) {
if(!string.IsNullOrEmpty(identifier)) {
var container = new MetaInfoContainer(0, fileType);
provider.AddNode(container);
provider.Add(container, MediaStream.ContainerCodecIdType, identifier);
}
}
protected static IEnumerable<string> ReadLines(StreamReader streamReader, int maxLineLength) {
var currentLine = new StringBuilder(maxLineLength);
int i;
while((i = streamReader.Read()) > -1) {
var c = (char)i;
if(c == '\r' || c == '\n') {
if(currentLine.Length > 0) {
yield return currentLine.ToString();
}
currentLine.Length = 0;
continue;
}
currentLine.Append(c);
if(currentLine.Length > maxLineLength) {
yield break;
}
}
if(currentLine.Length > 0) {
yield return currentLine.ToString();
}
}
}
public interface IFileType {
bool IsCandidate { get; }
bool NeedsMoreMagicBytes { get; }
string[] PossibleExtensions { get; }
void ElaborateCheck(Stream stream);
void CheckMagicByte(byte b);
void AddInfo(MetaDataProvider provider);
}
public class IDX {
private readonly Dictionary<string, string> info;
private Subs[] subtitles;
public Subs[] Subtitles => (Subs[])subtitles.Clone();
public IDX(string source) {
info = new Dictionary<string, string>();
Parse(source);
}
private static readonly Regex tagRegex = new(@"^([^#]+?)\:[ ]?" + "([^\r\n]+)", RegexOptions.Compiled | RegexOptions.ECMAScript | RegexOptions.Multiline);
private void Parse(string source) {
MatchCollection matches = tagRegex.Matches(source);
Match match, subMatch;
string language;
string languageId;
TimeSpan? delay = null;
List<TimeSpan> sub = null;
List<Subs> subs = new();
for(int i = 0; i < matches.Count; i++) {
match = matches[i];
string key = match.Groups[1].Value.Trim();
if(key.InvEquals("timestamp") && sub != null) {
try {
var timestampstr = Regex.Match(match.Groups[2].Value, "([^,]+)").Groups[1].Value;
timestampstr = timestampstr[..timestampstr.LastIndexOf(':')] + "." + timestampstr[(timestampstr.LastIndexOf(':') + 1)..];
sub.Add(TimeSpan.Parse(timestampstr).Add(delay != null ? delay.Value : TimeSpan.FromTicks(0)));
} catch(Exception ex) { }
} else if(key.InvEquals("Delay")) {
var timestampstr = Regex.Match(match.Groups[2].Value, "([^,]+)").Groups[1].Value;
timestampstr = timestampstr[..timestampstr.LastIndexOf(':')] + "." + timestampstr[(timestampstr.LastIndexOf(':') + 1)..];
delay = TimeSpan.Parse(timestampstr);
} else if(key.InvEquals("id")) {
subMatch = Regex.Match(match.Groups[2].Value, @"([^,]+), index\: (.+)");
if(!subMatch.Success) throw new Exception();
languageId = subMatch.Groups[1].Value;
if(!int.TryParse(subMatch.Groups[2].Value, out var index)) throw new Exception();
language = source[match.Index..(i + 1 < matches.Count ? matches[i + 1].Index : source.Length)];
language = Regex.Match(language, @"alt\: " + "([^\r\n]+)").Groups[1].Value;
delay = null;
sub = new List<TimeSpan>();
subs.Add(new Subs(index, languageId, language, sub));
} else {
info[key] = match.Groups[2].Value;
}
}
subtitles = subs.ToArray();
}
public class Subs {
public int Index { get; private set; }
public string LanguageId { get; private set; }
public string Language { get; private set; }
private readonly List<TimeSpan> subtitles;
public int SubtitleCount => subtitles.Count;
internal Subs(int index, string langId, string lang, List<TimeSpan> subs) {
Index = index;
Language = lang;
LanguageId = langId;
subtitles = subs;
}
}
}
| |
#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;
using System.Collections;
using System.Web.UI;
using Spring.Util;
#endregion
namespace Spring.Web.Support
{
/// <summary>
/// An implementation of <see cref="IHierarchicalWebNavigator"/> specific for <see cref="Control"/>s.
/// The navigator hierarchy equals the control hierarchy when using a <see cref="WebFormsResultWebNavigator"/>.
/// </summary>
/// <remarks>
/// <para>
/// This implementation supports 2 different navigator hierarchies:
/// <ul>
/// <li>The default hierarchy defined by <see cref="IHierarchicalWebNavigator.ParentNavigator"/></li>
/// <li>The hierarchy defined by a web form's <see cref="Control.Parent"/> hierarchy.</li>
/// </ul>
/// </para>
/// <para>
/// This implementation always checks the standard hierarchy first and - if a destination cannot be resolved, falls back
/// to the control hierarchy for resolving a specified navigation destination.
/// </para>
/// </remarks>
public class WebFormsResultWebNavigator : DefaultResultWebNavigator
{
/// <summary>
/// Holds the result match from <see cref="FindNavigableParent"/>.
/// </summary>
protected class NavigableControlInfo
{
/// <summary>
/// The matching control
/// </summary>
public readonly Control Control;
/// <summary>
/// The <see cref="IWebNavigator"/> instance associated with the control. May be null.
/// </summary>
public readonly IWebNavigator WebNavigator;
/// <summary>
/// Initializes the new match instance.
/// </summary>
/// <param name="control">the matching control. Must not be null!</param>
public NavigableControlInfo( Control control )
{
AssertUtils.ArgumentNotNull(control, "control");
Control = control;
if (Control is IWebNavigable)
{
WebNavigator = ((IWebNavigable)Control).WebNavigator;
}
else if (Control is IWebNavigator)
{
WebNavigator = (IWebNavigator)control;
}
}
}
/// <summary>
/// Finds the next <see cref="IWebNavigator"/> up the control hierarchy,
/// starting at the specified <paramref name="control"/>.
/// </summary>
/// <remarks>
/// This method checks both, for controls implementing <see cref="IWebNavigator"/> or <see cref="IWebNavigable"/>. In addition
/// when MasterPages are used, it interprets the control hierarchy as control->page->masterpage. (<see cref="WebUtils.GetLogicalParent"/>).
/// </remarks>
/// <param name="control">the control to start the search with.</param>
/// <param name="includeSelf">include checking the control itself or start search with its parent.</param>
/// <param name="restrictToValidNavigatorsOnly">requires <see cref="IWebNavigable"/>s to hold a valid <see cref="IWebNavigable.WebNavigator"/> instance.</param>
/// <returns>If found, the next <see cref="IWebNavigator"/> or <see cref="IWebNavigable"/>.
/// <c>null</c> otherwise</returns>
protected static NavigableControlInfo FindNavigableParent( Control control, bool includeSelf, bool restrictToValidNavigatorsOnly )
{
while (control != null)
{
if (!includeSelf)
{
// Get next parent in hierarchy
control = WebUtils.GetLogicalParent( control );
}
includeSelf = false;
if (control is IWebNavigable || control is IWebNavigator)
{
NavigableControlInfo nci = new NavigableControlInfo(control);
if (!restrictToValidNavigatorsOnly)
{
return nci;
}
if (nci.WebNavigator != null)
{
return nci;
}
}
}
return null;
}
private readonly Control _owner;
/// <summary>
/// The <see cref="Control"/> that this <see cref="WebFormsResultWebNavigator"/> is associated with.
/// </summary>
public Control Owner
{
get { return _owner; }
}
/// <summary>
/// Creates a new instance of a <see cref="IHierarchicalWebNavigator"/> for the specified control.
/// </summary>
/// <param name="owner">the control to be associated with this navigator.</param>
/// <param name="parent">the direct parent of this navigator</param>
/// <param name="initialResults">a dictionary containing results</param>
/// <param name="ignoreCase">specifies how to handle case for destination names.</param>
public WebFormsResultWebNavigator( Control owner, IWebNavigator parent, IDictionary initialResults, bool ignoreCase )
: base( parent, initialResults, ignoreCase )
{
AssertUtils.ArgumentNotNull( owner, "owner" );
_owner = owner;
}
/// <summary>
/// Determines, whether this navigator or one of its parents can
/// navigate to the destination specified in <paramref name="destination"/>.
/// </summary>
/// <param name="destination">the name of the navigation destination</param>
/// <returns>true, if this navigator can navigate to the destination.</returns>
public override bool CanNavigateTo( string destination )
{
return CheckCanNavigate( destination, true );
}
/// <summary>
/// Check, whether this navigator can navigate to the specified <paramref name="destination"/>.
/// </summary>
/// <param name="destination">the destination name to check.</param>
/// <param name="includeControlHierarchy">
/// whether the check shall include the <see cref="Owner"/> control hierarchy or
/// the standard <see cref="IHierarchicalWebNavigator.ParentNavigator"/> hierarchy only.
/// </param>
protected bool CheckCanNavigate( string destination, bool includeControlHierarchy )
{
// check the default path
if (base.CanNavigateTo( destination ))
{
return true;
}
// include checking the control hierarchy
if (includeControlHierarchy)
{
NavigableControlInfo nci = FindNavigableParent( this._owner, false, true );
if (nci != null)
{
// when delegating upwards, the control containing the matching result
// will appear as sender - this makes dealing with expressions more "natural".
return nci.WebNavigator.CanNavigateTo( destination );
}
}
return false;
}
/// <summary>
/// Returns a redirect url string that points to the
/// <see cref="Spring.Web.Support.Result.TargetPage"/> defined by this
/// result evaluated using this Page for expression
/// </summary>
/// <param name="destination">Name of the result.</param>
/// <param name="sender">the instance that issued this request</param>
/// <param name="context">The context to use for evaluating the SpEL expression in the Result</param>
/// <returns>A redirect url string.</returns>
public override string GetResultUri( string destination, object sender, object context )
{
if (this.CheckCanNavigate( destination, false ))
{
return base.GetResultUri( destination, sender, context );
}
NavigableControlInfo nci = FindNavigableParent( this._owner, false, true );
if (nci != null)
{
// when delegating upwards, the control containing the matching result
// will appear as sender - this makes dealing with expressions more "natural".
return nci.WebNavigator.GetResultUri( destination, nci.Control, context );
}
return HandleUnknownDestination( destination, sender, context );
}
/// <summary>
/// Redirects user to a URL mapped to specified result name.
/// </summary>
/// <param name="destination">Name of the result.</param>
/// <param name="sender">the instance that issued this request</param>
/// <param name="context">The context to use for evaluating the SpEL expression in the Result.</param>
public override void NavigateTo( string destination, object sender, object context )
{
if (this.CheckCanNavigate( destination, false ))
{
base.NavigateTo( destination, sender, context );
return;
}
NavigableControlInfo nci = FindNavigableParent( this._owner, false, true );
if (nci != null)
{
// when delegating upwards, the control containing the matching result
// will appear as sender - this makes dealing with expressions more "natural".
nci.WebNavigator.NavigateTo( destination, nci.Control, context );
return;
}
HandleUnknownDestination( destination, sender, context );
}
/// <summary>
/// Return the next available <see cref="IWebNavigator"/> within
/// this <see cref="Owner"/> control's parent hierarchy.
/// </summary>
public IWebNavigator ParentControlNavigator
{
get
{
// nci.WebNavigator is guaranteed to be non-null!
NavigableControlInfo nci = FindNavigableParent( this._owner, false, true );
if (nci == null) return null;
return nci.WebNavigator;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI;
using StardewModdingAPI.Utilities;
using StardewValley;
using StardewValley.Buildings;
using StardewValley.Characters;
using StardewValley.Menus;
namespace Pathoschild.Stardew.TractorMod.Framework
{
/// <summary>Manages textures loaded for the tractor and garage.</summary>
internal class TextureManager : IAssetLoader, IDisposable
{
/*********
** Fields
*********/
/// <summary>The absolute path to the Tractor Mod folder.</summary>
private readonly string DirectoryPath;
/// <summary>The base path for assets loaded through the game's content pipeline so other mods can edit them.</summary>
private readonly string PublicAssetBasePath;
/// <summary>The content helper from which to load assets.</summary>
private readonly IContentHelper ContentHelper;
/// <summary>The monitor with which to log errors.</summary>
private readonly IMonitor Monitor;
/// <summary>A case-insensitive list of files in the <c>assets</c> folder.</summary>
private readonly IDictionary<string, string> AssetMap;
/*********
** Accessors
*********/
/// <summary>The garage texture to apply.</summary>
public Texture2D GarageTexture { get; private set; }
/// <summary>The tractor texture to apply.</summary>
public Texture2D TractorTexture { get; private set; }
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="directoryPath">The absolute path to the Tractor Mod folder.</param>
/// <param name="publicAssetBasePath">The base path for assets loaded through the game's content pipeline so other mods can edit them.</param>
/// <param name="contentHelper">The content helper from which to load assets.</param>
/// <param name="monitor">The monitor with which to log errors.</param>
public TextureManager(string directoryPath, string publicAssetBasePath, IContentHelper contentHelper, IMonitor monitor)
{
this.DirectoryPath = directoryPath;
this.PublicAssetBasePath = publicAssetBasePath;
this.ContentHelper = contentHelper;
this.Monitor = monitor;
this.AssetMap = this.BuildAssetMap(directoryPath);
}
/// <summary>Update the textures if needed.</summary>
public void UpdateTextures()
{
// tractor
if (this.TryLoadFromContent("tractor", out Texture2D texture, out string error))
this.TractorTexture = texture;
else
this.Monitor.Log(error, LogLevel.Error);
// garage
if (this.TryLoadFromContent("garage", out texture, out error))
this.GarageTexture = texture;
else
this.Monitor.Log(error, LogLevel.Error);
}
/// <summary>Apply the mod textures to the given menu, if applicable.</summary>
/// <param name="menu">The menu to change.</param>
/// <param name="isFarmExpansion">Whether the menu is the Farm Expansion build menu.</param>
/// <param name="isPelicanFiber">Whether the menu is the Pelican Fiber build menu.</param>
/// <param name="isGarage">Whether a blueprint is for a tractor garage.</param>
/// <param name="reflection">The SMAPI API for accessing internal code.</param>
public void ApplyTextures(IClickableMenu menu, bool isFarmExpansion, bool isPelicanFiber, Func<BluePrint, bool> isGarage, IReflectionHelper reflection)
{
// vanilla menu
if (menu is CarpenterMenu carpenterMenu)
{
if (isGarage(carpenterMenu.CurrentBlueprint))
{
Building building = reflection.GetField<Building>(carpenterMenu, "currentBuilding").GetValue();
if (building.texture.Value != this.GarageTexture && this.GarageTexture != null)
building.texture = new Lazy<Texture2D>(() => this.GarageTexture);
}
return;
}
// Farm Expansion & Pelican Fiber menus
if (isFarmExpansion || isPelicanFiber)
{
BluePrint currentBlueprint = reflection.GetProperty<BluePrint>(menu, isFarmExpansion ? "CurrentBlueprint" : "currentBlueprint").GetValue();
if (isGarage(currentBlueprint))
{
Building building = reflection.GetField<Building>(menu, "currentBuilding").GetValue();
if (building.texture.Value != this.GarageTexture && this.GarageTexture != null)
building.texture = new Lazy<Texture2D>(() => this.GarageTexture);
}
}
}
/// <summary>Apply the mod textures to the given stable, if applicable.</summary>
/// <param name="horse">The horse to change.</param>
/// <param name="isTractor">Get whether a horse is a tractor.</param>
public void ApplyTextures(Horse horse, Func<Horse, bool> isTractor)
{
if (this.TractorTexture != null && isTractor(horse))
horse.Sprite.spriteTexture = this.TractorTexture;
}
/// <summary>Apply the mod textures to the given stable, if applicable.</summary>
/// <param name="stable">The stable to change.</param>
/// <param name="isGarage">Get whether a stable is a garage.</param>
public void ApplyTextures(Stable stable, Func<Stable, bool> isGarage)
{
if (this.GarageTexture != null && isGarage(stable))
stable.texture = new Lazy<Texture2D>(() => this.GarageTexture);
}
/// <inheritdoc />
public void Dispose()
{
this.GarageTexture?.Dispose();
this.TractorTexture?.Dispose();
}
/*********
** Private methods
*********/
/// <inheritdoc />
bool IAssetLoader.CanLoad<T>(IAssetInfo asset)
{
return
asset.AssetNameEquals("Buildings/TractorGarage")
|| asset.AssetNameEquals($"{this.PublicAssetBasePath}/Tractor")
|| asset.AssetNameEquals($"{this.PublicAssetBasePath}/Garage");
}
/// <inheritdoc />
T IAssetLoader.Load<T>(IAssetInfo asset)
{
// Allow for garages from older versions that didn't get normalized correctly.
// This can be removed once support for legacy data is dropped.
if (asset.AssetNameEquals($"Buildings/TractorGarage"))
return (T)(object)this.GarageTexture;
// load tractor or garage texture
string key = PathUtilities.GetSegments(asset.AssetName).Last();
return this.TryLoadFromFile(key, out Texture2D texture, out string error)
? (T)(object)texture
: throw new InvalidOperationException(error);
}
/// <summary>Try to load the asset for a texture from the game's content folder so other mods can apply edits.</summary>
/// <param name="spritesheet">The spritesheet name without the path or extension (like 'Tractor' or 'Garage').</param>
/// <param name="texture">The loaded texture, if found.</param>
/// <param name="error">A human-readable error to show to the user if texture wasn't found.</param>
private bool TryLoadFromContent(string spritesheet, out Texture2D texture, out string error)
{
try
{
texture = Game1.content.Load<Texture2D>($"{this.PublicAssetBasePath}/{spritesheet}");
error = null;
}
catch (Exception ex)
{
texture = null;
error = ex.ToString();
return false;
}
return texture != null;
}
/// <summary>Try to load the asset for a texture from the assets folder (including seasonal logic if applicable).</summary>
/// <param name="spritesheet">The spritesheet name without the path or extension (like 'tractor' or 'garage').</param>
/// <param name="texture">The loaded texture, if found.</param>
/// <param name="error">A human-readable error to show to the user if texture wasn't found.</param>
private bool TryLoadFromFile(string spritesheet, out Texture2D texture, out string error)
{
texture = this.TryGetTextureKey(spritesheet, out string key, out error)
? this.ContentHelper.Load<Texture2D>(key)
: null;
return texture != null;
}
/// <summary>Try to get the asset key for a texture from the assets folder (including seasonal logic if applicable).</summary>
/// <param name="spritesheet">The spritesheet name without the path or extension (like 'tractor' or 'garage').</param>
/// <param name="key">The asset key to use, if found.</param>
/// <param name="error">A human-readable error to show to the user if texture wasn't found.</param>
private bool TryGetTextureKey(string spritesheet, out string key, out string error)
{
string seasonalKey = $"{Game1.currentSeason}_{spritesheet}.png";
string defaultKey = $"{spritesheet}.png";
foreach (string possibleKey in new[] { seasonalKey, defaultKey })
{
if (this.AssetMap.TryGetValue(possibleKey, out string actualKey) && File.Exists(Path.Combine(this.DirectoryPath, $"assets/{actualKey}")))
{
key = $"assets/{actualKey}";
error = null;
return true;
}
}
key = null;
error = $"Couldn't find file '{defaultKey}' in the mod folder. This mod isn't installed correctly; try reinstalling the mod to fix it.";
return false;
}
/// <summary>Initialize a case-insensitive list of files in the <c>assets</c> folder.</summary>
/// <param name="directoryPath">The absolute path to the mod folder.</param>
private IDictionary<string, string> BuildAssetMap(string directoryPath)
{
var assetMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
// get assets folder
DirectoryInfo dir = new DirectoryInfo(Path.Combine(directoryPath, "assets"));
if (!dir.Exists)
{
this.Monitor.Log("Tractor Mod's 'assets' folder is missing. The mod will not work correctly. Try reinstalling the mod to fix this.", LogLevel.Error);
return assetMap;
}
// create map
foreach (FileInfo file in dir.GetFiles())
assetMap[file.Name] = file.Name;
return assetMap;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Common.Core;
#if VS14
using Microsoft.VisualStudio.ProjectSystem.Utilities;
#endif
using static VisualRust.ProjectSystem.FileSystemMirroring.IO.MsBuildFileSystemWatcherEntries.EntryState;
using static VisualRust.ProjectSystem.FileSystemMirroring.IO.MsBuildFileSystemWatcherEntries.EntryType;
namespace VisualRust.ProjectSystem.FileSystemMirroring.IO {
public class MsBuildFileSystemWatcherEntries {
private readonly Dictionary<string, Entry> _entries = new Dictionary<string, Entry>(StringComparer.OrdinalIgnoreCase);
public bool RescanRequired { get; private set; }
public void AddFile(string relativeFilePath, string shortPath) {
AddEntry(relativeFilePath, shortPath, File);
}
public void DeleteFile(string relativeFilePath) {
try {
Entry entry;
if (_entries.TryGetValue(relativeFilePath, out entry)) {
DeleteEntry(entry);
}
} catch (InvalidStateException) {
RescanRequired = true;
}
}
public void RenameFile(string previousRelativePath, string relativeFilePath, string shortPath) {
try {
RenameEntry(previousRelativePath, relativeFilePath, shortPath, File);
} catch (InvalidStateException) {
RescanRequired = true;
}
}
public void AddDirectory(string relativePath, string shortPath) {
AddEntry(relativePath, shortPath, Directory);
}
public void DeleteDirectory(string relativePath) {
try {
relativePath = PathHelper.EnsureTrailingSlash(relativePath);
foreach (var entry in _entries.Values.Where(v => v.RelativePath.StartsWithIgnoreCase(relativePath) ||
v.ShortPath.StartsWithIgnoreCase(relativePath)).ToList()) {
DeleteEntry(entry);
}
} catch (InvalidStateException) {
RescanRequired = true;
}
}
public ISet<string> RenameDirectory(string previousRelativePath, string relativePath, string shortPath) {
try {
previousRelativePath = PathHelper.EnsureTrailingSlash(previousRelativePath);
relativePath = PathHelper.EnsureTrailingSlash(relativePath);
shortPath = PathHelper.EnsureTrailingSlash(shortPath);
var newPaths = new HashSet<string>();
var entriesToRename = _entries.Values
.Where(v => v.State == Unchanged || v.State == Added || v.State == RenamedThenAdded)
.Where(v => v.RelativePath.StartsWithIgnoreCase(previousRelativePath) ||
v.ShortPath.StartsWithIgnoreCase(previousRelativePath)).ToList();
foreach (var entry in entriesToRename) {
var newEntryPath = entry.RelativePath.Replace(previousRelativePath, relativePath, 0, previousRelativePath.Length);
RenameEntry(entry.RelativePath, newEntryPath, shortPath, entry.Type);
newPaths.Add(newEntryPath);
}
return newPaths;
} catch (InvalidStateException) {
RescanRequired = true;
return null;
}
}
public void MarkAllDeleted() {
foreach (var entry in _entries.Values.ToList()) {
entry.PreviousRelativePath = null;
switch (entry.State) {
case Unchanged:
case Renamed:
case RenamedThenAdded:
entry.State = Deleted;
break;
case Added:
_entries.Remove(entry.RelativePath);
break;
case Deleted:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
RescanRequired = false;
}
private Entry AddEntry(string relativeFilePath, string shortPath, EntryType type) {
if (type == EntryType.Directory) {
relativeFilePath = PathHelper.EnsureTrailingSlash(relativeFilePath);
shortPath = PathHelper.EnsureTrailingSlash(shortPath);
}
Entry entry;
if (!_entries.TryGetValue(relativeFilePath, out entry)) {
entry = new Entry(relativeFilePath, shortPath, type) {
State = Added
};
_entries[relativeFilePath] = entry;
return entry;
}
switch (entry.State) {
case Unchanged:
case RenamedThenAdded:
case Added:
break;
case Deleted:
entry.State = Unchanged;
break;
case Renamed:
entry.State = RenamedThenAdded;
break;
default:
throw new ArgumentOutOfRangeException();
}
return entry;
}
private void DeleteEntry(Entry entry) {
switch (entry.State) {
case Unchanged:
entry.State = Deleted;
return;
case Added:
_entries.Remove(entry.RelativePath);
UpdateRenamedEntryOnDelete(entry);
return;
case Deleted:
return;
case RenamedThenAdded:
entry.State = Renamed;
UpdateRenamedEntryOnDelete(entry);
return;
case Renamed:
throw new InvalidStateException();
default:
throw new ArgumentOutOfRangeException();
}
}
private void RenameEntry(string previousRelativePath, string relativePath, string shortPath, EntryType type) {
Entry renamedEntry;
if (_entries.TryGetValue(previousRelativePath, out renamedEntry)) {
switch (renamedEntry.State) {
case Unchanged:
renamedEntry.State = Renamed;
var entry = AddEntry(relativePath, shortPath, type);
entry.PreviousRelativePath = previousRelativePath;
return;
case Added:
_entries.Remove(previousRelativePath);
if (renamedEntry.PreviousRelativePath == null) {
AddEntry(relativePath, shortPath, type);
} else {
UpdateRenamingChain(renamedEntry, relativePath, shortPath, type);
}
return;
case RenamedThenAdded:
renamedEntry.State = Renamed;
if (renamedEntry.PreviousRelativePath == null) {
AddEntry(relativePath, shortPath, type);
} else {
UpdateRenamingChain(renamedEntry, relativePath, shortPath, type);
renamedEntry.PreviousRelativePath = null;
}
return;
case Deleted:
case Renamed:
throw new InvalidStateException();
default:
throw new ArgumentOutOfRangeException();
}
}
}
private void UpdateRenamingChain(Entry renamedEntry, string relativePath, string shortPath, EntryType type) {
var previouslyRenamedEntryPath = renamedEntry.PreviousRelativePath;
Entry previouslyRenamedEntry;
if (!_entries.TryGetValue(previouslyRenamedEntryPath, out previouslyRenamedEntry)) {
return;
}
if (previouslyRenamedEntryPath == relativePath) {
switch (previouslyRenamedEntry.State) {
case Renamed:
previouslyRenamedEntry.State = Unchanged;
return;
case RenamedThenAdded:
case Unchanged:
case Added:
case Deleted:
throw new InvalidStateException();
default:
throw new ArgumentOutOfRangeException();
}
}
var entry = AddEntry(relativePath, shortPath, type);
entry.PreviousRelativePath = previouslyRenamedEntryPath;
}
private void UpdateRenamedEntryOnDelete(Entry entry) {
if (entry.PreviousRelativePath == null) {
return;
}
Entry renamedEntry;
if (!_entries.TryGetValue(entry.PreviousRelativePath, out renamedEntry)) {
return;
}
switch (renamedEntry.State) {
case Renamed:
renamedEntry.State = Deleted;
return;
case RenamedThenAdded:
renamedEntry.State = Added;
return;
case Unchanged:
case Added:
case Deleted:
throw new InvalidStateException();
default:
throw new ArgumentOutOfRangeException();
}
}
public MsBuildFileSystemWatcher.Changeset ProduceChangeset() {
var changeset = new MsBuildFileSystemWatcher.Changeset();
foreach (var entry in _entries.Values.ToList()) {
switch (entry.State) {
case Added:
case RenamedThenAdded:
if (entry.PreviousRelativePath != null) {
switch (entry.Type) {
case File:
changeset.RenamedFiles.Add(entry.PreviousRelativePath, entry.RelativePath);
break;
case Directory:
changeset.RenamedDirectories.Add(entry.PreviousRelativePath, entry.RelativePath);
break;
default:
throw new ArgumentOutOfRangeException();
}
} else {
switch (entry.Type) {
case File:
changeset.AddedFiles.Add(entry.RelativePath);
break;
case Directory:
changeset.AddedDirectories.Add(entry.RelativePath);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
entry.State = Unchanged;
break;
case Deleted:
switch (entry.Type) {
case File:
changeset.RemovedFiles.Add(entry.RelativePath);
break;
case Directory:
changeset.RemovedDirectories.Add(entry.RelativePath);
break;
default:
throw new ArgumentOutOfRangeException();
}
_entries.Remove(entry.RelativePath);
break;
case Renamed:
_entries.Remove(entry.RelativePath);
break;
default:
entry.State = Unchanged;
break;
}
}
return changeset;
}
[DebuggerDisplay("{Type} {PreviousRelativePath == null ? RelativePath : PreviousRelativePath + \" -> \" + RelativePath}, {State}")]
private class Entry {
public Entry(string relativePath, string shortPath, EntryType type) {
RelativePath = relativePath;
ShortPath = shortPath;
Type = type;
}
public string RelativePath { get; }
public EntryType Type { get; }
public string PreviousRelativePath { get; set; }
public EntryState State { get; set; } = Unchanged;
public string ShortPath { get; }
}
private class InvalidStateException : Exception {
}
internal enum EntryState {
Unchanged,
Added,
Deleted,
Renamed,
// This state marks special case when file/directory was first renamed and then another file/directory with the same name was added
RenamedThenAdded
}
internal enum EntryType {
File,
Directory
}
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.Tools.ServiceModel.Svcutil;
using Xunit;
namespace SvcutilTest
{
public partial class E2ETest : ClassFixture
{
private void TestFixture()
{
this_TestGroupBaselinesDir = Path.Combine(g_BaselinesDir, this_TestCaseName);
this_TestGroupOutputDir = Path.Combine(g_TestResultsDir, this_TestCaseName);
this_TestGroupBootstrapDir = Path.Combine(g_TestBootstrapDir, this_TestCaseName);
this_TestGroupProjDir = Path.Combine(g_TestResultsDir, this_TestCaseName, "Project");
if (!Directory.Exists(this_TestGroupOutputDir))
{
WriteLog("Svcutil version: " + g_SvcutilPkgVersion);
WriteLog("SdkVersion version: " + g_SdkVersion);
FileUtil.TryDeleteDirectory(this_TestGroupOutputDir);
Directory.CreateDirectory(this_TestGroupOutputDir);
FileUtil.TryDeleteDirectory(this_TestGroupProjDir);
Directory.CreateDirectory(this_TestGroupProjDir);
FileUtil.TryDeleteDirectory(this_TestGroupBootstrapDir);
Directory.CreateDirectory(this_TestGroupBootstrapDir);
Directory.CreateDirectory(this_TestGroupBaselinesDir);
}
Assert.True(Directory.Exists(this_TestGroupOutputDir), $"{nameof(this_TestGroupOutputDir)} is not initialized!");
Assert.True(Directory.Exists(this_TestGroupBaselinesDir), $"{nameof(this_TestGroupBaselinesDir)} is not initialized!");
}
private void TestSvcutil(string options, bool expectSuccess = true)
{
Assert.False(string.IsNullOrWhiteSpace(this_TestCaseName), $"{nameof(this_TestCaseName)} not initialized!");
Assert.False(options == null, $"{nameof(options)} not initialized!");
// this sets the current directory to the project's.
ProcessRunner.ProcessResult processResult = this_TestCaseProject.RunSvcutil(options, expectSuccess, this_TestCaseLogger);
_ = $"{processResult.OutputText}{Environment.NewLine}{((TestLogger)this_TestCaseLogger)}";
ValidateTest(options, this_TestCaseProject.DirectoryPath, processResult.ExitCode, processResult.OutputText, expectSuccess);
}
[Theory]
[Trait("Category", "BVT")]
[InlineData("silent")]
[InlineData("normal")]
[InlineData("verbose")]
[InlineData("debug")]
public void Help(string verbosity)
{
this_TestCaseName = "Help";
TestFixture();
var testCaseName = $"Help_{verbosity}";
InitializeE2E(testCaseName);
var options = $"-h -v {verbosity}";
TestSvcutil(options);
}
[Trait("Category", "Test")]
[Theory]
[InlineData("tfmDefault", null)]
[InlineData("tfmNetCoreapp31", "netcoreapp3.1")]
[InlineData("tfmNet50", "net5.0")]
[InlineData("tfmNet60", "net6.0")]
[InlineData("tfmNetstd20", "netstandard2.0")]
[InlineData("tfmNetstd21", "netstandard2.1")]
[InlineData("tfm100", "netcoreapp100.0")]
public void TFMBootstrap(string testCaseName, string targetFramework)
{
this_TestCaseName = "TFMBootstrap";
TestFixture();
InitializeE2E(testCaseName, createUniqueProject: true, sdkVersion: g_SdkVersion);
// set bootstrapper dir the same as the test output dir to validate generated files.
this_TestCaseBootstrapDir = this_TestCaseOutputDir;
// the boostrapper won't delete the folder if not created by it or with the -v Debug option
Directory.CreateDirectory(Path.Combine(this_TestCaseOutputDir, "SvcutilBootstrapper"));
var uri = $"\"\"{Path.Combine(g_TestCasesDir, "wsdl", "Simple.wsdl")}\"\"";
var tf = string.IsNullOrEmpty(targetFramework) ? string.Empty : $"-tf {targetFramework}";
var tr = $"-r \"\"{{Newtonsoft.Json,*}}\"\" -bd {this_TestCaseBootstrapDir.Replace("\\", "/")}";
var options = $"{uri.Replace("\\", "/")} {tf} {tr} -nl -tc global -v minimal -d ../{testCaseName} -n \"\"*,{testCaseName}_NS\"\"";
TestSvcutil(options);
}
[Trait("Category", "Test")]
[Theory]
[InlineData("XmlSerializer", "-ser XmlSerializer")]
[InlineData("DataContractSerializer", "-ser DataContractSerializer")]
[InlineData("Auto", "-ser Auto")]
[InlineData("MessageContract", "-mc")]
[InlineData("EnableDataBinding", "-edb")]
[InlineData("Internal", "-i")]
[InlineData("CollectionArray", "-ct System.Array")]
[InlineData("ExcludeType", "-et System.Net.HttpStatusCode")]
[InlineData("NoStdLib", "-nsl")]
[InlineData("wrapped", "-wr")]
[InlineData("Sync", "-syn")]
[InlineData("None", " ")]
public void CodeGenOptions(string testCaseName, string optionModifier)
{
this_TestCaseName = "CodeGenOptions";
TestFixture();
InitializeE2E(testCaseName);
var uri = Path.Combine(g_TestCasesDir, "wsdl", "WcfProjectNService", "tempuri.org.wsdl");
var options = $"{uri} {optionModifier} -nl -tf netcoreapp1.0";
this_TestCaseName = testCaseName;
TestSvcutil(AppendCommonOptions(options));
}
[Trait("Category", "Test")]
[Theory]
[InlineData("badUrl", "http://$NO_REPLACEMENT$^$Simple.svc")]
[InlineData("badwsdl", "$testCasesPath$/errorScenarios/badwsdl.wsdl.txt")]
[InlineData("collection", "/ct:MyCollectionType")]
[InlineData("exclude", "/et:MyExcludeType")]
[InlineData("invalidAddress", "http://invalidaddress -bd $testCaseBootstratDir$")]
[InlineData("noInputs", " ")]
[InlineData("ser", "/--serializer MySerializer")]
[InlineData("refVersionDoubleQuoted", "-r {Newtonsoft.Json, \"\"*\"\"}")]
public void ErrorScenarios(string testCaseName, string options)
{
this_TestCaseName = "ErrorScenarios";
TestFixture();
InitializeE2E(testCaseName);
options = options
.Replace("$serviceUrl$", g_ServiceUrl)
.Replace("$testCaseBootstratDir$", $"\"\"{this_TestCaseBootstrapDir}\"\"")
.Replace("$testCasesPath$", g_TestCasesDir);
this_TestCaseName = testCaseName;
TestSvcutil(AppendCommonOptions(options), expectSuccess: false);
}
[Trait("Category", "Test")]
[Theory]
[InlineData("multiDocFullPath", "$wsdlDir$tempuri.org.wsdl")]
[InlineData("multiDocAll", "$wsdlDir$*")]
[InlineData("multiDocWsdlWildcard", "$wsdlDir$*.wsdl")]
[InlineData("multiDocWsdlRelXsdWildcard", "$wsdlDir$*.wsdl ../wsdl/*.xsd")]
[InlineData("multiDocFullAndWildcard", "$wsdlDir$tempuri.org.wsdl $wsdlDir$*.xsd")]
[InlineData("multiDocAllRelative", "../wsdl/*")]
[InlineData("multiDocWsdlWildcardRelative", "../wsdl/*.wsdl")]
[InlineData("multiDocWsdlXsdWildcardRelative", "../wsdl/*.wsdl ../wsdl/*.xsd")]
[InlineData("multiDocRelativeAndWildcard", "../wsdl/tempuri.org.wsdl ../wsdl/*.xsd")]
[InlineData("multiDocRelativePath", "../wsdl/tempuri.org.wsdl")]
public void MultipleDocuments(string testCaseName, string uri)
{
this_TestCaseName = "MultipleDocuments";
TestFixture();
InitializeE2E(testCaseName);
//copy wsdl files into test project's path to make it easier to pass the params as relative paths.
var wsdlFile = Path.Combine(this_TestGroupOutputDir, "wsdl", "tempuri.org.wsdl");
if (!File.Exists(wsdlFile))
{
var wsdlDocsSrdDir = Path.Combine(g_TestCasesDir, "wsdl", "WcfProjectNService");
FileUtil.CopyDirectory(wsdlDocsSrdDir, Path.GetDirectoryName(wsdlFile));
}
Assert.True(File.Exists(wsdlFile), $"{wsdlFile} not initialized!");
uri = uri.Replace("$wsdlDir$", $"{Path.GetDirectoryName(wsdlFile)}{Path.DirectorySeparatorChar}");
this_TestCaseName = testCaseName;
TestSvcutil(AppendCommonOptions(uri));
}
[Trait("Category", "Test")]
[Theory]
[InlineData("wildcardNamespace", "-n *,TestNamespace", true)]
[InlineData("invalidNamespace", "-n *,Invalid/TestNamespace", false)]
[InlineData("urlNamespace", "-n http://schemas.datacontract.org/2004/07/WcfProjectNService,TestUrlNamespace", true)]
public void NamespaceParam(string testCaseName, string options, bool expectSuccess)
{
this_TestCaseName = "NamespaceParam";
TestFixture();
InitializeE2E(testCaseName);
var url = $"{Path.Combine(g_TestCasesDir, "wsdl", "WcfProjectNService", "tempuri.org.wsdl")}";
var dir = $"-d ../{ testCaseName}";
TestSvcutil(dir + " " + url + " " + options, expectSuccess);
}
[Trait("Category", "BVT")]
[Theory]
[InlineData("TypeReuse60", "net6.0")]
public void TypeReuse(string testCaseName, string targetFramework)
{
this_TestCaseName = "TypeReuse";
TestFixture();
InitializeE2E(testCaseName, createUniqueProject: true, targetFramework: targetFramework, sdkVersion: g_SdkVersion);
var uri = SetupProjectDependencies();
var outDir = Path.Combine(this_TestCaseOutputDir, "ServiceReference");
var options = $"{uri} -nl -v minimal -d {outDir.Replace("\\", "/")} -n \"\"*,{testCaseName}_NS\"\" -bd {this_TestCaseBootstrapDir.Replace("\\", "/")}";
TestSvcutil(options, expectSuccess: true);
}
private string SetupProjectDependencies()
{
var libProjPath = Path.Combine(this_TestGroupOutputDir, "TypesLib", "TypesLib.csproj");
var binProjPath = Path.Combine(this_TestGroupOutputDir, "BinLib", "BinLib.csproj");
var assemblyPath = Path.Combine(Path.GetDirectoryName(binProjPath), "bin", "Debug", "netstandard1.3", "BinLib.dll");
if (!File.Exists(assemblyPath))
{
var typeReuseProjectsPath = Path.Combine(g_TestCasesDir, "TypeReuse");
FileUtil.CopyDirectory(typeReuseProjectsPath, this_TestGroupOutputDir);
CreateGlobalJson(this_TestGroupOutputDir, this_TestCaseProject.SdkVersion);
MSBuildProj binProj = MSBuildProj.FromPathAsync(binProjPath, null, CancellationToken.None).Result;
ProcessRunner.ProcessResult result = binProj.BuildAsync(true, null, CancellationToken.None).Result;
Assert.True(result.ExitCode == 0, result.OutputText);
}
Assert.True(File.Exists(binProjPath), $"{nameof(binProjPath)} not initialized!");
Assert.True(File.Exists(libProjPath), $"{nameof(libProjPath)} not initialized!");
this_TestCaseProject.AddDependency(ProjectDependency.FromAssembly(assemblyPath));
this_TestCaseProject.AddDependency(ProjectDependency.FromProject(libProjPath));
this_TestCaseProject.SaveAsync(this_TestCaseLogger, CancellationToken.None).Wait();
ProcessRunner.ProcessResult ret = this_TestCaseProject.BuildAsync(true, this_TestCaseLogger, CancellationToken.None).Result;
Assert.True(ret.ExitCode == 0, ret.OutputText);
// keep the boostrapper projects in the outputs to be evaluated against baselines.
this_TestCaseBootstrapDir = this_TestCaseOutputDir;
Directory.CreateDirectory(Path.Combine(this_TestCaseBootstrapDir, "SvcutilBootstrapper"));
var uri = PathHelper.GetRelativePath(Path.Combine(this_TestGroupOutputDir, "TypeReuseSvc.wsdl"), new DirectoryInfo(this_TestCaseOutputDir));
return uri;
}
[Trait("Category", "BVT")]
[Theory]
[InlineData("UpdateServiceRefDefault", false)]
[InlineData("UpdateServiceRefBootstrapping", true)]
public void UpdateServiceRefBasic(string referenceFolderName, bool bootstrapping)
{
this_TestCaseName = "UpdateServiceRefBasic";
TestFixture();
var testCaseName = referenceFolderName;
InitializeE2E(testCaseName, createUniqueProject: true, sdkVersion: g_SdkVersion);
var paramsFile = SetupServiceReferenceFolder("dotnet-svcutil.params.json", referenceFolderName);
if (bootstrapping)
{
var updateOptions = UpdateOptions.FromFile(paramsFile);
// this forces bootstrapping of svcutil as the project reference is not available at runtime.
updateOptions.References.Add(ProjectDependency.FromPackage("Newtonsoft.Json", "*"));
updateOptions.Save(paramsFile);
}
var options = "-u -v minimal";
TestSvcutil(options, expectSuccess: true);
}
[Trait("Category", "Test")]
[Theory]
[InlineData("UpdateServiceRefOptionsDefault", 1, null, true)]
[InlineData("UpdateServiceRefOptions Folder With Spaces", 1, null, true)]
[InlineData("UpdateServiceRefOptions Folder With Spaces Full", 1, "\"\"UpdateServiceRefOptions Folder With Spaces Full\"\"", true)]
[InlineData("UpdateServiceRefOptionsRef", 1, "UpdateServiceRefOptionsRef", true)]
[InlineData("UpdateServiceRefOptionsRef2", 2, "UpdateServiceRefOptionsRef2", true)]
[InlineData("UpdateServiceRefOptions/Level1/Level2/UpdateRefLevels", 1, null, true)]
[InlineData("UpdateServiceRefOptions/Level1/Level2/UpdateRefLevelsFull", 1, "UpdateServiceRefOptions/Level1/Level2/UpdateRefLevelsFull", true)]
[InlineData("UpdateServiceRefOptionsFilePath", 1, "UpdateServiceRefOptionsFilePath/dotnet-svcutil.params.json", true)]
[InlineData("UpdateServiceRefOptionsFullPath", 1, "$testCaseOutputDir$/UpdateServiceRefOptionsFullPath/dotnet-svcutil.params.json", true)]
[InlineData("UpdateServiceRefOptionsExtraOptions", 1, "-nl", true)]
[InlineData("UpdateServiceRefOptionsExtraOptionsWarn", 1, "-edb -nb -elm", true)]
[InlineData("UpdateServiceRefOptionsDefaultOnMultipleRefs", 3, null, false)]
[InlineData("UpdateServiceRefOptionsOnMissingRef", 1, "Inexistent", false)]
public void UpdateServiceRefOptions(string referenceFolderName, int refCount, string cmdOptions, bool expectSuccess)
{
this_TestCaseName = "UpdateServiceRefOptions";
TestFixture();
var testCaseName = referenceFolderName.Replace(" ", "_").Split('/').Last();
InitializeE2E(testCaseName, createUniqueProject: true, sdkVersion: g_SdkVersion);
cmdOptions = cmdOptions?.Replace("$testCaseOutputDir$", this_TestCaseOutputDir.Replace("\\", "/"));
var paramsFile = SetupServiceReferenceFolder("dotnet-svcutil.params.json", referenceFolderName, refCount, addNamespace: true);
// disable type reuse (bootstrapping) to speed up test.
var udpateOptions = UpdateOptions.FromFile(paramsFile);
udpateOptions.TypeReuseMode = TypeReuseMode.None;
udpateOptions.Save(paramsFile);
var options = $"-u {cmdOptions} -v minimal";
TestSvcutil(options, expectSuccess);
}
[Trait("Category", "Test")]
[Theory]
[InlineData("Connected Services/CSServiceReference", false)]
[InlineData("Connected Services/CSServiceReferenceRoundtrip", true)]
public void UpdateServiceRefWCFCS(string referenceFolderName, bool addNamespace)
{
this_TestCaseName = "UpdateServiceRefWCFCS";
TestFixture();
var testCaseName = referenceFolderName.Replace(" ", "_").Split('/').Last();
InitializeE2E(testCaseName, createUniqueProject: true, sdkVersion: g_SdkVersion);
var paramsFile = SetupServiceReferenceFolder("ConnectedService.json", referenceFolderName, refCount: 1, addNamespace: false);
if (addNamespace)
{
// This will read the params file in WCF CS format but write it in Svcutil format.
var wcfcsoptions = WCFCSUpdateOptions.FromFile(paramsFile);
wcfcsoptions.NamespaceMappings.Clear();
wcfcsoptions.NamespaceMappings.Add(new KeyValuePair<string, string>("*", $"{testCaseName}_NS"));
wcfcsoptions.Save(paramsFile);
}
var options = "-u -v minimal";
TestSvcutil(options, expectSuccess: true);
}
private string SetupServiceReferenceFolder(string paramsFileName, string referenceFolderName, int refCount = 1, bool addNamespace = true)
{
var srcParamsFilePath = Path.Combine(g_TestCasesDir, "updateServiceReference", paramsFileName);
Assert.True(File.Exists(srcParamsFilePath), $"{nameof(srcParamsFilePath)} not initialized!");
// copy common test group project files into test cases's directory.
Directory.EnumerateFiles(this_TestGroupOutputDir, "*", SearchOption.TopDirectoryOnly).Where(f =>
{
File.Copy(f, Path.Combine(this_TestCaseProject.DirectoryPath, Path.GetFileName(f)));
return true;
});
var dstParamsFile = string.Empty;
for (int idx = 0; idx < refCount; idx++)
{
var suffix = idx == 0 ? string.Empty : $"_{idx}";
dstParamsFile = this_TestCaseProject.AddFakeServiceReference(srcParamsFilePath, referenceFolderName + suffix, addNamespace);
File.WriteAllText(dstParamsFile, File.ReadAllText(dstParamsFile).Replace("$testCasesPath$", g_TestCasesDir.Replace("\\", "/")));
}
return dstParamsFile;
}
[Trait("Category", "Test")]
[Theory]
[InlineData("BasicAuth.svc", false)]
[InlineData("BasicHttps.svc", true)]
[InlineData("BasicHttp.svc", true)]
[InlineData("BasicHttp_4_4_0.svc", true)]
[InlineData("BasicHttpSoap.svc", true)]
[InlineData("BasicHttpRpcEncSingleNs.svc", true)]
[InlineData("BasicHttpRpcLitSingleNs.svc", true)]
[InlineData("BasicHttpDocLitSingleNs.svc", true)]
[InlineData("BasicHttpRpcEncDualNs.svc", true)]
[InlineData("BasicHttpRpcLitDualNs.svc", true)]
[InlineData("BasicHttpDocLitDualNs.svc", true)]
public void WcfRuntimeBasicSvcs(string serviceName, bool expectSuccess)
{
this_TestCaseName = "WcfRuntimeBasicSvcs";
TestFixture();
WcfRuntimeSvcs(serviceName, expectSuccess);
}
[Trait("Category", "Test")]
[Theory]
[InlineData("BasicHttpsTransSecMessCredsUserName.svc", true)]
public void WcfRuntimeBasicHttpsTransSecMessCredsUserName(string serviceName, bool expectSuccess)
{
this_TestCaseName = "WcfRuntimeBasicHttpsTransSecMessCredsUserName";
TestFixture();
WcfRuntimeSvcs(serviceName, expectSuccess);
}
[Trait("Category", "Test")]
[Theory]
[InlineData("TcpTransSecMessCredsUserName.svc", true)]
public void WcfRuntimeNettcpTransSecMessCredsUserName(string serviceName, bool expectSuccess)
{
this_TestCaseName = "WcfRuntimeNettcpTransSecMessCredsUserName";
TestFixture();
var testCaseName = serviceName.Replace(".svc", "");
InitializeE2E(testCaseName);
var uri = $"{g_ServiceUrl}/{serviceName}".Replace("http", "net.tcp");
this_TestCaseName = testCaseName;
TestSvcutil(AppendCommonOptions(uri), expectSuccess);
}
[Trait("Category", "Test")]
[Theory]
[InlineData("HttpsTransSecMessCredsUserName.svc", true)]
public void WsHttpBindingAndws2007HttpBindingTransSecMessCredsUserName(string serviceName, bool expectSuccess)
{
this_TestCaseName = "WsHttpBindingAndws2007HttpBindingTransSecMessCredsUserName";
TestFixture();
WcfRuntimeSvcs(serviceName, expectSuccess);
}
[Trait("Category", "Test")]
[Theory]
[InlineData("Duplex.svc", true)]
public void WcfRuntimeDuplexCallback(string serviceName, bool expectSuccess)
{
this_TestCaseName = "DuplexCallback";
TestFixture();
WcfRuntimeSvcs(serviceName, expectSuccess);
}
[Trait("Category", "Test")]
[Theory]
[InlineData("NetHttp.svc", true)]
[InlineData("NetHttpWebSockets.svc", true)]
[InlineData("NetHttps.svc", true)]
[InlineData("NetHttpsWebSockets.svc", true)]
public void WcfRuntimeNetHttpSvcs(string serviceName, bool expectSuccess)
{
this_TestCaseName = "WcfRuntimeNetHttpSvcs";
TestFixture();
WcfRuntimeSvcs(serviceName, expectSuccess);
}
[Trait("Category", "Test")]
[Theory]
[InlineData("ReliableSessionService.svc", true)]
public void WcfRuntimeReliableSessionSvc(string serviceName, bool expectSuccess)
{
this_TestCaseName = "WcfRuntimeReliableSessionSvc";
TestFixture();
WcfRuntimeSvcs(serviceName, expectSuccess);
}
private void WcfRuntimeSvcs(string serviceName, bool expectSuccess)
{
var testCaseName = serviceName.Replace(".svc", "");
InitializeE2E(testCaseName);
var uri = $"{g_ServiceUrl}/{serviceName}";
this_TestCaseName = testCaseName;
TestSvcutil(AppendCommonOptions(uri), expectSuccess);
}
/*
// TODO:
// this is not an actual test but it is a way to keep the repo clean of dead-baselines.
// in order to reliably run this test, it must run at the end, given that this
// is a partial class it is hard to enforce the order.
// need to find a way to keep this test running reliably.
[Trait("Category", "Test")]
[Fact]
public void CheckBaslines()
{
this_TestCaseName = nameof(CheckBaslines);
TestFixture();
var allBaselines = Directory.EnumerateFiles(g_BaselinesDir, "*", SearchOption.AllDirectories).ToList();
var allOutputs = Directory.EnumerateFiles(g_TestResultsDir, "*", SearchOption.AllDirectories).ToList();
var baselinesWithNoOutputs = allBaselines.Where(b =>
!allOutputs.Any(o =>
{
var relPath1 = PathHelper.GetRelativePath(o, g_TestResultsDir);
var relPath2 = PathHelper.GetRelativePath(b, g_BaselinesDir);
return relPath1.Equals(relPath2, RuntimeEnvironmentHelper.FileStringComparison);
})).ToList();
// The purpose of this test is to ensure all baselines are validated so no dead-baselines are kept in the repo.
// This test must be the last to run so it must be the defined after all other tests in this file.
if (baselinesWithNoOutputs.Count() > 0)
{
Assert.True(false, GenerateBaselineDeleteScript(baselinesWithNoOutputs));
}
}*/
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Linq.Expressions;
using System.Linq;
using Ankor.Core.Action;
using Ankor.Core.Change;
using Ankor.Core.Event;
using Ankor.Core.Messaging.Json;
namespace Ankor.Core.Ref {
internal class DynaRef : DynamicObject, IRef, IEquatable<DynaRef> {
private readonly IInternalModel model;
private readonly string path;
internal protected DynaRef(IInternalModel model, string path) {
this.model = model;
this.path = path;
}
internal static DynaRef CreateRef(IInternalModel jModel, string path) {
return new DynaRef(jModel, path);
}
public string Path {
get { return this.path; }
}
public dynamic Dynamic {
get { return this; }
}
public string PropertyName {
get { return PathSyntax.GetPropertyName(path); }
}
public object Value {
get { return InternalGetValue(); }
set { ApplyChange(new LocalSource(), Change.Change.ValueChange(value)); }
}
/// <summary>
/// Apply a change on this ref, set value and fire event.
/// </summary>
public void ApplyChange(IEventSource source, Change.Change change) {
switch (change.Type) {
case ChangeType.Value:
HandleValueChange(change);
break;
case ChangeType.Insert:
HandleInsertChange(change);
break;
case ChangeType.Delete:
HandleDeleteChange(change);
break;
case ChangeType.Replace:
HandleReplaceChange(change);
break;
default: throw new ArgumentException("change type not yet supported " + change.Type);
}
model.Dispatcher.Dispatch(new ChangeEvent(source, this, change));
}
private void HandleReplaceChange(Change.Change change) {
object val = Value;
if (!IsList(val)) {
throw new ArgumentException("replace change is (for now) only supported for arrays");
}
IList list = ((IList)val);
ICollection newElems = ((ICollection) change.Value);
int startIndex = ToListIndex(change);
if (startIndex > list.Count) {
throw new ArgumentException("replace change index " + startIndex + " cannot be bigger than current list size " + list.Count);
}
foreach (var newElem in newElems) {
if (list.Count > startIndex) {
list[startIndex] = newElem;
} else {
list.Add(newElem);
}
startIndex++;
}
}
private void HandleDeleteChange(Change.Change change) {
object val = Value;
if (!IsList(val)) {
throw new ArgumentException("delete change is (for now) only supported for arrays");
}
((IList) val).RemoveAt(ToListIndex(change));
}
private void HandleValueChange(Change.Change change) {
if (!Equals(change.Value, this.Value)) {
// is this ok for non skalar types?
InternalSetValue(change.Value);
}
}
private void HandleInsertChange(Change.Change change) {
object val = Value;
if (!IsList(val)) {
throw new ArgumentException("Cannot insert on non array ref " + ToString());
}
var list = ((IList) val);
var index = ToListIndex(change);
if (index < 0) {
throw new ArgumentException("index must be positive " + index);
} else if (index < list.Count) {
list.Insert(index, change.Value);
} else if (index == list.Count) {
list.Add(change.Value);
} else {
throw new ArgumentException("index " + index + " cannot be greater than list size " + list.Count);
}
}
private static int ToListIndex(Change.Change change) {
if (change.Key is string) {
return int.Parse((string) change.Key);
}
if (change.Key is long) {
return (int) (long) change.Key;
}
return (int)change.Key;
}
private bool IsList() {
return IsList(Value);
}
private static bool IsList(object val) {
return val is IList;
}
#region EQUALITY
public static bool operator ==(DynaRef left, DynaRef right) {
return Equals(left, right);
}
public static bool operator !=(DynaRef left, DynaRef right) {
return !Equals(left, right);
}
public bool Equals(IRef other) {
if (ReferenceEquals(null, other)) {
return false;
}
if (ReferenceEquals(this, other)) {
return true;
}
if (other is DynaRef) {
if (!model.Equals(((DynaRef)other).model )) {
return false;
}
}
//return model.Equals(other.Model) && string.Equals(path, other.Path);
return string.Equals(path, other.Path);
}
public bool Equals(DynaRef other) {
return this.Equals((IRef)other);
}
public override bool Equals(object obj) {
if (ReferenceEquals(null, obj)) {
return false;
}
if (ReferenceEquals(this, obj)) {
return true;
}
if (obj.GetType() != this.GetType()) {
return false;
}
return Equals((DynaRef) obj);
}
public override int GetHashCode() {
unchecked {
return (model.GetHashCode()*397) ^ path.GetHashCode();
}
}
#endregion
IEnumerator IEnumerable.GetEnumerator() {
//if (model.IsArray(path)) {
if (IsList()) {
return ((IEnumerable<IRef>)this).GetEnumerator();
} else {
return ((IEnumerable<KeyValuePair<string, IRef>>)this).GetEnumerator();
}
}
public IEnumerator<IRef> GetEnumerator() {
//return model.GetRefEnumerator(path);
var list = this.Value as IList;
if (list != null) {
int i = 0;
var refList = new List<DynaRef>(from object entry in list select CreateRef(model, PathSyntax.AddArrayIndex(path, i++)));
return refList.GetEnumerator();
}
throw new ArgumentException("cannot enumerate on non array ref '" + path + "'");
}
IEnumerator<KeyValuePair<string, IRef>> IEnumerable<KeyValuePair<string, IRef>>.GetEnumerator() {
return ((IEnumerable<KeyValuePair<string, IRef>>)this.InternalGetValue()).GetEnumerator();
}
/// <summary>
/// Do set the value on this ref w.o. any event notifications.
/// </summary>
private void InternalSetValue(object value) {
if (value is DynaRef) { // auto deref if necessary
value = (value as DynaRef).Value;
}
//Console.WriteLine("SET value " + path + " to " + value);
model.InternalSetValue(value, path);
}
private object InternalGetValue() {
//Console.WriteLine("GET value " + path);
return model.InternalGetValue(path);
}
private PathSyntax PathSyntax {
get { return model.PathSyntax; }
}
public override string ToString() {
return String.Format("dref {0}", path);
}
public override bool TrySetMember(SetMemberBinder binder, object value) {
//Console.WriteLine("Try Set Member on " + path + " for " + binder.Name);
AppendPath(binder.Name).Value = value;
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object result) {
var dynaRef = AppendPath(binder.Name);
result = dynaRef;
//Console.WriteLine("Try Get value at " + path + " for " + binder.Name + " got " + result);
return result != null;
}
public IRef this[string subpath] {
get { return AppendPath(subpath); }
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) {
if (indexes.Length != 1) {
throw new ArgumentException("multiple indexes not supported @" + ToString());
}
if (!(indexes[0] is int)) {
throw new ArgumentException(string.Format("only int index supported (not {0}) @ {1}", indexes[0].GetType(), this));
}
result = AppendIndex((int)indexes[0]);
return result != null;
//WriteDebug("TryGetIndex " + string.Join(",", indexes));
}
public IRef AppendPath(string subPath) {
return DynaRef.CreateRef(model, MakeAbsolutePath(subPath));
}
public IRef AppendIndex(int index) {
return CreateRef(model, PathSyntax.AddArrayIndex(path, index));
}
private bool IsAncestorOf(IRef property) {
return PathSyntax.IsAncestor(this.path, property.Path);
}
public bool IsDescendantOf(IRef property) {
return PathSyntax.IsDescendant(this.path, property.Path);
}
private string MakeRelativePath(string absolutePath) {
return PathSyntax.MakeRelativePath(path, absolutePath);
}
private string MakeAbsolutePath(string subPath) {
return PathSyntax.MakeAbsolutePath(path, subPath);
}
public event PropertyChangedEventHandler PropertyChanged {
add {
model.EventRegistry.Add(value, new ChangeEventListener(e => {
PropertyChangedEventArgs args = null;
if (this.Equals(e.Property) || this.IsDescendantOf(e.Property)) {
args = new PropertyChangedEventArgs("Value"); // my Value changed or a parent of me changed
} else if (this.IsAncestorOf(e.Property)) {
// change is somewhere deeper below me, need this for manual pattern matching handlers
// maybe remove this and use another event (generic) or the java like annotation patterns
string relativePath = MakeRelativePath(e.Property.Path);
args = new PropertyChangedEventArgs(relativePath);
}
if (args != null) {
value(this, args);
}
}));
//Console.WriteLine("Registered PropertyChanged at '" + Path + "' from " + value.GetHashCode());
}
remove {
model.EventRegistry.RemoveByKey(value);
}
}
//private void OnModelPropertyChanged(object sender, PropertyChangedEventArgs e) {
// var handler = propertyChanged;
// string changePath = e.PropertyName;
// if (handler != null) {
// if (changePath.Equals(path)) { // exactly myself
// handler(this, new PropertyChangedEventArgs("Value"));
// } else if (PathSyntax.IsDescendent(changePath, path)) { // change is somewhere deeper below me (is a descendant) ATTENTION the >.< for startswith
// // this is for manual pattern matching change handlers. maybe go for another event here
// string relativePath = MakeRelativePath(changePath);
// handler(this, new PropertyChangedEventArgs(relativePath));
// } else if (PathSyntax.IsDescendent(path, changePath)) { // i am descendent, maybe i have changed
// // TODO should check against old value?! but where to get it from, model is already new
// handler(this, new PropertyChangedEventArgs("Value"));
// //handler(this, new PropertyChangedEventArgs(""));
// }
// }
//}
public event ActionReceivedEventHandler ActionReceived {
add {
model.EventRegistry.Add(new ActionEventListener(e => {
if (e.Property.Path == this.path) { // only actions that are for this ref
value(this, e);
}
}));
}
remove { throw new NotImplementedException(); }
}
public void Dispose() {
// jModel.PropertyChanged -= OnModelPropertyChanged;
// TODO remove the listeners
}
public void Fire(AAction aAction) {
Fire(aAction, new LocalSource());
}
public void Fire(string actionName) {
Fire(new AAction(actionName));
}
public void Fire(AAction action, IEventSource remoteSource) {
model.Dispatcher.Dispatch(new ActionEvent(new LocalSource(), this, action));
}
#region DEBUG_OVERRIDES
public override System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames() {
WriteDebug("GetDynamicMemberNames");
return base.GetDynamicMemberNames();
}
public override DynamicMetaObject GetMetaObject(System.Linq.Expressions.Expression parameter) {
WriteDebug("GetMetaObject ");
var target = base.GetMetaObject(parameter);
return target;
//return new MyDynamicMetaObject(parameter, BindingRestrictions.Empty, this, target);
}
public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result) {
WriteDebug("03");
return base.TryBinaryOperation(binder, arg, out result);
}
public override bool TryConvert(ConvertBinder binder, out object result) {
WriteDebug("TryConvert() to " + binder.Type);
return base.TryConvert(binder, out result);
}
public override bool TryCreateInstance(CreateInstanceBinder binder, object[] args, out object result) {
WriteDebug("05");
return base.TryCreateInstance(binder, args, out result);
}
public override bool TryDeleteMember(DeleteMemberBinder binder) {
WriteDebug("06");
return base.TryDeleteMember(binder);
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {
WriteDebug("07");
return base.TryInvokeMember(binder, args, out result);
}
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result) {
WriteDebug("08");
return base.TryInvoke(binder, args, out result);
}
public override bool TryUnaryOperation(UnaryOperationBinder binder, out object result) {
WriteDebug("09");
return base.TryUnaryOperation(binder, out result);
}
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) {
WriteDebug("11");
return base.TrySetIndex(binder, indexes, value);
}
public override bool TryDeleteIndex(DeleteIndexBinder binder, object[] indexes) {
WriteDebug("12");
return base.TryDeleteIndex(binder, indexes);
}
private void WriteDebug(string id) {
//Console.WriteLine("CALLED " + id + " p: " + path );
}
#endregion
#region DEBUG_META_OBJECT
public class MyDynamicMetaObject : DynamicMetaObject {
private string path;
private DynamicMetaObject target;
public MyDynamicMetaObject(Expression expression, BindingRestrictions restrictions) : base(expression, restrictions) { }
public MyDynamicMetaObject(Expression expression, BindingRestrictions restrictions, DynaRef dobj, DynamicMetaObject target)
: base(expression, restrictions, dobj) {
this.path = dobj.path;
this.target = target;
}
private void WriteDebug(string id) {
//Console.WriteLine("CALLED " + id + " p: " + path);
}
public override DynamicMetaObject BindConvert(ConvertBinder binder) {
WriteDebug("BindConvert " + binder.Type);
return target.BindConvert(binder);
}
public override DynamicMetaObject BindGetMember(GetMemberBinder binder) {
WriteDebug("BindGetMember "+ binder.Name);
return target.BindGetMember(binder);
}
public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) {
WriteDebug("003");
return target.BindSetMember(binder, value);
}
public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) {
WriteDebug("004");
return target.BindDeleteMember(binder);
}
public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) {
WriteDebug("005");
return target.BindGetIndex(binder, indexes);
}
public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) {
WriteDebug("006");
return target.BindSetIndex(binder, indexes, value);
}
#region Overrides of DynamicMetaObject
public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes) {
WriteDebug("007");
return target.BindDeleteIndex(binder, indexes);
}
public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
WriteDebug("008");
return target.BindInvokeMember(binder, args);
}
public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) {
WriteDebug("009");
return target.BindInvoke(binder, args);
}
public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) {
WriteDebug("010");
return target.BindCreateInstance(binder, args);
}
public override DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder) {
WriteDebug("011");
return target.BindUnaryOperation(binder);
}
public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg) {
WriteDebug("012");
return target.BindBinaryOperation(binder, arg);
}
public override IEnumerable<string> GetDynamicMemberNames() {
WriteDebug("013");
return target.GetDynamicMemberNames();
}
#endregion
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CocosSharp
{
// ideas taken from:
// . The ocean spray in your face [Jeff Lander]
// http://www.double.co.nz/dust/col0798.pdf
// . Building an Advanced Particle System [John van der Burg]
// http://www.gamasutra.com/features/20000623/vanderburg_01.htm
// . LOVE game engine
// http://love2d.org/
//
//
// Radius mode support, from 71 squared
// http://particledesigner.71squared.com/
//
// IMPORTANT: Particle Designer is supported by cocos2d, but
// 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d,
// cocos2d uses a another approach, but the results are almost identical.
//
public enum CCEmitterMode
{
Gravity,
Radius,
}
public enum CCPositionType
{
Free, // Living particles are attached to the world and are unaffected by emitter repositioning.
Relative, // Living particles are attached to the world but will follow the emitter repositioning.
// Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite.
Grouped, // Living particles are attached to the emitter and are translated along with it.
}
public abstract class CCParticleSystem : CCNode
{
public const int ParticleDurationInfinity = -1;
public const int ParticleStartSizeEqualToEndSize = -1;
public const int ParticleStartRadiusEqualToEndRadius = -1;
// ivars
GravityMoveMode gravityMode;
RadialMoveMode radialMode;
#region Structures
protected struct GravityMoveMode
{
internal CCPoint Gravity { get; set; }
internal float RadialAccel { get; set; }
internal float RadialAccelVar { get; set; }
internal float Speed { get; set; }
internal float SpeedVar { get; set; }
internal float TangentialAccel { get; set; }
internal float TangentialAccelVar { get; set; }
internal bool RotationIsDir { get; set; }
}
protected struct RadialMoveMode
{
internal float EndRadius { get; set; }
internal float EndRadiusVar { get; set; }
internal float RotatePerSecond { get; set; }
internal float RotatePerSecondVar { get; set; }
internal float StartRadius { get; set; }
internal float StartRadiusVar { get; set; }
}
// Particle structures
protected struct CCParticleBase
{
internal float TimeToLive { get; set; }
internal float Rotation { get; set; }
internal float Size { get; set; }
internal float DeltaRotation { get; set; }
internal float DeltaSize { get; set; }
internal CCPoint Position { get; set; }
internal CCPoint StartPosition { get; set; }
internal CCColor4F Color { get; set; }
internal CCColor4F DeltaColor { get; set; }
}
protected struct CCParticleGravity
{
internal int AtlasIndex { get; set; }
internal CCParticleBase ParticleBase;
internal CCPoint Direction { get; set; }
internal float RadialAccel { get; set; }
internal float TangentialAccel { get; set; }
}
protected struct CCParticleRadial
{
internal int AtlasIndex { get; set; }
internal CCParticleBase ParticleBase;
internal float Angle { get; set; }
internal float Radius { get; set; }
internal float DegreesPerSecond { get; set; }
internal float DeltaRadius { get; set; }
}
#endregion Structures
#region Properties
public bool IsActive { get; private set; }
public bool AutoRemoveOnFinish { get; set; }
public bool OpacityModifyRGB { get; set; }
public virtual int TotalParticles { get; set; }
protected int AllocatedParticles { get; set; }
public int ParticleCount { get; private set; }
public int AtlasIndex { get; set; }
protected float Elapsed { get; private set; }
public float Duration { get; set; }
public float Life { get; set; }
public float LifeVar { get; set; }
public float Angle { get; set; }
public float AngleVar { get; set; }
public float StartSize { get; set; }
public float StartSizeVar { get; set; }
public float EndSize { get; set; }
public float EndSizeVar { get; set; }
public float StartSpin { get; set; }
public float StartSpinVar { get; set; }
public float EndSpin { get; set; }
public float EndSpinVar { get; set; }
public float EmissionRate { get; set; }
protected float EmitCounter { get; set; }
public CCPoint SourcePosition { get; set; }
public CCPoint PositionVar { get; set; }
public CCPositionType PositionType { get; set; }
public CCColor4F StartColor { get; set; }
public CCColor4F StartColorVar { get; set; }
public CCColor4F EndColor { get; set; }
public CCColor4F EndColorVar { get; set; }
// We only want this to be set when system initialised
public CCEmitterMode EmitterMode { get; private set; }
protected CCParticleGravity[] GravityParticles { get; set; }
protected CCParticleRadial[] RadialParticles { get; set; }
public bool IsFull
{
get { return (ParticleCount == TotalParticles); }
}
protected GravityMoveMode GravityMode
{
get
{
Debug.Assert(EmitterMode == CCEmitterMode.Gravity, "Particle Mode should be Gravity");
return gravityMode;
}
set { gravityMode = value; }
}
protected RadialMoveMode RadialMode
{
get
{
Debug.Assert(EmitterMode == CCEmitterMode.Radius, "Particle Mode should be Radius");
return radialMode;
}
set { radialMode = value; }
}
// Gravity mode
public CCPoint Gravity
{
get { return GravityMode.Gravity; }
set { gravityMode.Gravity = value; }
}
public float TangentialAccel
{
get { return GravityMode.TangentialAccel; }
set { gravityMode.TangentialAccel = value; }
}
public float TangentialAccelVar
{
get { return GravityMode.TangentialAccelVar; }
set { gravityMode.TangentialAccelVar = value; }
}
public float RadialAccel
{
get { return GravityMode.RadialAccel; }
set { gravityMode.RadialAccel = value; }
}
public float RadialAccelVar
{
get { return GravityMode.RadialAccelVar; }
set { gravityMode.RadialAccelVar = value; }
}
public bool RotationIsDir
{
get { return GravityMode.RotationIsDir; }
set { gravityMode.RotationIsDir = value; }
}
public float Speed
{
get { return GravityMode.Speed; }
set { gravityMode.Speed = value; }
}
public float SpeedVar
{
get { return GravityMode.SpeedVar; }
set { gravityMode.SpeedVar = value; }
}
// Radius mode
public float StartRadius
{
get { return RadialMode.StartRadius; }
set { radialMode.StartRadius = value; }
}
public float StartRadiusVar
{
get { return RadialMode.StartRadiusVar; }
set { radialMode.StartRadiusVar = value; }
}
public float EndRadius
{
get { return RadialMode.EndRadius; }
set { radialMode.EndRadius = value; }
}
public float EndRadiusVar
{
get { return RadialMode.EndRadiusVar; }
set { radialMode.EndRadiusVar = value; }
}
public float RotatePerSecond
{
get { return RadialMode.RotatePerSecond; }
set { radialMode.RotatePerSecond = value; }
}
public float RotatePerSecondVar
{
get { return RadialMode.RotatePerSecondVar; }
set { radialMode.RotatePerSecondVar = value; }
}
#endregion Properties
#region Constructors
public CCParticleSystem(string plistFile, string directoryName = null)
: this(new CCParticleSystemConfig(plistFile, directoryName))
{ }
protected CCParticleSystem(int numberOfParticles, CCEmitterMode emitterMode = CCEmitterMode.Gravity)
: this(numberOfParticles, true, emitterMode)
{
}
CCParticleSystem(int numberOfParticles, bool shouldAllocParticles, CCEmitterMode emitterMode = CCEmitterMode.Gravity)
{
TotalParticles = numberOfParticles;
AllocatedParticles = numberOfParticles;
PositionType = CCPositionType.Free;
EmitterMode = emitterMode;
IsActive = true;
AutoRemoveOnFinish = false;
if(shouldAllocParticles)
{
if (emitterMode == CCEmitterMode.Gravity)
{
GravityParticles = new CCParticleGravity[numberOfParticles];
}
else
{
RadialParticles = new CCParticleRadial[numberOfParticles];
}
}
}
public CCParticleSystem(CCParticleSystemConfig particleConfig) : this(particleConfig.MaxParticles, false)
{
Duration = particleConfig.Duration;;
Life = particleConfig.Life;
LifeVar = particleConfig.LifeVar;
EmissionRate = TotalParticles / Life;
Angle = particleConfig.Angle;
AngleVar = particleConfig.AngleVar;
CCColor4F startColor = new CCColor4F();
startColor.R = particleConfig.StartColor.R;
startColor.G = particleConfig.StartColor.G;
startColor.B = particleConfig.StartColor.B;
startColor.A = particleConfig.StartColor.A;
StartColor = startColor;
CCColor4F startColorVar = new CCColor4F();
startColorVar.R = particleConfig.StartColorVar.R;
startColorVar.G = particleConfig.StartColorVar.G;
startColorVar.B = particleConfig.StartColorVar.B;
startColorVar.A = particleConfig.StartColorVar.A;
StartColorVar = startColorVar;
CCColor4F endColor = new CCColor4F();
endColor.R = particleConfig.EndColor.R;
endColor.G = particleConfig.EndColor.G;
endColor.B = particleConfig.EndColor.B;
endColor.A = particleConfig.EndColor.A;
EndColor = endColor;
CCColor4F endColorVar = new CCColor4F();
endColorVar.R = particleConfig.EndColorVar.R;
endColorVar.G = particleConfig.EndColorVar.G;
endColorVar.B = particleConfig.EndColorVar.B;
endColorVar.A = particleConfig.EndColorVar.A;
EndColorVar = endColorVar;
StartSize = particleConfig.StartSize;
StartSizeVar = particleConfig.StartSizeVar;
EndSize = particleConfig.EndSize;
EndSizeVar = particleConfig.EndSizeVar;
CCPoint position;
position.X = particleConfig.Position.X;
position.Y = particleConfig.Position.Y;
Position = position;
CCPoint positionVar;
positionVar.X = particleConfig.PositionVar.X;
positionVar.Y = particleConfig.PositionVar.X;
PositionVar = positionVar;
StartSpin = particleConfig.StartSpin;
StartSpinVar = particleConfig.StartSpinVar;
EndSpin = particleConfig.EndSpin;
EndSpinVar = particleConfig.EndSpinVar;
EmitterMode = particleConfig.EmitterMode;
if (EmitterMode == CCEmitterMode.Gravity)
{
GravityParticles = new CCParticleGravity[TotalParticles];
GravityMoveMode newGravityMode = new GravityMoveMode();
CCPoint gravity;
gravity.X = particleConfig.Gravity.X;
gravity.Y = particleConfig.Gravity.Y;
newGravityMode.Gravity = gravity;
newGravityMode.Speed = particleConfig.GravitySpeed;
newGravityMode.SpeedVar = particleConfig.GravitySpeedVar;
newGravityMode.RadialAccel = particleConfig.GravityRadialAccel;
newGravityMode.RadialAccelVar = particleConfig.GravityRadialAccelVar;
newGravityMode.TangentialAccel = particleConfig.GravityTangentialAccel;
newGravityMode.TangentialAccelVar = particleConfig.GravityTangentialAccelVar;
newGravityMode.RotationIsDir = particleConfig.GravityRotationIsDir;
GravityMode = newGravityMode;
}
else if (EmitterMode == CCEmitterMode.Radius)
{
RadialParticles = new CCParticleRadial[TotalParticles];
RadialMoveMode newRadialMode = new RadialMoveMode();
newRadialMode.StartRadius = particleConfig.RadialStartRadius;
newRadialMode.StartRadiusVar = particleConfig.RadialStartRadiusVar;
newRadialMode.EndRadius = particleConfig.RadialEndRadius;
newRadialMode.EndRadiusVar = particleConfig.RadialEndRadiusVar;
newRadialMode.RotatePerSecond = particleConfig.RadialRotatePerSecond;
newRadialMode.RotatePerSecondVar = particleConfig.RadialRotatePerSecondVar;
RadialMode = newRadialMode;
}
else
{
Debug.Assert(false, "Invalid emitterType in config file");
return;
}
}
#endregion Constructors
public override void OnEnter()
{
base.OnEnter();
Schedule(1);
}
public override void OnExit()
{
Unschedule();
base.OnExit();
}
#region Particle management
public void StopSystem()
{
IsActive = false;
Elapsed = Duration;
EmitCounter = 0;
}
public void ResetSystem()
{
IsActive = true;
Elapsed = 0;
if (EmitterMode == CCEmitterMode.Gravity)
{
for (int i = 0; i < ParticleCount; ++i)
{
GravityParticles[i].ParticleBase.TimeToLive = 0;
}
}
else
{
for (int i = 0; i < ParticleCount; ++i)
{
RadialParticles[i].ParticleBase.TimeToLive = 0;
}
}
}
// Initialise particle
void InitParticle(ref CCParticleGravity particleGrav, ref CCParticleBase particleBase)
{
InitParticleBase(ref particleBase);
// direction
float a = MathHelper.ToRadians(Angle + AngleVar * CCRandom.Float_Minus1_1());
if(EmitterMode == CCEmitterMode.Gravity)
{
CCPoint v = new CCPoint(CCMathHelper.Cos(a), CCMathHelper.Sin(a));
float s = GravityMode.Speed + GravityMode.SpeedVar * CCRandom.Float_Minus1_1();
particleGrav.Direction = v * s;
particleGrav.RadialAccel = GravityMode.RadialAccel + GravityMode.RadialAccelVar * CCRandom.Float_Minus1_1();
particleGrav.TangentialAccel = GravityMode.TangentialAccel + GravityMode.TangentialAccelVar * CCRandom.Float_Minus1_1();
if (GravityMode.RotationIsDir)
{
particleBase.Rotation = -MathHelper.ToDegrees(CCPoint.ToAngle(particleGrav.Direction));
}
}
}
void InitParticle(ref CCParticleRadial particleRadial, ref CCParticleBase particleBase)
{
InitParticleBase(ref particleBase);
// direction
float a = MathHelper.ToRadians(Angle + AngleVar * CCRandom.Float_Minus1_1());
// Set the default diameter of the particle from the source position
float startRadius = RadialMode.StartRadius + RadialMode.StartRadiusVar * CCRandom.Float_Minus1_1();
float endRadius = RadialMode.EndRadius + RadialMode.EndRadiusVar * CCRandom.Float_Minus1_1();
particleRadial.Radius = startRadius;
particleRadial.DeltaRadius = (RadialMode.EndRadius == ParticleStartRadiusEqualToEndRadius) ?
0 : (endRadius - startRadius) / particleBase.TimeToLive;
particleRadial.Angle = a;
particleRadial.DegreesPerSecond =
MathHelper.ToRadians(RadialMode.RotatePerSecond + RadialMode.RotatePerSecondVar * CCRandom.Float_Minus1_1());
}
void InitParticleBase(ref CCParticleBase particleBase)
{
float timeToLive = Math.Max(0, Life + LifeVar * CCRandom.Float_Minus1_1());
particleBase.TimeToLive = timeToLive;
CCPoint particlePos;
particlePos.X = SourcePosition.X + PositionVar.X * CCRandom.Float_Minus1_1();
particlePos.Y = SourcePosition.Y + PositionVar.Y * CCRandom.Float_Minus1_1();
particleBase.Position = particlePos;
CCColor4F start = new CCColor4F();
start.R = MathHelper.Clamp(StartColor.R + StartColorVar.R * CCRandom.Float_Minus1_1(), 0, 1);
start.G = MathHelper.Clamp(StartColor.G + StartColorVar.G * CCRandom.Float_Minus1_1(), 0, 1);
start.B = MathHelper.Clamp(StartColor.B + StartColorVar.B * CCRandom.Float_Minus1_1(), 0, 1);
start.A = MathHelper.Clamp(StartColor.A + StartColorVar.A * CCRandom.Float_Minus1_1(), 0, 1);
particleBase.Color = start;
CCColor4F end = new CCColor4F();
end.R = MathHelper.Clamp(EndColor.R + EndColorVar.R * CCRandom.Float_Minus1_1(), 0, 1);
end.G = MathHelper.Clamp(EndColor.G + EndColorVar.G * CCRandom.Float_Minus1_1(), 0, 1);
end.B = MathHelper.Clamp(EndColor.B + EndColorVar.B * CCRandom.Float_Minus1_1(), 0, 1);
end.A = MathHelper.Clamp(EndColor.A + EndColorVar.A * CCRandom.Float_Minus1_1(), 0, 1);
CCColor4F deltaColor = new CCColor4F();
deltaColor.R = (end.R - start.R) / timeToLive;
deltaColor.G = (end.G - start.G) / timeToLive;
deltaColor.B = (end.B - start.B) / timeToLive;
deltaColor.A = (end.A - start.A) / timeToLive;
particleBase.DeltaColor = deltaColor;
float startSize = Math.Max(0, StartSize + StartSizeVar * CCRandom.Float_Minus1_1());
particleBase.Size = startSize;
if (EndSize == ParticleStartSizeEqualToEndSize)
{
particleBase.DeltaSize = 0;
}
else
{
float endS = EndSize + EndSizeVar * CCRandom.Float_Minus1_1();
endS = Math.Max(0, endS);
particleBase.DeltaSize = (endS - startSize) / timeToLive;
}
float startSpin = StartSpin + StartSpinVar * CCRandom.Float_Minus1_1();
float endSpin = EndSpin + EndSpinVar * CCRandom.Float_Minus1_1();
particleBase.Rotation = startSpin;
particleBase.DeltaRotation = (endSpin - startSpin) / timeToLive;
if (PositionType == CCPositionType.Free)
{
particleBase.StartPosition = Layer.VisibleBoundsWorldspace.Origin;
}
else if (PositionType == CCPositionType.Relative)
{
particleBase.StartPosition = Position;
}
}
// Update particle
bool UpdateParticleBase(ref CCParticleBase particleBase, float dt)
{
particleBase.TimeToLive -= dt;
if(particleBase.TimeToLive > 0)
{
CCColor4F color = particleBase.Color;
color.R += (particleBase.DeltaColor.R * dt);
color.G += (particleBase.DeltaColor.G * dt);
color.B += (particleBase.DeltaColor.B * dt);
color.A += (particleBase.DeltaColor.A * dt);
particleBase.Color = color;
particleBase.Size += (particleBase.DeltaSize * dt);
if(particleBase.Size < 0)
{
particleBase.Size = 0;
}
particleBase.Rotation += (particleBase.DeltaRotation * dt);
return true;
}
return false;
}
bool UpdateParticle(ref CCParticleRadial particleRadial, float dt)
{
if(UpdateParticleBase(ref particleRadial.ParticleBase, dt))
{
particleRadial.Angle += particleRadial.DegreesPerSecond * dt;
particleRadial.Radius += particleRadial.DeltaRadius * dt;
CCPoint position = particleRadial.ParticleBase.Position;
position.X = -CCMathHelper.Cos(particleRadial.Angle) * particleRadial.Radius;
position.Y = -CCMathHelper.Sin(particleRadial.Angle) * particleRadial.Radius;
particleRadial.ParticleBase.Position = position;
return true;
}
return false;
}
bool UpdateParticle(ref CCParticleGravity particleGrav, float dt)
{
if(UpdateParticleBase(ref particleGrav.ParticleBase, dt))
{
float radial_x = 0;
float radial_y = 0;
float tmp_x, tmp_y;
float tangential_x, tangential_y;
CCPoint pos = particleGrav.ParticleBase.Position;
float x = pos.X;
float y = pos.Y;
if (x != 0 || y != 0)
{
float l = 1.0f / (float) Math.Sqrt(x * x + y * y);
radial_x = x * l;
radial_y = y * l;
}
tangential_x = radial_x;
tangential_y = radial_y;
float radialAccel = particleGrav.RadialAccel;
radial_x *= radialAccel;
radial_y *= radialAccel;
float tangentAccel = particleGrav.TangentialAccel;
float newy = tangential_x;
tangential_x = -tangential_y;
tangential_y = newy;
tangential_x *= tangentAccel;
tangential_y *= tangentAccel;
CCPoint gravity = GravityMode.Gravity;
tmp_x = (radial_x + tangential_x + gravity.X) * dt;
tmp_y = (radial_y + tangential_y + gravity.Y) * dt;
CCPoint direction = particleGrav.Direction;
direction.X += tmp_x;
direction.Y += tmp_y;
particleGrav.Direction = direction;
CCPoint position = particleGrav.ParticleBase.Position;
position.X += direction.X * dt;
position.Y += direction.Y * dt;
particleGrav.ParticleBase.Position = position;
return true;
}
return false;
}
#endregion Particle management
#region Updating system
public void UpdateWithNoTime()
{
Update(0.0f);
}
public virtual void UpdateQuads()
{
// should be overriden
}
protected virtual void PostStep()
{
// should be overriden
}
public override void Update(float dt)
{
if (EmitterMode == CCEmitterMode.Gravity)
{
UpdateGravityParticles(dt);
}
else
{
UpdateRadialParticles(dt);
}
UpdateQuads();
PostStep();
}
void UpdateGravityParticles(float dt)
{
if (IsActive && EmissionRate > 0)
{
float rate = 1.0f / EmissionRate;
//issue #1201, prevent bursts of particles, due to too high emitCounter
if (ParticleCount < TotalParticles)
{
EmitCounter += dt;
}
while (ParticleCount < TotalParticles && EmitCounter > rate)
{
InitParticle(ref GravityParticles[ParticleCount], ref GravityParticles[ParticleCount].ParticleBase);
++ParticleCount;
EmitCounter -= rate;
}
Elapsed += dt;
if (Duration != -1 && Duration < Elapsed)
{
StopSystem();
}
}
int index = 0;
if (Visible)
{
while (index < ParticleCount)
{
if (UpdateParticle(ref GravityParticles[index], dt))
{
// update particle counter
++index;
}
else
{
// life < 0
int currentIndex = GravityParticles[index].AtlasIndex;
if (index != ParticleCount - 1)
{
GravityParticles[index] = GravityParticles[ParticleCount - 1];
}
--ParticleCount;
if (ParticleCount == 0 && AutoRemoveOnFinish)
{
Unschedule();
Parent.RemoveChild(this, true);
return;
}
}
}
}
}
void UpdateRadialParticles(float dt)
{
if (IsActive && EmissionRate > 0)
{
float rate = 1.0f / EmissionRate;
//issue #1201, prevent bursts of particles, due to too high emitCounter
if (ParticleCount < TotalParticles)
{
EmitCounter += dt;
}
while (ParticleCount < TotalParticles && EmitCounter > rate)
{
InitParticle(ref RadialParticles[ParticleCount], ref RadialParticles[ParticleCount].ParticleBase);
++ParticleCount;
EmitCounter -= rate;
}
Elapsed += dt;
if (Duration != -1 && Duration < Elapsed)
{
StopSystem();
}
}
int index = 0;
if (Visible)
{
while (index < ParticleCount)
{
if (UpdateParticle(ref RadialParticles[index], dt))
{
// update particle counter
++index;
}
else
{
// life < 0
int currentIndex = RadialParticles[index].AtlasIndex;
if (index != ParticleCount - 1)
{
RadialParticles[index] = RadialParticles[ParticleCount - 1];
}
--ParticleCount;
if (ParticleCount == 0 && AutoRemoveOnFinish)
{
Unschedule();
Parent.RemoveChild(this, true);
return;
}
}
}
}
}
#endregion Updating system
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class TransactionTest
{
[Fact]
public void TestYukon()
{
new TransactionTestWorker(DataTestClass.SQL2005_Northwind + ";multipleactiveresultsets=true;").StartTest();
}
[Fact]
public void TestKatmai()
{
new TransactionTestWorker(DataTestClass.SQL2008_Northwind + ";multipleactiveresultsets=true;").StartTest();
}
}
internal class TransactionTestWorker
{
private static string s_tempTableName1 = string.Format("TEST_{0}{1}{2}", Environment.GetEnvironmentVariable("ComputerName"), Environment.TickCount, Guid.NewGuid()).Replace('-', '_');
private static string s_tempTableName2 = s_tempTableName1 + "_2";
private string _connectionString;
public TransactionTestWorker(string connectionString)
{
_connectionString = connectionString;
}
public void StartTest()
{
try
{
PrepareTables();
CommitTransactionTest();
ResetTables();
RollbackTransactionTest();
ResetTables();
ScopedTransactionTest();
ResetTables();
ExceptionTest();
ResetTables();
ReadUncommitedIsolationLevel_ShouldReturnUncommitedData();
ResetTables();
ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction();
ResetTables();
}
finally
{
//make sure to clean up
DropTempTables();
}
}
private void PrepareTables()
{
using (var conn = new SqlConnection(_connectionString))
{
conn.Open();
SqlCommand command = new SqlCommand(string.Format("CREATE TABLE [{0}]([CustomerID] [nchar](5) NOT NULL PRIMARY KEY, [CompanyName] [nvarchar](40) NOT NULL, [ContactName] [nvarchar](30) NULL)", s_tempTableName1), conn);
command.ExecuteNonQuery();
command.CommandText = "create table " + s_tempTableName2 + "(col1 int, col2 varchar(32))";
command.ExecuteNonQuery();
}
}
private void DropTempTables()
{
using (var conn = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand(
string.Format("DROP TABLE [{0}]; DROP TABLE [{1}]", s_tempTableName1, s_tempTableName2), conn);
conn.Open();
command.ExecuteNonQuery();
}
}
public void ResetTables()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(string.Format("TRUNCATE TABLE [{0}]; TRUNCATE TABLE [{1}]", s_tempTableName1, s_tempTableName2), connection))
{
command.ExecuteNonQuery();
}
}
}
private void CommitTransactionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand("select * from " + s_tempTableName1 + " where CustomerID='ZYXWV'", connection);
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
command.Transaction = tx;
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
}
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + s_tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command2.ExecuteNonQuery();
}
tx.Commit();
using (SqlDataReader reader = command.ExecuteReader())
{
int count = 0;
while (reader.Read()) { count++; }
Assert.True(count == 1, "Error: incorrect number of rows in table after update.");
Assert.Equal(count, 1);
}
}
}
private void RollbackTransactionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand("select * from " + s_tempTableName1 + " where CustomerID='ZYXWV'",
connection);
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
command.Transaction = tx;
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
}
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + s_tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command2.ExecuteNonQuery();
}
tx.Rollback();
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error Rollback Test : incorrect number of rows in table after rollback.");
int count = 0;
while (reader.Read()) count++;
Assert.Equal(count, 0);
}
connection.Close();
}
}
private void ScopedTransactionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand("select * from " + s_tempTableName1 + " where CustomerID='ZYXWV'",
connection);
connection.Open();
SqlTransaction tx = connection.BeginTransaction("transName");
command.Transaction = tx;
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.False(reader.HasRows, "Error: table is in incorrect state for test.");
}
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + s_tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command2.ExecuteNonQuery();
}
tx.Save("saveName");
//insert another one
using (SqlCommand command2 = connection.CreateCommand())
{
command2.Transaction = tx;
command2.CommandText = "INSERT INTO " + s_tempTableName1 + " VALUES ( 'ZYXW2', 'XY2', 'KK' );";
command2.ExecuteNonQuery();
}
tx.Rollback("saveName");
using (SqlDataReader reader = command.ExecuteReader())
{
Assert.True(reader.HasRows, "Error Scoped Transaction Test : incorrect number of rows in table after rollback to save state one.");
int count = 0;
while (reader.Read()) count++;
Assert.Equal(count, 1);
}
tx.Rollback();
connection.Close();
}
}
private void ExceptionTest()
{
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
string invalidSaveStateMessage = SystemDataResourceManager.Instance.SQL_NullEmptyTransactionName;
string executeCommandWithoutTransactionMessage = SystemDataResourceManager.Instance.ADP_TransactionRequired("ExecuteNonQuery");
string transactionConflictErrorMessage = SystemDataResourceManager.Instance.ADP_TransactionConnectionMismatch;
string parallelTransactionErrorMessage = SystemDataResourceManager.Instance.ADP_ParallelTransactionsNotSupported("SqlConnection");
AssertException<InvalidOperationException>(() =>
{
SqlCommand command = new SqlCommand("sql", connection);
command.ExecuteNonQuery();
}, executeCommandWithoutTransactionMessage);
AssertException<InvalidOperationException>(() =>
{
SqlConnection con1 = new SqlConnection(_connectionString);
con1.Open();
SqlCommand command = new SqlCommand("sql", con1);
command.Transaction = tx;
command.ExecuteNonQuery();
}, transactionConflictErrorMessage);
AssertException<InvalidOperationException>(() =>
{
connection.BeginTransaction(null);
}, parallelTransactionErrorMessage);
AssertException<InvalidOperationException>(() =>
{
connection.BeginTransaction("");
}, parallelTransactionErrorMessage);
AssertException<ArgumentException>(() =>
{
tx.Rollback(null);
}, invalidSaveStateMessage);
AssertException<ArgumentException>(() =>
{
tx.Rollback("");
}, invalidSaveStateMessage);
AssertException<ArgumentException>(() =>
{
tx.Save(null);
}, invalidSaveStateMessage);
AssertException<ArgumentException>(() =>
{
tx.Save("");
}, invalidSaveStateMessage);
}
}
public static void AssertException<T>(Action action, string expectedErrorMessage) where T : Exception
{
var exception = Assert.Throws<T>(action);
Assert.Equal(exception.Message, expectedErrorMessage);
}
private void ReadUncommitedIsolationLevel_ShouldReturnUncommitedData()
{
using (SqlConnection connection1 = new SqlConnection(_connectionString))
{
connection1.Open();
SqlTransaction tx1 = connection1.BeginTransaction();
using (SqlCommand command1 = connection1.CreateCommand())
{
command1.Transaction = tx1;
command1.CommandText = "INSERT INTO " + s_tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command1.ExecuteNonQuery();
}
using (SqlConnection connection2 = new SqlConnection(_connectionString))
{
SqlCommand command2 =
new SqlCommand("select * from " + s_tempTableName1 + " where CustomerID='ZYXWV'",
connection2);
connection2.Open();
SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadUncommitted);
command2.Transaction = tx2;
using (SqlDataReader reader = command2.ExecuteReader())
{
int count = 0;
while (reader.Read()) count++;
Assert.True(count == 1, "Should Expected 1 row because Isolation Level is read uncommited which should return uncommited data.");
}
tx2.Rollback();
connection2.Close();
}
tx1.Rollback();
connection1.Close();
}
}
private void ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction()
{
using (SqlConnection connection1 = new SqlConnection(_connectionString))
{
connection1.Open();
SqlTransaction tx1 = connection1.BeginTransaction();
using (SqlCommand command1 = connection1.CreateCommand())
{
command1.Transaction = tx1;
command1.CommandText = "INSERT INTO " + s_tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
command1.ExecuteNonQuery();
}
using (SqlConnection connection2 = new SqlConnection(_connectionString))
{
SqlCommand command2 =
new SqlCommand("select * from " + s_tempTableName1 + " where CustomerID='ZYXWV'",
connection2);
connection2.Open();
SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadCommitted);
command2.Transaction = tx2;
AssertException<SqlException>(() => command2.ExecuteReader(), SystemDataResourceManager.Instance.SQL_Timeout as string);
tx2.Rollback();
connection2.Close();
}
tx1.Rollback();
connection1.Close();
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License");you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Util
{
using System;
using System.Collections;
using System.IO;
using System.Reflection;
/**
* Intends to provide support for the very evil index to triplet Issue and
* will likely replace the color constants interface for HSSF 2.0.
* This class Contains static inner class members for representing colors.
* Each color has an index (for the standard palette in Excel (tm) ),
* native (RGB) triplet and string triplet. The string triplet Is as the
* color would be represented by Gnumeric. Having (string) this here Is a bit of a
* collusion of function between HSSF and the HSSFSerializer but I think its
* a reasonable one in this case.
*
* @author Andrew C. Oliver (acoliver at apache dot org)
* @author Brian Sanders (bsanders at risklabs dot com) - full default color palette
*/
public class HSSFColor : NPOI.SS.UserModel.IColor
{
private static Hashtable indexHash;
public const short COLOR_NORMAL = 0x7fff;
// TODO make subclass instances immutable
/** Creates a new instance of HSSFColor */
public HSSFColor()
{
}
/**
* this function returns all colors in a hastable. Its not implemented as a
* static member/staticly initialized because that would be dirty in a
* server environment as it Is intended. This means you'll eat the time
* it takes to Create it once per request but you will not hold onto it
* if you have none of those requests.
*
* @return a hashtable containing all colors keyed by <c>int</c> excel-style palette indexes
*/
public static Hashtable GetIndexHash()
{
if (indexHash == null)
{
indexHash = CreateColorsByIndexMap();
}
return indexHash;
}
/**
* This function returns all the Colours, stored in a Hashtable that
* can be edited. No caching is performed. If you don't need to edit
* the table, then call {@link #getIndexHash()} which returns a
* statically cached imuatable map of colours.
*/
public static Hashtable GetMutableIndexHash()
{
return CreateColorsByIndexMap();
}
private static Hashtable CreateColorsByIndexMap()
{
HSSFColor[] colors = GetAllColors();
Hashtable result = new Hashtable(colors.Length * 3 / 2);
for (int i = 0; i < colors.Length; i++)
{
HSSFColor color = colors[i];
int index1 = color.Indexed;
if (result.ContainsKey(index1))
{
HSSFColor prevColor = (HSSFColor)result[index1];
throw new InvalidDataException("Dup color index (" + index1
+ ") for colors (" + prevColor.GetType().Name
+ "),(" + color.GetType().Name + ")");
}
result[index1] = color;
}
for (int i = 0; i < colors.Length; i++)
{
HSSFColor color = colors[i];
int index2 = GetIndex2(color);
if (index2 == -1)
{
// most colors don't have a second index
continue;
}
//if (result.ContainsKey(index2))
//{
//if (false)
//{ // Many of the second indexes clash
// HSSFColor prevColor = (HSSFColor)result[index2];
// throw new InvalidDataException("Dup color index (" + index2
// + ") for colors (" + prevColor.GetType().Name
// + "),(" + color.GetType().Name + ")");
//}
//}
result[index2] = color;
}
return result;
}
private static int GetIndex2(HSSFColor color)
{
FieldInfo f = color.GetType().GetField("Index2", BindingFlags.Static | BindingFlags.Public);
if (f == null)
{
return -1;
}
short s = (short)f.GetValue(color);
return Convert.ToInt32(s);
}
internal static HSSFColor[] GetAllColors()
{
return new HSSFColor[] {
new Black(), new Brown(), new OliveGreen(), new DarkGreen(),
new DarkTeal(), new DarkBlue(), new Indigo(), new Grey80Percent(),
new Orange(), new DarkYellow(), new Green(), new Teal(), new Blue(),
new BlueGrey(), new Grey50Percent(), new Red(), new LightOrange(), new Lime(),
new SeaGreen(), new Aqua(), new LightBlue(), new Violet(), new Grey40Percent(),
new Pink(), new Gold(), new Yellow(), new BrightGreen(), new Turquoise(),
new DarkRed(), new SkyBlue(), new Plum(), new Grey25Percent(), new Rose(),
new LightYellow(), new LightGreen(), new LightTurquoise(), new PaleBlue(),
new Lavender(), new White(), new CornflowerBlue(), new LemonChiffon(),
new Maroon(), new Orchid(), new Coral(), new RoyalBlue(),
new LightCornflowerBlue(), new Tan(),
};
}
/// <summary>
/// this function returns all colors in a hastable. Its not implemented as a
/// static member/staticly initialized because that would be dirty in a
/// server environment as it Is intended. This means you'll eat the time
/// it takes to Create it once per request but you will not hold onto it
/// if you have none of those requests.
/// </summary>
/// <returns>a hashtable containing all colors keyed by String gnumeric-like triplets</returns>
public static Hashtable GetTripletHash()
{
return CreateColorsByHexStringMap();
}
private static Hashtable CreateColorsByHexStringMap()
{
HSSFColor[] colors = GetAllColors();
Hashtable result = new Hashtable(colors.Length * 3 / 2);
for (int i = 0; i < colors.Length; i++)
{
HSSFColor color = colors[i];
String hexString = color.GetHexString();
if (result.ContainsKey(hexString))
{
throw new InvalidDataException("Dup color hexString (" + hexString
+ ") for color (" + color.GetType().Name + ")");
}
result[hexString] = color;
}
return result;
}
/**
* @return index to the standard palette
*/
public virtual short Indexed
{
get
{
return Black.Index;
}
}
public byte[] RGB
{
get { return this.GetTriplet(); }
}
/**
* @return triplet representation like that in Excel
*/
public virtual byte[] GetTriplet()
{
return Black.Triplet;
}
// its a hack but its a good hack
/**
* @return a hex string exactly like a gnumeric triplet
*/
public virtual String GetHexString()
{
return Black.HexString;
}
/**
* Class BLACK
*
*/
public class Black : HSSFColor
{
public const short Index = 0x8;
public static readonly byte[] Triplet = { 0, 0, 0 };
public const string HexString = "0:0:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class BROWN
*
*/
public class Brown : HSSFColor
{
public const short Index = 0x3c;
public static readonly byte[] Triplet = { 153, 51, 0 };
public const string HexString = "9999:3333:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class OLIVE_GREEN
*
*/
public class OliveGreen: HSSFColor
{
public const short Index = 0x3b;
public static readonly byte[] Triplet = { 51, 51, 0 };
public const string HexString = "3333:3333:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class DARK_GREEN
*
*/
public class DarkGreen: HSSFColor
{
public const short Index = 0x3a;
public static readonly byte[] Triplet = { 0, 51, 0 };
public const string HexString = "0:3333:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class DARK_TEAL
*
*/
public class DarkTeal: HSSFColor
{
public const short Index = 0x38;
public static readonly byte[] Triplet = { 0, 51, 102 };
public const string HexString = "0:3333:6666";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class DARK_BLUE
*
*/
public class DarkBlue: HSSFColor
{
public const short Index = 0x12;
public const short Index2 = 0x20;
public static readonly byte[] Triplet = { 0, 0, 128 };
public const string HexString = "0:0:8080";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class INDIGO
*
*/
public class Indigo: HSSFColor
{
public const short Index = 0x3e;
public static readonly byte[] Triplet = { 51, 51, 153 };
public const string HexString = "3333:3333:9999";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class GREY_80_PERCENT
*
*/
public class Grey80Percent: HSSFColor
{
public const short Index = 0x3f;
public static readonly byte[] Triplet = { 51, 51, 51 };
public const string HexString = "3333:3333:3333";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class DARK_RED
*
*/
public class DarkRed: HSSFColor
{
public const short Index = 0x10;
public const short Index2 = 0x25;
public static readonly byte[] Triplet = { 128, 0, 0 };
public const string HexString = "8080:0:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class ORANGE
*
*/
public class Orange: HSSFColor
{
public const short Index = 0x35;
public static readonly byte[] Triplet = { 255, 102, 0 };
public const string HexString = "FFFF:6666:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class DARK_YELLOW
*
*/
public class DarkYellow: HSSFColor
{
public const short Index = 0x13;
public static readonly byte[] Triplet = { 128, 128, 0 };
public const string HexString = "8080:8080:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class GREEN
*
*/
public class Green: HSSFColor
{
public const short Index = 0x11;
public static readonly byte[] Triplet = { 0, 128, 0 };
public const string HexString = "0:8080:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class TEAL
*
*/
public class Teal: HSSFColor
{
public const short Index = 0x15;
public const short Index2 = 0x26;
public static readonly byte[] Triplet = { 0, 128, 128 };
public const string HexString = "0:8080:8080";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class BLUE
*
*/
public class Blue: HSSFColor
{
public const short Index = 0xc;
public const short Index2 = 0x27;
public static readonly byte[] Triplet = { 0, 0, 255 };
public const string HexString = "0:0:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class BLUE_GREY
*
*/
public class BlueGrey: HSSFColor
{
public const short Index = 0x36;
public static readonly byte[] Triplet = { 102, 102, 153 };
public const string HexString = "6666:6666:9999";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class GREY_50_PERCENT
*
*/
public class Grey50Percent: HSSFColor
{
public const short Index = 0x17;
public static readonly byte[] Triplet = { 128, 128, 128 };
public const string HexString = "8080:8080:8080";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class RED
*
*/
public class Red: HSSFColor
{
public const short Index = 0xa;
public static readonly byte[] Triplet = { 255, 0, 0 };
public const string HexString = "FFFF:0:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LIGHT_ORANGE
*
*/
public class LightOrange: HSSFColor
{
public const short Index = 0x34;
public static readonly byte[] Triplet = { 255, 153, 0 };
public const string HexString = "FFFF:9999:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LIME
*
*/
public class Lime: HSSFColor
{
public const short Index = 0x32;
public static readonly byte[] Triplet = { 153, 204, 0 };
public const string HexString = "9999:CCCC:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class SEA_GREEN
*
*/
public class SeaGreen: HSSFColor
{
public const short Index = 0x39;
public static readonly byte[] Triplet = { 51, 153, 102 };
public const string HexString = "3333:9999:6666";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class AQUA
*
*/
public class Aqua: HSSFColor
{
public const short Index = 0x31;
public static readonly byte[] Triplet = { 51, 204, 204 };
public const string HexString = "3333:CCCC:CCCC";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
public class LightBlue: HSSFColor
{
public const short Index = 0x30;
public static readonly byte[] Triplet = { 51, 102, 255 };
public const string HexString = "3333:6666:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
public class Violet: HSSFColor
{
public const short Index = 0x14;
public const short Index2 = 0x24;
public static readonly byte[] Triplet = { 128, 0, 128 };
public const string HexString = "8080:0:8080";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class GREY_40_PERCENT
*
*/
public class Grey40Percent : HSSFColor
{
public const short Index = 0x37;
public static readonly byte[] Triplet = { 150, 150, 150 };
public const string HexString = "9696:9696:9696";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
public class Pink: HSSFColor
{
public const short Index = 0xe;
public const short Index2 = 0x21;
public static readonly byte[] Triplet = { 255, 0, 255 };
public const string HexString = "FFFF:0:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
public class Gold: HSSFColor
{
public const short Index = 0x33;
public static readonly byte[] Triplet = { 255, 204, 0 };
public const string HexString = "FFFF:CCCC:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
public class Yellow: HSSFColor
{
public const short Index = 0xd;
public const short Index2 = 0x22;
public static readonly byte[] Triplet = { 255, 255, 0 };
public const string HexString = "FFFF:FFFF:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
public class BrightGreen: HSSFColor
{
public const short Index = 0xb;
public const short Index2 = 0x23;
public static readonly byte[] Triplet = { 0, 255, 0 };
public const string HexString = "0:FFFF:0";
public override String GetHexString()
{
return HexString;
}
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
}
/**
* Class TURQUOISE
*
*/
public class Turquoise: HSSFColor
{
public const short Index = 0xf;
public const short Index2 = 0x23;
public static readonly byte[] Triplet = { 0, 255, 255 };
public const string HexString = "0:FFFF:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class SKY_BLUE
*
*/
public class SkyBlue: HSSFColor
{
public const short Index = 0x28;
public static readonly byte[] Triplet = { 0, 204, 255 };
public const string HexString = "0:CCCC:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class PLUM
*
*/
public class Plum: HSSFColor
{
public const short Index = 0x3d;
public const short Index2 = 0x19;
public static readonly byte[] Triplet = { 153, 51, 102 };
public const string HexString = "9999:3333:6666";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class GREY_25_PERCENT
*
*/
public class Grey25Percent: HSSFColor
{
public const short Index = 0x16;
public static readonly byte[] Triplet = { 192, 192, 192 };
public const string HexString = "C0C0:C0C0:C0C0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class ROSE
*
*/
public class Rose: HSSFColor
{
public const short Index = 0x2d;
public static readonly byte[] Triplet = { 255, 153, 204 };
public const string HexString = "FFFF:9999:CCCC";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class TAN
*
*/
public class Tan: HSSFColor
{
public const short Index = 0x2f;
public static readonly byte[] Triplet = { 255, 204, 153 };
public const string HexString = "FFFF:CCCC:9999";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LIGHT_YELLOW
*
*/
public class LightYellow: HSSFColor
{
public const short Index = 0x2b;
public static readonly byte[] Triplet = { 255, 255, 153 };
public const string HexString = "FFFF:FFFF:9999";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LIGHT_GREEN
*
*/
public class LightGreen: HSSFColor
{
public const short Index = 0x2a;
public static readonly byte[] Triplet = { 204, 255, 204 };
public const string HexString = "CCCC:FFFF:CCCC";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LIGHT_TURQUOISE
*
*/
public class LightTurquoise: HSSFColor
{
public const short Index = 0x29;
public const short Index2 = 0x1b;
public static readonly byte[] Triplet = { 204, 255, 255 };
public const string HexString = "CCCC:FFFF:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class PALE_BLUE
*
*/
public class PaleBlue: HSSFColor
{
public const short Index = 0x2c;
public static readonly byte[] Triplet = { 153, 204, 255 };
public const string HexString = "9999:CCCC:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LAVENDER
*
*/
public class Lavender: HSSFColor
{
public const short Index = 0x2e;
public static readonly byte[] Triplet = { 204, 153, 255 };
public const string HexString = "CCCC:9999:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class WHITE
*
*/
public class White: HSSFColor
{
public const short Index = 0x9;
public static readonly byte[] Triplet = { 255, 255, 255 };
public const string HexString = "FFFF:FFFF:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class CORNFLOWER_BLUE
*/
public class CornflowerBlue: HSSFColor
{
public const short Index = 0x18;
public static readonly byte[] Triplet = { 153, 153, 255 };
public const string HexString = "9999:9999:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LEMON_CHIFFON
*/
public class LemonChiffon: HSSFColor
{
public const short Index = 0x1a;
public static readonly byte[] Triplet = { 255, 255, 204 };
public const string HexString = "FFFF:FFFF:CCCC";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class MAROON
*/
public class Maroon: HSSFColor
{
public const short Index = 0x19;
public static readonly byte[] Triplet = { 127, 0, 0 };
public const string HexString = "8000:0:0";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class ORCHID
*/
public class Orchid: HSSFColor
{
public const short Index = 0x1c;
public static readonly byte[] Triplet = { 102, 0, 102 };
public const string HexString = "6666:0:6666";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class CORAL
*/
public class Coral : HSSFColor
{
public const short Index = 0x1d;
public static readonly byte[] Triplet = { 255, 128, 128 };
public const string HexString = "FFFF:8080:8080";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class ROYAL_BLUE
*/
public class RoyalBlue : HSSFColor
{
public const short Index = 0x1e;
public static readonly byte[] Triplet = { 0, 102, 204 };
public const string HexString = "0:6666:CCCC";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Class LIGHT_CORNFLOWER_BLUE
*/
public class LightCornflowerBlue : HSSFColor
{
public const short Index = 0x1f;
public static readonly byte[] Triplet = { 204, 204, 255 };
public const string HexString = "CCCC:CCCC:FFFF";
public override short Indexed
{
get{return Index;}
}
public override byte[] GetTriplet()
{
return Triplet;
}
public override String GetHexString()
{
return HexString;
}
}
/**
* Special Default/Normal/Automatic color.
* <i>Note:</i> This class Is NOT in the default HashTables returned by HSSFColor.
* The index Is a special case which Is interpreted in the various SetXXXColor calls.
*
* @author Jason
*
*/
public class Automatic : HSSFColor
{
private static HSSFColor instance = new Automatic();
public const short Index = 0x40;
public override byte[] GetTriplet()
{
return Black.Triplet;
}
public override String GetHexString()
{
return Black.HexString;
}
public static HSSFColor GetInstance()
{
return instance;
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
using Microsoft.VisualStudio.Text;
using NuGet;
namespace NuGetConsole.Implementation.Console
{
internal interface IPrivateConsoleDispatcher : IConsoleDispatcher, IDisposable
{
event EventHandler<EventArgs<Tuple<SnapshotSpan, bool>>> ExecuteInputLine;
void PostInputLine(InputLine inputLine);
void PostKey(VsKeyInfo key);
void CancelWaitKey();
}
/// <summary>
/// This class handles input line posting and command line dispatching/execution.
/// </summary>
internal class ConsoleDispatcher : IPrivateConsoleDispatcher
{
private readonly BlockingCollection<VsKeyInfo> _keyBuffer = new BlockingCollection<VsKeyInfo>();
private CancellationTokenSource _cancelWaitKeySource;
private bool _isExecutingReadKey;
/// <summary>
/// The IPrivateWpfConsole instance this dispatcher works with.
/// </summary>
private IPrivateWpfConsole WpfConsole { get; set; }
/// <summary>
/// Child dispatcher based on host type. Its creation is postponed to Start(), so that
/// a WpfConsole's dispatcher can be accessed while inside a host construction.
/// </summary>
private Dispatcher _dispatcher;
private readonly object _lockObj = new object();
public event EventHandler StartCompleted;
public event EventHandler StartWaitingKey;
public ConsoleDispatcher(IPrivateWpfConsole wpfConsole)
{
UtilityMethods.ThrowIfArgumentNull(wpfConsole);
this.WpfConsole = wpfConsole;
}
public bool IsExecutingCommand
{
get
{
return (_dispatcher != null) && _dispatcher.IsExecuting;
}
}
public void PostKey(VsKeyInfo key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
_keyBuffer.Add(key);
}
public bool IsExecutingReadKey
{
get { return _isExecutingReadKey; }
}
public bool IsKeyAvailable
{
get
{
// In our BlockingCollection<T> producer/consumer this is
// not critical so no need for locking.
return _keyBuffer.Count > 0;
}
}
public void CancelWaitKey()
{
if (_isExecutingReadKey && !_cancelWaitKeySource.IsCancellationRequested)
{
_cancelWaitKeySource.Cancel();
}
}
public void AcceptKeyInput()
{
Debug.Assert(_dispatcher != null);
if (_dispatcher != null && WpfConsole != null)
{
WpfConsole.BeginInputLine();
}
}
public VsKeyInfo WaitKey()
{
try
{
// raise the StartWaitingKey event on main thread
RaiseEventSafe(StartWaitingKey);
// set/reset the cancellation token
_cancelWaitKeySource = new CancellationTokenSource();
_isExecutingReadKey = true;
// blocking call
VsKeyInfo key = _keyBuffer.Take(_cancelWaitKeySource.Token);
return key;
}
catch (OperationCanceledException)
{
return null;
}
finally
{
_isExecutingReadKey = false;
}
}
private void RaiseEventSafe(EventHandler handler)
{
if (handler != null)
{
Microsoft.VisualStudio.Shell.ThreadHelper.Generic.Invoke(() => handler(this, EventArgs.Empty));
}
}
public bool IsStartCompleted { get; private set; }
#region IConsoleDispatcher
public void Start()
{
// Only Start once
lock (_lockObj)
{
if (_dispatcher == null)
{
IHost host = WpfConsole.Host;
if (host == null)
{
throw new InvalidOperationException("Can't start Console dispatcher. Host is null.");
}
if (host is IAsyncHost)
{
_dispatcher = new AsyncHostConsoleDispatcher(this);
}
else
{
_dispatcher = new SyncHostConsoleDispatcher(this);
}
Task.Factory.StartNew(
// gives the host a chance to do initialization works before the console starts accepting user inputs
() => host.Initialize(WpfConsole)
).ContinueWith(
task =>
{
if (task.IsFaulted)
{
var exception = ExceptionUtility.Unwrap(task.Exception);
WriteError(exception.Message);
}
if (host.IsCommandEnabled)
{
Microsoft.VisualStudio.Shell.ThreadHelper.Generic.Invoke(_dispatcher.Start);
}
RaiseEventSafe(StartCompleted);
IsStartCompleted = true;
},
TaskContinuationOptions.NotOnCanceled
);
}
}
}
private void WriteError(string message)
{
if (WpfConsole != null)
{
WpfConsole.Write(message + Environment.NewLine, Colors.Red, null);
}
}
public void ClearConsole()
{
Debug.Assert(_dispatcher != null);
if (_dispatcher != null)
{
_dispatcher.ClearConsole();
}
}
#endregion
#region IPrivateConsoleDispatcher
public event EventHandler<EventArgs<Tuple<SnapshotSpan, bool>>> ExecuteInputLine;
void OnExecute(SnapshotSpan inputLineSpan, bool isComplete)
{
ExecuteInputLine.Raise(this, Tuple.Create(inputLineSpan, isComplete));
}
public void PostInputLine(InputLine inputLine)
{
Debug.Assert(_dispatcher != null);
if (_dispatcher != null)
{
_dispatcher.PostInputLine(inputLine);
}
}
#endregion
private abstract class Dispatcher
{
protected ConsoleDispatcher ParentDispatcher { get; private set; }
protected IPrivateWpfConsole WpfConsole { get; private set; }
private bool _isExecuting;
public bool IsExecuting
{
get
{
return _isExecuting;
}
protected set
{
_isExecuting = value;
WpfConsole.SetExecutionMode(_isExecuting);
}
}
protected Dispatcher(ConsoleDispatcher parentDispatcher)
{
ParentDispatcher = parentDispatcher;
WpfConsole = parentDispatcher.WpfConsole;
}
/// <summary>
/// Process a input line.
/// </summary>
/// <param name="inputLine"></param>
protected Tuple<bool, bool> Process(InputLine inputLine)
{
SnapshotSpan inputSpan = inputLine.SnapshotSpan;
if (inputLine.Flags.HasFlag(InputLineFlag.Echo))
{
WpfConsole.BeginInputLine();
if (inputLine.Flags.HasFlag(InputLineFlag.Execute))
{
WpfConsole.WriteLine(inputLine.Text);
inputSpan = WpfConsole.EndInputLine(true).Value;
}
else
{
WpfConsole.Write(inputLine.Text);
}
}
if (inputLine.Flags.HasFlag(InputLineFlag.Execute))
{
string command = inputLine.Text;
bool isExecuted = WpfConsole.Host.Execute(WpfConsole, command, null);
WpfConsole.InputHistory.Add(command);
ParentDispatcher.OnExecute(inputSpan, isExecuted);
return Tuple.Create(true, isExecuted);
}
return Tuple.Create(false, false);
}
public void PromptNewLine()
{
WpfConsole.Write(WpfConsole.Host.Prompt + (char)32); // 32 is the space
WpfConsole.BeginInputLine();
}
public void ClearConsole()
{
// When inputting commands
if (WpfConsole.InputLineStart != null)
{
WpfConsole.Host.Abort(); // Clear constructing multi-line command
WpfConsole.Clear();
PromptNewLine();
}
else
{
WpfConsole.Clear();
}
}
public abstract void Start();
public abstract void PostInputLine(InputLine inputLine);
}
/// <summary>
/// This class dispatches inputs for synchronous hosts.
/// </summary>
private class SyncHostConsoleDispatcher : Dispatcher
{
public SyncHostConsoleDispatcher(ConsoleDispatcher parentDispatcher)
: base(parentDispatcher)
{
}
public override void Start()
{
PromptNewLine();
}
public override void PostInputLine(InputLine inputLine)
{
IsExecuting = true;
try
{
if (Process(inputLine).Item1)
{
PromptNewLine();
}
}
finally
{
IsExecuting = false;
}
}
}
/// <summary>
/// This class dispatches inputs for asynchronous hosts.
/// </summary>
private class AsyncHostConsoleDispatcher : Dispatcher
{
private Queue<InputLine> _buffer;
private Marshaler _marshaler;
public AsyncHostConsoleDispatcher(ConsoleDispatcher parentDispatcher)
: base(parentDispatcher)
{
_marshaler = new Marshaler(this);
}
private bool IsStarted
{
get
{
return _buffer != null;
}
}
public override void Start()
{
if (IsStarted)
{
// Can only start once... ConsoleDispatcher is already protecting this.
throw new InvalidOperationException();
}
_buffer = new Queue<InputLine>();
IAsyncHost asyncHost = WpfConsole.Host as IAsyncHost;
if (asyncHost == null)
{
// ConsoleDispatcher is already checking this.
throw new InvalidOperationException();
}
asyncHost.ExecuteEnd += _marshaler.AsyncHost_ExecuteEnd;
PromptNewLine();
}
public override void PostInputLine(InputLine inputLine)
{
// The editor should be completely readonly unless started.
Debug.Assert(IsStarted);
if (IsStarted)
{
_buffer.Enqueue(inputLine);
ProcessInputs();
}
}
private void ProcessInputs()
{
if (IsExecuting)
{
return;
}
if (_buffer.Count > 0)
{
InputLine inputLine = _buffer.Dequeue();
Tuple<bool, bool> executeState = Process(inputLine);
if (executeState.Item1)
{
IsExecuting = true;
if (!executeState.Item2)
{
// If NOT really executed, processing the same as ExecuteEnd event
OnExecuteEnd();
}
}
}
}
private void OnExecuteEnd()
{
if (IsStarted)
{
// Filter out noise. A host could execute private commands.
Debug.Assert(IsExecuting);
IsExecuting = false;
PromptNewLine();
ProcessInputs();
}
}
/// <summary>
/// This private Marshaler marshals async host event to main thread so that the dispatcher
/// doesn't need to worry about threading.
/// </summary>
private class Marshaler : Marshaler<AsyncHostConsoleDispatcher>
{
public Marshaler(AsyncHostConsoleDispatcher impl)
: base(impl)
{
}
public void AsyncHost_ExecuteEnd(object sender, EventArgs e)
{
Invoke(() => _impl.OnExecuteEnd());
}
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_keyBuffer != null)
{
_keyBuffer.Dispose();
}
if (_cancelWaitKeySource != null)
{
_cancelWaitKeySource.Dispose();
}
}
}
void IDisposable.Dispose()
{
try
{
Dispose(true);
}
finally
{
GC.SuppressFinalize(this);
}
}
~ConsoleDispatcher()
{
Dispose(false);
}
}
[Flags]
internal enum InputLineFlag
{
Echo = 1,
Execute = 2
}
internal class InputLine
{
public SnapshotSpan SnapshotSpan { get; private set; }
public string Text { get; private set; }
public InputLineFlag Flags { get; private set; }
public InputLine(string text, bool execute)
{
this.Text = text;
this.Flags = InputLineFlag.Echo;
if (execute)
{
this.Flags |= InputLineFlag.Execute;
}
}
public InputLine(SnapshotSpan snapshotSpan)
{
this.SnapshotSpan = snapshotSpan;
this.Text = snapshotSpan.GetText();
this.Flags = InputLineFlag.Execute;
}
}
}
| |
// 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;
namespace Microsoft.VisualStudio.Pug
{
internal partial class JadeTokenizer : Tokenizer<JadeToken>
{
private void OnTag()
{
var ident = string.Empty;
var blockIndent = CalculateLineIndent();
// regular tag like
// html
// body
var range = ParseTagName();
if (range.Length > 0)
{
ident = this._cs.GetSubstringAt(range.Start, range.Length);
if (JadeTagKeywords.IsKeyword(ident))
{
// extends, javascripts:, stylesheets:
var length = this._cs.CurrentChar == ':' ? range.Length + 1 : range.Length;
AddToken(JadeTokenType.TagKeyword, range.Start, length);
if (this._cs.CurrentChar != ':' && StringComparer.Ordinal.Equals(ident, "mixin"))
{
SkipWhiteSpace();
if (!this._cs.IsAtNewLine())
{
OnTag();
}
}
else
{
SkipToEndOfLine();
}
return;
}
if (this._cs.CurrentChar == ':')
{
// Block expansion like
// li.first: a(href='#') foo
AddToken(JadeTokenType.TagName, range.Start, range.Length);
this._cs.MoveToNextChar();
SkipWhiteSpace();
if (!this._cs.IsAtNewLine())
{
OnTag();
}
return;
}
if (JadeCodeKeywords.IsKeyword(ident))
{
AddToken(JadeTokenType.CodeKeyword, range.Start, range.Length);
OnInlineCode();
return;
}
AddToken(JadeTokenType.TagName, range.Start, range.Length);
}
while (!this._cs.IsWhiteSpace() && !this._cs.IsEndOfStream())
{
if (this._cs.CurrentChar == '.' && Char.IsWhiteSpace(this._cs.NextChar))
{
// If this is last ., then what follows is a text literal
if (StringComparer.OrdinalIgnoreCase.Equals(ident, "script"))
{
this._cs.MoveToNextChar();
OnScript(blockIndent);
}
else if (StringComparer.OrdinalIgnoreCase.Equals(ident, "style"))
{
this._cs.MoveToNextChar();
OnStyle(blockIndent);
}
else if (IsAllWhiteSpaceBeforeEndOfLine(this._cs.Position + 1))
{
SkipToEndOfBlock(blockIndent, text: true);
}
else
{
this._cs.MoveToNextChar();
}
return;
}
if (this._cs.CurrentChar == '(')
{
OnAttributes(')');
}
if (this._cs.CurrentChar == '#' || this._cs.CurrentChar == '.')
{
var isID = this._cs.CurrentChar == '#';
// container(a=b).bar or container(a=b)#bar
var selectorRange = GetNonWSSequence("(:=.#");
if (selectorRange.Length > 0)
{
AddToken(
isID ? JadeTokenType.IdLiteral : JadeTokenType.ClassLiteral,
selectorRange.Start,
selectorRange.Length
);
if (Char.IsWhiteSpace(this._cs.CurrentChar) && this._cs.LookAhead(-1) == '.')
{
this._cs.Position--;
}
}
}
if (this._cs.CurrentChar != '.' && this._cs.CurrentChar != '#' && this._cs.CurrentChar != '(')
{
break;
}
}
if (this._cs.CurrentChar == ':')
{
// Block expansion like
// li.first: a(href='#') foo
this._cs.MoveToNextChar();
SkipWhiteSpace();
if (!this._cs.IsAtNewLine())
{
OnTag();
}
return;
}
// There may be ws between tag name and = sign. However, = must be on the same line.
var allWsToEol = IsAllWhiteSpaceBeforeEndOfLine(this._cs.Position);
if (!allWsToEol)
{
SkipWhiteSpace();
if (this._cs.CurrentChar == '=' || (this._cs.CurrentChar == '!' && this._cs.NextChar == '='))
{
// Something like 'foo ='
var length = this._cs.CurrentChar == '!' ? 2 : 1;
AddToken(JadeTokenType.Operator, this._cs.Position, length);
this._cs.Advance(length);
OnInlineCode();
}
else
{
OnText(strings: false, html: true, entities: true);
}
}
else
{
if (StringComparer.OrdinalIgnoreCase.Equals(ident, "script"))
{
OnScript(blockIndent);
}
else if (StringComparer.OrdinalIgnoreCase.Equals(ident, "style"))
{
OnStyle(blockIndent);
}
else
{
SkipToEndOfLine();
}
}
}
protected ITextRange ParseTagName()
{
var start = this._cs.Position;
var count = 0;
while (!this._cs.IsEndOfStream() && !this._cs.IsWhiteSpace() &&
(this._cs.IsAnsiLetter() || this._cs.IsDecimal() || this._cs.CurrentChar == '_' || (count > 0 && this._cs.CurrentChar == '-')))
{
if (this._cs.CurrentChar == ':')
{
if (this._cs.NextChar != '_' && (this._cs.NextChar < 'A' || this._cs.NextChar > 'z'))
{
break; // allow tags with namespaces
}
}
this._cs.MoveToNextChar();
count++;
}
return TextRange.FromBounds(start, this._cs.Position);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace MouseTester
{
public class MouseLog
{
public const int INVALID_HANDLE = -1;
private string desc1 = "Mouse 1";
private string desc2 = "Mouse 2";
private double normR = 1.0000;
private double normT = 0.0000;
private int handle1 = INVALID_HANDLE;
private int handle2 = INVALID_HANDLE;
private List<MouseEvent> events = new List<MouseEvent>(1000000);
public double NormR
{
get
{
return this.normR;
}
set
{
this.normR = value;
}
}
public double NormT
{
get
{
return this.normT;
}
set
{
this.normT = value;
}
}
public int Handle1
{
get
{
return this.handle1;
}
set
{
this.handle1 = value;
}
}
public int Handle2
{
get
{
return this.handle2;
}
set
{
this.handle2 = value;
}
}
public string Desc1
{
get
{
return this.desc1;
}
set
{
this.desc1 = value;
}
}
public string Desc2
{
get
{
return this.desc2;
}
set
{
this.desc2 = value;
}
}
public List<MouseEvent> Events
{
get
{
return this.events;
}
}
public void Add(MouseEvent e)
{
this.events.Add(e);
}
public void Clear()
{
this.events.Clear();
}
public void Load(string fname)
{
this.Clear();
try
{
using (StreamReader sr = File.OpenText(fname))
{
this.desc1 = sr.ReadLine();
this.handle1 = int.Parse(sr.ReadLine());
this.desc2 = sr.ReadLine();
this.handle2 = int.Parse(sr.ReadLine());
this.normR = double.Parse(sr.ReadLine());
this.normT = double.Parse(sr.ReadLine());
string headerline = sr.ReadLine();
while (sr.Peek() > -1)
{
string line = sr.ReadLine();
string[] values = line.Split(',');
this.Add(new MouseEvent(int.Parse(values[0]), 0, int.Parse(values[1]), int.Parse(values[2]), double.Parse(values[3])));
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
public void Save(string fname)
{
try
{
using (StreamWriter sw = File.CreateText(fname))
{
sw.WriteLine(this.desc1);
sw.WriteLine(this.handle1.ToString());
sw.WriteLine(this.desc2);
sw.WriteLine(this.handle2.ToString());
sw.WriteLine(this.normR.ToString());
sw.WriteLine(this.normT.ToString());
sw.WriteLine("handle,xCount,yCount,Time (ms)");
foreach (MouseEvent e in this.events)
{
sw.WriteLine(e.handle.ToString() + "," + e.lastx.ToString() + "," + e.lasty.ToString() + "," + e.ts.ToString(CultureInfo.InvariantCulture));
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
public Boolean Valid_handles()
{
if (this.handle1 == INVALID_HANDLE || this.handle2 == INVALID_HANDLE)
{
return false;
}
else
{
return true;
}
}
public void Normalize()
{
double x1 = 0.0;
double y1 = 0.0;
double x2 = 0.0;
double y2 = 0.0;
int count1 = 0;
int count2 = 0;
foreach (MouseEvent me in this.events)
{
if (me.handle == this.handle1)
{
x1 += (double)me.lastx;
y1 += (double)me.lasty;
count1++;
}
if (me.handle == this.handle2)
{
x2 += (double)me.lastx;
y2 += (double)me.lasty;
count2++;
}
}
if (count1 == 0)
{
return;
}
if (count2 == 0)
{
return;
}
double r1 = Math.Sqrt(x1 * x1 + y1 * y1);
double r2 = Math.Sqrt(x2 * x2 + y2 * y2);
double t1 = Math.Atan2(y1, x1);
double t2 = Math.Atan2(y2, x2);
this.normR = r1 / r2;
this.normT = t1 - t2;
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.TestProtos;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Google.ProtocolBuffers
{
[TestClass]
public class CodedOutputStreamTest
{
/// <summary>
/// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and
/// checks that the result matches the given bytes
/// </summary>
private static void AssertWriteVarint(byte[] data, ulong value)
{
// Only do 32-bit write if the value fits in 32 bits.
if ((value >> 32) == 0)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput);
output.WriteRawVarint32((uint) value);
output.Flush();
TestUtil.AssertBytesEqual(data, rawOutput.ToArray());
// Also try computing size.
Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value));
}
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput);
output.WriteRawVarint64(value);
output.Flush();
TestUtil.AssertBytesEqual(data, rawOutput.ToArray());
// Also try computing size.
Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value));
}
// Try different buffer sizes.
for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
{
// Only do 32-bit write if the value fits in 32 bits.
if ((value >> 32) == 0)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output =
CodedOutputStream.CreateInstance(rawOutput, bufferSize);
output.WriteRawVarint32((uint) value);
output.Flush();
TestUtil.AssertBytesEqual(data, rawOutput.ToArray());
}
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput, bufferSize);
output.WriteRawVarint64(value);
output.Flush();
TestUtil.AssertBytesEqual(data, rawOutput.ToArray());
}
}
}
/// <summary>
/// Tests WriteRawVarint32() and WriteRawVarint64()
/// </summary>
[TestMethod]
public void WriteVarint()
{
AssertWriteVarint(new byte[] {0x00}, 0);
AssertWriteVarint(new byte[] {0x01}, 1);
AssertWriteVarint(new byte[] {0x7f}, 127);
// 14882
AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7));
// 2961488830
AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b},
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x0bL << 28));
// 64-bit
// 7256456126
AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b},
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x1bL << 28));
// 41256202580718336
AssertWriteVarint(
new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49},
(0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
(0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49));
// 11964378330978735131
AssertWriteVarint(
new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01},
unchecked((ulong)
((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
(0x3bL << 28) | (0x56L << 35) | (0x00L << 42) |
(0x05L << 49) | (0x26L << 56) | (0x01L << 63))));
}
/// <summary>
/// Parses the given bytes using WriteRawLittleEndian32() and checks
/// that the result matches the given value.
/// </summary>
private static void AssertWriteLittleEndian32(byte[] data, uint value)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput);
output.WriteRawLittleEndian32(value);
output.Flush();
TestUtil.AssertBytesEqual(data, rawOutput.ToArray());
// Try different buffer sizes.
for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
{
rawOutput = new MemoryStream();
output = CodedOutputStream.CreateInstance(rawOutput, bufferSize);
output.WriteRawLittleEndian32(value);
output.Flush();
TestUtil.AssertBytesEqual(data, rawOutput.ToArray());
}
}
/// <summary>
/// Parses the given bytes using WriteRawLittleEndian64() and checks
/// that the result matches the given value.
/// </summary>
private static void AssertWriteLittleEndian64(byte[] data, ulong value)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput);
output.WriteRawLittleEndian64(value);
output.Flush();
TestUtil.AssertBytesEqual(data, rawOutput.ToArray());
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
{
rawOutput = new MemoryStream();
output = CodedOutputStream.CreateInstance(rawOutput, blockSize);
output.WriteRawLittleEndian64(value);
output.Flush();
TestUtil.AssertBytesEqual(data, rawOutput.ToArray());
}
}
/// <summary>
/// Tests writeRawLittleEndian32() and writeRawLittleEndian64().
/// </summary>
[TestMethod]
public void WriteLittleEndian()
{
AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678);
AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0);
AssertWriteLittleEndian64(
new byte[] {0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12},
0x123456789abcdef0L);
AssertWriteLittleEndian64(
new byte[] {0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a},
0x9abcdef012345678UL);
}
[TestMethod]
public void WriteWholeMessage()
{
TestAllTypes message = TestUtil.GetAllSet();
byte[] rawBytes = message.ToByteArray();
TestUtil.AssertEqualBytes(TestUtil.GoldenMessage.ToByteArray(), rawBytes);
// Try different block sizes.
for (int blockSize = 1; blockSize < 256; blockSize *= 2)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output =
CodedOutputStream.CreateInstance(rawOutput, blockSize);
message.WriteTo(output);
output.Flush();
TestUtil.AssertEqualBytes(rawBytes, rawOutput.ToArray());
}
}
/// <summary>
/// Tests writing a whole message with every packed field type. Ensures the
/// wire format of packed fields is compatible with C++.
/// </summary>
[TestMethod]
public void WriteWholePackedFieldsMessage()
{
TestPackedTypes message = TestUtil.GetPackedSet();
byte[] rawBytes = message.ToByteArray();
TestUtil.AssertEqualBytes(TestUtil.GetGoldenPackedFieldsMessage().ToByteArray(),
rawBytes);
}
[TestMethod]
public void EncodeZigZag32()
{
Assert.AreEqual(0u, CodedOutputStream.EncodeZigZag32(0));
Assert.AreEqual(1u, CodedOutputStream.EncodeZigZag32(-1));
Assert.AreEqual(2u, CodedOutputStream.EncodeZigZag32(1));
Assert.AreEqual(3u, CodedOutputStream.EncodeZigZag32(-2));
Assert.AreEqual(0x7FFFFFFEu, CodedOutputStream.EncodeZigZag32(0x3FFFFFFF));
Assert.AreEqual(0x7FFFFFFFu, CodedOutputStream.EncodeZigZag32(unchecked((int) 0xC0000000)));
Assert.AreEqual(0xFFFFFFFEu, CodedOutputStream.EncodeZigZag32(0x7FFFFFFF));
Assert.AreEqual(0xFFFFFFFFu, CodedOutputStream.EncodeZigZag32(unchecked((int) 0x80000000)));
}
[TestMethod]
public void EncodeZigZag64()
{
Assert.AreEqual(0u, CodedOutputStream.EncodeZigZag64(0));
Assert.AreEqual(1u, CodedOutputStream.EncodeZigZag64(-1));
Assert.AreEqual(2u, CodedOutputStream.EncodeZigZag64(1));
Assert.AreEqual(3u, CodedOutputStream.EncodeZigZag64(-2));
Assert.AreEqual(0x000000007FFFFFFEuL,
CodedOutputStream.EncodeZigZag64(unchecked((long) 0x000000003FFFFFFFUL)));
Assert.AreEqual(0x000000007FFFFFFFuL,
CodedOutputStream.EncodeZigZag64(unchecked((long) 0xFFFFFFFFC0000000UL)));
Assert.AreEqual(0x00000000FFFFFFFEuL,
CodedOutputStream.EncodeZigZag64(unchecked((long) 0x000000007FFFFFFFUL)));
Assert.AreEqual(0x00000000FFFFFFFFuL,
CodedOutputStream.EncodeZigZag64(unchecked((long) 0xFFFFFFFF80000000UL)));
Assert.AreEqual(0xFFFFFFFFFFFFFFFEL,
CodedOutputStream.EncodeZigZag64(unchecked((long) 0x7FFFFFFFFFFFFFFFUL)));
Assert.AreEqual(0xFFFFFFFFFFFFFFFFL,
CodedOutputStream.EncodeZigZag64(unchecked((long) 0x8000000000000000UL)));
}
[TestMethod]
public void RoundTripZigZag32()
{
// Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
// were chosen semi-randomly via keyboard bashing.
Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(0)));
Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(1)));
Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-1)));
Assert.AreEqual(14927, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(14927)));
Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-3612)));
}
[TestMethod]
public void RoundTripZigZag64()
{
Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(0)));
Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(1)));
Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-1)));
Assert.AreEqual(14927, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(14927)));
Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-3612)));
Assert.AreEqual(856912304801416L,
CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(856912304801416L)));
Assert.AreEqual(-75123905439571256L,
CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L)));
}
[TestMethod]
public void TestNegativeEnumNoTag()
{
Assert.AreEqual(10, CodedOutputStream.ComputeInt32SizeNoTag(-2));
Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag(-2));
byte[] bytes = new byte[10];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteEnumNoTag(-2);
Assert.AreEqual(0, output.SpaceLeft);
Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes));
}
[TestMethod]
public void TestNegativeEnumWithTag()
{
Assert.AreEqual(11, CodedOutputStream.ComputeInt32Size(8, -2));
Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, -2));
byte[] bytes = new byte[11];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteEnum(8, "", -2, -2);
Assert.AreEqual(0, output.SpaceLeft);
//fyi, 0x40 == 0x08 << 3 + 0, field num + wire format shift
Assert.AreEqual("40-FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes));
}
[TestMethod]
public void TestNegativeEnumArrayPacked()
{
int arraySize = 1 + (10 * 5);
int msgSize = 1 + 1 + arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WritePackedEnumArray(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 });
Assert.AreEqual(0, output.SpaceLeft);
CodedInputStream input = CodedInputStream.CreateInstance(bytes);
uint tag;
string name;
Assert.IsTrue(input.ReadTag(out tag, out name));
List<int> values = new List<int>();
input.ReadInt32Array(tag, name, values);
Assert.AreEqual(6, values.Count);
for (int i = 0; i > -6; i--)
Assert.AreEqual(i, values[Math.Abs(i)]);
}
[TestMethod]
public void TestNegativeEnumArray()
{
int arraySize = 1 + 1 + (11 * 5);
int msgSize = arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteEnumArray(8, "", new int[] { 0, -1, -2, -3, -4, -5 });
Assert.AreEqual(0, output.SpaceLeft);
CodedInputStream input = CodedInputStream.CreateInstance(bytes);
uint tag;
string name;
Assert.IsTrue(input.ReadTag(out tag, out name));
List<int> values = new List<int>();
input.ReadInt32Array(tag, name, values);
Assert.AreEqual(6, values.Count);
for (int i = 0; i > -6; i--)
Assert.AreEqual(i, values[Math.Abs(i)]);
}
[TestMethod]
public void TestCodedInputOutputPosition()
{
byte[] content = new byte[110];
for (int i = 0; i < content.Length; i++)
content[i] = (byte)i;
byte[] child = new byte[120];
{
MemoryStream ms = new MemoryStream(child);
CodedOutputStream cout = CodedOutputStream.CreateInstance(ms, 20);
// Field 11: numeric value: 500
cout.WriteTag(11, WireFormat.WireType.Varint);
Assert.AreEqual(1, cout.Position);
cout.WriteInt32NoTag(500);
Assert.AreEqual(3, cout.Position);
//Field 12: length delimited 120 bytes
cout.WriteTag(12, WireFormat.WireType.LengthDelimited);
Assert.AreEqual(4, cout.Position);
cout.WriteBytesNoTag(ByteString.CopyFrom(content));
Assert.AreEqual(115, cout.Position);
// Field 13: fixed numeric value: 501
cout.WriteTag(13, WireFormat.WireType.Fixed32);
Assert.AreEqual(116, cout.Position);
cout.WriteSFixed32NoTag(501);
Assert.AreEqual(120, cout.Position);
cout.Flush();
}
byte[] bytes = new byte[130];
{
CodedOutputStream cout = CodedOutputStream.CreateInstance(bytes);
// Field 1: numeric value: 500
cout.WriteTag(1, WireFormat.WireType.Varint);
Assert.AreEqual(1, cout.Position);
cout.WriteInt32NoTag(500);
Assert.AreEqual(3, cout.Position);
//Field 2: length delimited 120 bytes
cout.WriteTag(2, WireFormat.WireType.LengthDelimited);
Assert.AreEqual(4, cout.Position);
cout.WriteBytesNoTag(ByteString.CopyFrom(child));
Assert.AreEqual(125, cout.Position);
// Field 3: fixed numeric value: 500
cout.WriteTag(3, WireFormat.WireType.Fixed32);
Assert.AreEqual(126, cout.Position);
cout.WriteSFixed32NoTag(501);
Assert.AreEqual(130, cout.Position);
cout.Flush();
}
//Now test Input stream:
{
CodedInputStream cin = CodedInputStream.CreateInstance(new MemoryStream(bytes), new byte[50]);
uint tag;
int intValue = 0;
string ignore;
Assert.AreEqual(0, cin.Position);
// Field 1:
Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 1);
Assert.AreEqual(1, cin.Position);
Assert.IsTrue(cin.ReadInt32(ref intValue) && intValue == 500);
Assert.AreEqual(3, cin.Position);
//Field 2:
Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 2);
Assert.AreEqual(4, cin.Position);
uint childlen = cin.ReadRawVarint32();
Assert.AreEqual(120u, childlen);
Assert.AreEqual(5, cin.Position);
int oldlimit = cin.PushLimit((int)childlen);
Assert.AreEqual(5, cin.Position);
// Now we are reading child message
{
// Field 11: numeric value: 500
Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 11);
Assert.AreEqual(6, cin.Position);
Assert.IsTrue(cin.ReadInt32(ref intValue) && intValue == 500);
Assert.AreEqual(8, cin.Position);
//Field 12: length delimited 120 bytes
Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 12);
Assert.AreEqual(9, cin.Position);
ByteString bstr = null;
Assert.IsTrue(cin.ReadBytes(ref bstr) && bstr.Length == 110 && bstr.ToByteArray()[109] == 109);
Assert.AreEqual(120, cin.Position);
// Field 13: fixed numeric value: 501
Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 13);
// ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit
Assert.AreEqual(121, cin.Position);
Assert.IsTrue(cin.ReadSFixed32(ref intValue) && intValue == 501);
Assert.AreEqual(125, cin.Position);
Assert.IsTrue(cin.IsAtEnd);
}
cin.PopLimit(oldlimit);
Assert.AreEqual(125, cin.Position);
// Field 3: fixed numeric value: 501
Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 3);
Assert.AreEqual(126, cin.Position);
Assert.IsTrue(cin.ReadSFixed32(ref intValue) && intValue == 501);
Assert.AreEqual(130, cin.Position);
Assert.IsTrue(cin.IsAtEnd);
}
}
}
}
| |
// 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;
namespace System.Xml
{
/// <devdoc>
/// <para>
/// XmlNameTable implemented as a simple hash table.
/// </para>
/// </devdoc>
public class NameTable : XmlNameTable
{
//
// Private types
//
private class Entry
{
internal string str;
internal int hashCode;
internal Entry next;
internal Entry(string str, int hashCode, Entry next)
{
this.str = str;
this.hashCode = hashCode;
this.next = next;
}
}
//
// Fields
//
private Entry[] _entries;
private int _count;
private int _mask;
private int _hashCodeRandomizer;
//
// Constructor
/// <devdoc>
/// Public constructor.
/// </devdoc>
public NameTable()
{
_mask = 31;
_entries = new Entry[_mask + 1];
_hashCodeRandomizer = Environment.TickCount;
}
//
// XmlNameTable public methods
/// <devdoc>
/// Add the given string to the NameTable or return
/// the existing string if it is already in the NameTable.
/// </devdoc>
public override string Add(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
int len = key.Length;
if (len == 0)
{
return string.Empty;
}
int hashCode;
unchecked
{
hashCode = len + _hashCodeRandomizer;
// use key.Length to eliminate the range check
for (int i = 0; i < key.Length; i++)
{
hashCode += (hashCode << 7) ^ key[i];
}
// mix it a bit more
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
}
for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next)
{
if (e.hashCode == hashCode && e.str.Equals(key))
{
return e.str;
}
}
return AddEntry(key, hashCode);
}
/// <devdoc>
/// Add the given string to the NameTable or return
/// the existing string if it is already in the NameTable.
/// </devdoc>
public override string Add(char[] key, int start, int len)
{
if (len == 0)
{
return string.Empty;
}
int hashCode;
unchecked
{
hashCode = len + _hashCodeRandomizer;
hashCode += (hashCode << 7) ^ key[start]; // this will throw IndexOutOfRangeException in case the start index is invalid
int end = start + len;
for (int i = start + 1; i < end; i++)
{
hashCode += (hashCode << 7) ^ key[i];
}
// mix it a bit more
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
}
for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next)
{
if (e.hashCode == hashCode && TextEquals(e.str, key, start, len))
{
return e.str;
}
}
return AddEntry(new string(key, start, len), hashCode);
}
/// <devdoc>
/// Find the matching string in the NameTable.
/// </devdoc>
public override string Get(string value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.Length == 0)
{
return string.Empty;
}
int hashCode;
unchecked
{
int len = value.Length + _hashCodeRandomizer;
hashCode = len;
// use value.Length to eliminate the range check
for (int i = 0; i < value.Length; i++)
{
hashCode += (hashCode << 7) ^ value[i];
}
// mix it a bit more
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
}
for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next)
{
if (e.hashCode == hashCode && e.str.Equals(value))
{
return e.str;
}
}
return null;
}
/// <devdoc>
/// Find the matching string atom given a range of
/// characters.
/// </devdoc>
public override string Get(char[] key, int start, int len)
{
if (len == 0)
{
return string.Empty;
}
int hashCode;
unchecked
{
hashCode = len + _hashCodeRandomizer;
hashCode += (hashCode << 7) ^ key[start]; // this will throw IndexOutOfRangeException in case the start index is invalid
int end = start + len;
for (int i = start + 1; i < end; i++)
{
hashCode += (hashCode << 7) ^ key[i];
}
// mix it a bit more
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
}
for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next)
{
if (e.hashCode == hashCode && TextEquals(e.str, key, start, len))
{
return e.str;
}
}
return null;
}
//
// Private methods
//
private string AddEntry(string str, int hashCode)
{
int index = hashCode & _mask;
Entry e = new Entry(str, hashCode, _entries[index]);
_entries[index] = e;
if (_count++ == _mask)
{
Grow();
}
return e.str;
}
private void Grow()
{
int newMask = _mask * 2 + 1;
Entry[] oldEntries = _entries;
Entry[] newEntries = new Entry[newMask + 1];
// use oldEntries.Length to eliminate the range check
for (int i = 0; i < oldEntries.Length; i++)
{
Entry e = oldEntries[i];
while (e != null)
{
int newIndex = e.hashCode & newMask;
Entry tmp = e.next;
e.next = newEntries[newIndex];
newEntries[newIndex] = e;
e = tmp;
}
}
_entries = newEntries;
_mask = newMask;
}
private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length)
{
if (str1.Length != str2Length)
{
return false;
}
// use array.Length to eliminate the range check
for (int i = 0; i < str1.Length; i++)
{
if (str1[i] != str2[str2Start + i])
{
return false;
}
}
return true;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Xunit;
namespace Compute.Tests.DiskRPTests
{
public class DiskRPCreateOptionTests : DiskRPTestsBase
{
private static string DiskRPLocation = "centraluseuap";
/// <summary>
/// positive test for testing upload disks
/// </summary>
[Fact]
public void UploadDiskPositiveTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
var rgName = TestUtilities.GenerateName(TestPrefix);
var diskName = TestUtilities.GenerateName(DiskNamePrefix);
Disk disk = GenerateDefaultDisk(DiskCreateOption.Upload, rgName, 32767);
disk.Location = DiskRPLocation;
try
{
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation });
//put disk
m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk);
Disk diskOut = m_CrpClient.Disks.Get(rgName, diskName);
Validate(disk, diskOut, disk.Location);
Assert.Equal(disk.CreationData.CreateOption, diskOut.CreationData.CreateOption);
m_CrpClient.Disks.Delete(rgName, diskName);
}
finally
{
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
}
/// <summary>
/// positive test for testing disks created from a gallery image version
/// </summary>
[Fact]
public void DiskFromGalleryImageVersion()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
var rgName = TestUtilities.GenerateName(TestPrefix);
var diskName = TestUtilities.GenerateName(DiskNamePrefix);
Disk disk = GenerateBaseDisk(DiskCreateOption.FromImage);
disk.Location = "centraluseuap";
disk.CreationData.GalleryImageReference = new ImageDiskReference
{
Id = "/subscriptions/0296790d-427c-48ca-b204-8b729bbd8670/resourceGroups/longrunningrg-centraluseuap/providers/Microsoft.Compute/galleries/swaggergallery/images/swaggerimage/versions/1.1.0",
Lun = 0
};
try
{
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation });
//put disk
m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk);
Disk diskOut = m_CrpClient.Disks.Get(rgName, diskName);
Validate(disk, diskOut, disk.Location);
Assert.Equal(disk.CreationData.CreateOption, diskOut.CreationData.CreateOption);
m_CrpClient.Disks.Delete(rgName, diskName);
}
finally
{
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
}
/// <summary>
/// positive test for snapshot created via CopyStart operation
/// </summary>
[Fact]
public void CopyStartSnapshotPositiveTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
// Data
const string location = "centraluseuap";
const string remoteLocation = "eastus2euap";
var rgName = TestUtilities.GenerateName(TestPrefix);
var remoteRgName = TestUtilities.GenerateName(TestPrefix);
var diskName = TestUtilities.GenerateName(DiskNamePrefix);
var sourceSnapshotName = TestUtilities.GenerateName(DiskNamePrefix);
var snapshotName = TestUtilities.GenerateName(DiskNamePrefix);
Disk sourceDisk = GenerateDefaultDisk(DiskCreateOption.Empty, remoteRgName, diskSizeGB: 5, location: remoteLocation);
try
{
// **********
// SETUP
// **********
// Create resource group
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location });
m_ResourcesClient.ResourceGroups.CreateOrUpdate(remoteRgName, new ResourceGroup { Location = remoteLocation });
// Put disk
Disk diskOut = m_CrpClient.Disks.CreateOrUpdate(remoteRgName, diskName, sourceDisk);
Validate(sourceDisk, diskOut, remoteLocation);
// Generate snapshot using disk info
Snapshot sourceSnapshot = GenerateDefaultSnapshot(diskOut.Id, incremental: true, location: remoteLocation);
Snapshot sourceSnapshotOut = m_CrpClient.Snapshots.CreateOrUpdate(remoteRgName, sourceSnapshotName, sourceSnapshot);
// Generate snapshot using snapshot info
Snapshot snapshot = GenerateCopyStartSnapshot(sourceSnapshotOut.Id, location: location);
// **********
// TEST
// **********
// Put
m_CrpClient.Snapshots.CreateOrUpdate(rgName, snapshotName, snapshot);
Snapshot snapshotOut = PollCloneSnaphotToCompletion(rgName, snapshotName);
Validate(snapshot, snapshotOut, incremental: true);
OperateSnapshot(snapshot, rgName, snapshotName, incremental: true);
}
finally
{
// Delete resource group
m_ResourcesClient.ResourceGroups.Delete(rgName);
m_ResourcesClient.ResourceGroups.Delete(remoteRgName);
}
}
}
/// <summary>
/// positive test for testing UploadPreparedSecure disk
/// </summary>
[Fact]
public void DiskWithUploadPreparedSecureCreateOptionTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
var rgName = TestUtilities.GenerateName(TestPrefix);
var diskName = TestUtilities.GenerateName(DiskNamePrefix);
Disk disk = GenerateDefaultDisk(DiskCreateOption.UploadPreparedSecure, rgName, 32767);
disk.SecurityProfile = new DiskSecurityProfile { SecurityType = DiskSecurityTypes.ConfidentialVMDiskEncryptedWithCustomerKey };
disk.Location = DiskRPLocation;
disk.SecurityProfile.SecureVMDiskEncryptionSetId = "/subscriptions/0296790d-427c-48ca-b204-8b729bbd8670/resourceGroups/longrunningrg-centraluseuap/providers/Microsoft.Compute/diskEncryptionSets/cvm-des3";
try
{
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation });
//put disk
m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk);
Disk diskOut = m_CrpClient.Disks.Get(rgName, diskName);
Validate(disk, diskOut, disk.Location);
Assert.Equal(disk.CreationData.CreateOption, diskOut.CreationData.CreateOption);
Assert.NotNull(diskOut.SecurityProfile);
Assert.Equal(disk.SecurityProfile.SecurityType, diskOut.SecurityProfile.SecurityType);
Assert.Equal(disk.SecurityProfile.SecureVMDiskEncryptionSetId, diskOut.SecurityProfile.SecureVMDiskEncryptionSetId);
m_CrpClient.Disks.Delete(rgName, diskName);
}
finally
{
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
}
/// <summary>
/// positive test for testing ImportSecure disk
/// </summary>
[Fact]
public void DiskWithImportSecureCreateOptionTest()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
var rgName = TestUtilities.GenerateName(TestPrefix);
var diskName = TestUtilities.GenerateName(DiskNamePrefix);
Disk disk = GenerateBaseDisk(DiskCreateOption.ImportSecure);
disk.OsType = OperatingSystemTypes.Windows;
disk.CreationData.SourceUri = "https://swaggeraccount.blob.core.windows.net/swagger/abcd.vhd";
disk.CreationData.SecurityDataUri = "https://swaggeraccount.blob.core.windows.net/swagger/vmgs.vhd";
disk.CreationData.StorageAccountId = "/subscriptions/0296790d-427c-48ca-b204-8b729bbd8670/resourceGroups/longrunningrg-centraluseuap/providers/Microsoft.Storage/storageAccounts/swaggeraccount";
disk.SecurityProfile = new DiskSecurityProfile { SecurityType = DiskSecurityTypes.TrustedLaunch };
disk.HyperVGeneration = HyperVGeneration.V2;
disk.Location = DiskRPLocation;
try
{
m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation });
//put disk
m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk);
Disk diskOut = m_CrpClient.Disks.Get(rgName, diskName);
Validate(disk, diskOut, disk.Location);
Assert.Equal(disk.CreationData.CreateOption, diskOut.CreationData.CreateOption);
Assert.NotNull(diskOut.SecurityProfile);
Assert.Equal(disk.CreationData.SecurityDataUri, diskOut.CreationData.SecurityDataUri);
Assert.Equal(disk.SecurityProfile.SecurityType, diskOut.SecurityProfile.SecurityType);
m_CrpClient.Disks.Delete(rgName, diskName);
}
finally
{
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
}
}
}
| |
/*
* Copyright (c) 2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
namespace OpenMetaverse.Rendering
{
public class LindenMesh
{
const string MESH_HEADER = "Linden Binary Mesh 1.0";
const string MORPH_FOOTER = "End Morphs";
#region Mesh Structs
public struct Face
{
public short[] Indices;
}
public struct Vertex
{
public Vector3 Coord;
public Vector3 Normal;
public Vector3 BiNormal;
public Vector2 TexCoord;
public Vector2 DetailTexCoord;
public float Weight;
public override string ToString()
{
return String.Format("Coord: {0} Norm: {1} BiNorm: {2} TexCoord: {3} DetailTexCoord: {4}", Coord, Normal, BiNormal, TexCoord, DetailTexCoord, Weight);
}
}
public struct MorphVertex
{
public uint VertexIndex;
public Vector3 Coord;
public Vector3 Normal;
public Vector3 BiNormal;
public Vector2 TexCoord;
public override string ToString()
{
return String.Format("Index: {0} Coord: {1} Norm: {2} BiNorm: {3} TexCoord: {4}", VertexIndex, Coord, Normal, BiNormal, TexCoord);
}
}
public struct Morph
{
public string Name;
public int NumVertices;
public MorphVertex[] Vertices;
public override string ToString()
{
return Name;
}
}
public struct VertexRemap
{
public int RemapSource;
public int RemapDestination;
public override string ToString()
{
return String.Format("{0} -> {1}", RemapSource, RemapDestination);
}
}
#endregion Mesh Structs
/// <summary>
/// Level of Detail mesh
/// </summary>
public class LODMesh
{
public float MinPixelWidth;
protected string _header;
protected bool _hasWeights;
protected bool _hasDetailTexCoords;
protected Vector3 _position;
protected Vector3 _rotationAngles;
protected byte _rotationOrder;
protected Vector3 _scale;
protected ushort _numFaces;
protected Face[] _faces;
public virtual void LoadMesh(string filename)
{
byte[] buffer = File.ReadAllBytes(filename);
BitPack input = new BitPack(buffer, 0);
_header = input.UnpackString(24).TrimEnd(new char[] { '\0' });
if (!String.Equals(_header, MESH_HEADER))
throw new FileLoadException("Unrecognized mesh format");
// Populate base mesh variables
_hasWeights = (input.UnpackByte() != 0);
_hasDetailTexCoords = (input.UnpackByte() != 0);
_position = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
_rotationAngles = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
_rotationOrder = input.UnpackByte();
_scale = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
_numFaces = (ushort)input.UnpackUShort();
_faces = new Face[_numFaces];
for (int i = 0; i < _numFaces; i++)
_faces[i].Indices = new short[] { input.UnpackShort(), input.UnpackShort(), input.UnpackShort() };
}
}
public float MinPixelWidth;
public string Name { get { return _name; } }
public string Header { get { return _header; } }
public bool HasWeights { get { return _hasWeights; } }
public bool HasDetailTexCoords { get { return _hasDetailTexCoords; } }
public Vector3 Position { get { return _position; } }
public Vector3 RotationAngles { get { return _rotationAngles; } }
//public byte RotationOrder
public Vector3 Scale { get { return _scale; } }
public ushort NumVertices { get { return _numVertices; } }
public Vertex[] Vertices { get { return _vertices; } }
public ushort NumFaces { get { return _numFaces; } }
public Face[] Faces { get { return _faces; } }
public ushort NumSkinJoints { get { return _numSkinJoints; } }
public string[] SkinJoints { get { return _skinJoints; } }
public Morph[] Morphs { get { return _morphs; } }
public int NumRemaps { get { return _numRemaps; } }
public VertexRemap[] VertexRemaps { get { return _vertexRemaps; } }
public SortedList<int, LODMesh> LODMeshes { get { return _lodMeshes; } }
protected string _name;
protected string _header;
protected bool _hasWeights;
protected bool _hasDetailTexCoords;
protected Vector3 _position;
protected Vector3 _rotationAngles;
protected byte _rotationOrder;
protected Vector3 _scale;
protected ushort _numVertices;
protected Vertex[] _vertices;
protected ushort _numFaces;
protected Face[] _faces;
protected ushort _numSkinJoints;
protected string[] _skinJoints;
protected Morph[] _morphs;
protected int _numRemaps;
protected VertexRemap[] _vertexRemaps;
protected SortedList<int, LODMesh> _lodMeshes;
public LindenMesh(string name)
{
_name = name;
_lodMeshes = new SortedList<int, LODMesh>();
}
public virtual void LoadMesh(string filename)
{
byte[] buffer = File.ReadAllBytes(filename);
BitPack input = new BitPack(buffer, 0);
_header = input.UnpackString(24).TrimEnd(new char[] { '\0' });
if (!String.Equals(_header, MESH_HEADER))
throw new FileLoadException("Unrecognized mesh format");
// Populate base mesh variables
_hasWeights = (input.UnpackByte() != 0);
_hasDetailTexCoords = (input.UnpackByte() != 0);
_position = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
_rotationAngles = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
_rotationOrder = input.UnpackByte();
_scale = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
_numVertices = (ushort)input.UnpackUShort();
// Populate the vertex array
_vertices = new Vertex[_numVertices];
for (int i = 0; i < _numVertices; i++)
_vertices[i].Coord = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
for (int i = 0; i < _numVertices; i++)
_vertices[i].Normal = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
for (int i = 0; i < _numVertices; i++)
_vertices[i].BiNormal = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
for (int i = 0; i < _numVertices; i++)
_vertices[i].TexCoord = new Vector2(input.UnpackFloat(), input.UnpackFloat());
if (_hasDetailTexCoords)
{
for (int i = 0; i < _numVertices; i++)
_vertices[i].DetailTexCoord = new Vector2(input.UnpackFloat(), input.UnpackFloat());
}
if (_hasWeights)
{
for (int i = 0; i < _numVertices; i++)
_vertices[i].Weight = input.UnpackFloat();
}
_numFaces = input.UnpackUShort();
_faces = new Face[_numFaces];
for (int i = 0; i < _numFaces; i++)
_faces[i].Indices = new short[] { input.UnpackShort(), input.UnpackShort(), input.UnpackShort() };
if (_hasWeights)
{
_numSkinJoints = input.UnpackUShort();
_skinJoints = new string[_numSkinJoints];
for (int i = 0; i < _numSkinJoints; i++)
_skinJoints[i] = input.UnpackString(64).TrimEnd(new char[] { '\0' });
}
else
{
_numSkinJoints = 0;
_skinJoints = new string[0];
}
// Grab morphs
List<Morph> morphs = new List<Morph>();
string morphName = input.UnpackString(64).TrimEnd(new char[] { '\0' });
while (morphName != MORPH_FOOTER)
{
if (input.BytePos + 48 >= input.Data.Length) throw new FileLoadException("Encountered end of file while parsing morphs");
Morph morph = new Morph();
morph.Name = morphName;
morph.NumVertices = input.UnpackInt();
morph.Vertices = new MorphVertex[morph.NumVertices];
for (int i = 0; i < morph.NumVertices; i++)
{
MorphVertex vertex;
vertex.VertexIndex = input.UnpackUInt();
vertex.Coord = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
vertex.Normal = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
vertex.BiNormal = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
vertex.TexCoord = new Vector2(input.UnpackFloat(), input.UnpackFloat());
}
morphs.Add(morph);
// Grab the next name
morphName = input.UnpackString(64).TrimEnd(new char[] { '\0' });
}
_morphs = morphs.ToArray();
// Check if there are remaps or if we're at the end of the file
if (input.BytePos < input.Data.Length - 1)
{
_numRemaps = input.UnpackInt();
_vertexRemaps = new VertexRemap[_numRemaps];
for (int i = 0; i < _numRemaps; i++)
{
_vertexRemaps[i].RemapSource = input.UnpackInt();
_vertexRemaps[i].RemapDestination = input.UnpackInt();
}
}
else
{
_numRemaps = 0;
_vertexRemaps = new VertexRemap[0];
}
}
public virtual void LoadLODMesh(int level, string filename)
{
LODMesh lod = new LODMesh();
lod.LoadMesh(filename);
_lodMeshes[level] = lod;
}
}
}
| |
// 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 ConvertToVector128SingleVector128Double()
{
var test = new SimpleUnaryOpConvTest__ConvertToVector128SingleVector128Double();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 SimpleUnaryOpConvTest__ConvertToVector128SingleVector128Double
{
private struct TestStruct
{
public Vector128<Double> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpConvTest__ConvertToVector128SingleVector128Double testClass)
{
var result = Sse2.ConvertToVector128Single(_fld);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Double[] _data = new Double[Op1ElementCount];
private static Vector128<Double> _clsVar;
private Vector128<Double> _fld;
private SimpleUnaryOpTest__DataTable<Single, Double> _dataTable;
static SimpleUnaryOpConvTest__ConvertToVector128SingleVector128Double()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleUnaryOpConvTest__ConvertToVector128SingleVector128Double()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Single, Double>(_data, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ConvertToVector128Single(
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ConvertToVector128Single(
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ConvertToVector128Single(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Single), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Single), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToVector128Single), new Type[] { typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ConvertToVector128Single(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr);
var result = Sse2.ConvertToVector128Single(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr));
var result = Sse2.ConvertToVector128Single(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr));
var result = Sse2.ConvertToVector128Single(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpConvTest__ConvertToVector128SingleVector128Double();
var result = Sse2.ConvertToVector128Single(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ConvertToVector128Single(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ConvertToVector128Single(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits((float)firstOp[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != ((i < 2) ? BitConverter.SingleToInt32Bits((float)firstOp[i]) : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ConvertToVector128Single)}<Single>(Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.Build.Construction;
using System.Linq;
namespace Microsoft.DotNet.ProjectJsonMigration.Transforms
{
internal class ItemTransformApplicator : ITransformApplicator
{
private readonly ProjectRootElement _projectElementGenerator = ProjectRootElement.Create();
public void Execute<T, U>(
T element,
U destinationElement,
bool mergeExisting) where T : ProjectElement where U : ProjectElementContainer
{
if (typeof(T) != typeof(ProjectItemElement))
{
throw new ArgumentException($"Expected element to be of type {nameof(ProjectItemElement)}, but got {typeof(T)}");
}
if (typeof(U) != typeof(ProjectItemGroupElement))
{
throw new ArgumentException($"Expected destinationElement to be of type {nameof(ProjectItemGroupElement)}, but got {typeof(U)}");
}
if (element == null)
{
return;
}
if (destinationElement == null)
{
throw new ArgumentException("expected destinationElement to not be null");
}
var item = element as ProjectItemElement;
var destinationItemGroup = destinationElement as ProjectItemGroupElement;
MigrationTrace.Instance.WriteLine($"{nameof(ItemTransformApplicator)}: Item {{ ItemType: {item.ItemType}, Condition: {item.Condition}, Include: {item.Include}, Exclude: {item.Exclude} }}");
MigrationTrace.Instance.WriteLine($"{nameof(ItemTransformApplicator)}: ItemGroup {{ Condition: {destinationItemGroup.Condition} }}");
if (mergeExisting)
{
// Don't duplicate items or includes
item = MergeWithExistingItemsWithSameCondition(item, destinationItemGroup);
if (item == null)
{
MigrationTrace.Instance.WriteLine($"{nameof(ItemTransformApplicator)}: Item completely merged");
return;
}
// Handle duplicate includes between different conditioned items
item = MergeWithExistingItemsWithNoCondition(item, destinationItemGroup);
if (item == null)
{
MigrationTrace.Instance.WriteLine($"{nameof(ItemTransformApplicator)}: Item completely merged");
return;
}
item = MergeWithExistingItemsWithACondition(item, destinationItemGroup);
if (item == null)
{
MigrationTrace.Instance.WriteLine($"{nameof(ItemTransformApplicator)}: Item completely merged");
return;
}
}
AddItemToItemGroup(item, destinationItemGroup);
}
public void Execute<T, U>(
IEnumerable<T> elements,
U destinationElement,
bool mergeExisting) where T : ProjectElement where U : ProjectElementContainer
{
foreach (var element in elements)
{
Execute(element, destinationElement, mergeExisting);
}
}
private void AddItemToItemGroup(ProjectItemElement item, ProjectItemGroupElement itemGroup)
{
var outputItem = itemGroup.ContainingProject.CreateItemElement("___TEMP___");
outputItem.CopyFrom(item);
itemGroup.AppendChild(outputItem);
outputItem.AddMetadata(item.Metadata);
}
private ProjectItemElement MergeWithExistingItemsWithACondition(ProjectItemElement item, ProjectItemGroupElement destinationItemGroup)
{
// This logic only applies to conditionless items
if (item.ConditionChain().Any() || destinationItemGroup.ConditionChain().Any())
{
return item;
}
var existingItemsWithACondition =
FindExistingItemsWithACondition(item, destinationItemGroup.ContainingProject, destinationItemGroup);
MigrationTrace.Instance.WriteLine($"{nameof(ItemTransformApplicator)}: Merging Item with {existingItemsWithACondition.Count()} existing items with a different condition chain.");
foreach (var existingItem in existingItemsWithACondition)
{
// If this item is encompassing items in a condition, remove the encompassed includes from the existing item
var encompassedIncludes = item.GetEncompassedIncludes(existingItem);
if (encompassedIncludes.Any())
{
MigrationTrace.Instance.WriteLine($"{nameof(ItemTransformApplicator)}: encompassed includes {string.Join(", ", encompassedIncludes)}");
existingItem.RemoveIncludes(encompassedIncludes);
}
// continue if the existing item is now empty
if (!existingItem.Includes().Any())
{
MigrationTrace.Instance.WriteLine($"{nameof(ItemTransformApplicator)}: Removing Item {{ ItemType: {existingItem.ItemType}, Condition: {existingItem.Condition}, Include: {existingItem.Include}, Exclude: {existingItem.Exclude} }}");
existingItem.Parent.RemoveChild(existingItem);
continue;
}
// If we haven't continued, the existing item may have includes
// that need to be removed before being redefined, to avoid duplicate includes
// Create or merge with existing remove
var remainingIntersectedIncludes = existingItem.IntersectIncludes(item);
if (remainingIntersectedIncludes.Any())
{
var existingRemoveItem = destinationItemGroup.Items
.Where(i =>
string.IsNullOrEmpty(i.Include)
&& string.IsNullOrEmpty(i.Exclude)
&& !string.IsNullOrEmpty(i.Remove))
.FirstOrDefault();
if (existingRemoveItem != null)
{
var removes = new HashSet<string>(existingRemoveItem.Remove.Split(';'));
foreach (var include in remainingIntersectedIncludes)
{
removes.Add(include);
}
existingRemoveItem.Remove = string.Join(";", removes);
}
else
{
var clearPreviousItem = _projectElementGenerator.CreateItemElement(item.ItemType);
clearPreviousItem.Remove = string.Join(";", remainingIntersectedIncludes);
AddItemToItemGroup(clearPreviousItem, existingItem.Parent as ProjectItemGroupElement);
}
}
}
return item;
}
private ProjectItemElement MergeWithExistingItemsWithNoCondition(ProjectItemElement item, ProjectItemGroupElement destinationItemGroup)
{
// This logic only applies to items being placed into a condition
if (!item.ConditionChain().Any() && !destinationItemGroup.ConditionChain().Any())
{
return item;
}
var existingItemsWithNoCondition =
FindExistingItemsWithNoCondition(item, destinationItemGroup.ContainingProject, destinationItemGroup);
MigrationTrace.Instance.WriteLine($"{nameof(ItemTransformApplicator)}: Merging Item with {existingItemsWithNoCondition.Count()} existing items with a different condition chain.");
// Handle the item being placed inside of a condition, when it is overlapping with a conditionless item
// If it is not definining new metadata or excludes, the conditioned item can be merged with the
// conditionless item
foreach (var existingItem in existingItemsWithNoCondition)
{
var encompassedIncludes = existingItem.GetEncompassedIncludes(item);
if (encompassedIncludes.Any())
{
MigrationTrace.Instance.WriteLine($"{nameof(ItemTransformApplicator)}: encompassed includes {string.Join(", ", encompassedIncludes)}");
item.RemoveIncludes(encompassedIncludes);
if (!item.Includes().Any())
{
MigrationTrace.Instance.WriteLine($"{nameof(ItemTransformApplicator)}: Ignoring Item {{ ItemType: {existingItem.ItemType}, Condition: {existingItem.Condition}, Include: {existingItem.Include}, Exclude: {existingItem.Exclude} }}");
return null;
}
}
}
// If we haven't returned, and there are existing items with a separate condition, we need to
// overwrite with those items inside the destinationItemGroup by using a Remove
if (existingItemsWithNoCondition.Any())
{
// Merge with the first remove if possible
var existingRemoveItem = destinationItemGroup.Items
.Where(i =>
string.IsNullOrEmpty(i.Include)
&& string.IsNullOrEmpty(i.Exclude)
&& !string.IsNullOrEmpty(i.Remove))
.FirstOrDefault();
if (existingRemoveItem != null)
{
existingRemoveItem.Remove += ";" + item.Include;
}
else
{
var clearPreviousItem = _projectElementGenerator.CreateItemElement(item.ItemType);
clearPreviousItem.Remove = item.Include;
AddItemToItemGroup(clearPreviousItem, destinationItemGroup);
}
}
return item;
}
private ProjectItemElement MergeWithExistingItemsWithSameCondition(ProjectItemElement item, ProjectItemGroupElement destinationItemGroup)
{
var existingItemsWithSameCondition =
FindExistingItemsWithSameCondition(item, destinationItemGroup.ContainingProject, destinationItemGroup);
MigrationTrace.Instance.WriteLine($"{nameof(TransformApplicator)}: Merging Item with {existingItemsWithSameCondition.Count()} existing items with the same condition chain.");
foreach (var existingItem in existingItemsWithSameCondition)
{
var mergeResult = MergeItems(item, existingItem);
item = mergeResult.InputItem;
// Existing Item is null when it's entire set of includes has been merged with the MergeItem
if (mergeResult.ExistingItem == null)
{
existingItem.Parent.RemoveChild(existingItem);
}
MigrationTrace.Instance.WriteLine($"{nameof(TransformApplicator)}: Adding Merged Item {{ ItemType: {mergeResult.MergedItem.ItemType}, Condition: {mergeResult.MergedItem.Condition}, Include: {mergeResult.MergedItem.Include}, Exclude: {mergeResult.MergedItem.Exclude} }}");
AddItemToItemGroup(mergeResult.MergedItem, destinationItemGroup);
}
return item;
}
/// <summary>
/// Merges two items on their common sets of includes.
/// The output is 3 items, the 2 input items and the merged items. If the common
/// set of includes spans the entirety of the includes of either of the 2 input
/// items, that item will be returned as null.
///
/// The 3rd output item, the merged item, will have the Union of the excludes and
/// metadata from the 2 input items. If any metadata between the 2 input items is different,
/// this will throw.
///
/// This function will mutate the Include property of the 2 input items, removing the common subset.
/// </summary>
private MergeResult MergeItems(ProjectItemElement item, ProjectItemElement existingItem)
{
if (!string.Equals(item.ItemType, existingItem.ItemType, StringComparison.Ordinal))
{
throw new InvalidOperationException("Cannot merge items of different types.");
}
if (!item.IntersectIncludes(existingItem).Any())
{
throw new InvalidOperationException("Cannot merge items without a common include.");
}
var commonIncludes = item.IntersectIncludes(existingItem).ToList();
var mergedItem = _projectElementGenerator.AddItem(item.ItemType, string.Join(";", commonIncludes));
mergedItem.UnionExcludes(existingItem.Excludes());
mergedItem.UnionExcludes(item.Excludes());
mergedItem.AddMetadata(MergeMetadata(existingItem.Metadata, item.Metadata));
item.RemoveIncludes(commonIncludes);
existingItem.RemoveIncludes(commonIncludes);
var mergeResult = new MergeResult
{
InputItem = string.IsNullOrEmpty(item.Include) ? null : item,
ExistingItem = string.IsNullOrEmpty(existingItem.Include) ? null : existingItem,
MergedItem = mergedItem
};
return mergeResult;
}
private ICollection<ProjectMetadataElement> MergeMetadata(
ICollection<ProjectMetadataElement> existingMetadataElements,
ICollection<ProjectMetadataElement> newMetadataElements)
{
var mergedMetadata = new List<ProjectMetadataElement>(existingMetadataElements);
foreach (var newMetadata in newMetadataElements)
{
var existingMetadata = mergedMetadata.FirstOrDefault(m =>
m.Name.Equals(newMetadata.Name, StringComparison.OrdinalIgnoreCase));
if (existingMetadata == null)
{
mergedMetadata.Add(newMetadata);
}
else
{
MergeMetadata(existingMetadata, newMetadata);
}
}
return mergedMetadata;
}
public void MergeMetadata(ProjectMetadataElement existingMetadata, ProjectMetadataElement newMetadata)
{
if (existingMetadata.Value != newMetadata.Value)
{
existingMetadata.Value = string.Join(";", new [] { existingMetadata.Value, newMetadata.Value });
}
}
private IEnumerable<ProjectItemElement> FindExistingItemsWithSameCondition(
ProjectItemElement item,
ProjectRootElement project,
ProjectElementContainer destinationContainer)
{
return project.Items
.Where(i => i.Condition == item.Condition)
.Where(i => i.Parent.ConditionChainsAreEquivalent(destinationContainer))
.Where(i => i.ItemType == item.ItemType)
.Where(i => i.IntersectIncludes(item).Any());
}
private IEnumerable<ProjectItemElement> FindExistingItemsWithNoCondition(
ProjectItemElement item,
ProjectRootElement project,
ProjectElementContainer destinationContainer)
{
return project.Items
.Where(i => !i.ConditionChain().Any())
.Where(i => i.ItemType == item.ItemType)
.Where(i => i.IntersectIncludes(item).Any());
}
private IEnumerable<ProjectItemElement> FindExistingItemsWithACondition(
ProjectItemElement item,
ProjectRootElement project,
ProjectElementContainer destinationContainer)
{
return project.Items
.Where(i => i.ConditionChain().Any())
.Where(i => i.ItemType == item.ItemType)
.Where(i => i.IntersectIncludes(item).Any());
}
private class MergeResult
{
public ProjectItemElement InputItem { get; set; }
public ProjectItemElement ExistingItem { get; set; }
public ProjectItemElement MergedItem { get; set; }
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Sql.Auditing.Model;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Storage;
using Microsoft.WindowsAzure.Management.Storage;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Azure.Commands.Sql.Common
{
/// <summary>
/// This class is responsible for all the REST communication with the management libraries
/// </summary>
public class AzureEndpointsCommunicator
{
/// <summary>
/// The storage management client used by this communicator
/// </summary>
private static Microsoft.Azure.Management.Storage.StorageManagementClient StorageV2Client { get; set; }
/// <summary>
/// Gets or sets the Azure subscription
/// </summary>
private static IAzureSubscription Subscription { get; set; }
/// <summary>
/// The resources management client used by this communicator
/// </summary>
private static ResourceManagementClient ResourcesClient { get; set; }
/// <summary>
/// Gets or sets the Azure profile
/// </summary>
public IAzureContext Context { get; set; }
/// <summary>
/// Default Constructor.
/// </summary>
/// <param name="context">The Azure context</param>
public AzureEndpointsCommunicator(IAzureContext context)
{
Context = context;
if (context.Subscription != Subscription)
{
Subscription = context.Subscription;
ResourcesClient = null;
StorageV2Client = null;
}
}
private static class StorageAccountType
{
public const string ClassicStorage = "Microsoft.ClassicStorage/storageAccounts";
public const string Storage = "Microsoft.Storage/storageAccounts";
}
/// <summary>
/// Provides the storage keys for the storage account within the given resource group
/// </summary>
/// <returns>A dictionary with two entries, one for each possible key type with the appropriate key</returns>
public async Task<Dictionary<StorageKeyKind, string>> GetStorageKeysAsync(string resourceGroupName, string storageAccountName)
{
Management.Storage.StorageManagementClient client = GetCurrentStorageV2Client(Context);
string url = Context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager).ToString();
if (!url.EndsWith("/"))
{
url = url + "/";
}
url = url + "subscriptions/" + (client.Credentials.SubscriptionId != null ? client.Credentials.SubscriptionId.Trim() : "");
url = url + "/resourceGroups/" + resourceGroupName;
url = url + "/providers/Microsoft.ClassicStorage/storageAccounts/" + storageAccountName;
url = url + "/listKeys?api-version=2014-06-01";
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
await client.Credentials.ProcessHttpRequestAsync(httpRequest, CancellationToken.None).ConfigureAwait(false);
HttpResponseMessage httpResponse = await client.HttpClient.SendAsync(httpRequest, CancellationToken.None).ConfigureAwait(false);
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Dictionary<StorageKeyKind, string> result = new Dictionary<StorageKeyKind, string>();
try
{
JToken responseDoc = JToken.Parse(responseContent);
string primaryKey = (string)responseDoc["primaryKey"];
string secondaryKey = (string)responseDoc["secondaryKey"];
if (string.IsNullOrEmpty(primaryKey) || string.IsNullOrEmpty(secondaryKey))
throw new Exception(); // this is caught by the synced wrapper
result.Add(StorageKeyKind.Primary, primaryKey);
result.Add(StorageKeyKind.Secondary, secondaryKey);
return result;
}
catch
{
return GetV2Keys(resourceGroupName, storageAccountName);
}
}
private Dictionary<StorageKeyKind, string> GetV2Keys(string resourceGroupName, string storageAccountName)
{
Microsoft.Azure.Management.Storage.StorageManagementClient storageClient = GetCurrentStorageV2Client(Context);
var r = storageClient.StorageAccounts.ListKeys(resourceGroupName, storageAccountName);
string k1 = r.StorageAccountKeys.Key1;
string k2 = r.StorageAccountKeys.Key2;
Dictionary<StorageKeyKind, String> result = new Dictionary<StorageKeyKind, String>();
result.Add(StorageKeyKind.Primary, k1);
result.Add(StorageKeyKind.Secondary, k2);
return result;
}
/// <summary>
/// Gets the storage keys for the given storage account.
/// </summary>
public Dictionary<StorageKeyKind, string> GetStorageKeys(string resourceGroupName, string storageAccountName)
{
try
{
return this.GetStorageKeysAsync(resourceGroupName, storageAccountName).GetAwaiter().GetResult();
}
catch (Exception e)
{
throw new Exception(string.Format(Properties.Resources.StorageAccountNotFound, storageAccountName), e);
}
}
/// <summary>
/// Returns the resource group of the provided storage account
/// </summary>
public string GetStorageResourceGroup(string storageAccountName)
{
ResourceManagementClient resourcesClient = GetCurrentResourcesClient(Context);
foreach (string storageAccountType in new[] { StorageAccountType.ClassicStorage, StorageAccountType.Storage })
{
string resourceGroup = GetStorageResourceGroup(
resourcesClient,
storageAccountName,
storageAccountType);
if (resourceGroup != null)
{
return resourceGroup;
}
}
throw new Exception(string.Format(Properties.Resources.StorageAccountNotFound, storageAccountName));
}
private string GetStorageResourceGroup(
ResourceManagementClient resourcesClient,
string storageAccountName,
string resourceType)
{
ResourceListResult res = resourcesClient.Resources.List(new ResourceListParameters
{
ResourceGroupName = null,
ResourceType = resourceType,
TagName = null,
TagValue = null
});
var allResources = new List<GenericResourceExtended>(res.Resources);
GenericResourceExtended account = allResources.Find(r => r.Name == storageAccountName);
if (account != null)
{
string resId = account.Id;
string[] segments = resId.Split('/');
int indexOfResoureGroup = new List<string>(segments).IndexOf("resourceGroups") + 1;
return segments[indexOfResoureGroup];
}
else
{
return null;
}
}
public Dictionary<StorageKeyKind, string> GetStorageKeys(string storageName)
{
var resourceGroup = GetStorageResourceGroup(storageName);
return GetStorageKeys(resourceGroup, storageName);
}
/// <summary>
/// Lazy creation of a single instance of a storage client
/// </summary>
private Microsoft.Azure.Management.Storage.StorageManagementClient GetCurrentStorageV2Client(IAzureContext context)
{
if (StorageV2Client == null)
{
StorageV2Client = AzureSession.Instance.ClientFactory.CreateClient<Microsoft.Azure.Management.Storage.StorageManagementClient>(Context, AzureEnvironment.Endpoint.ResourceManager);
}
return StorageV2Client;
}
/// <summary>
/// Lazy creation of a single instance of a resoures client
/// </summary>
private ResourceManagementClient GetCurrentResourcesClient(IAzureContext context)
{
if (ResourcesClient == null)
{
ResourcesClient = AzureSession.Instance.ClientFactory.CreateClient<ResourceManagementClient>(Context, AzureEnvironment.Endpoint.ResourceManager);
}
return ResourcesClient;
}
}
}
| |
//
// System.Xml.XmlReaderCommonTests
//
// Authors:
// Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
//
// (C) 2003 Atsushi Enomoto
// Note: Most of testcases are moved from XmlTextReaderTests.cs and
// XmlNodeReaderTests.cs.
//
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using NUnit.Framework;
namespace MonoTests.System.Xml
{
[TestFixture]
public class XmlReaderTests : Assertion
{
[SetUp]
public void GetReady ()
{
document = new XmlDocument ();
document.LoadXml (xml1);
}
XmlDocument document;
const string xml1 = "<root attr1='value1'><child /></root>";
const string xml2 = "<root><foo/><bar>test.</bar></root>";
const string xml3 = "<root> test of <b>mixed</b> string.<![CDATA[ cdata string.]]></root>";
const string xml4 = "<root>test of <b>mixed</b> string.</root>";
XmlTextReader xtr;
XmlNodeReader xnr;
// copy from XmlTextReaderTests
private void AssertStartDocument (XmlReader xmlReader)
{
Assert (xmlReader.ReadState == ReadState.Initial);
Assert (xmlReader.NodeType == XmlNodeType.None);
Assert (xmlReader.Depth == 0);
Assert (!xmlReader.EOF);
}
private void AssertNode (
XmlReader xmlReader,
XmlNodeType nodeType,
int depth,
bool isEmptyElement,
string name,
string prefix,
string localName,
string namespaceURI,
string value,
int attributeCount)
{
Assert ("Read() return value", xmlReader.Read ());
Assert ("ReadState", xmlReader.ReadState == ReadState.Interactive);
Assert ("!EOF", !xmlReader.EOF);
AssertNodeValues ("", xmlReader, nodeType, depth,
isEmptyElement, name, prefix, localName,
namespaceURI, value, value != String.Empty,
attributeCount, attributeCount > 0);
}
private void AssertNodeValues (
string label,
XmlReader xmlReader,
XmlNodeType nodeType,
int depth,
bool isEmptyElement,
string name,
string prefix,
string localName,
string namespaceURI,
string value,
int attributeCount)
{
AssertNodeValues (label, xmlReader, nodeType, depth,
isEmptyElement, name, prefix, localName,
namespaceURI, value, value != String.Empty,
attributeCount, attributeCount > 0);
}
private void AssertNodeValues (
string label,
XmlReader xmlReader,
XmlNodeType nodeType,
int depth,
bool isEmptyElement,
string name,
string prefix,
string localName,
string namespaceURI,
string value,
bool hasValue,
int attributeCount,
bool hasAttributes)
{
label = String.Concat (label, "(", xmlReader.GetType ().Name, ")");
AssertEquals (label + ": NodeType", nodeType, xmlReader.NodeType);
AssertEquals (label + ": IsEmptyElement", isEmptyElement, xmlReader.IsEmptyElement);
AssertEquals (label + ": name", name, xmlReader.Name);
AssertEquals (label + ": prefix", prefix, xmlReader.Prefix);
AssertEquals (label + ": localName", localName, xmlReader.LocalName);
AssertEquals (label + ": namespaceURI", namespaceURI, xmlReader.NamespaceURI);
AssertEquals (label + ": Depth", depth, xmlReader.Depth);
AssertEquals (label + ": hasValue", hasValue, xmlReader.HasValue);
AssertEquals (label + ": Value", value, xmlReader.Value);
AssertEquals (label + ": hasAttributes", hasAttributes, xmlReader.HasAttributes);
AssertEquals (label + ": attributeCount", attributeCount, xmlReader.AttributeCount);
}
private void AssertAttribute (
XmlReader xmlReader,
string name,
string prefix,
string localName,
string namespaceURI,
string value)
{
AssertEquals ("value", value, xmlReader [name]);
Assert (xmlReader.GetAttribute (name) == value);
if (namespaceURI != String.Empty) {
Assert (xmlReader[localName, namespaceURI] == value);
Assert (xmlReader.GetAttribute (localName, namespaceURI) == value);
}
}
private void AssertEndDocument (XmlReader xmlReader)
{
Assert ("could read", !xmlReader.Read ());
AssertEquals ("NodeType is not XmlNodeType.None", XmlNodeType.None, xmlReader.NodeType);
AssertEquals ("Depth is not 0", 0, xmlReader.Depth);
AssertEquals ("ReadState is not ReadState.EndOfFile", ReadState.EndOfFile, xmlReader.ReadState);
Assert ("not EOF", xmlReader.EOF);
xmlReader.Close ();
AssertEquals ("ReadState is not ReadState.Cosed", ReadState.Closed, xmlReader.ReadState);
}
private delegate void TestMethod (XmlReader reader);
private void RunTest (string xml, TestMethod method)
{
xtr = new XmlTextReader (new StringReader (xml));
method (xtr);
// DTD validation
xtr = new XmlTextReader (new StringReader (xml));
XmlValidatingReader xvr = new XmlValidatingReader (xtr);
xvr.ValidationType = ValidationType.DTD;
xvr.EntityHandling = EntityHandling.ExpandCharEntities;
method (xvr);
// XSD validation
xtr = new XmlTextReader (new StringReader (xml));
xvr = new XmlValidatingReader (xtr);
xvr.EntityHandling = EntityHandling.ExpandCharEntities;
method (xvr);
document.XmlResolver = null;
document.LoadXml (xml);
xnr = new XmlNodeReader (document);
method (xnr);
#if NET_2_0
/*
// XPathNavigatorReader tests
System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument (new StringReader (xml));
XmlReader xpr = doc.CreateNavigator ().ReadSubtree ();
method (xpr);
*/
#endif
}
[Test]
public void InitialState ()
{
RunTest (xml1, new TestMethod (InitialState));
}
private void InitialState (XmlReader reader)
{
AssertEquals ("Depth", 0, reader.Depth);
AssertEquals ("EOF", false, reader.EOF);
AssertEquals ("HasValue", false, reader.HasValue);
AssertEquals ("IsEmptyElement", false, reader.IsEmptyElement);
AssertEquals ("LocalName", String.Empty, reader.LocalName);
AssertEquals ("NodeType", XmlNodeType.None, reader.NodeType);
AssertEquals ("ReadState", ReadState.Initial, reader.ReadState);
}
[Test]
public void Read ()
{
RunTest (xml1, new TestMethod (Read));
}
public void Read (XmlReader reader)
{
reader.Read ();
AssertEquals ("<root>.NodeType", XmlNodeType.Element, reader.NodeType);
AssertEquals ("<root>.Name", "root", reader.Name);
AssertEquals ("<root>.ReadState", ReadState.Interactive, reader.ReadState);
AssertEquals ("<root>.Depth", 0, reader.Depth);
// move to 'child'
reader.Read ();
AssertEquals ("<child/>.Depth", 1, reader.Depth);
AssertEquals ("<child/>.NodeType", XmlNodeType.Element, reader.NodeType);
AssertEquals ("<child/>.Name", "child", reader.Name);
reader.Read ();
AssertEquals ("</root>.Depth", 0, reader.Depth);
AssertEquals ("</root>.NodeType", XmlNodeType.EndElement, reader.NodeType);
AssertEquals ("</root>.Name", "root", reader.Name);
reader.Read ();
AssertEquals ("end.EOF", true, reader.EOF);
AssertEquals ("end.NodeType", XmlNodeType.None, reader.NodeType);
}
[Test]
[Category ("NotDotNet")]
public void ReadAttributeValue ()
{
RunTest ("<root attr=''/>", new TestMethod (ReadAttributeValue));
}
public void ReadAttributeValue (XmlReader reader)
{
reader.Read (); // root
Assert (reader.MoveToFirstAttribute ());
// It looks like that MS.NET shows AttributeCount and
// HasAttributes as the same as element node!
this.AssertNodeValues ("#1",
reader, XmlNodeType.Attribute,
1, false, "attr", "", "attr", "", "", true, 1, true);
Assert (reader.ReadAttributeValue ());
// MS.NET XmlTextReader fails. Its Prefix returns
// null instead of "". It is fixed in MS.NET 2.0.
this.AssertNodeValues ("#2",
reader, XmlNodeType.Text,
2, false, "", "", "", "", "", true, 1, true);
Assert (reader.MoveToElement ());
this.AssertNodeValues ("#3",
reader, XmlNodeType.Element,
0, true, "root", "", "root", "", "", false, 1, true);
}
[Test]
public void ReadEmptyElement ()
{
RunTest (xml2, new TestMethod (ReadEmptyElement));
}
public void ReadEmptyElement (XmlReader reader)
{
reader.Read (); // root
AssertEquals (false, reader.IsEmptyElement);
reader.Read (); // foo
AssertEquals ("foo", reader.Name);
AssertEquals (true, reader.IsEmptyElement);
reader.Read (); // bar
AssertEquals ("bar", reader.Name);
AssertEquals (false, reader.IsEmptyElement);
}
[Test]
public void ReadStringFromElement ()
{
RunTest (xml3, new TestMethod (ReadStringFromElement));
}
public void ReadStringFromElement (XmlReader reader)
{
// Note: ReadString() test works only when the reader is
// positioned at the container element.
// In case the reader is positioned at the first
// character node, XmlTextReader and XmlNodeReader works
// different!!
reader.Read ();
string s = reader.ReadString ();
AssertEquals ("readString.1.ret_val", " test of ", s);
AssertEquals ("readString.1.Name", "b", reader.Name);
s = reader.ReadString ();
AssertEquals ("readString.2.ret_val", "mixed", s);
AssertEquals ("readString.2.NodeType", XmlNodeType.EndElement, reader.NodeType);
s = reader.ReadString (); // never proceeds.
AssertEquals ("readString.3.ret_val", String.Empty, s);
AssertEquals ("readString.3.NodeType", XmlNodeType.EndElement, reader.NodeType);
reader.Read ();
AssertEquals ("readString.4.NodeType", XmlNodeType.Text, reader.NodeType);
AssertEquals ("readString.4.Value", " string.", reader.Value);
s = reader.ReadString (); // reads the same Text node.
AssertEquals ("readString.5.ret_val", " string. cdata string.", s);
AssertEquals ("readString.5.NodeType", XmlNodeType.EndElement, reader.NodeType);
}
[Test]
public void ReadInnerXml ()
{
const string xml = "<root><foo>test of <b>mixed</b> string.</foo><bar /></root>";
RunTest (xml, new TestMethod (ReadInnerXml));
}
public void ReadInnerXml (XmlReader reader)
{
reader.Read ();
reader.Read ();
AssertEquals ("initial.ReadState", ReadState.Interactive, reader.ReadState);
AssertEquals ("initial.EOF", false, reader.EOF);
AssertEquals ("initial.NodeType", XmlNodeType.Element, reader.NodeType);
string s = reader.ReadInnerXml ();
AssertEquals ("read_all", "test of <b>mixed</b> string.", s);
AssertEquals ("after.Name", "bar", reader.Name);
AssertEquals ("after.NodeType", XmlNodeType.Element, reader.NodeType);
}
[Test]
public void EmptyElement ()
{
RunTest ("<foo/>", new TestMethod (EmptyElement));
}
public void EmptyElement (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, // depth
true, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertEndDocument (xmlReader);
}
[Test]
public void NestedEmptyTag ()
{
string xml = "<foo><bar/></foo>";
RunTest (xml, new TestMethod (NestedEmptyTag));
}
public void NestedEmptyTag (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, //depth
false, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
1, //depth
true, // isEmptyElement
"bar", // name
String.Empty, // prefix
"bar", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.EndElement, // nodeType
0, //depth
false, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertEndDocument (xmlReader);
}
[Test]
public void NestedText ()
{
string xml = "<foo>bar</foo>";
RunTest (xml, new TestMethod (NestedText));
}
public void NestedText (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, //depth
false, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Text, // nodeType
1, //depth
false, // isEmptyElement
String.Empty, // name
String.Empty, // prefix
String.Empty, // localName
String.Empty, // namespaceURI
"bar", // value
0 // attributeCount
);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.EndElement, // nodeType
0, //depth
false, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertEndDocument (xmlReader);
}
[Test]
public void EmptyElementWithAttributes ()
{
string xml = @"<foo bar=""baz"" quux='quuux' x:foo='x-foo' xmlns:x = 'urn:xfoo' />";
RunTest (xml, new TestMethod (EmptyElementWithAttributes ));
}
public void EmptyElementWithAttributes (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, //depth
true, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
4 // attributeCount
);
AssertAttribute (
xmlReader, // xmlReader
"bar", // name
String.Empty, // prefix
"bar", // localName
String.Empty, // namespaceURI
"baz" // value
);
AssertAttribute (
xmlReader, // xmlReader
"quux", // name
String.Empty, // prefix
"quux", // localName
String.Empty, // namespaceURI
"quuux" // value
);
AssertAttribute (
xmlReader, // xmlReader
"notexist", // name
String.Empty, // prefix
"notexist", // localName
String.Empty, // namespaceURI
null // value
);
AssertAttribute (
xmlReader, // xmlReader
"x:foo", // name
"x", // prefix
"foo", // localName
"urn:xfoo", // namespaceURI
"x-foo" // value
);
AssertAttribute (
xmlReader, // xmlReader
"x:bar", // name
"x", // prefix
"bar", // localName
"urn:xfoo", // namespaceURI
null // value
);
AssertEndDocument (xmlReader);
}
[Test]
public void ProcessingInstructionBeforeDocumentElement ()
{
string xml = "<?foo bar?><baz/>";
RunTest (xml, new TestMethod (ProcessingInstructionBeforeDocumentElement));
}
public void ProcessingInstructionBeforeDocumentElement (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.ProcessingInstruction, // nodeType
0, //depth
false, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
"bar", // value
0 // attributeCount
);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, //depth
true, // isEmptyElement
"baz", // name
String.Empty, // prefix
"baz", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertEndDocument (xmlReader);
}
[Test]
public void CommentBeforeDocumentElement ()
{
string xml = "<!--foo--><bar/>";
RunTest (xml, new TestMethod (CommentBeforeDocumentElement));
}
public void CommentBeforeDocumentElement (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Comment, // nodeType
0, //depth
false, // isEmptyElement
String.Empty, // name
String.Empty, // prefix
String.Empty, // localName
String.Empty, // namespaceURI
"foo", // value
0 // attributeCount
);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, //depth
true, // isEmptyElement
"bar", // name
String.Empty, // prefix
"bar", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertEndDocument (xmlReader);
}
[Test]
public void PredefinedEntities ()
{
string xml = "<foo><>&'"</foo>";
RunTest (xml, new TestMethod (PredefinedEntities));
}
public void PredefinedEntities (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, //depth
false, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Text, // nodeType
1, //depth
false, // isEmptyElement
String.Empty, // name
String.Empty, // prefix
String.Empty, // localName
String.Empty, // namespaceURI
"<>&'\"", // value
0 // attributeCount
);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.EndElement, // nodeType
0, //depth
false, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertEndDocument (xmlReader);
}
[Test]
public void CharacterReferences ()
{
string xml = "<foo>FOO</foo>";
RunTest (xml, new TestMethod (CharacterReferences));
}
public void CharacterReferences (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, //depth
false, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Text, // nodeType
1, //depth
false, // isEmptyElement
String.Empty, // name
String.Empty, // prefix
String.Empty, // localName
String.Empty, // namespaceURI
"FOO", // value
0 // attributeCount
);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.EndElement, // nodeType
0, //depth
false, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertEndDocument (xmlReader);
}
[Test]
public void PredefinedEntitiesInAttribute ()
{
string xml = "<foo bar='<>&'"'/>";
RunTest (xml, new TestMethod (PredefinedEntitiesInAttribute ));
}
public void PredefinedEntitiesInAttribute (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, //depth
true, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
1 // attributeCount
);
AssertAttribute (
xmlReader, // xmlReader
"bar", // name
String.Empty, // prefix
"bar", // localName
String.Empty, // namespaceURI
"<>&'\"" // value
);
AssertEndDocument (xmlReader);
}
[Test]
public void CharacterReferencesInAttribute ()
{
string xml = "<foo bar='FOO'/>";
RunTest (xml, new TestMethod (CharacterReferencesInAttribute));
}
public void CharacterReferencesInAttribute (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, //depth
true, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
1 // attributeCount
);
AssertAttribute (
xmlReader, // xmlReader
"bar", // name
String.Empty, // prefix
"bar", // localName
String.Empty, // namespaceURI
"FOO" // value
);
AssertEndDocument (xmlReader);
}
[Test]
public void CDATA ()
{
string xml = "<foo><![CDATA[<>&]]></foo>";
RunTest (xml, new TestMethod (CDATA));
}
public void CDATA (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, //depth
false, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.CDATA, // nodeType
1, //depth
false, // isEmptyElement
String.Empty, // name
String.Empty, // prefix
String.Empty, // localName
String.Empty, // namespaceURI
"<>&", // value
0 // attributeCount
);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.EndElement, // nodeType
0, //depth
false, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertEndDocument (xmlReader);
}
[Test]
public void EmptyElementInDefaultNamespace ()
{
string xml = @"<foo xmlns='http://foo/' />";
RunTest (xml, new TestMethod (EmptyElementInDefaultNamespace));
}
public void EmptyElementInDefaultNamespace (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, // depth
true, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
"http://foo/", // namespaceURI
String.Empty, // value
1 // attributeCount
);
AssertAttribute (
xmlReader, // xmlReader
"xmlns", // name
String.Empty, // prefix
"xmlns", // localName
"http://www.w3.org/2000/xmlns/", // namespaceURI
"http://foo/" // value
);
AssertEquals ("http://foo/", xmlReader.LookupNamespace (String.Empty));
AssertEndDocument (xmlReader);
}
[Test]
public void ChildElementInNamespace ()
{
string xml = @"<foo:bar xmlns:foo='http://foo/'><baz:quux xmlns:baz='http://baz/' /></foo:bar>";
RunTest (xml, new TestMethod (ChildElementInNamespace));
}
public void ChildElementInNamespace (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, // depth
false, // isEmptyElement
"foo:bar", // name
"foo", // prefix
"bar", // localName
"http://foo/", // namespaceURI
String.Empty, // value
1 // attributeCount
);
AssertAttribute (
xmlReader, // xmlReader
"xmlns:foo", // name
"xmlns", // prefix
"foo", // localName
"http://www.w3.org/2000/xmlns/", // namespaceURI
"http://foo/" // value
);
AssertEquals ("http://foo/", xmlReader.LookupNamespace ("foo"));
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
1, // depth
true, // isEmptyElement
"baz:quux", // name
"baz", // prefix
"quux", // localName
"http://baz/", // namespaceURI
String.Empty, // value
1 // attributeCount
);
AssertAttribute (
xmlReader, // xmlReader
"xmlns:baz", // name
"xmlns", // prefix
"baz", // localName
"http://www.w3.org/2000/xmlns/", // namespaceURI
"http://baz/" // value
);
AssertEquals ("http://foo/", xmlReader.LookupNamespace ("foo"));
AssertEquals ("http://baz/", xmlReader.LookupNamespace ("baz"));
AssertNode (
xmlReader, // xmlReader
XmlNodeType.EndElement, // nodeType
0, // depth
false, // isEmptyElement
"foo:bar", // name
"foo", // prefix
"bar", // localName
"http://foo/", // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertEquals ("http://foo/", xmlReader.LookupNamespace ("foo"));
AssertNull (xmlReader.LookupNamespace ("baz"));
AssertEndDocument (xmlReader);
}
[Test]
public void ChildElementInDefaultNamespace ()
{
string xml = @"<foo:bar xmlns:foo='http://foo/'><baz xmlns='http://baz/' /></foo:bar>";
RunTest (xml, new TestMethod (ChildElementInDefaultNamespace));
}
public void ChildElementInDefaultNamespace (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, // depth
false, // isEmptyElement
"foo:bar", // name
"foo", // prefix
"bar", // localName
"http://foo/", // namespaceURI
String.Empty, // value
1 // attributeCount
);
AssertAttribute (
xmlReader, // xmlReader
"xmlns:foo", // name
"xmlns", // prefix
"foo", // localName
"http://www.w3.org/2000/xmlns/", // namespaceURI
"http://foo/" // value
);
AssertEquals ("http://foo/", xmlReader.LookupNamespace ("foo"));
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
1, // depth
true, // isEmptyElement
"baz", // name
String.Empty, // prefix
"baz", // localName
"http://baz/", // namespaceURI
String.Empty, // value
1 // attributeCount
);
AssertAttribute (
xmlReader, // xmlReader
"xmlns", // name
String.Empty, // prefix
"xmlns", // localName
"http://www.w3.org/2000/xmlns/", // namespaceURI
"http://baz/" // value
);
AssertEquals ("http://foo/", xmlReader.LookupNamespace ("foo"));
AssertEquals ("http://baz/", xmlReader.LookupNamespace (String.Empty));
AssertNode (
xmlReader, // xmlReader
XmlNodeType.EndElement, // nodeType
0, // depth
false, // isEmptyElement
"foo:bar", // name
"foo", // prefix
"bar", // localName
"http://foo/", // namespaceURI
String.Empty, // value
0 // attributeCount
);
AssertEquals ("http://foo/", xmlReader.LookupNamespace ("foo"));
AssertEndDocument (xmlReader);
}
[Test]
public void AttributeInNamespace ()
{
string xml = @"<foo bar:baz='quux' xmlns:bar='http://bar/' />";
RunTest (xml, new TestMethod (AttributeInNamespace));
}
public void AttributeInNamespace (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, // depth
true, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
2 // attributeCount
);
AssertAttribute (
xmlReader, // xmlReader
"bar:baz", // name
"bar", // prefix
"baz", // localName
"http://bar/", // namespaceURI
"quux" // value
);
AssertAttribute (
xmlReader, // xmlReader
"xmlns:bar", // name
"xmlns", // prefix
"bar", // localName
"http://www.w3.org/2000/xmlns/", // namespaceURI
"http://bar/" // value
);
AssertEquals ("http://bar/", xmlReader.LookupNamespace ("bar"));
AssertEndDocument (xmlReader);
}
[Test]
public void MoveToElementFromAttribute ()
{
string xml = @"<foo bar=""baz"" />";
RunTest (xml, new TestMethod (MoveToElementFromAttribute));
}
public void MoveToElementFromAttribute (XmlReader xmlReader)
{
Assert (xmlReader.Read ());
AssertEquals (XmlNodeType.Element, xmlReader.NodeType);
Assert (xmlReader.MoveToFirstAttribute ());
AssertEquals (XmlNodeType.Attribute, xmlReader.NodeType);
Assert (xmlReader.MoveToElement ());
AssertEquals (XmlNodeType.Element, xmlReader.NodeType);
}
[Test]
public void MoveToElementFromElement ()
{
string xml = @"<foo bar=""baz"" />";
RunTest (xml, new TestMethod (MoveToElementFromElement));
}
public void MoveToElementFromElement (XmlReader xmlReader)
{
Assert (xmlReader.Read ());
AssertEquals (XmlNodeType.Element, xmlReader.NodeType);
Assert (!xmlReader.MoveToElement ());
AssertEquals (XmlNodeType.Element, xmlReader.NodeType);
}
[Test]
public void MoveToFirstAttributeWithNoAttributes ()
{
string xml = @"<foo />";
RunTest (xml, new TestMethod (MoveToFirstAttributeWithNoAttributes));
}
public void MoveToFirstAttributeWithNoAttributes (XmlReader xmlReader)
{
Assert (xmlReader.Read ());
AssertEquals (XmlNodeType.Element, xmlReader.NodeType);
Assert (!xmlReader.MoveToFirstAttribute ());
AssertEquals (XmlNodeType.Element, xmlReader.NodeType);
}
[Test]
public void MoveToNextAttributeWithNoAttributes ()
{
string xml = @"<foo />";
RunTest (xml, new TestMethod (MoveToNextAttributeWithNoAttributes));
}
public void MoveToNextAttributeWithNoAttributes (XmlReader xmlReader)
{
Assert (xmlReader.Read ());
AssertEquals (XmlNodeType.Element, xmlReader.NodeType);
Assert (!xmlReader.MoveToNextAttribute ());
AssertEquals (XmlNodeType.Element, xmlReader.NodeType);
}
[Test]
public void MoveToNextAttribute()
{
string xml = @"<foo bar=""baz"" quux='quuux'/>";
RunTest (xml, new TestMethod (MoveToNextAttribute));
}
public void MoveToNextAttribute (XmlReader xmlReader)
{
AssertStartDocument (xmlReader);
AssertNode (
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, //depth
true, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
2 // attributeCount
);
AssertAttribute (
xmlReader, // xmlReader
"bar", // name
String.Empty, // prefix
"bar", // localName
String.Empty, // namespaceURI
"baz" // value
);
AssertAttribute (
xmlReader, // xmlReader
"quux", // name
String.Empty, // prefix
"quux", // localName
String.Empty, // namespaceURI
"quuux" // value
);
Assert (xmlReader.MoveToNextAttribute ());
AssertEquals ("bar", xmlReader.Name);
AssertEquals ("baz", xmlReader.Value);
Assert (xmlReader.MoveToNextAttribute ());
AssertEquals ("quux", xmlReader.Name);
AssertEquals ("quuux", xmlReader.Value);
Assert (!xmlReader.MoveToNextAttribute ());
Assert (xmlReader.MoveToElement ());
AssertNodeValues (
"#1",
xmlReader, // xmlReader
XmlNodeType.Element, // nodeType
0, //depth
true, // isEmptyElement
"foo", // name
String.Empty, // prefix
"foo", // localName
String.Empty, // namespaceURI
String.Empty, // value
2 // attributeCount
);
AssertEndDocument (xmlReader);
}
[Test]
// [Category ("NotDotNet")] // MS XmlNodeReader never moves to xml declaration.
[Ignore ("Too inconsistent reference implementations to determine which is correct behavior.")]
public void MoveToXmlDeclAttributes ()
{
string xml = "<?xml version=\"1.0\" standalone=\"yes\"?><root/>";
RunTest (xml, new TestMethod (MoveToXmlDeclAttributes));
}
public void MoveToXmlDeclAttributes (XmlReader xmlReader)
{
xmlReader.Read ();
this.AssertNodeValues ("#1", xmlReader,
XmlNodeType.XmlDeclaration,
0,
false,
"xml",
String.Empty,
"xml",
String.Empty,
"version=\"1.0\" standalone=\"yes\"",
2);
Assert ("MoveToFirstAttribute",
xmlReader.MoveToFirstAttribute ());
this.AssertNodeValues ("#2", xmlReader,
XmlNodeType.Attribute,
0, // FIXME: might be 1
false,
"version",
String.Empty,
"version",
String.Empty,
"1.0",
2);
xmlReader.ReadAttributeValue ();
this.AssertNodeValues ("#3", xmlReader,
XmlNodeType.Text,
1, // FIXME might be 2
false,
String.Empty,
null, // FIXME: should be String.Empty,
String.Empty,
null, // FIXME: should be String.Empty,
"1.0",
2);
xmlReader.MoveToNextAttribute ();
this.AssertNodeValues ("#4", xmlReader,
XmlNodeType.Attribute,
0, // FIXME: might be 1
false,
"standalone",
String.Empty,
"standalone",
String.Empty,
"yes",
2);
xmlReader.ReadAttributeValue ();
this.AssertNodeValues ("#5", xmlReader,
XmlNodeType.Text,
1, // FIXME: might be 2
false,
String.Empty,
null, // FIXME: should be String.Empty,
String.Empty,
null, // FIXME: should be String.Empty,
"yes",
2);
}
[Test]
public void AttributeOrder ()
{
string xml = @"<foo _1='1' _2='2' _3='3' />";
RunTest (xml, new TestMethod (AttributeOrder));
}
public void AttributeOrder (XmlReader xmlReader)
{
Assert (xmlReader.Read ());
AssertEquals (XmlNodeType.Element, xmlReader.NodeType);
Assert (xmlReader.MoveToFirstAttribute ());
AssertEquals ("_1", xmlReader.Name);
Assert (xmlReader.MoveToNextAttribute ());
AssertEquals ("_2", xmlReader.Name);
Assert (xmlReader.MoveToNextAttribute ());
AssertEquals ("_3", xmlReader.Name);
Assert (!xmlReader.MoveToNextAttribute ());
}
[Test]
[Category ("NotDotNet")]
public void IndexerAndAttributes ()
{
string xml = @"<?xml version='1.0' standalone='no'?><foo _1='1' _2='2' _3='3' />";
RunTest (xml, new TestMethod (IndexerAndAttributes));
}
public void IndexerAndAttributes (XmlReader xmlReader)
{
Assert (xmlReader.Read ());
AssertEquals ("1.0", xmlReader ["version"]);
AssertEquals ("1.0", xmlReader.GetAttribute ("version"));
// .NET 1.1 BUG. XmlTextReader returns null, while XmlNodeReader returns "".
AssertEquals (null, xmlReader ["encoding"]);
AssertEquals (null, xmlReader.GetAttribute ("encoding"));
AssertEquals ("no", xmlReader ["standalone"]);
AssertEquals ("no", xmlReader.GetAttribute ("standalone"));
AssertEquals ("1.0", xmlReader [0]);
AssertEquals ("1.0", xmlReader.GetAttribute (0));
AssertEquals ("no", xmlReader [1]);
AssertEquals ("no", xmlReader.GetAttribute (1));
Assert (xmlReader.Read ());
AssertEquals (XmlNodeType.Element, xmlReader.NodeType);
AssertEquals ("1", xmlReader ["_1"]);
Assert (xmlReader.MoveToFirstAttribute ());
AssertEquals ("_1", xmlReader.Name);
AssertEquals ("1", xmlReader ["_1"]);
Assert (xmlReader.MoveToNextAttribute ());
AssertEquals ("_2", xmlReader.Name);
AssertEquals ("1", xmlReader ["_1"]);
Assert (xmlReader.MoveToNextAttribute ());
AssertEquals ("_3", xmlReader.Name);
AssertEquals ("1", xmlReader ["_1"]);
Assert (!xmlReader.MoveToNextAttribute ());
}
[Test]
public void ProhibitedMultipleAttributes ()
{
string xml = @"<foo _1='1' _1='1' />";
try {
RunTest (xml, new TestMethod (ReadAll));
} catch (XmlException) {
}
xml = @"<foo _1='1' _1='2' />";
try {
RunTest (xml, new TestMethod (ReadAll));
} catch (XmlException) {
}
}
public void ReadAll (XmlReader xmlReader)
{
while (!xmlReader.EOF)
xmlReader.Read ();
}
[Test]
public void SurrogatePairContent ()
{
string xml = "<root xmlns='𐄀'/>";
RunTest (xml, new TestMethod (SurrogatePairContent));
}
public void SurrogatePairContent (XmlReader xmlReader)
{
xmlReader.Read ();
AssertEquals (true, xmlReader.MoveToAttribute ("xmlns"));
AssertEquals ("xmlns", xmlReader.Name);
AssertEquals (2, xmlReader.Value.Length);
AssertEquals (0xD800, (int) xmlReader.Value [0]);
AssertEquals (0xDD00, (int) xmlReader.Value [1]);
}
[Test]
public void ReadOuterXmlOnEndElement ()
{
string xml = "<root><foo></foo></root>";
RunTest (xml, new TestMethod (ReadOuterXmlOnEndElement));
}
public void ReadOuterXmlOnEndElement (XmlReader xmlReader)
{
xmlReader.Read ();
xmlReader.Read ();
xmlReader.Read ();
AssertEquals (String.Empty, xmlReader.ReadOuterXml ());
}
[Test]
public void ReadInnerXmlOnEndElement ()
{
string xml = "<root><foo></foo></root>";
RunTest (xml, new TestMethod (ReadInnerXmlOnEndElement));
}
private void ReadInnerXmlOnEndElement (XmlReader xmlReader)
{
xmlReader.Read ();
xmlReader.Read ();
xmlReader.Read ();
AssertEquals (String.Empty, xmlReader.ReadInnerXml ());
}
}
}
| |
// Copyright (c) 2004-2012 Zenfolio, 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.
//
// Main application window.
//
using System;
using System.Globalization;
using System.Windows.Forms;
using Zenfolio.Examples.Browser.ZfApiRef;
namespace Zenfolio.Examples.Browser
{
/// <summary>
/// Main application window
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.ComponentModel.IContainer components;
private System.Windows.Forms.TreeView _tvGroups;
private System.Windows.Forms.ImageList _ilGroups;
private System.Windows.Forms.Splitter _splitter;
private AxSHDocVw.AxWebBrowser _axWebBrowser;
private ZenfolioClient _client;
/// <summary>
/// Tree node types enumeration
/// </summary>
public enum NodeType
{
Root = 0,
Group,
Gallery,
Collection,
Photo
}
/// <summary>
/// Constructor, initializes the object.
/// </summary>
public MainForm()
{
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(
bool disposing
)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
this._tvGroups = new System.Windows.Forms.TreeView();
this._ilGroups = new System.Windows.Forms.ImageList(this.components);
this._splitter = new System.Windows.Forms.Splitter();
this._axWebBrowser = new AxSHDocVw.AxWebBrowser();
((System.ComponentModel.ISupportInitialize)(this._axWebBrowser)).BeginInit();
this.SuspendLayout();
//
// _tvGroups
//
this._tvGroups.Dock = System.Windows.Forms.DockStyle.Left;
this._tvGroups.ImageList = this._ilGroups;
this._tvGroups.ItemHeight = 18;
this._tvGroups.Location = new System.Drawing.Point(0, 0);
this._tvGroups.Name = "_tvGroups";
this._tvGroups.Size = new System.Drawing.Size(180, 668);
this._tvGroups.TabIndex = 1;
this._tvGroups.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.OnGroupsSelect);
this._tvGroups.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.OnGroupsExpand);
//
// _ilGroups
//
this._ilGroups.ImageSize = new System.Drawing.Size(16, 16);
this._ilGroups.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("_ilGroups.ImageStream")));
this._ilGroups.TransparentColor = System.Drawing.Color.Transparent;
//
// _splitter
//
this._splitter.Location = new System.Drawing.Point(180, 0);
this._splitter.Name = "_splitter";
this._splitter.Size = new System.Drawing.Size(4, 668);
this._splitter.TabIndex = 2;
this._splitter.TabStop = false;
//
// _axWebBrowser
//
this._axWebBrowser.Dock = System.Windows.Forms.DockStyle.Fill;
this._axWebBrowser.Enabled = true;
this._axWebBrowser.Location = new System.Drawing.Point(184, 0);
this._axWebBrowser.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("_axWebBrowser.OcxState")));
this._axWebBrowser.Size = new System.Drawing.Size(843, 668);
this._axWebBrowser.TabIndex = 3;
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(1027, 668);
this.Controls.Add(this._axWebBrowser);
this.Controls.Add(this._splitter);
this.Controls.Add(this._tvGroups);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "MainForm";
this.Text = "Zenfolio Browser";
this.Load += new System.EventHandler(this.OnLoad);
((System.ComponentModel.ISupportInitialize)(this._axWebBrowser)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
try
{
Application.Run(new MainForm());
}
catch (Exception e)
{
MessageBoxOptions options = (MessageBoxOptions)0;
if (CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft)
{
options |= MessageBoxOptions.RightAlign |
MessageBoxOptions.RtlReading;
}
MessageBox.Show(e.ToString(), "Exception", MessageBoxButtons.OK,
MessageBoxIcon.Error, MessageBoxDefaultButton.Button1,
options);
}
}
/// <summary>
/// Occurs before a form is displayed for the first time.
/// Makes all necessary initializations.
/// </summary>
private void OnLoad(object sender, EventArgs e)
{
_client = new ZenfolioClient();
LoginDialog loginDialog = new LoginDialog();
// try to login in a loop until successfully logged in or
// cancelled by the user
bool loggedIn = false;
while (!loggedIn)
{
// ask for username and password
DialogResult res = loginDialog.ShowDialog(this);
// exit if the user doesn't want to enter credentials
if (res != DialogResult.OK)
{
Application.Exit();
return;
}
// try to login
loggedIn = _client.Login(loginDialog.UserName,
loginDialog.Password);
}
// load own profile
User user = _client.LoadPrivateProfile();
// load and wrap Groups hierarchy
Group rootGroup = _client.LoadGroupHierarchy(user.LoginName);
TreeNode rootNode = CreateGroupNode(rootGroup);
// fix-up the root node of the Group hierarchy
rootNode.ImageIndex = (int)NodeType.Root;
rootNode.SelectedImageIndex = rootNode.ImageIndex;
rootNode.Text = user.DisplayName;
_tvGroups.Nodes.Add(rootNode);
// initialize browser pane
_axWebBrowser.Navigate("about:blank");
_axWebBrowser.TheaterMode = true;
}
/// <summary>
/// Creates a TreeNode representing Group element.
/// </summary>
/// <param name="element">Group element to wrap.</param>
/// <returns>Constructed tree node.</returns>
private TreeNode CreateGroupNode(
GroupElement element
)
{
TreeNode ret = new TreeNode(element.Title);
ret.Tag = element;
Group group = element as Group;
PhotoSet photoSet = element as PhotoSet;
if (group != null)
{
ret.ImageIndex = (int)NodeType.Group;
foreach (GroupElement child in group.Elements)
ret.Nodes.Add(CreateGroupNode(child));
}
else if (photoSet != null)
{
ret.ImageIndex = photoSet.Type == PhotoSetType.Gallery
? (int)NodeType.Gallery
: (int)NodeType.Collection;
// photoSets contain photos which are not loaded yet; add
// a dummy node for lazy expansion
if (photoSet.PhotoCount > 0)
ret.Nodes.Add("_Dummy_");
}
ret.SelectedImageIndex = ret.ImageIndex;
return ret;
}
/// <summary>
/// Called when user tries to expand the tree node. Checks if this is a gallery node and
/// loads photos if they not loaded yet.
/// </summary>
private void OnGroupsExpand(object sender, TreeViewCancelEventArgs e)
{
NodeType nt = (NodeType)e.Node.ImageIndex;
if (nt == NodeType.Gallery || nt == NodeType.Collection)
{
PhotoSet ps = (PhotoSet)e.Node.Tag;
//Load photo set on demand
if (ps.Photos == null || ps.Photos.Length == 0)
{
// clear dummy nodes
e.Node.Nodes.Clear();
ps = _client.LoadPhotoSet(ps.Id, 0, true);
e.Node.Tag = ps;
// add nodes for each of the loaded photos
foreach (Photo p in ps.Photos)
{
string name = p.Title;
if (name==null || name.Length == 0) name = p.FileName;
TreeNode n = new TreeNode(name, (int)NodeType.Photo, (int)NodeType.Photo);
n.Tag = p;
e.Node.Nodes.Add(n);
}
}
}
}
/// <summary>
/// Called when user selects a tree node in the left pane. Checks if user selected a
/// node representing a photo. Displays photo in the browser pane if necessary.
/// </summary>
private void OnGroupsSelect(object sender, TreeViewEventArgs e)
{
// display the selected photo in the browser pane
NodeType nt = (NodeType)e.Node.ImageIndex;
if (nt == NodeType.Photo)
{
Photo p = (Photo)e.Node.Tag;
// construct large photo URL
string url = p.UrlHost + p.UrlCore + "-4.jpg"
+ "?sn=" + p.Sequence
+ "&tk=" + p.UrlToken;
// this gives access to protected photos
if (p.AccessDescriptor.AccessType != AccessType.Public)
url += "&token=" + _client.Token;
// make the browser load this image
_axWebBrowser.Navigate(url);
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace searchservice
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Indexers operations.
/// </summary>
public partial class Indexers : IServiceOperations<SearchandStorage>, IIndexers
{
/// <summary>
/// Initializes a new instance of the Indexers class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Indexers(SearchandStorage client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SearchandStorage
/// </summary>
public SearchandStorage Client { get; private set; }
/// <summary>
/// Resets the change tracking state associated with an Azure Search indexer.
/// <see href="https://msdn.microsoft.com/library/azure/dn946897.aspx" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to reset.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> ResetWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (indexerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "indexerName");
}
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("indexerName", indexerName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Reset", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexers('{indexerName}')/search.reset").ToString();
_url = _url.Replace("{indexerName}", System.Uri.EscapeDataString(indexerName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Runs an Azure Search indexer on-demand.
/// <see href="https://msdn.microsoft.com/library/azure/dn946885.aspx" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to run.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> RunWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (indexerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "indexerName");
}
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("indexerName", indexerName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Run", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexers('{indexerName}')/search.run").ToString();
_url = _url.Replace("{indexerName}", System.Uri.EscapeDataString(indexerName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates a new Azure Search indexer or updates an indexer if it already
/// exists.
/// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to create or update.
/// </param>
/// <param name='indexer'>
/// The definition of the indexer to create or update.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Indexer>> CreateOrUpdateWithHttpMessagesAsync(string indexerName, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (indexerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "indexerName");
}
if (indexer == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "indexer");
}
if (indexer != null)
{
indexer.Validate();
}
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("indexerName", indexerName);
tracingParameters.Add("indexer", indexer);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexers('{indexerName}')").ToString();
_url = _url.Replace("{indexerName}", System.Uri.EscapeDataString(indexerName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(indexer != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(indexer, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Indexer>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Indexer>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Indexer>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes an Azure Search indexer.
/// <see href="https://msdn.microsoft.com/library/azure/dn946898.aspx" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to delete.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (indexerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "indexerName");
}
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("indexerName", indexerName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexers('{indexerName}')").ToString();
_url = _url.Replace("{indexerName}", System.Uri.EscapeDataString(indexerName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 404 && (int)_statusCode != 204)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieves an indexer definition from Azure Search.
/// <see href="https://msdn.microsoft.com/library/azure/dn946874.aspx" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to retrieve.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Indexer>> GetWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (indexerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "indexerName");
}
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("indexerName", indexerName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexers('{indexerName}')").ToString();
_url = _url.Replace("{indexerName}", System.Uri.EscapeDataString(indexerName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Indexer>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Indexer>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all indexers available for an Azure Search service.
/// <see href="https://msdn.microsoft.com/library/azure/dn946883.aspx" />
/// </summary>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<IndexerListResult>> ListWithHttpMessagesAsync(SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexers").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IndexerListResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<IndexerListResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates a new Azure Search indexer.
/// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" />
/// </summary>
/// <param name='indexer'>
/// The definition of the indexer to create.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Indexer>> CreateWithHttpMessagesAsync(Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (indexer == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "indexer");
}
if (indexer != null)
{
indexer.Validate();
}
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("indexer", indexer);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexers").ToString();
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(indexer != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(indexer, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Indexer>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Indexer>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Returns the current status and execution history of an indexer.
/// <see href="https://msdn.microsoft.com/library/azure/dn946884.aspx" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer for which to retrieve status.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<IndexerExecutionInfo>> GetStatusWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (indexerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "indexerName");
}
string apiVersion = "2015-02-28";
System.Guid? clientRequestId = default(System.Guid?);
if (searchRequestOptions != null)
{
clientRequestId = searchRequestOptions.ClientRequestId;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("indexerName", indexerName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetStatus", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexers('{indexerName}')/search.status").ToString();
_url = _url.Replace("{indexerName}", System.Uri.EscapeDataString(indexerName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, Client.SerializationSettings).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<IndexerExecutionInfo>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<IndexerExecutionInfo>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using System.Text;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using Microsoft.Scripting.Runtime;
namespace IronPython.Runtime {
/// <summary>
/// StringFormatter provides Python's % style string formatting services.
/// </summary>
internal class StringFormatter {
private const int UnspecifiedPrecision = -1; // Use the default precision
private readonly CodeContext/*!*/ _context;
private readonly object? _data;
private int _dataIndex;
private readonly string _str;
private int _index;
private char _curCh;
// The options for formatting the current formatting specifier in the format string
private FormatSettings _opts;
// Should ddd.0 be displayed as "ddd" or "ddd.0". "'%g' % ddd.0" needs "ddd", but str(ddd.0) needs "ddd.0"
private bool _trailingZeroAfterWholeFloat;
private bool _asBytes;
private StringBuilder _buf;
// This is a ThreadStatic since so that formatting operations on one thread do not interfere with other threads
[ThreadStatic]
private static NumberFormatInfo? NumberFormatInfoForThreadLower;
[ThreadStatic]
private static NumberFormatInfo? NumberFormatInfoForThreadUpper;
private static NumberFormatInfo nfil {
get {
if (NumberFormatInfoForThreadLower == null) {
NumberFormatInfo numberFormatInfo = ((CultureInfo)CultureInfo.InvariantCulture.Clone()).NumberFormat;
// The CLI formats as "Infinity", but CPython formats differently
numberFormatInfo.PositiveInfinitySymbol = "inf";
numberFormatInfo.NegativeInfinitySymbol = "-inf";
numberFormatInfo.NaNSymbol = "nan";
NumberFormatInfoForThreadLower = numberFormatInfo;
}
return NumberFormatInfoForThreadLower;
}
}
private static NumberFormatInfo nfiu {
get {
if (NumberFormatInfoForThreadUpper == null) {
NumberFormatInfo numberFormatInfo = ((CultureInfo)CultureInfo.InvariantCulture.Clone()).NumberFormat;
// The CLI formats as "Infinity", but CPython formats differently
numberFormatInfo.PositiveInfinitySymbol = "INF";
numberFormatInfo.NegativeInfinitySymbol = "-INF";
numberFormatInfo.NaNSymbol = "NAN";
NumberFormatInfoForThreadUpper = numberFormatInfo;
}
return NumberFormatInfoForThreadUpper;
}
}
private NumberFormatInfo _nfi;
#region Constructors
private StringFormatter(CodeContext/*!*/ context, string str, object? data) {
_str = str;
_data = data;
_context = context;
_nfi = nfil;
_buf = null!;
}
#endregion
#region Public API Surface
public static string Format(CodeContext/*!*/ context, string str, object? data, bool trailingZeroAfterWholeFloat = false)
=> new StringFormatter(context, str, data) { _trailingZeroAfterWholeFloat = trailingZeroAfterWholeFloat }.Format();
internal static byte[] FormatBytes(CodeContext/*!*/ context, ReadOnlySpan<byte> str, object? data)
=> new StringFormatter(context, str.MakeString(), data) { _asBytes = true }.Format().MakeByteArray();
#endregion
#region Private APIs
private string Format() {
_index = 0;
_buf = new StringBuilder(_str.Length * 2);
int modIndex;
while ((modIndex = _str.IndexOf('%', _index)) != -1) {
_buf.Append(_str, _index, modIndex - _index);
_index = modIndex + 1;
DoFormatCode();
}
_buf.Append(_str, _index, _str.Length - _index);
CheckDataUsed();
return _buf.ToString();
}
private void DoFormatCode() {
// we already pulled the first %
if (_index == _str.Length)
throw PythonOps.ValueError("incomplete format, expected format character at index {0}", _index);
// Index is placed right after the %.
Debug.Assert(_str[_index - 1] == '%');
_curCh = _str[_index++];
if (_curCh == '%') {
// Escaped '%' character using "%%". Just print it and we are done
_buf.Append('%');
return;
}
var key = ReadMappingKey();
_opts = new FormatSettings();
ReadConversionFlags();
ReadMinimumFieldWidth();
ReadPrecision();
ReadLengthModifier();
// use the key (or lack thereof) to get the value
object? value;
if (key == null) {
value = GetData(_dataIndex++);
} else {
value = GetKey(key);
}
_opts.Value = value;
WriteConversion();
}
/// <summary>
/// Read a possible mapping key for %(key)s.
/// </summary>
/// <returns>The key name enclosed between the '%(key)s',
/// or null if there are no paranthesis such as '%s'.</returns>
private object? ReadMappingKey() {
// Caller has set _curCh to the character past the %, and
// _index to 2 characters past the original '%'.
Debug.Assert(_curCh == _str[_index - 1]);
Debug.Assert(_str[_index - 2] == '%');
if (_curCh != '(') {
// No parenthesized key.
return null;
}
// CPython supports nested parenthesis (See "S3.6.2:String Formatting Operations").
// Keywords inbetween %(...)s can contain parenthesis.
//
// For example, here are the keys returned for various format strings:
// %(key)s - return 'key'
// %((key))s - return '(key)'
// %()s - return ''
// %((((key))))s - return '(((key)))'
// %((%)s)s - return '(%)s'
// %((%s))s - return (%s)
// %(a(b)c)s - return a(b)c
// %((a)s)s - return (a)s
// %(((a)s))s - return ((a)s)
// Use a counter rule.
int nested = 1; // already passed the 1st '('
int start = _index; // character index after 1st opening '('
int end = start;
while (end < _str.Length) {
if (_str[end] == '(') {
nested++;
} else if (_str[end] == ')') {
nested--;
}
if (nested == 0) {
// Found final matching closing parent
string key = _str.Substring(_index, end - start);
// Update fields
_index = end + 1;
if (_index == _str.Length) {
// This error could happen with a format string like '%((key))'
throw PythonOps.ValueError("incomplete format");
}
_curCh = _str[_index++];
if (_asBytes) return Bytes.Make(key.MakeByteArray());
return key;
}
end++;
}
// Error: missing closing ')'.
// This could happen with '%((key)s'
throw PythonOps.ValueError("incomplete format key");
}
private void ReadConversionFlags() {
bool fFoundConversion;
do {
fFoundConversion = true;
switch (_curCh) {
case '#': _opts.AltForm = true; break;
case '-': _opts.LeftAdj = true; _opts.ZeroPad = false; break;
case '0': if (!_opts.LeftAdj) _opts.ZeroPad = true; break;
case '+': _opts.SignChar = true; _opts.Space = false; break;
case ' ': if (!_opts.SignChar) _opts.Space = true; break;
default: fFoundConversion = false; break;
}
if (fFoundConversion) _curCh = _str[_index++];
} while (fFoundConversion);
}
private int ReadNumberOrStar() {
return ReadNumberOrStar(0);
}
private int ReadNumberOrStar(int noValSpecified) {
int res = noValSpecified;
if (_curCh == '*') {
if (!(_data is PythonTuple)) { throw PythonOps.TypeError("* requires a tuple for values"); }
_curCh = _str[_index++];
res = _context.LanguageContext.ConvertToInt32(GetData(_dataIndex++));
} else {
if (char.IsDigit(_curCh)) {
res = 0;
try {
while (char.IsDigit(_curCh) && _index < this._str.Length) {
res = checked(res * 10 + ((int)(_curCh - '0')));
_curCh = _str[_index++];
}
} catch (OverflowException) {
throw PythonOps.ValueError("width too big");
}
}
}
return res;
}
private void ReadMinimumFieldWidth() {
int fieldWidth = ReadNumberOrStar();
if (fieldWidth < 0) {
_opts.FieldWidth = fieldWidth * -1;
_opts.LeftAdj = true;
} else {
_opts.FieldWidth = fieldWidth;
}
if (_opts.FieldWidth == int.MaxValue) {
throw PythonOps.MemoryError("not enough memory for field width");
}
}
private void ReadPrecision() {
if (_curCh == '.') {
_curCh = _str[_index++];
// possibility: "8.f", "8.0f", or "8.2f"
_opts.Precision = ReadNumberOrStar();
if (_opts.Precision > 1048575) throw PythonOps.OverflowError("precision too large"); // CPython allows for larger precision values but what's the point...
} else {
_opts.Precision = UnspecifiedPrecision;
}
}
private void ReadLengthModifier() {
switch (_curCh) {
// ignored, not necessary for Python
case 'h':
case 'l':
case 'L':
_curCh = _str[_index++];
break;
}
}
private void WriteConversion() {
// conversion type (required)
switch (_curCh) {
// string (ascii() version)
case 'a': AppendAscii(); return;
// signed integer decimal
case 'd':
case 'i': AppendInt(); return;
// unsigned octal
case 'o': AppendOctal(); return;
// unsigned decimal
case 'u': AppendInt(); return;
// unsigned hexadecimal
case 'x': AppendHex(_curCh); return;
case 'X': AppendHex(_curCh); return;
// floating point exponential format
case 'e':
// floating point decimal
case 'f':
// Same as "e" if exponent is less than -4 or more than precision, "f" otherwise.
case 'g': AppendFloat(_curCh); return;
// same as 3 above but uppercase
case 'E':
case 'F':
case 'G': _nfi = nfiu; AppendFloat(_curCh); _nfi = nfil; return;
// single character (int or single char str)
case 'c': AppendChar(); return;
// string (repr() version)
case 'r': AppendRepr(); return;
// string (str() version)
case 's':
if (_asBytes) goto case 'b';
AppendString(); return;
// bytes
case 'b':
if (!_asBytes) goto default;
AppendBytes(); return;
default:
if (_curCh > 0xff)
throw PythonOps.ValueError("unsupported format character '{0}' (0x{1:X}) at index {2}", '?', (int)_curCh, _index - 1);
else
throw PythonOps.ValueError("unsupported format character '{0}' (0x{1:X}) at index {2}", _curCh, (int)_curCh, _index - 1);
}
}
private object? GetData(int index) {
if (_data is PythonTuple dt) {
if (index < dt.__len__()) {
return dt[index];
}
} else {
if (index == 0) {
return _data;
}
}
throw PythonOps.TypeError("not enough arguments for format string");
}
private object? GetKey(object key) {
if (_data is IDictionary<object, object> map) {
if (map.TryGetValue(key, out object? res)) {
return res;
}
} else if (_data is PythonDictionary dict) {
if (dict.TryGetValue(key, out object? res)) {
return res;
}
} else {
if (PythonOps.IsMappingType(DefaultContext.Default, _data)) {
return PythonOps.GetIndex(_context, _data, key);
}
throw PythonOps.TypeError("format requires a mapping");
}
throw PythonOps.KeyError(key);
}
private object GetIntegerValue(out bool fPos, bool allowDouble = true) {
if (!allowDouble && _opts.Value is float || _opts.Value is double || _opts.Value is Extensible<double>) {
// TODO: this should fail in 3.5
PythonOps.Warn(_context, PythonExceptions.DeprecationWarning, "automatic int conversions have been deprecated");
}
object val;
if (_context.LanguageContext.TryConvertToInt32(_opts.Value, out int intVal)) {
val = intVal;
fPos = intVal >= 0;
} else {
if (Converter.TryConvertToBigInteger(_opts.Value, out BigInteger bigInt)) {
val = bigInt;
fPos = bigInt >= BigInteger.Zero;
} else {
throw PythonOps.TypeError("int argument required");
}
}
return val;
}
private void AppendChar() {
char val;
if (_asBytes) {
if (_opts.Value is Bytes bytes && bytes.Count == 1) {
val = (char)bytes[0];
} else if (_opts.Value is ByteArray byteArray && byteArray.Count == 1) {
val = (char)(int)byteArray[0];
} else if (Converter.TryConvertToIndex(_opts.Value, out object index)) {
try {
val = index switch {
int i => (char)checked((byte)i),
BigInteger bi => (char)checked((byte)bi),
_ => throw new InvalidOperationException(), // unreachable
};
} catch (OverflowException) {
throw PythonOps.ValueError("%c arg not in range(256)");
}
}
else {
throw PythonOps.TypeError("%c requires an integer in range(256) or a single byte");
}
} else {
val = Converter.ExplicitConvertToChar(_opts.Value);
}
if (_opts.FieldWidth > 1) {
if (!_opts.LeftAdj) {
_buf.Append(' ', _opts.FieldWidth - 1);
}
_buf.Append(val);
if (_opts.LeftAdj) {
_buf.Append(' ', _opts.FieldWidth - 1);
}
} else {
_buf.Append(val);
}
}
private void CheckDataUsed() {
if (!PythonOps.IsMappingType(DefaultContext.Default, _data)) {
if ((!(_data is PythonTuple) && _dataIndex != 1) ||
(_data is PythonTuple && _dataIndex != ((PythonTuple)_data).__len__())) {
throw PythonOps.TypeError("not all arguments converted during string formatting");
}
}
}
private void AppendInt() {
object val = GetIntegerValue(out bool fPos);
if (_opts.LeftAdj) {
string str = ZeroPadInt(val, fPos, _opts.Precision);
var pad = _opts.FieldWidth - str.Length;
if (fPos && (_opts.SignChar || _opts.Space)) {
_buf.Append(_opts.SignChar ? '+' : ' ');
pad--;
}
_buf.Append(str);
if (pad > 0) _buf.Append(' ', pad);
} else if (_opts.ZeroPad || _opts.Precision > 0) {
int minNumDigits = _opts.Precision;
if (_opts.ZeroPad && _opts.FieldWidth > minNumDigits) {
minNumDigits = _opts.FieldWidth;
if (!fPos || _opts.SignChar || _opts.Space) minNumDigits--;
}
var str = ZeroPadInt(val, fPos, minNumDigits);
if (fPos && (_opts.SignChar || _opts.Space)) {
var pad = _opts.FieldWidth - str.Length - 1;
if (pad > 0) _buf.Append(' ', pad);
_buf.Append(_opts.SignChar ? '+' : ' ');
} else {
var pad = _opts.FieldWidth - str.Length;
if (pad > 0) _buf.Append(' ', pad);
}
_buf.Append(str);
} else {
if (fPos && (_opts.SignChar || _opts.Space)) {
var str = string.Format(_nfi, "{0:D}", val);
var pad = _opts.FieldWidth - (str.Length + 1);
if (pad > 0) _buf.Append(' ', pad);
_buf.Append(_opts.SignChar ? '+' : ' ');
_buf.Append(str);
} else {
_buf.AppendFormat(_nfi, "{0," + _opts.FieldWidth + ":D}", val);
}
}
}
private static readonly bool supportsPrecisionGreaterThan99 = 0.ToString("D100", CultureInfo.InvariantCulture) != "D100"; // support is new in .NET 6
private string ZeroPadInt(object val, bool fPos, int minNumDigits) {
if (minNumDigits < 2) {
return string.Format(_nfi, "{0:D}", val);
}
if (minNumDigits < 100 || supportsPrecisionGreaterThan99) {
return string.Format(_nfi, "{0:D" + minNumDigits + "}", val);
}
var res = string.Format(_nfi, "{0:D}", val);
if (fPos) {
var zeroPad = minNumDigits - res.Length;
if (zeroPad > 0) {
res = new string('0', zeroPad) + res;
}
} else {
var zeroPad = minNumDigits - res.Length + 1; // '-' does not count
if (zeroPad > 0) {
res = '-' + new string('0', zeroPad) + res.Substring(1);
}
}
return res;
}
private static readonly char[] zero = new char[] { '0' };
// With .NET Framework "F" formatting is truncated after 15 digits:
private static readonly bool truncatedToString = (1.0 / 3).ToString("F17", CultureInfo.InvariantCulture) == "0.33333333333333300";
// Return the new type char to use
private char AdjustForG(char type, double v) {
if (type != 'G' && type != 'g')
return type;
if (double.IsNaN(v) || double.IsInfinity(v))
return type;
double absV = Math.Abs(v);
if (_opts.Precision == 0) {
_opts.Precision = 1;
}
if ((v != 0.0) && // 0.0 should not be displayed as scientific notation
absV < 1e-4 || // Values less than 0.0001 will need scientific notation
absV >= Math.Pow(10, _opts.Precision)) { // Values bigger than 1e<precision> will need scientific notation
type = (type == 'G') ? 'E' : 'e';
// For e/E formatting, precision means the number of digits after the decimal point.
// One digit is displayed before the decimal point.
int fractionDigitsRequired = _opts.Precision - 1;
string expForm = absV.ToString("E" + fractionDigitsRequired, CultureInfo.InvariantCulture);
string mantissa = expForm.Substring(0, expForm.IndexOf('E')).TrimEnd(zero);
if (mantissa.Length == 1) {
_opts.Precision = 0;
} else {
// We do -2 to ignore the digit before the decimal point and the decimal point itself
Debug.Assert(mantissa[1] == '.');
_opts.Precision = mantissa.Length - 2;
}
} else {
string fixedPointForm;
bool convertType = true;
if (truncatedToString) {
// "0.000ddddd" is allowed when the precision is 5. The 3 leading zeros are not counted
int numberDecimalDigits = _opts.Precision;
if (absV < 1e-3) numberDecimalDigits += 3;
else if (absV < 1e-2) numberDecimalDigits += 2;
else if (absV < 1e-1) numberDecimalDigits += 1;
fixedPointForm = absV.ToString("F" + numberDecimalDigits, CultureInfo.InvariantCulture).TrimEnd(zero);
if (numberDecimalDigits > 15) {
// System.Double(0.33333333333333331).ToString("F17") == "0.33333333333333300"
string fixedPointFormG = absV.ToString("G" + _opts.Precision, CultureInfo.InvariantCulture);
if (fixedPointFormG.Length > fixedPointForm.Length) {
fixedPointForm = fixedPointFormG;
convertType = false;
}
}
} else {
fixedPointForm = absV.ToString("G" + _opts.Precision, CultureInfo.InvariantCulture);
}
if (convertType) {
type = (type == 'G') ? 'F' : 'f';
// For f/F formatting, precision means the number of digits after the decimal point.
var mostSignificantDigit = 1 + (absV == 0 ? 0 : (int)Math.Floor(Math.Log10(absV)));
if (_opts.AltForm) {
_opts.Precision -= mostSignificantDigit;
} else {
var decimalPointIdx = fixedPointForm.IndexOf('.');
var fractionLength = decimalPointIdx == -1 ? 0 : (fixedPointForm.Length - decimalPointIdx - 1);
_opts.Precision = Math.Min(_opts.Precision - mostSignificantDigit, fractionLength);
}
}
}
return type;
}
private void AppendFloat(char format) {
double val;
if (!Converter.TryConvertToDouble(_opts.Value, out val))
throw PythonOps.TypeError("float argument required");
Debug.Assert(format == 'E' || format == 'e' || // scientific exponential format
format == 'F' || format == 'f' || // floating point decimal
format == 'G' || format == 'g'); // Same as "e" if exponent is less than -4 or more than precision, "f" otherwise.
// update our precision first...
if (_opts.Precision == UnspecifiedPrecision) {
_opts.Precision = 6;
}
format = AdjustForG(format, val);
var fPos = DoubleOps.Sign(val) >= 0 || double.IsNaN(val);
var str = FormatWithPrecision(val, fPos, format);
var pad = _opts.FieldWidth - str.Length;
// then append
if (_opts.LeftAdj) {
_buf.Append(str);
if (pad > 0) _buf.Append(' ', pad);
} else if (_opts.ZeroPad) {
if (pad > 0) {
if (!fPos || _opts.SignChar || _opts.Space) {
_buf.Append(str[0]);
_buf.Append('0', pad);
_buf.Append(str, 1, str.Length - 1);
} else {
_buf.Append('0', pad);
_buf.Append(str);
}
} else {
_buf.Append(str);
}
} else {
if (pad > 0) _buf.Append(' ', pad);
_buf.Append(str);
}
}
private static readonly bool needsFixupFloatMinus = $"{-0.1:f0}" == "0"; // fixed in .NET Core 3.1
private string FormatWithPrecision(double val, bool fPos, char format) {
string res;
if (double.IsNaN(val) || double.IsInfinity(val)) {
res = val.ToString(_nfi);
if (fPos) {
if (_opts.SignChar) {
res = "+" + res;
} else if (_opts.Space) {
res = " " + res;
}
}
return res;
} else {
if (_opts.Precision < 100 || supportsPrecisionGreaterThan99) {
res = val.ToString($"{format}{_opts.Precision}", _nfi);
} else {
res = val.ToString($"{format}99", _nfi);
res += new string('0', _opts.Precision - 99);
}
res = FixupFloatMinus(val, fPos, res);
if (fPos) {
if (_opts.SignChar) {
res = "+" + res;
} else if (_opts.Space) {
res = " " + res;
}
}
}
if (format == 'e' || format == 'E') {
res = AdjustExponent(res);
if (_opts.Precision == 0 && _opts.AltForm) {
res = res.Insert(res.IndexOf(format), ".");
}
} else {
if (_opts.Precision == 0 && _opts.AltForm) {
res += ".";
}
}
// If AdjustForG() sets opts.Precision == 0, it means that no significant digits should be displayed after
// the decimal point. ie. 123.4 should be displayed as "123", not "123.4". However, we might still need a
// decorative ".0". ie. to display "123.0"
if (_trailingZeroAfterWholeFloat && (format == 'f' || format == 'F') && _opts.Precision == 0)
res += ".0";
return res;
// Ensure negative values rounded to 0 show up as -0.
static string FixupFloatMinus(double val, bool fPos, string x) {
if (needsFixupFloatMinus && !fPos && val >= -0.5 && x[0] != '-') {
Debug.Assert(x[0] == '0');
return "-" + x;
}
return x;
}
// A strange string formatting bug requires that we use Standard Numeric Format and
// not Custom Numeric Format. Standard Numeric Format produces always a 3 digit exponent
// which needs to be taken care off.
// Example: 9.3126672485384569e+23, precision=16
// format string "e16" ==> "9.3126672485384569e+023", but we want "e+23", not "e+023"
// format string "0.0000000000000000e+00" ==> "9.3126672485384600e+23", which is a precision error
// so, we have to format with "e16" and strip the zero manually
static string AdjustExponent(string val) {
if (val[val.Length - 3] == '0') {
return val.Remove(val.Length - 3, 1);
} else {
return val;
}
}
}
private static string GetAltFormPrefixForRadix(char format, int radix) {
return radix switch {
8 => format + "0",
16 => format + "0",
_ => "",
};
}
/// <summary>
/// AppendBase appends an integer at the specified radix doing all the
/// special forms for Python.
/// </summary>
private void AppendBase(char format, int radix) {
var str = ProcessNumber(format, radix, ref _opts, GetIntegerValue(out bool fPos, allowDouble: false));
if (!fPos) {
// if negative number, the leading space has no impact
_opts.Space = false;
}
// pad out for additional precision
if (str.Length < _opts.Precision) {
int len = _opts.Precision - str.Length;
str.Append('0', len);
}
// pad result to minimum field width
if (_opts.FieldWidth != 0) {
int signLen = (!fPos || _opts.SignChar) ? 1 : 0;
int spaceLen = _opts.Space ? 1 : 0;
int len = _opts.FieldWidth - (str.Length + signLen + spaceLen);
if (len > 0) {
// we account for the size of the alternate form, if we'll end up adding it.
if (_opts.AltForm) {
len -= GetAltFormPrefixForRadix(format, radix).Length;
}
if (len > 0) {
// and finally append the right form
if (_opts.LeftAdj) {
str.Insert(0, " ", len);
} else {
if (_opts.ZeroPad) {
str.Append('0', len);
} else {
_buf.Append(' ', len);
}
}
}
}
}
// append the alternate form
if (_opts.AltForm)
str.Append(GetAltFormPrefixForRadix(format, radix));
// add any sign if necessary
if (!fPos) {
_buf.Append('-');
} else if (_opts.SignChar) {
_buf.Append('+');
} else if (_opts.Space) {
_buf.Append(' ');
}
// append the final value
for (int i = str.Length - 1; i >= 0; i--) {
_buf.Append(str[i]);
}
static StringBuilder ProcessNumber(char format, int radix, ref FormatSettings _opts, object intVal) {
StringBuilder str;
// we build up the number backwards inside a string builder,
// and after we've finished building this up we append the
// string to our output buffer backwards.
if (intVal is BigInteger bi) {
BigInteger val = bi;
if (val < 0) val *= -1;
str = new StringBuilder();
// use .NETs faster conversion if we can
if (radix == 16) {
AppendNumberReversed(str, char.IsLower(format) ? val.ToString("x") : val.ToString("X"));
} else if (radix == 10) {
AppendNumberReversed(str, val.ToString());
} else {
if (val == 0) str.Append('0');
while (val != 0) {
int digit = (int)(val % radix);
if (digit < 10) str.Append((char)((digit) + '0'));
else if (char.IsLower(format)) str.Append((char)((digit - 10) + 'a'));
else str.Append((char)((digit - 10) + 'A'));
val /= radix;
}
}
} else {
int val = (int)intVal;
if (val == int.MinValue) return ProcessNumber(format, radix, ref _opts, (BigInteger)val);
if (val < 0) val *= -1;
str = new StringBuilder();
if (val == 0) str.Append('0');
while (val != 0) {
int digit = val % radix;
if (digit < 10) str.Append((char)((digit) + '0'));
else if (char.IsLower(format)) str.Append((char)((digit - 10) + 'a'));
else str.Append((char)((digit - 10) + 'A'));
val /= radix;
}
}
return str;
}
}
private static void AppendNumberReversed(StringBuilder str, string res) {
int start = 0;
while (start < (res.Length - 1) && res[start] == '0') {
start++;
}
for (int i = res.Length - 1; i >= start; i--) {
str.Append(res[i]);
}
}
private void AppendHex(char format) {
AppendBase(format, 16);
}
private void AppendOctal() {
AppendBase('o', 8);
}
private void AppendBytes() {
Debug.Assert(_asBytes);
if (_opts.Value is Bytes bytes || Bytes.TryInvokeBytesOperator(_context, _opts.Value, out bytes!)) {
AppendString(StringOps.Latin1Encoding.GetString(bytes.UnsafeByteArray));
} else if (_opts.Value is ByteArray byteArray) {
AppendString(StringOps.Latin1Encoding.GetString(byteArray.UnsafeByteList.AsByteSpan()));
} else {
throw PythonOps.TypeError($"%b requires bytes, or an object that implements __bytes__, not '{PythonOps.GetPythonTypeName(_opts.Value)}'");
}
}
private void AppendString() {
AppendString(PythonOps.ToString(_context, _opts.Value));
}
private void AppendAscii() {
AppendString(PythonOps.Ascii(_context, _opts.Value));
}
private void AppendRepr() {
AppendString(PythonOps.Repr(_context, _opts.Value));
}
private void AppendString(string s) {
if (_opts.Precision != UnspecifiedPrecision && s.Length > _opts.Precision) s = s.Substring(0, _opts.Precision);
if (!_opts.LeftAdj && _opts.FieldWidth > s.Length) {
_buf.Append(' ', _opts.FieldWidth - s.Length);
}
_buf.Append(s);
if (_opts.LeftAdj && _opts.FieldWidth > s.Length) {
_buf.Append(' ', _opts.FieldWidth - s.Length);
}
}
#endregion
#region Private data structures
// The conversion specifier format is as follows:
// % (mappingKey) conversionFlags fieldWidth . precision lengthModifier conversionType
// where:
// mappingKey - value to be formatted
// conversionFlags - # 0 - + <space>
// lengthModifier - h, l, and L. Ignored by Python
// conversionType - d i o u x X e E f F g G c r s %
// Ex:
// %(varName)#4o - Display "varName" as octal and prepend with leading 0 if necessary, for a total of atleast 4 characters
[Flags]
private enum FormatOptions {
ZeroPad = 0x01, // Use zero-padding to fit FieldWidth
LeftAdj = 0x02, // Use left-adjustment to fit FieldWidth. Overrides ZeroPad
AltForm = 0x04, // Add a leading 0 if necessary for octal, or add a leading 0x or 0X for hex
Space = 0x08, // Leave a white-space
SignChar = 0x10 // Force usage of a sign char even if the value is positive
}
private struct FormatSettings {
#region FormatOptions property accessors
public bool ZeroPad {
get {
return ((Options & FormatOptions.ZeroPad) != 0);
}
set {
if (value) {
Options |= FormatOptions.ZeroPad;
} else {
Options &= (~FormatOptions.ZeroPad);
}
}
}
public bool LeftAdj {
get {
return ((Options & FormatOptions.LeftAdj) != 0);
}
set {
if (value) {
Options |= FormatOptions.LeftAdj;
} else {
Options &= (~FormatOptions.LeftAdj);
}
}
}
public bool AltForm {
get {
return ((Options & FormatOptions.AltForm) != 0);
}
set {
if (value) {
Options |= FormatOptions.AltForm;
} else {
Options &= (~FormatOptions.AltForm);
}
}
}
public bool Space {
get {
return ((Options & FormatOptions.Space) != 0);
}
set {
if (value) {
Options |= FormatOptions.Space;
} else {
Options &= (~FormatOptions.Space);
}
}
}
public bool SignChar {
get {
return ((Options & FormatOptions.SignChar) != 0);
}
set {
if (value) {
Options |= FormatOptions.SignChar;
} else {
Options &= (~FormatOptions.SignChar);
}
}
}
#endregion
internal FormatOptions Options;
// Minimum number of characters that the entire formatted string should occupy.
// Smaller results will be left-padded with white-space or zeros depending on Options
internal int FieldWidth;
// Number of significant digits to display, before and after the decimal point.
// For floats (except G/g format specification), it gets adjusted to the number of
// digits to display after the decimal point since that is the value required by
// the .NET string formatting.
// For clarity, we should break this up into the two values - the precision specified by the
// format string, and the value to be passed in to StringBuilder.AppendFormat
internal int Precision;
internal object? Value;
}
#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;
namespace System.Linq.Expressions
{
/// <summary>
/// Strongly-typed and parameterized exception factory.
/// </summary>
internal static partial class Error
{
/// <summary>
/// ArgumentException with message like "reducible nodes must override Expression.Reduce()"
/// </summary>
internal static Exception ReducibleMustOverrideReduce()
{
return new ArgumentException(Strings.ReducibleMustOverrideReduce);
}
/// <summary>
/// ArgumentException with message like "node cannot reduce to itself or null"
/// </summary>
internal static Exception MustReduceToDifferent()
{
return new ArgumentException(Strings.MustReduceToDifferent);
}
/// <summary>
/// ArgumentException with message like "cannot assign from the reduced node type to the original node type"
/// </summary>
internal static Exception ReducedNotCompatible()
{
return new ArgumentException(Strings.ReducedNotCompatible);
}
/// <summary>
/// ArgumentException with message like "Setter must have parameters."
/// </summary>
internal static Exception SetterHasNoParams()
{
return new ArgumentException(Strings.SetterHasNoParams);
}
/// <summary>
/// ArgumentException with message like "Property cannot have a managed pointer type."
/// </summary>
internal static Exception PropertyCannotHaveRefType()
{
return new ArgumentException(Strings.PropertyCannotHaveRefType);
}
/// <summary>
/// ArgumentException with message like "Indexing parameters of getter and setter must match."
/// </summary>
internal static Exception IndexesOfSetGetMustMatch()
{
return new ArgumentException(Strings.IndexesOfSetGetMustMatch);
}
/// <summary>
/// ArgumentException with message like "Accessor method should not have VarArgs."
/// </summary>
internal static Exception AccessorsCannotHaveVarArgs()
{
return new ArgumentException(Strings.AccessorsCannotHaveVarArgs);
}
/// <summary>
/// ArgumentException with message like "Accessor indexes cannot be passed ByRef."
/// </summary>
internal static Exception AccessorsCannotHaveByRefArgs()
{
return new ArgumentException(Strings.AccessorsCannotHaveByRefArgs);
}
/// <summary>
/// ArgumentException with message like "Bounds count cannot be less than 1"
/// </summary>
internal static Exception BoundsCannotBeLessThanOne()
{
return new ArgumentException(Strings.BoundsCannotBeLessThanOne);
}
/// <summary>
/// ArgumentException with message like "type must not be ByRef"
/// </summary>
internal static Exception TypeMustNotBeByRef()
{
return new ArgumentException(Strings.TypeMustNotBeByRef);
}
/// <summary>
/// ArgumentException with message like "Type doesn't have constructor with a given signature"
/// </summary>
internal static Exception TypeDoesNotHaveConstructorForTheSignature()
{
return new ArgumentException(Strings.TypeDoesNotHaveConstructorForTheSignature);
}
/// <summary>
/// ArgumentException with message like "Setter should have void type."
/// </summary>
internal static Exception SetterMustBeVoid()
{
return new ArgumentException(Strings.SetterMustBeVoid);
}
/// <summary>
/// ArgumentException with message like "Property type must match the value type of setter"
/// </summary>
internal static Exception PropertyTypeMustMatchSetter()
{
return new ArgumentException(Strings.PropertyTypeMustMatchSetter);
}
/// <summary>
/// ArgumentException with message like "Both accessors must be static."
/// </summary>
internal static Exception BothAccessorsMustBeStatic()
{
return new ArgumentException(Strings.BothAccessorsMustBeStatic);
}
/// <summary>
/// ArgumentException with message like "Static method requires null instance, non-static method requires non-null instance."
/// </summary>
internal static Exception OnlyStaticMethodsHaveNullInstance()
{
return new ArgumentException(Strings.OnlyStaticMethodsHaveNullInstance);
}
/// <summary>
/// ArgumentException with message like "Property cannot have a void type."
/// </summary>
internal static Exception PropertyTypeCannotBeVoid()
{
return new ArgumentException(Strings.PropertyTypeCannotBeVoid);
}
/// <summary>
/// ArgumentException with message like "Can only unbox from an object or interface type to a value type."
/// </summary>
internal static Exception InvalidUnboxType()
{
return new ArgumentException(Strings.InvalidUnboxType);
}
/// <summary>
/// ArgumentException with message like "Argument must not have a value type."
/// </summary>
internal static Exception ArgumentMustNotHaveValueType()
{
return new ArgumentException(Strings.ArgumentMustNotHaveValueType);
}
/// <summary>
/// ArgumentException with message like "must be reducible node"
/// </summary>
internal static Exception MustBeReducible()
{
return new ArgumentException(Strings.MustBeReducible);
}
/// <summary>
/// ArgumentException with message like "Default body must be supplied if case bodies are not System.Void."
/// </summary>
internal static Exception DefaultBodyMustBeSupplied()
{
return new ArgumentException(Strings.DefaultBodyMustBeSupplied);
}
/// <summary>
/// ArgumentException with message like "MethodBuilder does not have a valid TypeBuilder"
/// </summary>
internal static Exception MethodBuilderDoesNotHaveTypeBuilder()
{
return new ArgumentException(Strings.MethodBuilderDoesNotHaveTypeBuilder);
}
/// <summary>
/// ArgumentException with message like "Label type must be System.Void if an expression is not supplied"
/// </summary>
internal static Exception LabelMustBeVoidOrHaveExpression()
{
return new ArgumentException(Strings.LabelMustBeVoidOrHaveExpression);
}
/// <summary>
/// ArgumentException with message like "Type must be System.Void for this label argument"
/// </summary>
internal static Exception LabelTypeMustBeVoid()
{
return new ArgumentException(Strings.LabelTypeMustBeVoid);
}
/// <summary>
/// ArgumentException with message like "Quoted expression must be a lambda"
/// </summary>
internal static Exception QuotedExpressionMustBeLambda()
{
return new ArgumentException(Strings.QuotedExpressionMustBeLambda);
}
/// <summary>
/// ArgumentException with message like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables."
/// </summary>
internal static Exception VariableMustNotBeByRef(object p0, object p1)
{
return new ArgumentException(Strings.VariableMustNotBeByRef(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object."
/// </summary>
internal static Exception DuplicateVariable(object p0)
{
return new ArgumentException(Strings.DuplicateVariable(p0));
}
/// <summary>
/// ArgumentException with message like "Start and End must be well ordered"
/// </summary>
internal static Exception StartEndMustBeOrdered()
{
return new ArgumentException(Strings.StartEndMustBeOrdered);
}
/// <summary>
/// ArgumentException with message like "fault cannot be used with catch or finally clauses"
/// </summary>
internal static Exception FaultCannotHaveCatchOrFinally()
{
return new ArgumentException(Strings.FaultCannotHaveCatchOrFinally);
}
/// <summary>
/// ArgumentException with message like "try must have at least one catch, finally, or fault clause"
/// </summary>
internal static Exception TryMustHaveCatchFinallyOrFault()
{
return new ArgumentException(Strings.TryMustHaveCatchFinallyOrFault);
}
/// <summary>
/// ArgumentException with message like "Body of catch must have the same type as body of try."
/// </summary>
internal static Exception BodyOfCatchMustHaveSameTypeAsBodyOfTry()
{
return new ArgumentException(Strings.BodyOfCatchMustHaveSameTypeAsBodyOfTry);
}
/// <summary>
/// InvalidOperationException with message like "Extension node must override the property {0}."
/// </summary>
internal static Exception ExtensionNodeMustOverrideProperty(object p0)
{
return new InvalidOperationException(Strings.ExtensionNodeMustOverrideProperty(p0));
}
/// <summary>
/// ArgumentException with message like "User-defined operator method '{0}' must be static."
/// </summary>
internal static Exception UserDefinedOperatorMustBeStatic(object p0)
{
return new ArgumentException(Strings.UserDefinedOperatorMustBeStatic(p0));
}
/// <summary>
/// ArgumentException with message like "User-defined operator method '{0}' must not be void."
/// </summary>
internal static Exception UserDefinedOperatorMustNotBeVoid(object p0)
{
return new ArgumentException(Strings.UserDefinedOperatorMustNotBeVoid(p0));
}
/// <summary>
/// InvalidOperationException with message like "No coercion operator is defined between types '{0}' and '{1}'."
/// </summary>
internal static Exception CoercionOperatorNotDefined(object p0, object p1)
{
return new InvalidOperationException(Strings.CoercionOperatorNotDefined(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "The unary operator {0} is not defined for the type '{1}'."
/// </summary>
internal static Exception UnaryOperatorNotDefined(object p0, object p1)
{
return new InvalidOperationException(Strings.UnaryOperatorNotDefined(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "The binary operator {0} is not defined for the types '{1}' and '{2}'."
/// </summary>
internal static Exception BinaryOperatorNotDefined(object p0, object p1, object p2)
{
return new InvalidOperationException(Strings.BinaryOperatorNotDefined(p0, p1, p2));
}
/// <summary>
/// InvalidOperationException with message like "Reference equality is not defined for the types '{0}' and '{1}'."
/// </summary>
internal static Exception ReferenceEqualityNotDefined(object p0, object p1)
{
return new InvalidOperationException(Strings.ReferenceEqualityNotDefined(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "The operands for operator '{0}' do not match the parameters of method '{1}'."
/// </summary>
internal static Exception OperandTypesDoNotMatchParameters(object p0, object p1)
{
return new InvalidOperationException(Strings.OperandTypesDoNotMatchParameters(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'."
/// </summary>
internal static Exception OverloadOperatorTypeDoesNotMatchConversionType(object p0, object p1)
{
return new InvalidOperationException(Strings.OverloadOperatorTypeDoesNotMatchConversionType(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "Conversion is not supported for arithmetic types without operator overloading."
/// </summary>
internal static Exception ConversionIsNotSupportedForArithmeticTypes()
{
return new InvalidOperationException(Strings.ConversionIsNotSupportedForArithmeticTypes);
}
/// <summary>
/// ArgumentException with message like "Argument must be array"
/// </summary>
internal static Exception ArgumentMustBeArray()
{
return new ArgumentException(Strings.ArgumentMustBeArray);
}
/// <summary>
/// ArgumentException with message like "Argument must be boolean"
/// </summary>
internal static Exception ArgumentMustBeBoolean()
{
return new ArgumentException(Strings.ArgumentMustBeBoolean);
}
/// <summary>
/// ArgumentException with message like "The user-defined equality method '{0}' must return a boolean value."
/// </summary>
internal static Exception EqualityMustReturnBoolean(object p0)
{
return new ArgumentException(Strings.EqualityMustReturnBoolean(p0));
}
/// <summary>
/// ArgumentException with message like "Argument must be either a FieldInfo or PropertyInfo"
/// </summary>
internal static Exception ArgumentMustBeFieldInfoOrPropertyInfo()
{
return new ArgumentException(Strings.ArgumentMustBeFieldInfoOrPropertyInfo);
}
/// <summary>
/// ArgumentException with message like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo"
/// </summary>
internal static Exception ArgumentMustBeFieldInfoOrPropertyInfoOrMethod()
{
return new ArgumentException(Strings.ArgumentMustBeFieldInfoOrPropertyInfoOrMethod);
}
/// <summary>
/// ArgumentException with message like "Argument must be an instance member"
/// </summary>
internal static Exception ArgumentMustBeInstanceMember()
{
return new ArgumentException(Strings.ArgumentMustBeInstanceMember);
}
/// <summary>
/// ArgumentException with message like "Argument must be of an integer type"
/// </summary>
internal static Exception ArgumentMustBeInteger()
{
return new ArgumentException(Strings.ArgumentMustBeInteger);
}
/// <summary>
/// ArgumentException with message like "Argument for array index must be of type Int32"
/// </summary>
internal static Exception ArgumentMustBeArrayIndexType()
{
return new ArgumentException(Strings.ArgumentMustBeArrayIndexType);
}
/// <summary>
/// ArgumentException with message like "Argument must be single dimensional array type"
/// </summary>
internal static Exception ArgumentMustBeSingleDimensionalArrayType()
{
return new ArgumentException(Strings.ArgumentMustBeSingleDimensionalArrayType);
}
/// <summary>
/// ArgumentException with message like "Argument types do not match"
/// </summary>
internal static Exception ArgumentTypesMustMatch()
{
return new ArgumentException(Strings.ArgumentTypesMustMatch);
}
/// <summary>
/// InvalidOperationException with message like "Cannot auto initialize elements of value type through property '{0}', use assignment instead"
/// </summary>
internal static Exception CannotAutoInitializeValueTypeElementThroughProperty(object p0)
{
return new InvalidOperationException(Strings.CannotAutoInitializeValueTypeElementThroughProperty(p0));
}
/// <summary>
/// InvalidOperationException with message like "Cannot auto initialize members of value type through property '{0}', use assignment instead"
/// </summary>
internal static Exception CannotAutoInitializeValueTypeMemberThroughProperty(object p0)
{
return new InvalidOperationException(Strings.CannotAutoInitializeValueTypeMemberThroughProperty(p0));
}
/// <summary>
/// ArgumentException with message like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither"
/// </summary>
internal static Exception IncorrectTypeForTypeAs(object p0)
{
return new ArgumentException(Strings.IncorrectTypeForTypeAs(p0));
}
/// <summary>
/// InvalidOperationException with message like "Coalesce used with type that cannot be null"
/// </summary>
internal static Exception CoalesceUsedOnNonNullType()
{
return new InvalidOperationException(Strings.CoalesceUsedOnNonNullType);
}
/// <summary>
/// InvalidOperationException with message like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'"
/// </summary>
internal static Exception ExpressionTypeCannotInitializeArrayType(object p0, object p1)
{
return new InvalidOperationException(Strings.ExpressionTypeCannotInitializeArrayType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for constructor parameter of type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchConstructorParameter(object p0, object p1)
{
return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchConstructorParameter(p0, p1);
}
/// <summary>
/// ArgumentException with message like " Argument type '{0}' does not match the corresponding member type '{1}'"
/// </summary>
internal static Exception ArgumentTypeDoesNotMatchMember(object p0, object p1)
{
return new ArgumentException(Strings.ArgumentTypeDoesNotMatchMember(p0, p1));
}
/// <summary>
/// ArgumentException with message like " The member '{0}' is not declared on type '{1}' being created"
/// </summary>
internal static Exception ArgumentMemberNotDeclOnType(object p0, object p1)
{
return new ArgumentException(Strings.ArgumentMemberNotDeclOnType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for parameter of type '{1}' of method '{2}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchMethodParameter(object p0, object p1, object p2)
{
return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchMethodParameter(p0, p1, p2);
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for return type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchReturn(object p0, object p1)
{
return new ArgumentException(Strings.ExpressionTypeDoesNotMatchReturn(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for assignment to type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchAssignment(object p0, object p1)
{
return new ArgumentException(Strings.ExpressionTypeDoesNotMatchAssignment(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for label of type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchLabel(object p0, object p1)
{
return new ArgumentException(Strings.ExpressionTypeDoesNotMatchLabel(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be invoked"
/// </summary>
internal static Exception ExpressionTypeNotInvocable(object p0)
{
return new ArgumentException(Strings.ExpressionTypeNotInvocable(p0));
}
/// <summary>
/// ArgumentException with message like "Field '{0}' is not defined for type '{1}'"
/// </summary>
internal static Exception FieldNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.FieldNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Instance field '{0}' is not defined for type '{1}'"
/// </summary>
internal static Exception InstanceFieldNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.InstanceFieldNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Field '{0}.{1}' is not defined for type '{2}'"
/// </summary>
internal static Exception FieldInfoNotDefinedForType(object p0, object p1, object p2)
{
return new ArgumentException(Strings.FieldInfoNotDefinedForType(p0, p1, p2));
}
/// <summary>
/// ArgumentException with message like "Incorrect number of indexes"
/// </summary>
internal static Exception IncorrectNumberOfIndexes()
{
return new ArgumentException(Strings.IncorrectNumberOfIndexes);
}
/// <summary>
/// ArgumentException with message like "Incorrect number of parameters supplied for lambda declaration"
/// </summary>
internal static Exception IncorrectNumberOfLambdaDeclarationParameters()
{
return new ArgumentException(Strings.IncorrectNumberOfLambdaDeclarationParameters);
}
/// <summary>
/// ArgumentException with message like "Incorrect number of arguments supplied for call to method '{0}'"
/// </summary>
internal static Exception IncorrectNumberOfMethodCallArguments(object p0)
{
return Dynamic.Utils.Error.IncorrectNumberOfMethodCallArguments(p0);
}
/// <summary>
/// ArgumentException with message like "Incorrect number of arguments for constructor"
/// </summary>
internal static Exception IncorrectNumberOfConstructorArguments()
{
return Dynamic.Utils.Error.IncorrectNumberOfConstructorArguments();
}
/// <summary>
/// ArgumentException with message like " Incorrect number of members for constructor"
/// </summary>
internal static Exception IncorrectNumberOfMembersForGivenConstructor()
{
return new ArgumentException(Strings.IncorrectNumberOfMembersForGivenConstructor);
}
/// <summary>
/// ArgumentException with message like "Incorrect number of arguments for the given members "
/// </summary>
internal static Exception IncorrectNumberOfArgumentsForMembers()
{
return new ArgumentException(Strings.IncorrectNumberOfArgumentsForMembers);
}
/// <summary>
/// ArgumentException with message like "Lambda type parameter must be derived from System.MulticastDelegate"
/// </summary>
internal static Exception LambdaTypeMustBeDerivedFromSystemDelegate()
{
return new ArgumentException(Strings.LambdaTypeMustBeDerivedFromSystemDelegate);
}
/// <summary>
/// ArgumentException with message like "Member '{0}' not field or property"
/// </summary>
internal static Exception MemberNotFieldOrProperty(object p0)
{
return new ArgumentException(Strings.MemberNotFieldOrProperty(p0));
}
/// <summary>
/// ArgumentException with message like "Method {0} contains generic parameters"
/// </summary>
internal static Exception MethodContainsGenericParameters(object p0)
{
return new ArgumentException(Strings.MethodContainsGenericParameters(p0));
}
/// <summary>
/// ArgumentException with message like "Method {0} is a generic method definition"
/// </summary>
internal static Exception MethodIsGeneric(object p0)
{
return new ArgumentException(Strings.MethodIsGeneric(p0));
}
/// <summary>
/// ArgumentException with message like "The method '{0}.{1}' is not a property accessor"
/// </summary>
internal static Exception MethodNotPropertyAccessor(object p0, object p1)
{
return new ArgumentException(Strings.MethodNotPropertyAccessor(p0, p1));
}
/// <summary>
/// ArgumentException with message like "The property '{0}' has no 'get' accessor"
/// </summary>
internal static Exception PropertyDoesNotHaveGetter(object p0)
{
return new ArgumentException(Strings.PropertyDoesNotHaveGetter(p0));
}
/// <summary>
/// ArgumentException with message like "The property '{0}' has no 'set' accessor"
/// </summary>
internal static Exception PropertyDoesNotHaveSetter(object p0)
{
return new ArgumentException(Strings.PropertyDoesNotHaveSetter(p0));
}
/// <summary>
/// ArgumentException with message like "The property '{0}' has no 'get' or 'set' accessors"
/// </summary>
internal static Exception PropertyDoesNotHaveAccessor(object p0)
{
return new ArgumentException(Strings.PropertyDoesNotHaveAccessor(p0));
}
/// <summary>
/// ArgumentException with message like "'{0}' is not a member of type '{1}'"
/// </summary>
internal static Exception NotAMemberOfType(object p0, object p1)
{
return new ArgumentException(Strings.NotAMemberOfType(p0, p1));
}
/// <summary>
/// PlatformNotSupportedException with message like "The instruction '{0}' is not supported for type '{1}'"
/// </summary>
internal static Exception ExpressionNotSupportedForType(object p0, object p1)
{
return new PlatformNotSupportedException(Strings.ExpressionNotSupportedForType(p0, p1));
}
/// <summary>
/// PlatformNotSupportedException with message like "The instruction '{0}' is not supported for nullable type '{1}'"
/// </summary>
internal static Exception ExpressionNotSupportedForNullableType(object p0, object p1)
{
return new PlatformNotSupportedException(Strings.ExpressionNotSupportedForNullableType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'"
/// </summary>
internal static Exception ParameterExpressionNotValidAsDelegate(object p0, object p1)
{
return new ArgumentException(Strings.ParameterExpressionNotValidAsDelegate(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Property '{0}' is not defined for type '{1}'"
/// </summary>
internal static Exception PropertyNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.PropertyNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Instance property '{0}' is not defined for type '{1}'"
/// </summary>
internal static Exception InstancePropertyNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.InstancePropertyNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Instance property '{0}' that takes no argument is not defined for type '{1}'"
/// </summary>
internal static Exception InstancePropertyWithoutParameterNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.InstancePropertyWithoutParameterNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Instance property '{0}{1}' is not defined for type '{2}'"
/// </summary>
internal static Exception InstancePropertyWithSpecifiedParametersNotDefinedForType(object p0, object p1, object p2)
{
return new ArgumentException(Strings.InstancePropertyWithSpecifiedParametersNotDefinedForType(p0, p1, p2));
}
/// <summary>
/// ArgumentException with message like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'"
/// </summary>
internal static Exception InstanceAndMethodTypeMismatch(object p0, object p1, object p2)
{
return new ArgumentException(Strings.InstanceAndMethodTypeMismatch(p0, p1, p2));
}
/// <summary>
/// ArgumentException with message like "Type '{0}' does not have a default constructor"
/// </summary>
internal static Exception TypeMissingDefaultConstructor(object p0)
{
return new ArgumentException(Strings.TypeMissingDefaultConstructor(p0));
}
/// <summary>
/// ArgumentException with message like "List initializers must contain at least one initializer"
/// </summary>
internal static Exception ListInitializerWithZeroMembers()
{
return new ArgumentException(Strings.ListInitializerWithZeroMembers);
}
/// <summary>
/// ArgumentException with message like "Element initializer method must be named 'Add'"
/// </summary>
internal static Exception ElementInitializerMethodNotAdd()
{
return new ArgumentException(Strings.ElementInitializerMethodNotAdd);
}
/// <summary>
/// ArgumentException with message like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter"
/// </summary>
internal static Exception ElementInitializerMethodNoRefOutParam(object p0, object p1)
{
return new ArgumentException(Strings.ElementInitializerMethodNoRefOutParam(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Element initializer method must have at least 1 parameter"
/// </summary>
internal static Exception ElementInitializerMethodWithZeroArgs()
{
return new ArgumentException(Strings.ElementInitializerMethodWithZeroArgs);
}
/// <summary>
/// ArgumentException with message like "Element initializer method must be an instance method"
/// </summary>
internal static Exception ElementInitializerMethodStatic()
{
return new ArgumentException(Strings.ElementInitializerMethodStatic);
}
/// <summary>
/// ArgumentException with message like "Type '{0}' is not IEnumerable"
/// </summary>
internal static Exception TypeNotIEnumerable(object p0)
{
return new ArgumentException(Strings.TypeNotIEnumerable(p0));
}
/// <summary>
/// InvalidOperationException with message like "Unexpected coalesce operator."
/// </summary>
internal static Exception UnexpectedCoalesceOperator()
{
return new InvalidOperationException(Strings.UnexpectedCoalesceOperator);
}
/// <summary>
/// InvalidOperationException with message like "Cannot cast from type '{0}' to type '{1}"
/// </summary>
internal static Exception InvalidCast(object p0, object p1)
{
return new InvalidOperationException(Strings.InvalidCast(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Unhandled binary: {0}"
/// </summary>
internal static Exception UnhandledBinary(object p0)
{
return new ArgumentException(Strings.UnhandledBinary(p0));
}
/// <summary>
/// ArgumentException with message like "Unhandled binding "
/// </summary>
internal static Exception UnhandledBinding()
{
return new ArgumentException(Strings.UnhandledBinding);
}
/// <summary>
/// ArgumentException with message like "Unhandled Binding Type: {0}"
/// </summary>
internal static Exception UnhandledBindingType(object p0)
{
return new ArgumentException(Strings.UnhandledBindingType(p0));
}
/// <summary>
/// ArgumentException with message like "Unhandled convert: {0}"
/// </summary>
internal static Exception UnhandledConvert(object p0)
{
return new ArgumentException(Strings.UnhandledConvert(p0));
}
/// <summary>
/// ArgumentException with message like "Unhandled Expression Type: {0}"
/// </summary>
internal static Exception UnhandledExpressionType(object p0)
{
return new ArgumentException(Strings.UnhandledExpressionType(p0));
}
/// <summary>
/// ArgumentException with message like "Unhandled unary: {0}"
/// </summary>
internal static Exception UnhandledUnary(object p0)
{
return new ArgumentException(Strings.UnhandledUnary(p0));
}
/// <summary>
/// ArgumentException with message like "Unknown binding type"
/// </summary>
internal static Exception UnknownBindingType()
{
return new ArgumentException(Strings.UnknownBindingType);
}
/// <summary>
/// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types."
/// </summary>
internal static Exception UserDefinedOpMustHaveConsistentTypes(object p0, object p1)
{
return new ArgumentException(Strings.UserDefinedOpMustHaveConsistentTypes(p0, p1));
}
/// <summary>
/// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type."
/// </summary>
internal static Exception UserDefinedOpMustHaveValidReturnType(object p0, object p1)
{
return new ArgumentException(Strings.UserDefinedOpMustHaveValidReturnType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators."
/// </summary>
internal static Exception LogicalOperatorMustHaveBooleanOperators(object p0, object p1)
{
return new ArgumentException(Strings.LogicalOperatorMustHaveBooleanOperators(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "No method '{0}' exists on type '{1}'."
/// </summary>
internal static Exception MethodDoesNotExistOnType(object p0, object p1)
{
return new InvalidOperationException(Strings.MethodDoesNotExistOnType(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "No method '{0}' on type '{1}' is compatible with the supplied arguments."
/// </summary>
internal static Exception MethodWithArgsDoesNotExistOnType(object p0, object p1)
{
return new InvalidOperationException(Strings.MethodWithArgsDoesNotExistOnType(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. "
/// </summary>
internal static Exception GenericMethodWithArgsDoesNotExistOnType(object p0, object p1)
{
return new InvalidOperationException(Strings.GenericMethodWithArgsDoesNotExistOnType(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments."
/// </summary>
internal static Exception MethodWithMoreThanOneMatch(object p0, object p1)
{
return new InvalidOperationException(Strings.MethodWithMoreThanOneMatch(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments."
/// </summary>
internal static Exception PropertyWithMoreThanOneMatch(object p0, object p1)
{
return new InvalidOperationException(Strings.PropertyWithMoreThanOneMatch(p0, p1));
}
/// <summary>
/// ArgumentException with message like "An incorrect number of type args were specified for the declaration of a Func type."
/// </summary>
internal static Exception IncorrectNumberOfTypeArgsForFunc()
{
return new ArgumentException(Strings.IncorrectNumberOfTypeArgsForFunc);
}
/// <summary>
/// ArgumentException with message like "An incorrect number of type args were specified for the declaration of an Action type."
/// </summary>
internal static Exception IncorrectNumberOfTypeArgsForAction()
{
return new ArgumentException(Strings.IncorrectNumberOfTypeArgsForAction);
}
/// <summary>
/// ArgumentException with message like "Argument type cannot be System.Void."
/// </summary>
internal static Exception ArgumentCannotBeOfTypeVoid()
{
return new ArgumentException(Strings.ArgumentCannotBeOfTypeVoid);
}
/// <summary>
/// ArgumentOutOfRangeException with message like "{0} must be greater than or equal to {1}"
/// </summary>
internal static Exception OutOfRange(object p0, object p1)
{
return new ArgumentOutOfRangeException(Strings.OutOfRange(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "Cannot redefine label '{0}' in an inner block."
/// </summary>
internal static Exception LabelTargetAlreadyDefined(object p0)
{
return new InvalidOperationException(Strings.LabelTargetAlreadyDefined(p0));
}
/// <summary>
/// InvalidOperationException with message like "Cannot jump to undefined label '{0}'."
/// </summary>
internal static Exception LabelTargetUndefined(object p0)
{
return new InvalidOperationException(Strings.LabelTargetUndefined(p0));
}
/// <summary>
/// InvalidOperationException with message like "Control cannot leave a finally block."
/// </summary>
internal static Exception ControlCannotLeaveFinally()
{
return new InvalidOperationException(Strings.ControlCannotLeaveFinally);
}
/// <summary>
/// InvalidOperationException with message like "Control cannot leave a filter test."
/// </summary>
internal static Exception ControlCannotLeaveFilterTest()
{
return new InvalidOperationException(Strings.ControlCannotLeaveFilterTest);
}
/// <summary>
/// InvalidOperationException with message like "Cannot jump to ambiguous label '{0}'."
/// </summary>
internal static Exception AmbiguousJump(object p0)
{
return new InvalidOperationException(Strings.AmbiguousJump(p0));
}
/// <summary>
/// InvalidOperationException with message like "Control cannot enter a try block."
/// </summary>
internal static Exception ControlCannotEnterTry()
{
return new InvalidOperationException(Strings.ControlCannotEnterTry);
}
/// <summary>
/// InvalidOperationException with message like "Control cannot enter an expression--only statements can be jumped into."
/// </summary>
internal static Exception ControlCannotEnterExpression()
{
return new InvalidOperationException(Strings.ControlCannotEnterExpression);
}
/// <summary>
/// InvalidOperationException with message like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values."
/// </summary>
internal static Exception NonLocalJumpWithValue(object p0)
{
return new InvalidOperationException(Strings.NonLocalJumpWithValue(p0));
}
/// <summary>
/// InvalidOperationException with message like "Extension should have been reduced."
/// </summary>
internal static Exception ExtensionNotReduced()
{
return new InvalidOperationException(Strings.ExtensionNotReduced);
}
/// <summary>
/// InvalidOperationException with message like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value."
/// </summary>
internal static Exception CannotCompileConstant(object p0)
{
return new InvalidOperationException(Strings.CannotCompileConstant(p0));
}
/// <summary>
/// NotSupportedException with message like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite."
/// </summary>
internal static Exception CannotCompileDynamic()
{
return new NotSupportedException(Strings.CannotCompileDynamic);
}
/// <summary>
/// InvalidOperationException with message like "Invalid lvalue for assignment: {0}."
/// </summary>
internal static Exception InvalidLvalue(ExpressionType p0)
{
return new InvalidOperationException(Strings.InvalidLvalue(p0));
}
/// <summary>
/// InvalidOperationException with message like "Invalid member type: {0}."
/// </summary>
internal static Exception InvalidMemberType(object p0)
{
return new InvalidOperationException(Strings.InvalidMemberType(p0));
}
/// <summary>
/// InvalidOperationException with message like "unknown lift type: '{0}'."
/// </summary>
internal static Exception UnknownLiftType(object p0)
{
return new InvalidOperationException(Strings.UnknownLiftType(p0));
}
/// <summary>
/// ArgumentException with message like "Invalid output directory."
/// </summary>
internal static Exception InvalidOutputDir()
{
return new ArgumentException(Strings.InvalidOutputDir);
}
/// <summary>
/// ArgumentException with message like "Invalid assembly name or file extension."
/// </summary>
internal static Exception InvalidAsmNameOrExtension()
{
return new ArgumentException(Strings.InvalidAsmNameOrExtension);
}
/// <summary>
/// ArgumentException with message like "Cannot create instance of {0} because it contains generic parameters"
/// </summary>
internal static Exception IllegalNewGenericParams(object p0)
{
return new ArgumentException(Strings.IllegalNewGenericParams(p0));
}
/// <summary>
/// InvalidOperationException with message like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined"
/// </summary>
internal static Exception UndefinedVariable(object p0, object p1, object p2)
{
return new InvalidOperationException(Strings.UndefinedVariable(p0, p1, p2));
}
/// <summary>
/// InvalidOperationException with message like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'"
/// </summary>
internal static Exception CannotCloseOverByRef(object p0, object p1)
{
return new InvalidOperationException(Strings.CannotCloseOverByRef(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "Unexpected VarArgs call to method '{0}'"
/// </summary>
internal static Exception UnexpectedVarArgsCall(object p0)
{
return new InvalidOperationException(Strings.UnexpectedVarArgsCall(p0));
}
/// <summary>
/// InvalidOperationException with message like "Rethrow statement is valid only inside a Catch block."
/// </summary>
internal static Exception RethrowRequiresCatch()
{
return new InvalidOperationException(Strings.RethrowRequiresCatch);
}
/// <summary>
/// InvalidOperationException with message like "Try expression is not allowed inside a filter body."
/// </summary>
internal static Exception TryNotAllowedInFilter()
{
return new InvalidOperationException(Strings.TryNotAllowedInFilter);
}
/// <summary>
/// InvalidOperationException with message like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type."
/// </summary>
internal static Exception MustRewriteToSameNode(object p0, object p1, object p2)
{
return new InvalidOperationException(Strings.MustRewriteToSameNode(p0, p1, p2));
}
/// <summary>
/// InvalidOperationException with message like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite."
/// </summary>
internal static Exception MustRewriteChildToSameType(object p0, object p1, object p2)
{
return new InvalidOperationException(Strings.MustRewriteChildToSameType(p0, p1, p2));
}
/// <summary>
/// InvalidOperationException with message like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is intentional, override '{1}' and change it to allow this rewrite."
/// </summary>
internal static Exception MustRewriteWithoutMethod(object p0, object p1)
{
return new InvalidOperationException(Strings.MustRewriteWithoutMethod(p0, p1));
}
/// <summary>
/// NotSupportedException with message like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression."
/// </summary>
internal static Exception TryNotSupportedForMethodsWithRefArgs(object p0)
{
return new NotSupportedException(Strings.TryNotSupportedForMethodsWithRefArgs(p0));
}
/// <summary>
/// NotSupportedException with message like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression."
/// </summary>
internal static Exception TryNotSupportedForValueTypeInstances(object p0)
{
return new NotSupportedException(Strings.TryNotSupportedForValueTypeInstances(p0));
}
/// <summary>
/// InvalidOperationException with message like "Dynamic operations can only be performed in homogeneous AppDomain."
/// </summary>
internal static Exception HomogeneousAppDomainRequired()
{
return new InvalidOperationException(Strings.HomogeneousAppDomainRequired);
}
/// <summary>
/// ArgumentException with message like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"
/// </summary>
internal static Exception TestValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1)
{
return new ArgumentException(Strings.TestValueTypeDoesNotMatchComparisonMethodParameter(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"
/// </summary>
internal static Exception SwitchValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1)
{
return new ArgumentException(Strings.SwitchValueTypeDoesNotMatchComparisonMethodParameter(p0, p1));
}
/// <summary>
/// NotSupportedException with message like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod."
/// </summary>
internal static Exception PdbGeneratorNeedsExpressionCompiler()
{
return new NotSupportedException(Strings.PdbGeneratorNeedsExpressionCompiler);
}
/// <summary>
/// The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
/// </summary>
internal static Exception ArgumentOutOfRange(string paramName)
{
return new ArgumentOutOfRangeException(paramName);
}
/// <summary>
/// The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.
/// </summary>
internal static Exception NotSupported()
{
return new NotSupportedException();
}
#if FEATURE_COMPILE
/// <summary>
/// NotImplementedException with message like "The operator '{0}' is not implemented for type '{1}'"
/// </summary>
internal static Exception OperatorNotImplementedForType(object p0, object p1)
{
return NotImplemented.ByDesignWithMessage(Strings.OperatorNotImplementedForType(p0, p1));
}
#endif
/// <summary>
/// ArgumentException with message like "The constructor should not be static"
/// </summary>
internal static Exception NonStaticConstructorRequired()
{
return new ArgumentException(Strings.NonStaticConstructorRequired);
}
/// <summary>
/// InvalidOperationException with message like "Can't compile a NewExpression with a constructor declared on an abstract class"
/// </summary>
internal static Exception NonAbstractConstructorRequired()
{
return new InvalidOperationException(Strings.NonAbstractConstructorRequired);
}
}
}
| |
// 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.Diagnostics;
using System.Collections.Generic;
using System.Collections.Concurrent;
using Internal.Runtime.Augments;
namespace Internal.Reflection.Core.NonPortable
{
internal static partial class RuntimeTypeUnifier
{
//
// TypeTable mapping raw RuntimeTypeHandles (normalized or otherwise) to RuntimeTypes.
//
// Note the relationship between RuntimeTypeHandleToRuntimeTypeCache and TypeTableForTypesWithEETypes and TypeTableForEENamedGenericTypes.
// The latter two exist to enforce the creation of one Type instance per semantic identity. RuntimeTypeHandleToRuntimeTypeCache, on the other
// hand, exists for fast lookup. It hashes and compares on the raw IntPtr value of the RuntimeTypeHandle. Because Redhawk
// can and does create multiple EETypes for the same semantically identical type, the same RuntimeType can legitimately appear twice
// in this table. The factory, however, does a second lookup in the true unifying tables rather than creating the RuntimeType itself.
// Thus, the one-to-one relationship between Type reference identity and Type semantic identity is preserved.
//
private sealed class RuntimeTypeHandleToRuntimeTypeCache : ConcurrentUnifierW<RawRuntimeTypeHandleKey, RuntimeType>
{
private RuntimeTypeHandleToRuntimeTypeCache() { }
protected sealed override RuntimeType Factory(RawRuntimeTypeHandleKey rawRuntimeTypeHandleKey)
{
RuntimeTypeHandle runtimeTypeHandle = rawRuntimeTypeHandleKey.RuntimeTypeHandle;
// Desktop compat: Allows Type.GetTypeFromHandle(default(RuntimeTypeHandle)) to map to null.
if (runtimeTypeHandle.RawValue == (IntPtr)0)
return null;
EETypePtr eeType = runtimeTypeHandle.ToEETypePtr();
return TypeTableForTypesWithEETypes.Table.GetOrAdd(eeType);
}
public static RuntimeTypeHandleToRuntimeTypeCache Table = new RuntimeTypeHandleToRuntimeTypeCache();
}
//
// Type table for *all* RuntimeTypes that have an EEType associated with it (named types,
// arrays, constructed generic types.)
//
// The EEType itself serves as the dictionary key.
//
// This table's key uses semantic identity as the compare function. Thus, it properly serves to unify all semantically equivalent types
// into a single Type instance.
//
private sealed class TypeTableForTypesWithEETypes : ConcurrentUnifierW<EETypePtr, RuntimeType>
{
private TypeTableForTypesWithEETypes() { }
protected sealed override RuntimeType Factory(EETypePtr eeType)
{
RuntimeImports.RhEETypeClassification classification = RuntimeImports.RhGetEETypeClassification(eeType);
switch (classification)
{
case RuntimeImports.RhEETypeClassification.Regular:
return new RuntimeEENamedNonGenericType(eeType);
case RuntimeImports.RhEETypeClassification.Array:
return new RuntimeEEArrayType(eeType);
case RuntimeImports.RhEETypeClassification.UnmanagedPointer:
return new RuntimeEEPointerType(eeType);
case RuntimeImports.RhEETypeClassification.GenericTypeDefinition:
return new RuntimeEENamedGenericType(eeType);
case RuntimeImports.RhEETypeClassification.Generic:
// Reflection blocked constructed generic types simply pretend to not be generic
// This is reasonable, as the behavior of reflection blocked types is supposed
// to be that they expose the minimal information about a type that is necessary
// for users of Object.GetType to move from that type to a type that isn't
// reflection blocked. By not revealing that reflection blocked types are generic
// we are making it appear as if implementation detail types exposed to user code
// are all non-generic, which is theoretically possible, and by doing so
// we avoid (in all known circumstances) the very complicated case of representing
// the interfaces, base types, and generic parameter types of reflection blocked
// generic type definitions.
if (RuntimeAugments.Callbacks.IsReflectionBlocked(new RuntimeTypeHandle(eeType)))
{
return new RuntimeEENamedNonGenericType(eeType);
}
if (RuntimeImports.AreTypesAssignable(eeType, EETypePtr.EETypePtrOf<MDArrayRank2>()))
return new RuntimeEEArrayType(eeType, rank: 2);
if (RuntimeImports.AreTypesAssignable(eeType, EETypePtr.EETypePtrOf<MDArrayRank3>()))
return new RuntimeEEArrayType(eeType, rank: 3);
if (RuntimeImports.AreTypesAssignable(eeType, EETypePtr.EETypePtrOf<MDArrayRank4>()))
return new RuntimeEEArrayType(eeType, rank: 4);
return new RuntimeEEConstructedGenericType(eeType);
default:
throw new ArgumentException(SR.Arg_InvalidRuntimeTypeHandle);
}
}
public static TypeTableForTypesWithEETypes Table = new TypeTableForTypesWithEETypes();
}
//
// Type table for all SZ RuntimeArrayTypes.
// The element type serves as the dictionary key.
//
private sealed class TypeTableForArrayTypes : ConcurrentUnifierWKeyed<RuntimeType, RuntimeArrayType>
{
protected sealed override RuntimeArrayType Factory(RuntimeType elementType)
{
// We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result
// type would be an open type.
RuntimeTypeHandle runtimeTypeHandle;
RuntimeTypeHandle elementTypeHandle;
if (elementType.InternalTryGetTypeHandle(out elementTypeHandle) &&
RuntimeAugments.Callbacks.TryGetArrayTypeForElementType(elementTypeHandle, out runtimeTypeHandle))
return (RuntimeArrayType)(RuntimeTypeUnifier.GetTypeForRuntimeTypeHandle(runtimeTypeHandle));
if (elementType.IsByRef)
throw new TypeLoadException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType));
if (elementType.InternalIsGenericTypeDefinition)
throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType));
if (!elementType.InternalIsOpen)
throw RuntimeAugments.Callbacks.CreateMissingArrayTypeException(elementType, false, 1);
return new RuntimeInspectionOnlyArrayType(elementType);
}
public static TypeTableForArrayTypes Table = new TypeTableForArrayTypes();
}
//
// Type table for all MultiDim RuntimeArrayTypes.
// The element type serves as the dictionary key.
//
private sealed class TypeTableForMultiDimArrayTypes : ConcurrentUnifierWKeyed<RuntimeType, RuntimeArrayType>
{
public TypeTableForMultiDimArrayTypes(int rank)
{
_rank = rank;
}
protected sealed override RuntimeArrayType Factory(RuntimeType elementType)
{
// We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result
// type would be an open type.
RuntimeTypeHandle runtimeTypeHandle;
RuntimeTypeHandle elementTypeHandle;
if (elementType.InternalTryGetTypeHandle(out elementTypeHandle) &&
RuntimeAugments.Callbacks.TryGetMultiDimArrayTypeForElementType(elementTypeHandle, _rank, out runtimeTypeHandle))
return (RuntimeArrayType)(RuntimeTypeUnifier.GetTypeForRuntimeTypeHandle(runtimeTypeHandle));
if (elementType.IsByRef)
throw new TypeLoadException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType));
if (elementType.InternalIsGenericTypeDefinition)
throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType));
if (!elementType.InternalIsOpen)
throw RuntimeAugments.Callbacks.CreateMissingArrayTypeException(elementType, true, _rank);
return new RuntimeInspectionOnlyArrayType(elementType, _rank);
}
private int _rank;
}
//
// For the hopefully rare case of multidim arrays, we have a dictionary of dictionaries.
//
private sealed class TypeTableForMultiDimArrayTypesTable : ConcurrentUnifier<int, TypeTableForMultiDimArrayTypes>
{
protected sealed override TypeTableForMultiDimArrayTypes Factory(int rank)
{
Debug.Assert(rank > 0);
return new TypeTableForMultiDimArrayTypes(rank);
}
public static TypeTableForMultiDimArrayTypesTable Table = new TypeTableForMultiDimArrayTypesTable();
}
//
// Type table for all RuntimeByRefTypes. (There's no such thing as an EEType for a byref so all ByRef types are "inspection only.")
// The target type serves as the dictionary key.
//
private sealed class TypeTableForByRefTypes : ConcurrentUnifierWKeyed<RuntimeType, RuntimeByRefType>
{
private TypeTableForByRefTypes() { }
protected sealed override RuntimeByRefType Factory(RuntimeType targetType)
{
return new RuntimeByRefType(targetType);
}
public static TypeTableForByRefTypes Table = new TypeTableForByRefTypes();
}
//
// Type table for all RuntimePointerTypes.
// The target type serves as the dictionary key.
//
private sealed class TypeTableForPointerTypes : ConcurrentUnifierWKeyed<RuntimeType, RuntimePointerType>
{
private TypeTableForPointerTypes() { }
protected sealed override RuntimePointerType Factory(RuntimeType elementType)
{
RuntimeTypeHandle thElementType;
if (elementType.InternalTryGetTypeHandle(out thElementType))
{
RuntimeTypeHandle thForPointerType;
if (RuntimeAugments.Callbacks.TryGetPointerTypeForTargetType(thElementType, out thForPointerType))
{
Debug.Assert(thForPointerType.Classification == RuntimeImports.RhEETypeClassification.UnmanagedPointer);
return (RuntimePointerType)(RuntimeTypeUnifier.GetTypeForRuntimeTypeHandle(thForPointerType));
}
}
return new RuntimeInspectionOnlyPointerType(elementType);
}
public static TypeTableForPointerTypes Table = new TypeTableForPointerTypes();
}
//
// Type table for all constructed generic types.
//
private sealed class TypeTableForConstructedGenericTypes : ConcurrentUnifierWKeyed<ConstructedGenericTypeKey, RuntimeConstructedGenericType>
{
private TypeTableForConstructedGenericTypes() { }
protected sealed override RuntimeConstructedGenericType Factory(ConstructedGenericTypeKey key)
{
// We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result
// type would be an open type.
RuntimeTypeHandle runtimeTypeHandle;
if (TryFindRuntimeTypeHandleForConstructedGenericType(key, out runtimeTypeHandle))
return (RuntimeConstructedGenericType)(RuntimeTypeUnifier.GetTypeForRuntimeTypeHandle(runtimeTypeHandle));
bool atLeastOneOpenType = false;
foreach (RuntimeType genericTypeArgument in key.GenericTypeArguments)
{
if (genericTypeArgument.IsByRef || genericTypeArgument.InternalIsGenericTypeDefinition)
throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidTypeArgument, genericTypeArgument));
if (genericTypeArgument.InternalIsOpen)
atLeastOneOpenType = true;
}
if (!atLeastOneOpenType)
throw RuntimeAugments.Callbacks.CreateMissingConstructedGenericTypeException(key.GenericTypeDefinition, key.GenericTypeArguments);
return new RuntimeInspectionOnlyConstructedGenericType(key.GenericTypeDefinition, key.GenericTypeArguments);
}
private bool TryFindRuntimeTypeHandleForConstructedGenericType(ConstructedGenericTypeKey key, out RuntimeTypeHandle runtimeTypeHandle)
{
runtimeTypeHandle = default(RuntimeTypeHandle);
RuntimeTypeHandle genericTypeDefinitionHandle = default(RuntimeTypeHandle);
if (!key.GenericTypeDefinition.InternalTryGetTypeHandle(out genericTypeDefinitionHandle))
return false;
if (RuntimeAugments.Callbacks.IsReflectionBlocked(genericTypeDefinitionHandle))
return false;
RuntimeType[] genericTypeArguments = key.GenericTypeArguments;
RuntimeTypeHandle[] genericTypeArgumentHandles = new RuntimeTypeHandle[genericTypeArguments.Length];
for (int i = 0; i < genericTypeArguments.Length; i++)
{
if (!genericTypeArguments[i].InternalTryGetTypeHandle(out genericTypeArgumentHandles[i]))
return false;
}
if (!RuntimeAugments.Callbacks.TryGetConstructedGenericTypeForComponents(genericTypeDefinitionHandle, genericTypeArgumentHandles, out runtimeTypeHandle))
return false;
return true;
}
public static TypeTableForConstructedGenericTypes Table = new TypeTableForConstructedGenericTypes();
}
}
}
| |
/*The MIT License (MIT)
Copyright (c) 2014 PMU Staff
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Server.Scripting;
using Server.IO;
using Server.Players;
using System.Xml;
using Server;
using Server.Network;
using Server.Maps;
using PMU.DatabaseConnector.MySql;
using PMU.DatabaseConnector;
using Server.Database;
namespace Script
{
public class exPlayer : IExPlayer
{
public Client Client { get; set; }
public string SpawnMap { get; set; }
public int SpawnX { get; set; }
public int SpawnY { get; set; }
public int DungeonID { get; set; } //is this being used?
public int DungeonX { get; set; }
public int DungeonY { get; set; }
public int DungeonMaxX { get; set; }
public int DungeonMaxY { get; set; }
public int DungeonSeed { get; set; }
public PitchBlackAbyss.Room[,] DungeonMap { get; set; } //note: not saved to DB, re-made each time needed
public bool DungeonGenerated { get; set; }
public bool FirstMapLoaded { get; set; }
public string HousingCenterMap { get; set; }
public int HousingCenterX { get; set; }
public int HousingCenterY { get; set; }
public string PlazaEntranceMap { get; set; }
public int PlazaEntranceX { get; set; }
public int PlazaEntranceY { get; set; }
//Move statuses
//public bool[] MoveUsed { get; set; } ~may not need this; Last Resort, the only move that references this, can be re-coded to be based on moves with PP run out.
public int LastMoveUsed { get; set; }
public int TimesUsed { get; set; }
public bool VoltorbFlip { get; set; }
public bool WillBeCascoon { get; set; }
public bool StoryEnabled { get; set; }
public bool AnniversaryEnabled {
get {
return true;
}
}
//Buffs ~obsolete
//public int StrBuffCount { get; set; }
//public int DefBuffCount { get; set; }
//public int SpeedBuffCount { get; set; }
//public int SpclAtkBuffCount { get; set; }
//public int SpclDefBuffCount { get; set; }
//public int ToxicDamage { get; set; }
//Transform
//Aqua Ring
//Wish
//Counter
public bool EvolutionActive { get; set; }
public bool PermaMuted { get; set; }
public bool DamageTurn { get; set; }
#region CTF Vars
public bool InCTF;
public CTF.Teams CTFSide;
public CTF.PlayerState CTFState;
#endregion
#region Snowball Game Vars
public bool InSnowballGame;
public SnowballGame.Teams SnowballGameSide;
public int SnowballGameLives;
public SnowballGame SnowballGameInstance;
#endregion
#region Electrostasis Tower
public int ElectrolockCharge { get; set; }
public int ElectrolockLevel { get; set; }
public List<int> ElectrolockSublevel { get; set; }
public List<string> ElectrolockSublevelTriggersActive { get; set; }
#endregion
public static exPlayer Get(Client client) {
exPlayer exPlayer = client.Player.ExPlayer as exPlayer;
if (exPlayer == null) {
client.Player.ExPlayer = new exPlayer(client);
exPlayer = client.Player.ExPlayer as exPlayer;
exPlayer.Load();
}
return exPlayer;
}
public exPlayer(Client client) {
Client = client;
ElectrolockSublevel = new List<int>();
ElectrolockSublevelTriggersActive = new List<string>();
}
public void Load() {
string query = "SELECT script_extras_general.SpawnMap, script_extras_general.SpawnX, script_extras_general.SpawnY, " +
"script_extras_general.DungeonID, script_extras_general.DungeonX, script_extras_general.DungeonY, " +
"script_extras_general.TurnsTaken, script_extras_general.EvolutionActive, script_extras_general.Permamuted, " +
"script_extras_general.HousingCenterMap, script_extras_general.HousingCenterX, script_extras_general.HousingCenterY, " +
"script_extras_general.DungeonMaxX, script_extras_general.DungeonMaxY, script_extras_general.DungeonSeed, " +
"script_extras_general.PlazaEntranceMap, script_extras_general.PlazaEntranceX, script_extras_general.PlazaEntranceY " +
"FROM script_extras_general " +
"WHERE script_extras_general.CharID = \'" + Client.Player.CharID + "\'";
DataColumnCollection row = null;
using (DatabaseConnection dbConnection = new DatabaseConnection(DatabaseID.Players)) {
row = dbConnection.Database.RetrieveRow(query);
}
if (row != null) {
SpawnMap = row["SpawnMap"].ValueString;
SpawnX = row["SpawnX"].ValueString.ToInt();
SpawnY = row["SpawnY"].ValueString.ToInt();
DungeonID = row["DungeonID"].ValueString.ToInt();
DungeonX = row["DungeonX"].ValueString.ToInt();
DungeonY = row["DungeonY"].ValueString.ToInt();
//TurnsTaken = row["TurnsTaken"].ValueString.ToInt();
EvolutionActive = row["EvolutionActive"].ValueString.ToBool();
PermaMuted = row["Permamuted"].ValueString.ToBool();
HousingCenterMap = row["HousingCenterMap"].ValueString;
HousingCenterX = row["HousingCenterX"].ValueString.ToInt();
HousingCenterY = row["HousingCenterY"].ValueString.ToInt();
DungeonMaxX = row["DungeonMaxX"].ValueString.ToInt();
DungeonMaxY = row["DungeonMaxY"].ValueString.ToInt();
DungeonSeed = row["DungeonSeed"].ValueString.ToInt();
PlazaEntranceMap = row["PlazaEntranceMap"].ValueString;
PlazaEntranceX = row["PlazaEntranceX"].ValueString.ToInt();
PlazaEntranceY = row["PlazaEntranceY"].ValueString.ToInt();
}
DungeonGenerated = false;
DungeonMap = new PitchBlackAbyss.Room[1,1];
}
public void Save() {
using (DatabaseConnection dbConnection = new DatabaseConnection(DatabaseID.Players)) {
dbConnection.Database.UpdateOrInsert("script_extras_general", new IDataColumn[] {
dbConnection.Database.CreateColumn(true, "CharID", Client.Player.CharID),
dbConnection.Database.CreateColumn(false, "SpawnMap", SpawnMap),
dbConnection.Database.CreateColumn(false, "SpawnX", SpawnX.ToString()),
dbConnection.Database.CreateColumn(false, "SpawnY", SpawnY.ToString()),
dbConnection.Database.CreateColumn(false, "DungeonID", DungeonID.ToString()),
dbConnection.Database.CreateColumn(false, "DungeonX", DungeonX.ToString()),
dbConnection.Database.CreateColumn(false, "DungeonY", DungeonY.ToString()),
//dbConnection.Database.CreateColumn(false, "TurnsTaken", TurnsTaken.ToString()),
dbConnection.Database.CreateColumn(false, "EvolutionActive", EvolutionActive.ToIntString()),
dbConnection.Database.CreateColumn(false, "Permamuted", PermaMuted.ToIntString()),
dbConnection.Database.CreateColumn(false, "HousingCenterMap", HousingCenterMap),
dbConnection.Database.CreateColumn(false, "HousingCenterX", HousingCenterX.ToString()),
dbConnection.Database.CreateColumn(false, "HousingCenterY", HousingCenterY.ToString()),
dbConnection.Database.CreateColumn(false, "DungeonMaxX", DungeonMaxX.ToString()),
dbConnection.Database.CreateColumn(false, "DungeonMaxY", DungeonMaxY.ToString()),
dbConnection.Database.CreateColumn(false, "DungeonSeed", DungeonSeed.ToString()),
dbConnection.Database.CreateColumn(false, "PlazaEntranceMap", PlazaEntranceMap),
dbConnection.Database.CreateColumn(false, "PlazaEntranceX", PlazaEntranceX.ToString()),
dbConnection.Database.CreateColumn(false, "PlazaEntranceY", PlazaEntranceY.ToString())
});
}
}
public bool VerifySpawnPoint() {
//Messenger.PlayerMsg(Client, "1", Text.Black);
try {
if (Client.Player.MapID == MapManager.GenerateMapID(469) || Client.Player.MapID == MapManager.GenerateMapID(470)) {
if (Client.Player.HasItem(152) > 0) {
Client.Player.TakeItem(152, 1);
}
}
return IsValidPlayerSpawn(SpawnMap);
} catch (Exception ex) {
Messenger.AdminMsg("Error: VerifySpawnPoint", Text.Black);
return false;
}
}
public bool IsValidPlayerSpawn(string mapID) {
//Messenger.PlayerMsg(Client, "2", Text.Black);
if (string.IsNullOrEmpty(mapID)) {
return false;
}
IMap map = MapManager.RetrieveMap(mapID);
if ((map.MapType == Enums.MapType.House && ((House)map).OwnerID == Client.Player.CharID) || mapID == Main.Crossroads || mapID == MapManager.GenerateMapID(412) || mapID == MapManager.GenerateMapID(478) || mapID == MapManager.GenerateMapID(878) || mapID == MapManager.GenerateMapID(1035)) {
return true;
} else {
return false;
}
}
public void WarpToSpawn(bool playSound) {
if (VerifySpawnPoint() == true) {
Messenger.PlayerWarp(Client, MapManager.RetrieveMap(SpawnMap), SpawnX, SpawnY);
//Messenger.AdminMsg(Client.Player.Name + " warped to spawn with X:" + SpawnX + ", Y:" + SpawnY, Text.Black);
} else {
SpawnMap = Main.Crossroads;
SpawnX = 25;
SpawnY = 25;
Messenger.PlayerWarp(Client, Main.Crossroads, 25, 25, true, playSound);
}
}
public void UnloadCTF() {
InCTF = false;
CTFSide = CTF.Teams.Red;
CTFState = CTF.PlayerState.Free;
}
public void UnloadSnowballGame() {
InSnowballGame = false;
SnowballGameLives = 0;
SnowballGameInstance = null;
SnowballGameSide = SnowballGame.Teams.Green;
}
}
}
| |
//
// ____ _ __ __ _ _
// | _ \| |__ | \/ | ___| |_ __ _| |
// | | | | '_ \| |\/| |/ _ \ __/ _` | |
// | |_| | |_) | | | | __/ || (_| | |
// |____/|_.__/|_| |_|\___|\__\__,_|_|
//
// Auto-generated from main on 2016-10-30 02:23:51Z.
// Please visit http://code.google.com/p/dblinq2007/ for more information.
//
using System;
using System.ComponentModel;
using System.Data;
#if MONO_STRICT
using System.Data.Linq;
#else // MONO_STRICT
using DbLinq.Data.Linq;
using DbLinq.Vendor;
#endif // MONO_STRICT
using System.Data.Linq.Mapping;
using System.Diagnostics;
public partial class Main : DataContext
{
#region Extensibility Method Declarations
partial void OnCreated();
#endregion
public Main(string connectionString) :
base(connectionString)
{
this.OnCreated();
}
public Main(string connection, MappingSource mappingSource) :
base(connection, mappingSource)
{
this.OnCreated();
}
public Main(IDbConnection connection, MappingSource mappingSource) :
base(connection, mappingSource)
{
this.OnCreated();
}
public Table<Chapters> Chapters
{
get
{
return this.GetTable<Chapters>();
}
}
public Table<Lessons> Lessons
{
get
{
return this.GetTable<Lessons>();
}
}
public Table<Questions> Questions
{
get
{
return this.GetTable<Questions>();
}
}
public Table<Subjects> Subjects
{
get
{
return this.GetTable<Subjects>();
}
}
}
#region Start MONO_STRICT
#if MONO_STRICT
public partial class Main
{
public Main(IDbConnection connection) :
base(connection)
{
this.OnCreated();
}
}
#region End MONO_STRICT
#endregion
#else // MONO_STRICT
public partial class Main
{
public Main(IDbConnection connection) :
base(connection, new DbLinq.Sqlite.SqliteVendor())
{
this.OnCreated();
}
public Main(IDbConnection connection, IVendor sqlDialect) :
base(connection, sqlDialect)
{
this.OnCreated();
}
public Main(IDbConnection connection, MappingSource mappingSource, IVendor sqlDialect) :
base(connection, mappingSource, sqlDialect)
{
this.OnCreated();
}
}
#region End Not MONO_STRICT
#endregion
#endif // MONO_STRICT
#endregion
[Table(Name="main.Chapters")]
public partial class Chapters : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
{
private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");
private System.Nullable<int> _id;
private string _name;
private System.Nullable<int> _subjectID;
private EntitySet<Lessons> _lessons;
private EntityRef<Subjects> _subjects = new EntityRef<Subjects>();
#region Extensibility Method Declarations
partial void OnCreated();
partial void OnIDChanged();
partial void OnIDChanging(System.Nullable<int> value);
partial void OnNameChanged();
partial void OnNameChanging(string value);
partial void OnSubjectIDChanged();
partial void OnSubjectIDChanging(System.Nullable<int> value);
#endregion
public Chapters()
{
_lessons = new EntitySet<Lessons>(new Action<Lessons>(this.Lessons_Attach), new Action<Lessons>(this.Lessons_Detach));
this.OnCreated();
}
[Column(Storage="_id", Name="ID", DbType="integer identity", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public System.Nullable<int> ID
{
get
{
return this._id;
}
set
{
if ((_id != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._id = value;
this.SendPropertyChanged("ID");
this.OnIDChanged();
}
}
}
[Column(Storage="_name", Name="Name", DbType="nvarchar(50)", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Name
{
get
{
return this._name;
}
set
{
if (((_name == value)
== false))
{
this.OnNameChanging(value);
this.SendPropertyChanging();
this._name = value;
this.SendPropertyChanged("Name");
this.OnNameChanged();
}
}
}
[Column(Storage="_subjectID", Name="SubjectID", DbType="integer", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public System.Nullable<int> SubjectID
{
get
{
return this._subjectID;
}
set
{
if ((_subjectID != value))
{
if (_subjects.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnSubjectIDChanging(value);
this.SendPropertyChanging();
this._subjectID = value;
this.SendPropertyChanged("SubjectID");
this.OnSubjectIDChanged();
}
}
}
#region Children
[Association(Storage="_lessons", OtherKey="ChaptersID", ThisKey="ID", Name="fk_Lessons_0")]
[DebuggerNonUserCode()]
public EntitySet<Lessons> Lessons
{
get
{
return this._lessons;
}
set
{
this._lessons = value;
}
}
#endregion
#region Parents
[Association(Storage="_subjects", OtherKey="ID", ThisKey="SubjectID", Name="fk_Chapters_0", IsForeignKey=true)]
[DebuggerNonUserCode()]
public Subjects Subjects
{
get
{
return this._subjects.Entity;
}
set
{
if (((this._subjects.Entity == value)
== false))
{
if ((this._subjects.Entity != null))
{
Subjects previousSubjects = this._subjects.Entity;
this._subjects.Entity = null;
previousSubjects.Chapters.Remove(this);
}
this._subjects.Entity = value;
if ((value != null))
{
value.Chapters.Add(this);
_subjectID = value.ID;
}
else
{
_subjectID = null;
}
}
}
}
#endregion
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;
if ((h != null))
{
h(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(string propertyName)
{
System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;
if ((h != null))
{
h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
#region Attachment handlers
private void Lessons_Attach(Lessons entity)
{
this.SendPropertyChanging();
entity.Chapters = this;
}
private void Lessons_Detach(Lessons entity)
{
this.SendPropertyChanging();
entity.Chapters = null;
}
#endregion
}
[Table(Name="main.Lessons")]
public partial class Lessons : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
{
private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");
private System.Nullable<int> _chaptersID;
private string _description;
private System.Nullable<int> _id;
private string _name;
private EntitySet<Questions> _questions;
private EntityRef<Chapters> _chapters = new EntityRef<Chapters>();
#region Extensibility Method Declarations
partial void OnCreated();
partial void OnChaptersIDChanged();
partial void OnChaptersIDChanging(System.Nullable<int> value);
partial void OnDescriptionChanged();
partial void OnDescriptionChanging(string value);
partial void OnIDChanged();
partial void OnIDChanging(System.Nullable<int> value);
partial void OnNameChanged();
partial void OnNameChanging(string value);
#endregion
public Lessons()
{
_questions = new EntitySet<Questions>(new Action<Questions>(this.Questions_Attach), new Action<Questions>(this.Questions_Detach));
this.OnCreated();
}
[Column(Storage="_chaptersID", Name="ChaptersID", DbType="integer", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public System.Nullable<int> ChaptersID
{
get
{
return this._chaptersID;
}
set
{
if ((_chaptersID != value))
{
if (_chapters.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnChaptersIDChanging(value);
this.SendPropertyChanging();
this._chaptersID = value;
this.SendPropertyChanged("ChaptersID");
this.OnChaptersIDChanged();
}
}
}
[Column(Storage="_description", Name="Description", DbType="nvarchar(1000)", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Description
{
get
{
return this._description;
}
set
{
if (((_description == value)
== false))
{
this.OnDescriptionChanging(value);
this.SendPropertyChanging();
this._description = value;
this.SendPropertyChanged("Description");
this.OnDescriptionChanged();
}
}
}
[Column(Storage="_id", Name="ID", DbType="integer identity", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public System.Nullable<int> ID
{
get
{
return this._id;
}
set
{
if ((_id != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._id = value;
this.SendPropertyChanged("ID");
this.OnIDChanged();
}
}
}
[Column(Storage="_name", Name="Name", DbType="nvarchar(50)", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Name
{
get
{
return this._name;
}
set
{
if (((_name == value)
== false))
{
this.OnNameChanging(value);
this.SendPropertyChanging();
this._name = value;
this.SendPropertyChanged("Name");
this.OnNameChanged();
}
}
}
#region Children
[Association(Storage="_questions", OtherKey="LessonID", ThisKey="ID", Name="fk_Questions_0")]
[DebuggerNonUserCode()]
public EntitySet<Questions> Questions
{
get
{
return this._questions;
}
set
{
this._questions = value;
}
}
#endregion
#region Parents
[Association(Storage="_chapters", OtherKey="ID", ThisKey="ChaptersID", Name="fk_Lessons_0", IsForeignKey=true)]
[DebuggerNonUserCode()]
public Chapters Chapters
{
get
{
return this._chapters.Entity;
}
set
{
if (((this._chapters.Entity == value)
== false))
{
if ((this._chapters.Entity != null))
{
Chapters previousChapters = this._chapters.Entity;
this._chapters.Entity = null;
previousChapters.Lessons.Remove(this);
}
this._chapters.Entity = value;
if ((value != null))
{
value.Lessons.Add(this);
_chaptersID = value.ID;
}
else
{
_chaptersID = null;
}
}
}
}
#endregion
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;
if ((h != null))
{
h(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(string propertyName)
{
System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;
if ((h != null))
{
h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
#region Attachment handlers
private void Questions_Attach(Questions entity)
{
this.SendPropertyChanging();
entity.Lessons = this;
}
private void Questions_Detach(Questions entity)
{
this.SendPropertyChanging();
entity.Lessons = null;
}
#endregion
}
[Table(Name="main.Questions")]
public partial class Questions : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
{
private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");
private string _ans1;
private string _ans2;
private string _ans3;
private string _ans4;
private System.Nullable<int> _correctAns;
private System.Nullable<int> _id;
private System.Nullable<int> _lessonID;
private string _question;
private System.Nullable<int> _type;
private EntityRef<Lessons> _lessons = new EntityRef<Lessons>();
#region Extensibility Method Declarations
partial void OnCreated();
partial void OnAns1Changed();
partial void OnAns1Changing(string value);
partial void OnAns2Changed();
partial void OnAns2Changing(string value);
partial void OnAns3Changed();
partial void OnAns3Changing(string value);
partial void OnAns4Changed();
partial void OnAns4Changing(string value);
partial void OnCorrectAnsChanged();
partial void OnCorrectAnsChanging(System.Nullable<int> value);
partial void OnIDChanged();
partial void OnIDChanging(System.Nullable<int> value);
partial void OnLessonIDChanged();
partial void OnLessonIDChanging(System.Nullable<int> value);
partial void OnQuestionChanged();
partial void OnQuestionChanging(string value);
partial void OnTypeChanged();
partial void OnTypeChanging(System.Nullable<int> value);
#endregion
public Questions()
{
this.OnCreated();
}
[Column(Storage="_ans1", Name="Ans1", DbType="nvarchar(50)", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Ans1
{
get
{
return this._ans1;
}
set
{
if (((_ans1 == value)
== false))
{
this.OnAns1Changing(value);
this.SendPropertyChanging();
this._ans1 = value;
this.SendPropertyChanged("Ans1");
this.OnAns1Changed();
}
}
}
[Column(Storage="_ans2", Name="Ans2", DbType="nvarchar(50)", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Ans2
{
get
{
return this._ans2;
}
set
{
if (((_ans2 == value)
== false))
{
this.OnAns2Changing(value);
this.SendPropertyChanging();
this._ans2 = value;
this.SendPropertyChanged("Ans2");
this.OnAns2Changed();
}
}
}
[Column(Storage="_ans3", Name="Ans3", DbType="nvarchar(50)", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Ans3
{
get
{
return this._ans3;
}
set
{
if (((_ans3 == value)
== false))
{
this.OnAns3Changing(value);
this.SendPropertyChanging();
this._ans3 = value;
this.SendPropertyChanged("Ans3");
this.OnAns3Changed();
}
}
}
[Column(Storage="_ans4", Name="Ans4", DbType="nvarchar(50)", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Ans4
{
get
{
return this._ans4;
}
set
{
if (((_ans4 == value)
== false))
{
this.OnAns4Changing(value);
this.SendPropertyChanging();
this._ans4 = value;
this.SendPropertyChanged("Ans4");
this.OnAns4Changed();
}
}
}
[Column(Storage="_correctAns", Name="CorrectAns", DbType="int", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public System.Nullable<int> CorrectAns
{
get
{
return this._correctAns;
}
set
{
if ((_correctAns != value))
{
this.OnCorrectAnsChanging(value);
this.SendPropertyChanging();
this._correctAns = value;
this.SendPropertyChanged("CorrectAns");
this.OnCorrectAnsChanged();
}
}
}
[Column(Storage="_id", Name="ID", DbType="integer identity", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public System.Nullable<int> ID
{
get
{
return this._id;
}
set
{
if ((_id != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._id = value;
this.SendPropertyChanged("ID");
this.OnIDChanged();
}
}
}
[Column(Storage="_lessonID", Name="LessonID", DbType="integer", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public System.Nullable<int> LessonID
{
get
{
return this._lessonID;
}
set
{
if ((_lessonID != value))
{
if (_lessons.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnLessonIDChanging(value);
this.SendPropertyChanging();
this._lessonID = value;
this.SendPropertyChanged("LessonID");
this.OnLessonIDChanged();
}
}
}
[Column(Storage="_question", Name="Question", DbType="nvarchar(200)", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Question
{
get
{
return this._question;
}
set
{
if (((_question == value)
== false))
{
this.OnQuestionChanging(value);
this.SendPropertyChanging();
this._question = value;
this.SendPropertyChanged("Question");
this.OnQuestionChanged();
}
}
}
[Column(Storage="_type", Name="type", DbType="integer", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public System.Nullable<int> Type
{
get
{
return this._type;
}
set
{
if ((_type != value))
{
this.OnTypeChanging(value);
this.SendPropertyChanging();
this._type = value;
this.SendPropertyChanged("Type");
this.OnTypeChanged();
}
}
}
#region Parents
[Association(Storage="_lessons", OtherKey="ID", ThisKey="LessonID", Name="fk_Questions_0", IsForeignKey=true)]
[DebuggerNonUserCode()]
public Lessons Lessons
{
get
{
return this._lessons.Entity;
}
set
{
if (((this._lessons.Entity == value)
== false))
{
if ((this._lessons.Entity != null))
{
Lessons previousLessons = this._lessons.Entity;
this._lessons.Entity = null;
previousLessons.Questions.Remove(this);
}
this._lessons.Entity = value;
if ((value != null))
{
value.Questions.Add(this);
_lessonID = value.ID;
}
else
{
_lessonID = null;
}
}
}
}
#endregion
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;
if ((h != null))
{
h(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(string propertyName)
{
System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;
if ((h != null))
{
h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[Table(Name="main.Subjects")]
public partial class Subjects : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
{
private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");
private System.Nullable<int> _id;
private string _name;
private EntitySet<Chapters> _chapters;
#region Extensibility Method Declarations
partial void OnCreated();
partial void OnIDChanged();
partial void OnIDChanging(System.Nullable<int> value);
partial void OnNameChanged();
partial void OnNameChanging(string value);
#endregion
public Subjects()
{
_chapters = new EntitySet<Chapters>(new Action<Chapters>(this.Chapters_Attach), new Action<Chapters>(this.Chapters_Detach));
this.OnCreated();
}
[Column(Storage="_id", Name="ID", DbType="integer identity", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public System.Nullable<int> ID
{
get
{
return this._id;
}
set
{
if ((_id != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._id = value;
this.SendPropertyChanged("ID");
this.OnIDChanged();
}
}
}
[Column(Storage="_name", Name="Name", DbType="nvarchar(50)", AutoSync=AutoSync.Never)]
[DebuggerNonUserCode()]
public string Name
{
get
{
return this._name;
}
set
{
if (((_name == value)
== false))
{
this.OnNameChanging(value);
this.SendPropertyChanging();
this._name = value;
this.SendPropertyChanged("Name");
this.OnNameChanged();
}
}
}
#region Children
[Association(Storage="_chapters", OtherKey="SubjectID", ThisKey="ID", Name="fk_Chapters_0")]
[DebuggerNonUserCode()]
public EntitySet<Chapters> Chapters
{
get
{
return this._chapters;
}
set
{
this._chapters = value;
}
}
#endregion
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;
if ((h != null))
{
h(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(string propertyName)
{
System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;
if ((h != null))
{
h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
#region Attachment handlers
private void Chapters_Attach(Chapters entity)
{
this.SendPropertyChanging();
entity.Subjects = this;
}
private void Chapters_Detach(Chapters entity)
{
this.SendPropertyChanging();
entity.Subjects = null;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using ModestTree;
using Zenject.Internal;
using System.Linq;
using TypeExtensions = ModestTree.TypeExtensions;
#if !NOT_UNITY3D
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
#endif
namespace Zenject
{
internal static class BindingUtil
{
#if !NOT_UNITY3D
public static void AssertIsValidPrefab(UnityEngine.Object prefab)
{
Assert.That(!ZenUtilInternal.IsNull(prefab), "Received null prefab during bind command");
#if UNITY_EDITOR
// Unfortunately we can't do this check because asset bundles return PrefabType.None here
// as discussed here: https://github.com/modesttree/Zenject/issues/269#issuecomment-323419408
//Assert.That(PrefabUtility.GetPrefabType(prefab) == PrefabType.Prefab,
//"Expected prefab but found game object with name '{0}' during bind command", prefab.name);
#endif
}
public static void AssertIsValidGameObject(GameObject gameObject)
{
Assert.That(!ZenUtilInternal.IsNull(gameObject), "Received null game object during bind command");
#if UNITY_EDITOR
// Unfortunately we can't do this check because asset bundles return PrefabType.None here
// as discussed here: https://github.com/modesttree/Zenject/issues/269#issuecomment-323419408
//Assert.That(PrefabUtility.GetPrefabType(gameObject) != PrefabType.Prefab,
//"Expected game object but found prefab instead with name '{0}' during bind command", gameObject.name);
#endif
}
public static void AssertIsNotComponent(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotComponent(type);
}
}
public static void AssertIsNotComponent<T>()
{
AssertIsNotComponent(typeof(T));
}
public static void AssertIsNotComponent(Type type)
{
Assert.That(!type.DerivesFrom(typeof(Component)),
"Invalid type given during bind command. Expected type '{0}' to NOT derive from UnityEngine.Component", type);
}
public static void AssertDerivesFromUnityObject(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertDerivesFromUnityObject(type);
}
}
public static void AssertDerivesFromUnityObject<T>()
{
AssertDerivesFromUnityObject(typeof(T));
}
public static void AssertDerivesFromUnityObject(Type type)
{
Assert.That(type.DerivesFrom<UnityEngine.Object>(),
"Invalid type given during bind command. Expected type '{0}' to derive from UnityEngine.Object", type);
}
public static void AssertTypesAreNotComponents(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotComponent(type);
}
}
public static void AssertIsValidResourcePath(string resourcePath)
{
Assert.That(!string.IsNullOrEmpty(resourcePath), "Null or empty resource path provided");
// We'd like to validate the path here but unfortunately there doesn't appear to be
// a way to do this besides loading it
}
public static void AssertIsInterfaceOrScriptableObject(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsInterfaceOrScriptableObject(type);
}
}
public static void AssertIsInterfaceOrScriptableObject<T>()
{
AssertIsInterfaceOrScriptableObject(typeof(T));
}
public static void AssertIsInterfaceOrScriptableObject(Type type)
{
Assert.That(type.DerivesFrom(typeof(ScriptableObject)) || type.IsInterface(),
"Invalid type given during bind command. Expected type '{0}' to either derive from UnityEngine.ScriptableObject or be an interface", type);
}
public static void AssertIsInterfaceOrComponent(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsInterfaceOrComponent(type);
}
}
public static void AssertIsInterfaceOrComponent<T>()
{
AssertIsInterfaceOrComponent(typeof(T));
}
public static void AssertIsInterfaceOrComponent(Type type)
{
Assert.That(type.DerivesFrom(typeof(Component)) || type.IsInterface(),
"Invalid type given during bind command. Expected type '{0}' to either derive from UnityEngine.Component or be an interface", type);
}
public static void AssertIsComponent(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsComponent(type);
}
}
public static void AssertIsComponent<T>()
{
AssertIsComponent(typeof(T));
}
public static void AssertIsComponent(Type type)
{
Assert.That(type.DerivesFrom(typeof(Component)),
"Invalid type given during bind command. Expected type '{0}' to derive from UnityEngine.Component", type);
}
#else
public static void AssertTypesAreNotComponents(IEnumerable<Type> types)
{
}
public static void AssertIsNotComponent(Type type)
{
}
public static void AssertIsNotComponent<T>()
{
}
public static void AssertIsNotComponent(IEnumerable<Type> types)
{
}
#endif
public static void AssertTypesAreNotAbstract(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotAbstract(type);
}
}
public static void AssertIsNotAbstract(IEnumerable<Type> types)
{
foreach (var type in types)
{
AssertIsNotAbstract(type);
}
}
public static void AssertIsNotAbstract<T>()
{
AssertIsNotAbstract(typeof(T));
}
public static void AssertIsNotAbstract(Type type)
{
Assert.That(!type.IsAbstract(),
"Invalid type given during bind command. Expected type '{0}' to not be abstract.", type);
}
public static void AssertIsDerivedFromType(Type concreteType, Type parentType)
{
#if !(UNITY_WSA && ENABLE_DOTNET)
// TODO: Is it possible to do this on WSA?
Assert.That(parentType.IsOpenGenericType() == concreteType.IsOpenGenericType(),
"Invalid type given during bind command. Expected type '{0}' and type '{1}' to both either be open generic types or not open generic types", parentType, concreteType);
if (parentType.IsOpenGenericType())
{
Assert.That(concreteType.IsOpenGenericType());
Assert.That(TypeExtensions.IsAssignableToGenericType(concreteType, parentType),
"Invalid type given during bind command. Expected open generic type '{0}' to derive from open generic type '{1}'", concreteType, parentType);
}
else
#endif
{
Assert.That(concreteType.DerivesFromOrEqual(parentType),
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'", concreteType, parentType.Name());
}
}
public static void AssertConcreteTypeListIsNotEmpty(IEnumerable<Type> concreteTypes)
{
Assert.That(concreteTypes.Count() >= 1,
"Must supply at least one concrete type to the current binding");
}
public static void AssertIsDerivedFromTypes(
IEnumerable<Type> concreteTypes, IEnumerable<Type> parentTypes, InvalidBindResponses invalidBindResponse)
{
if (invalidBindResponse == InvalidBindResponses.Assert)
{
AssertIsDerivedFromTypes(concreteTypes, parentTypes);
}
else
{
Assert.IsEqual(invalidBindResponse, InvalidBindResponses.Skip);
}
}
public static void AssertIsDerivedFromTypes(IEnumerable<Type> concreteTypes, IEnumerable<Type> parentTypes)
{
foreach (var concreteType in concreteTypes)
{
AssertIsDerivedFromTypes(concreteType, parentTypes);
}
}
public static void AssertIsDerivedFromTypes(Type concreteType, IEnumerable<Type> parentTypes)
{
foreach (var parentType in parentTypes)
{
AssertIsDerivedFromType(concreteType, parentType);
}
}
public static void AssertInstanceDerivesFromOrEqual(object instance, IEnumerable<Type> parentTypes)
{
if (!ZenUtilInternal.IsNull(instance))
{
foreach (var baseType in parentTypes)
{
AssertInstanceDerivesFromOrEqual(instance, baseType);
}
}
}
public static void AssertInstanceDerivesFromOrEqual(object instance, Type baseType)
{
if (!ZenUtilInternal.IsNull(instance))
{
Assert.That(instance.GetType().DerivesFromOrEqual(baseType),
"Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'", instance.GetType(), baseType.Name());
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics.Contracts;
/*
The algorithm is taken from book "Combinatorial Optimization. Algorithms and Complexity"
Christos H. Papadimitriou, Kenneth Steigitz
*/
namespace Microsoft.Glee.Optimization
{
/// <summary>
/// Solves the general liner program but always looking for minimum
/// </summary>
public class LP : LinearProgramInterface
{
[ContractInvariantMethod]
void ObjectInvariant()
{
// Commenting it out as it kill performances
// Contract.Invariant(this.status != Status.Infeasible || this.constraintCoeffs.Count > 0);
Contract.Invariant(this.knownValues != null);
Contract.Invariant(this.costsOfknownValues != null);
Contract.Invariant(this.constraintCoeffs.Count == this.relations.Count);
Contract.Invariant(this.constraintCoeffs.Count == this.rightSides.Count);
}
public double Epsilon
{
get { return epsilon; }
set { epsilon = value; }
}
readonly SortedDictionary<int, double> knownValues = new SortedDictionary<int, double>();
readonly Dictionary<int, double> costsOfknownValues = new Dictionary<int, double>();
SortedDictionary<int, double> KnownValues
{
get { return knownValues; }
}
int[] forbiddenPairs;
public int[] ForbiddenPairs
{
get { return forbiddenPairs; }
set { forbiddenPairs = value; }
}
internal double epsilon = 1.0E-8;
int nVars;
int nArtificials;
double maxVal = 1;
readonly private List<double[]> constraintCoeffs = new List<double[]>();
readonly internal List<Relation> relations = new List<Relation>();
readonly internal List<double> rightSides = new List<double>();
int nSlaksAndSurpluses;
#if DEBUGGLEE
public
#else
internal
#endif
double[] costs;
public bool CostsAreSet
{
get
{
return this.costs != null;
}
}
Microsoft.Glee.Optimization.Tableau tableau;
Solver solver;
/// <summary>
///
/// </summary>
/// <param name="lookForZeroColumns">the solver will try to eliminate variables that never appears with non-zero coefficients</param>
public LP(bool lookForZeroColumns)
{
this.LookForZeroColumns = lookForZeroColumns;
}
public LP()
: this(false)
{
}
#if DEBUGGLEE
static public LP FromFile(string fileName)
{
StreamReader sr = new StreamReader(fileName);
LP lp = new LP(false);
int nvars = Int32.Parse(sr.ReadLine());
double[] costs = new double[nvars];
string[] cw = sr.ReadLine().Split(new char[] { ' ' });
for (int i = 0; i < nvars; i++)
costs[i] = Double.Parse(cw[i]);
lp.InitCosts(costs);
sr.ReadLine();//swallow the line "constraints"
int nConstraints = Int32.Parse(sr.ReadLine());
for (int i = 0; i < nConstraints; i++)
{
string constr = sr.ReadLine();
string[] words = constr.Split(new char[] { ' ' });
List<string> ws = new List<string>();
foreach (string s in words)
{
if (s != "")
ws.Add(s);
}
double[] coeff = new double[nvars];
for (int j = 0; j < nvars; j++)
{
coeff[j] = Double.Parse((string)ws[j]);
}
Relation rel = (string)ws[nvars] == "=" ? Relation.Equal :
(string)ws[nvars] == "<=" ? Relation.LessOrEqual : Relation.GreaterOrEqual;
double rs = Double.Parse((string)ws[nvars + 1]);
lp.AddConstraint(coeff, rel, rs);
sr.ReadLine(); //eat the empty line
}
sr.Close();
return lp;
}
public void ToFileInMathFormat(string fileName) {
LP lp = new LP(false);
StreamWriter sw = new StreamWriter(fileName, false,System.Text.Encoding.ASCII);
sw.Write("f=[");
for (int i = 0; i < nVars; i++) {
sw.Write(this.costs[i].ToString() + "; ");
}
sw.WriteLine("]");
int k = 0;
sw.Write("A=[");
foreach (double[] coeff in this.constraintCoeffs) {
k = WriteConstraint(sw, k, coeff);
}
sw.WriteLine("];");
sw.Write("b=[");
k = 0;
foreach (double[] coeff in this.constraintCoeffs) {
Relation r = this.relations[k];
double rs=this.rightSides[k];
if (r == Relation.LessOrEqual)
sw.Write(rs + ";");
else if (r == Relation.GreaterOrEqual)
sw.Write(-rs + ";");
else {
sw.Write(-rs + ";");
sw.Write(rs + ";");
}
k++;
}
sw.WriteLine("];");
sw.WriteLine("lb = zeros({0},1);",this.nVars);
sw.Close();
}
private int WriteConstraint(StreamWriter sw, int k, double[] coeff) {
if (this.relations[k] == Relation.LessOrEqual)
WriteCoefficients(sw, coeff, false);
else if (this.relations[k] == Relation.GreaterOrEqual)
WriteCoefficients(sw, coeff, true);
else {
WriteCoefficients(sw, coeff, true);
WriteCoefficients(sw, coeff, false);
}
return k + 1;
}
private static void WriteCoefficients(StreamWriter sw, double[] coeff, bool changeSign) {
int sign=changeSign?-1:1;
foreach (double c in coeff)
sw.Write(sign*c + " ");
sw.WriteLine();
}
public void ToFile(string fileName)
{
LP lp = new LP(false);
StreamWriter sw = new StreamWriter(fileName);
sw.WriteLine(costs.Length);
for (int i = 0; i < nVars; i++)
{
sw.Write(this.costs[i].ToString() + " ");
}
sw.WriteLine("\nconstraints");
sw.WriteLine(this.constraintCoeffs.Count);
int k = 0;
foreach (double[] coeff in this.constraintCoeffs)
{
foreach (double c in coeff)
sw.Write(c + " ");
Relation r = (Relation)this.relations[k];
string rel = r == Relation.Equal ? " = " : r == Relation.LessOrEqual ? " <= " : " >= ";
sw.WriteLine(rel + " " + this.rightSides[k] + "\n");
k++;
}
sw.WriteLine("end");
sw.Close();
}
#endif
/// <summary>
/// finds a solution which is feasible but not necesserily optimal
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public double[] FeasibleSolution()
{
if (status == Status.Optimal)
return MinimalSolution();
//will create solver and tableau
DoStageOne();
if (solver.status != Status.Optimal || status == Status.Infeasible)
{
status = Status.Infeasible;
return null;
}
this.status = Status.Feasible;
double[] ret = tableau.GetSolution(nVars);
// CheckConstraints(ret);
return ret;
}
/// <summary>
/// returns an optimal solution: that is a solution where cx is minimal
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public double[] MinimalSolution()
{
Contract.Assume(this.CostsAreSet);
// System.Diagnostics.Debug.Assert(costs != null);
if (status == Status.Unknown)
{
this.Minimize();
}
else if (status == Status.Feasible)
DoStageTwo();
if (status == Status.Optimal)
return ExtendVector(tableau.GetSolution(nVars));
return null;
}
/// <summary>
/// Call this method only in case when the program is infeasible.
/// The linear program will be transformed to the form Ax=b.
/// The corresponding quadratic program is
/// minimize||Ax-b||, x>=0
/// where ||.|| is the Euclidean norm.
/// The solution always exists.
/// Null is returned however if the matrix is too big
/// </summary>
/// <returns>approximation to solution</returns>
public double[]
LeastSquareSolution()
{
// F: the following lines are a Clousot-nice way of writing this.status == status.Infeasible ==> this.constraints.Count > 0
//Contract.Requires(this.Status == Status.Infeasible);
Contract.Assume(this.constraintCoeffs.Count > 0);
//calculate matrix A row length
int l = this.constraintCoeffs[0].Length;
int n = l;
foreach (Relation r in relations)
if (r != Relation.Equal)
n++;
//this is code without any optimizations, well, almost any
int m = this.relations.Count;//number of rows in A
//if (2 * (m + n) //number of variables in the QP
// * (m + n) //number of constraints
// > Microsoft.Glee.Channel.SplitThresholdMatrixSize * 4)
// return null;
double[] A = new double[m * n];
int offset = 0;
int slackVarOffset = 0;
for (int i = 0; i < m; i++)
{
double[] coeff = this.constraintCoeffs[i];
//copy coefficients
for (int j = 0; j < l; j++)
A[offset + j] = coeff[j];
Relation r = relations[i];
if (r == Relation.LessOrEqual)
A[offset + l + slackVarOffset++] = 1; //c[i]*x+1*ui=b[i]
else if (r == Relation.GreaterOrEqual)
A[offset + l + slackVarOffset++] = -1;//c[i]*x-1*ui=b[i]
offset += n;
}
QP qp = new QP();
//setting Q
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
{
double q = 0;
for (offset = 0; offset < A.Length; offset += n)
q += A[offset + i] * A[offset + j];
if (i == j)
qp.SetQMember(i, j, q);
else
qp.SetQMember(i, j, q / 2);
}
double[] linearCost = new double[n];
for (int k = 0; k < n; k++)
{
double c = 0;
offset = k;
for (int j = 0; j < m; j++, offset += n)
{
Contract.Assert(j < this.rightSides.Count);
c += this.rightSides[j] * A[offset];
}
linearCost[k] = c;
}
qp.SetLinearCosts(linearCost);
//we have no constraints in qp except the default: solution has to be not negative
double[] sol = qp.Solution;
if (qp.Status != Status.Optimal)
throw new InvalidOperationException();
double[] ret = new double[l];
for (int i = 0; i < l; i++)
ret[i] = sol[i];
return ret;
}
double[] ExtendVector(double[] v)
{
if (knownValues.Count > 0)
{
var ret = new double[v.Length + KnownValues.Count];
var ofs = 0;
var k = 0; //points to the index in the array which is to be returned
foreach (var kv in KnownValues)
{
for (; k < kv.Key; k++)
{
Contract.Assume(k >= ofs, "Domain knowledge?");
ret[k] = v[k - ofs];
}
ret[k++] = kv.Value;
ofs++;
}
Contract.Assume(ofs <= k, "Weakness of numerical domains?");
for (var i = k; i < ret.Length; i++)
{
Contract.Assume(i - ofs < v.Length);
ret[i] = v[i - ofs];
}
return ret;
}
else
{
return v;
}
}
bool lookForZeroColumns;
public bool LookForZeroColumns
{
get { return lookForZeroColumns; }
set { lookForZeroColumns = value; }
}
void ShrinkCostsAndCoefficients()
{
int[] zeroColumns = new int[nVars];
if (LookForZeroColumns)
{
zeroColumns = new int[nVars];
for (int i = 0; i < nVars; i++)
{
foreach (double[] d in constraintCoeffs)
{
if (d[i] != 0)
{
zeroColumns[i] = 1;
break;
}
}
}
//insert to known values
for (int i = 0; i < nVars; i++)
if (zeroColumns[i] == 0)
KnownValues[i] = 0;
}
if (KnownValues.Count > 0)
{
//remember old costs
foreach (int i in this.knownValues.Keys)
costsOfknownValues[i] = this.costs[i];
//fix the right sides
foreach (KeyValuePair<int, double> kv in this.KnownValues)
{
for (int i = 0; i < constraintCoeffs.Count; i++)
this.rightSides[i] -= constraintCoeffs[i][kv.Key] * kv.Value;
}
for (int i = 0; i < this.constraintCoeffs.Count; i++)
constraintCoeffs[i] = ShrinkVector(constraintCoeffs[i]);
costs = ShrinkVector(costs);
nVars = costs.Length;
//make right sides non-negative, and recalculate nSlacksAndSurpluses and nArtificials
this.nSlaksAndSurpluses = this.nArtificials = 0;
for (int i = 0; i < this.constraintCoeffs.Count; i++)
{
if (this.rightSides[i] < 0)
{
this.rightSides[i] *= -1;
double[] cf = this.constraintCoeffs[i];
Contract.Assume(cf != null);
for (int j = 0; j < cf.Length; j++)
cf[j] *= -1;
this.relations[i] = OppositeRelation(this.relations[i]);
}
switch (relations[i])
{
case Relation.LessOrEqual:
this.nSlaksAndSurpluses++;
break;
case Relation.GreaterOrEqual:
this.nSlaksAndSurpluses++;
this.nArtificials++;
break;
default: //equality
this.nArtificials++;
break;
}
}
}
}
static private Relation OppositeRelation(Relation relation)
{
switch (relation)
{
case Relation.Equal:
return Relation.Equal;
case Relation.LessOrEqual:
return Relation.GreaterOrEqual;
case Relation.GreaterOrEqual:
return Relation.LessOrEqual;
default:
throw new InvalidOperationException();
}
}
double[] ShrinkVector(double[] v)
{
double[] ret = new double[v.Length - knownValues.Count];
int ofs = 0;
int i = 0;
foreach (int j in KnownValues.Keys)
{
for (int k = i; k < j; k++)
{
Contract.Assume(k >= ofs);
ret[k - ofs] = v[k];
}
i = j + 1;
ofs++;
}
for (int k = i; k < v.Length; k++)
{
Contract.Assume(k >= ofs);
ret[k - ofs] = v[k];
}
return ret;
}
internal static double DotProduct(double[] a, double[] b)
{
Contract.Requires(a.Length == b.Length);
int dim = a.Length;
double r = 0;
for (int i = 0; i < dim; i++)
{
r += a[i] * b[i];
}
return r;
}
internal static double DotProduct(double[] a, double[] b, int dim)
{
Contract.Requires(0 <= dim);
Contract.Requires(dim <= a.Length);
Contract.Requires(dim <= b.Length);
double r = 0;
for (int i = 0; i < dim; i++)
r += a[i] * b[i];
return r;
}
/// <summary>
/// The value of the cost function at an optimal solution.
/// </summary>
public double GetMinimalValue()
{
if (this.Status != Status.Optimal)
{
Minimize();
}
if (this.Status == Status.Optimal)
{
Contract.Assume(nVars <= costs.Length, "Should it be an object invariant?");
return DotProduct(this.tableau.GetSolution(nVars), costs, nVars) + CostOfKnowVariables();
}
return 0;
}
private double CostOfKnowVariables()
{
double r = 0;
foreach (KeyValuePair<int, double> kv in this.knownValues)
r += kv.Value * costsOfknownValues[kv.Key];
return r;
}
/// <summary>
/// set the cost function
/// </summary>
/// <param name="costs">the objective vector</param>
public void InitCosts(double[] costsParam)
{
if (costsParam == null)
throw new InvalidDataException();
if (nVars == 0)
nVars = costsParam.Length;
else
{
if (nVars != costsParam.Length)
throw new InvalidDataException();//"wrong length of costs");
}
this.costs = costsParam;
}
/// <summary>
/// If one just happens to know the i-th variable value it can be set
/// </summary>
/// <param name="i"></param>
/// <param name="val"></param>
public void SetVariable(int i, double val)
{
this.KnownValues[i] = val;
}
/// <summary>
/// adds a constraint: the coeffiecents should not be very close to zero or too huge.
/// If it is the case, as one can scale for example the whole programm to zero,
/// then such coefficient will be treated az zeros. We are talking here about the numbers
/// with absolute values less than 1.0E-8
/// </summary>
/// <param name="coeff">the constraint coefficents</param>
/// <param name="relation">could be 'less or equal', equal or 'greater or equal'</param>
/// <param name="rightSide">right side of the constraint</param>
public void AddConstraint(double[] coeff, Relation relation, double rightSide)
{
foreach (double m in coeff)
UpdateMaxVal(m);
UpdateMaxVal(rightSide);
status = Status.Unknown;
coeff = (double[])coeff.Clone();
if (nVars == 0)
{
//init nVars
nVars = coeff.Length;
}
else
{
if (nVars != coeff.Length)
throw new InvalidOperationException();//"Two constraints of different length have been added");
}
//if (relation==Relation.Equal&&LookForEqualitySingletons) {
// int k=-1;//the place of the singleton
// for (int i = 0; i < coeff.Length; i++)
// if (Math.Abs(coeff[i]) > Epsilon)
// if (k == -1)
// k = i;
// else {
// k = -2;
// break;
// }
// if (k != -2) {
// double oldRightSide;
// if (KnownValues.TryGetValue(k, out oldRightSide)) {
// if (Math.Abs(oldRightSide - rightSide / coeff[k]) > Epsilon) {
// this.Status = Status.Infeasible;
// return;
// }
// } else {
// KnownValues[k] = rightSide / coeff[k];
// return; // don't add this constraint
// }
// }
//}
//make right side not-negative
if (rightSide < 0)
{
rightSide *= -1;
for (int i = 0; i < coeff.Length; i++)
coeff[i] *= -1;
if (relation == Relation.LessOrEqual)
relation = Relation.GreaterOrEqual;
else if (relation == Relation.GreaterOrEqual)
relation = Relation.LessOrEqual;
}
this.constraintCoeffs.Add(coeff);
this.relations.Add(relation);
this.rightSides.Add(rightSide);
if (relation == Relation.LessOrEqual)
this.nSlaksAndSurpluses++;
else if (relation == Relation.GreaterOrEqual)
{
this.nSlaksAndSurpluses++;
this.nArtificials++;
}
else //equality
this.nArtificials++;
}
private void UpdateMaxVal(double m)
{
if (m < 0)
{
if (-m > maxVal)
maxVal = -m;
}
else if (m > maxVal)
maxVal = m;
}
void CreateStageOneSolver()
{
Contract.Assume(this.constraintCoeffs.Count > 0); // F: there should be at least 1 constraint
int m = this.constraintCoeffs.Count;
int length1 = this.nVars + this.nSlaksAndSurpluses + this.nArtificials;
Contract.Assume(length1 >= 0);
//will be initialized by zeroes
double[] X = new double[m * length1];
int[] basis = new int[m];
double[] x = new double[m];
nArtificials = 0;
int localSlacksAndSurps = 0;
int ioffset = 0;
for (int i = 0; i < m; i++, ioffset += length1)
{
//copy the coeff first
double[] coeff = (double[])constraintCoeffs[i];
for (int j = 0; j < nVars; j++)
{
X[ioffset + j] = coeff[j];
}
Relation r = (Relation)this.relations[i];
if (r == Relation.LessOrEqual)
{
//we have a slack variable
int j = this.nVars + localSlacksAndSurps++;
X[ioffset + j] = 1;
basis[i] = j;
}
else if (r == Relation.GreaterOrEqual)
{
//we have surplus variable
int j = this.nVars + localSlacksAndSurps++;
X[ioffset + j] = -1;
int artificial = this.nVars + this.nSlaksAndSurpluses + nArtificials++;
X[ioffset + artificial] = 1;
//artificial goes to the basis
basis[i] = artificial;
}
else
{ //equality
int artificial = this.nVars + this.nSlaksAndSurpluses + nArtificials++;
X[ioffset + artificial] = 1;
//artificial goes to the basis
basis[i] = artificial;
}
x[i] = (double)rightSides[i];
}
double[] artifCosts = new double[X.Length / x.Length];
Contract.Assume(0 <= this.nVars + this.nSlaksAndSurpluses);
for (int i = this.nVars + this.nSlaksAndSurpluses; i < artifCosts.Length; i++)
{
artifCosts[i] = 1;
}
solver = new Solver(basis, X, x, artifCosts, EpsilonForReducedCosts);
}
/// <summary>
/// make all coefficients not greater than 1, unless they are small aready
/// </summary>
void ScaleToMaxVal()
{
if (maxVal < 10)
return;
for (int i = 0; i < constraintCoeffs.Count; i++)
{
double[] cc = constraintCoeffs[i];
for (int j = 0; j < cc.Length; j++)
cc[j] /= maxVal;
}
for (int i = 0; i < rightSides.Count; i++)
rightSides[i] /= maxVal;
}
double epsilonForArtificials = 1.0E-8;
public double EpsilonForArtificials
{
get { return epsilonForArtificials; }
set { epsilonForArtificials = value; }
}
double epsilonForReducedCosts = 1.0E-8;
public double EpsilonForReducedCosts
{
get { return epsilonForReducedCosts; }
set { epsilonForReducedCosts = value; }
}
[ContractVerification(false)]
void DoStageOne()
{
ScaleToMaxVal();
CreateStageOneSolver();
solver.ForbiddenPairs = forbiddenPairs;
solver.Solve();
if (solver.status != Status.Optimal)
{
this.status = Status.Infeasible;
return;
}
//this.CheckConstraints(this.solver.tableau.Getx());
//drive out artificials from the basis
tableau = solver.tableau;
var X = tableau.ReturnMatrix();
var x = tableau.GetSolution();
var basis = tableau.ReturnBasis();
Contract.Assume(X != null);
Contract.Assume(x != null);
Contract.Assume(basis != null);
int n = tableau.ReturnLengthOne();
int artificialsStart = nVars + nSlaksAndSurpluses;
int ioffset = 0;
Contract.Assume(x.Length <= basis.Length);
for (int i = 0; i < x.Length; i++, ioffset += n)
{
Contract.Assert(x.Length <= basis.Length);
Contract.Assert(i < basis.Length);
if (basis[i] >= artificialsStart)
{
if (x[i] > EpsilonForArtificials)
{
this.status = Status.Infeasible; //one of the artificials remains non-zero
return;
}
//find any non-zero number in non-artificials
int nonNulColumn = -1;
for (int j = 0; j < artificialsStart; j++)
{
Contract.Assume(ioffset + j >= 0); // ioffset gets decremented sometime
Contract.Assume(ioffset + j < X.Length); // ioffset gets decremented sometime
if (Math.Abs(X[ioffset + j]) > Epsilon)
{
nonNulColumn = j;
break;
}
}
if (nonNulColumn != -1)
tableau.Pivot(i, nonNulColumn);
else
{
//we have to cross out the i-th row because it is all zero
var newX = new double[(x.Length - 1) * n];
var newx = new double[x.Length - 1];
var ioOffset = 0;
var Ioffset = 0;
var io = 0;
for (var I = 0; I < x.Length; I++, Ioffset += n)
{
if (I != i)
{
Contract.Assume(io < newx.Length);
newx[io] = x[I];
for (int J = 0; J < n; J++)
{
Contract.Assume(Ioffset + J < X.Length);
var v = X[Ioffset + J];
Contract.Assume(ioffset + J < newX.Length);
newX[ioOffset + J] = v;
}
io++;
ioOffset += n;
}
}
var newBasis = new int[x.Length - 1];
io = 0;
for (var I = 0; I < x.Length; I++)
{
Contract.Assert(x.Length <= basis.Length);
if (I != i)
{
Contract.Assume(io < newBasis.Length);
newBasis[io] = basis[I];
io++;
}
}
//continue the loop on new X and on changed tableau
X = newX;
x = newx;
tableau.UpdateMatrix(X, x.Length, n);
tableau.SetSolution(x);
tableau.UpdateBasis(newBasis);
basis = newBasis;
i--;
ioffset -= n;
}
}
}
}
/// <summary>
/// Solves the linear program, minimizing, by going through stages one and two
/// </summary>
public void Minimize()
{
//solve will change the tableau
if (nVars == 0)
{
return;
}
if (solver == null || solver.status == Status.Unknown)
{
ShrinkCostsAndCoefficients();
if (this.Status == Status.Infeasible)
{
return;
}
DoStageOne();
}
if (solver.status != Status.Optimal || status == Status.Infeasible)
{
return;
}
DoStageTwo();
}
void DoStageTwo()
{
var lengthWithNoArt = this.nVars + this.nSlaksAndSurpluses;
var extendedCosts = new double[lengthWithNoArt];
for (var i = 0; i < nVars; i++)
{
extendedCosts[i] = costs[i];
}
solver.SetCosts(extendedCosts);
solver.status = Status.Unknown;
solver.Solve();
status = solver.status;
}
Status status;
public Status Status
{
get { return status; }
set { status = value; }
}
/*
public void Test()
{
double[] x = MinimalSolution;
if (x != null)
CheckConstraints(x);
}*/
#if DEBUGSIMPLEX
public static double maxDelta = 0;
void CheckConstraints(double[] x)
{
int i = 0;
foreach (double[] a in this.constraintCoeffs)
{
double v = dot(a, x, nVars);
double rs = (double)rightSides[i];
double delta = 0;
switch ((Relation)this.relations[i])
{
case Relation.Equal:
delta = Math.Abs(v - rs);
break;
case Relation.GreaterOrEqual:
delta = Math.Min(0, rs - v);
break;
case Relation.LessOrEqual:
delta = Math.Max(0, v - rs);
break;
}
if (delta > maxDelta)
maxDelta = delta;
i++;
}
}
#endif
#region LinearProgramInterface Members
public void LimitVariableFromBelow(int var, double l)
{
if ((double)l != 0)
throw new InvalidOperationException();
}
public void LimitVariableFromAbove(int var, double l)
{
//throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
| |
// PresidentsImproved.cs (c) 2004 Kari Laitinen
// http://www.naturalprogramming.com
// 2004-11-12 File created.
// 2004-11-12 Last modification.
// Compilation: csc PresidentsImproved.cs Date.cs
// Solutions to exercises 11-11, 11-12, 11-13, and 11-14.
using System ;
class President
{
string president_name ;
Date birth_date_of_president ;
string birth_state_of_president ;
string party_name ;
Date inauguration_date ;
Date last_day_in_office ;
string vice_president_name ;
public President( string given_president_name,
string birth_date_as_string,
string given_birth_state,
string given_party_name,
string inauguration_date_as_string,
string last_day_in_office_as_string,
string given_vice_president_name )
{
president_name = given_president_name ;
birth_date_of_president = new Date( birth_date_as_string ) ;
birth_state_of_president = given_birth_state ;
party_name = given_party_name ;
inauguration_date = new Date( inauguration_date_as_string ) ;
last_day_in_office = new Date( last_day_in_office_as_string ) ;
vice_president_name = given_vice_president_name ;
}
public string get_president_name()
{
return president_name ;
}
public bool was_president_on( Date given_date )
{
return ( given_date.is_within_dates( inauguration_date,
last_day_in_office ) ) ;
}
public bool was_born_in_state( string given_state_name )
{
return ( birth_state_of_president.IndexOf( given_state_name ) != -1 ) ;
}
public string get_brief_president_info()
{
return ( "\n " + president_name.PadRight( 25 )
+ " president from " + inauguration_date
+ " to " + last_day_in_office ) ;
}
public string get_full_president_data()
{
int years_in_office, months_in_office, days_in_office ;
inauguration_date.get_distance_to( last_day_in_office,
out years_in_office,
out months_in_office,
out days_in_office ) ;
return ( "\n "
+ president_name + " born "
+ birth_date_of_president + ", "
+ birth_state_of_president
+ "\n Inauguration date : " + inauguration_date
+ "\n Last day in office : " + last_day_in_office
+ "\n Total time in office: " + years_in_office
+ " years, " + months_in_office + " months, and "
+ days_in_office + " days."
+ "\n Party: " + party_name
+ "\n Vice president(s): " + vice_president_name ) ;
}
}
class PresidentInfoApplication
{
President[] president_table = new President[ 80 ] ;
int number_of_presidents_in_table ;
int index_of_last_printing ;
const int SEARCH_NOT_READY = 1 ;
const int SEARCH_IS_READY = 2 ;
const int SEARCH_IS_SUCCESSFUL = 3 ;
const int SEARCH_NOT_SUCCESSFUL = 4 ;
public PresidentInfoApplication()
{
president_table[ 0 ] = new
President( "George Washington", "02/22/1732", "Virginia",
"Federalist", "04/30/1789", "03/03/1797", "John Adams");
president_table[ 1 ] = new
President("John Adams", "10/30/1735", "Massachusetts",
"Federalist", "03/04/1797", "03/03/1801", "Thomas Jefferson");
president_table[ 2 ] = new
President("Thomas Jefferson", "04/13/1743", "Virginia", "Dem.-Rep.",
"03/04/1801", "03/03/1809", "Aaron Burr + George Clinton");
president_table[ 3 ] = new
President("James Madison", "03/16/1751", "Virginia", "Dem.-Rep.",
"03/04/1809", "03/03/1817", "George Clinton + Elbridge Gerry" );
president_table[ 4 ] = new
President( "James Monroe", "04/28/1758", "Virginia", "Dem.-Rep.",
"03/04/1817", "03/03/1825", "Daniel D. Tompkins" );
president_table[ 5 ] = new
President( "John Quincy Adams", "07/11/1767", "Massachusetts",
"Dem.-Rep.", "03/04/1825", "03/03/1829", "John C. Calhoun" );
president_table[ 6 ] = new
President( "Andrew Jackson", "03/15/1767", "South Carolina","Democrat",
"03/04/1829", "03/03/1837", "John C. Calhoun + Martin Van Buren" );
president_table[ 7 ] = new
President( "Martin Van Buren", "12/05/1782", "New York",
"Democrat", "03/04/1837", "03/03/1841", "Richard M. Johnson" );
president_table[ 8 ] = new
President( "William Henry Harrison", "02/09/1773", "Virginia",
"Whig", "03/04/1841", "04/04/1841", "John Tyler" );
president_table[ 9 ] = new
President( "John Tyler", "03/29/1790", "Virginia",
"Whig", "04/06/1841", "03/03/1845", "" );
president_table[ 10 ] = new
President( "James Knox Polk", "11/02/1795", "North Carolina",
"Democrat", "03/04/1845", "03/03/1849", "George M. Dallas" );
president_table[ 11 ] = new
President( "Zachary Taylor", "11/24/1784", "Virginia",
"Whig", "03/05/1849", "07/09/1850", "Millard Fillmore" );
president_table[ 12 ] = new
President( "Millard Fillmore", "01/07/1800", "New York",
"Whig", "07/10/1850", "03/03/1853", "" );
president_table[ 13 ] = new
President( "Franklin Pierce", "11/23/1804", "New Hampshire",
"Democrat", "03/04/1853", "03/03/1857", "William R. King" );
president_table[ 14 ] = new
President( "James Buchanan", "04/23/1791", "Pennsylvania",
"Democrat", "03/04/1857", "03/03/1861", "John C. Breckinridge");
president_table[ 15 ] = new
President( "Abraham Lincoln", "02/12/1809", "Kentucky", "Republican",
"03/04/1861", "04/15/1865", "Hannibal Hamlin + Andrew Johnson" );
president_table[ 16 ] = new
President( "Andrew Johnson", "12/29/1808", "North Carolina",
"Democrat", "04/15/1865", "03/03/1869", "" );
president_table[ 17 ] = new
President( "Ulysses Simpson Grant", "04/27/1822", "Ohio", "Republican",
"03/04/1869", "03/03/1877", "Schuyler Colfax + Henry Wilson" );
president_table[ 18 ] = new
President( "Rutherford Birchard Hayes", "10/04/1822", "Ohio",
"Republican", "03/04/1877", "03/03/1881", "William A. Wheeler");
president_table[ 19 ] = new
President( "James Abram Garfield", "11/19/1831", "Ohio",
"Republican", "03/04/1881", "09/19/1881", "Chester Alan Arthur");
president_table[ 20 ] = new
President( "Chester Alan Arthur", "10/05/1829", "Vermont",
"Republican", "09/20/1881", "03/03/1885", "" );
president_table[ 21 ] = new
President( "Grover Cleveland", "03/18/1837", "New Jersey",
"Democrat", "03/04/1885", "03/03/1889", "Thomas A. Hendrics" );
president_table[ 22 ] = new
President( "Benjamin Harrison", "08/20/1933", "Ohio",
"Republican", "03/04/1889", "03/03/1893", "Levi P. Morton" );
president_table[ 23 ] = new
President( "Grover Cleveland", "03/18/1837", "New Jersey",
"Democrat", "03/04/1893", "03/03/1897", "Adlai E. Stevenson" );
president_table[ 24 ] = new
President( "William McKinley", "01/29/1843", "Ohio", "Republican",
"03/04/1897", "09/14/1901", "Garret A. Hobart + Theodore Roosevelt" );
president_table[ 25 ] = new
President( "Theodore Roosevelt", "10/27/1858", "New York",
"Republican", "09/14/1901","03/03/1909","Charles W. Fairbanks");
president_table[ 26 ] = new
President( "William Howard Taft", "09/15/1857", "Ohio",
"Republican", "03/04/1909", "03/03/1913", "James S. Sherman");
president_table[ 27 ] = new
President( "Woodrow Wilson", "12/28/1856", "Virginia",
"Democrat", "03/04/1913", "03/03/1921", "Thomas R. Marshall" );
president_table[ 28 ] = new
President( "Warren Gamaliel Harding", "11/02/1865", "Ohio",
"Republican", "03/04/1921", "08/02/1923", "Calvin Coolidge" );
president_table[ 29 ] = new
President( "Calvin Coolidge", "07/04/1872", "Vermont",
"Republican", "08/03/1923", "03/03/1929", "Charles G. Dawes" );
president_table[ 30 ] = new
President( "Herbert Clark Hoover", "08/10/1874", "Iowa",
"Republican", "03/04/1929", "03/03/1933", "Charles Curtis" );
president_table[ 31 ] = new
President( "Franklin Delano Roosevelt","01/30/1882","New York",
"Democrat", "03/04/1933", "04/12/1945",
"John N. Garner + Henry A. Wallace + Harry S. Truman" );
president_table[ 32 ] = new
President( "Harry S. Truman", "05/08/1884", "Missouri",
"Democrat", "04/12/1945", "01/20/1953", "Alben W. Barkley" );
president_table[ 33 ] = new
President( "Dwight David Eisenhover", "10/14/1890", "Texas",
"Republican","01/20/1953","01/20/1961","Richard Milhous Nixon");
president_table[ 34 ] = new
President( "John Fitzgerald Kennedy", "05/29/1917", "Massachusetts",
"Democrat", "01/20/1961", "11/22/1963", "Lyndon Baines Johnson" );
president_table[ 35 ] = new
President( "Lyndon Baines Johnson", "08/27/1908", "Texas",
"Democrat", "11/22/1963", "01/20/1969", "Hubert H. Humphrey");
president_table[ 36 ] = new
President( "Richard Milhous Nixon", "01/09/1913", "California",
"Republican", "01/20/1969", "08/09/1974",
"Spiro T. Agnew + Gerald Rudolph Ford");
president_table[ 37 ] = new
President( "Gerald Rudolph Ford", "07/14/1913", "Nebraska",
"Republican","08/09/1974","01/20/1977","Nelson A. Rockefeller");
president_table[ 38 ] = new
President( "Jimmy (James Earl) Carter", "10/01/1924", "Georgia",
"Democrat", "01/20/1977", "01/20/1981", "Walter F. Mondale" );
president_table[ 39 ] = new
President( "Ronald Wilson Reagan", "02/06/1911", "Illinois",
"Republican", "01/20/1981", "01/20/1989", "George Bush" ) ;
president_table[ 40 ] = new
President( "George Bush", "06/12/1924", "Massachusetts",
"Republican", "01/20/1989", "01/20/1993", "Dan Quayle" ) ;
president_table[ 41 ] = new
President( "Bill Clinton", "08/19/1946", "Arkansas",
"Democrat", "01/20/1993", "01/20/2001", "Albert Gore" ) ;
president_table[ 42 ] = new
President( "George W. Bush", "07/06/1946", "Connecticut",
"Republican", "01/20/2001", "01/20/2009", "Richard Cheney" ) ;
// The value of the following variable must be updated
// when new presidents are added to president_table.
number_of_presidents_in_table = 43 ;
index_of_last_printing = 0 ;
}
public void search_president_by_name()
{
Console.Write( "\n Enter first, last, or full name of president: ") ;
string given_president_name = Console.ReadLine() ;
int president_index = 0 ;
int array_search_status = SEARCH_NOT_READY ;
while ( array_search_status == SEARCH_NOT_READY )
{
if ( president_table[ president_index ].get_president_name()
.IndexOf( given_president_name ) != -1 )
{
array_search_status = SEARCH_IS_SUCCESSFUL ;
}
else if ( president_index >= number_of_presidents_in_table - 1 )
{
array_search_status = SEARCH_NOT_SUCCESSFUL ;
}
else
{
president_index ++ ;
}
}
if ( array_search_status == SEARCH_IS_SUCCESSFUL )
{
Console.Write( "\n\n THE #" + ( president_index + 1 )
+ " PRESIDENT OF THE UNITED STATES: \n"
+ president_table[ president_index ].
get_full_president_data() ) ;
index_of_last_printing = president_index ;
}
else
{
Console.Write( "\n\n Sorry, could not find \""
+ given_president_name + "\" in table.\n" ) ;
}
}
public void search_president_for_given_date()
{
Console.Write( "\n Please, type in a date in form MM/DD/YYYY "
+ "\n Use two digits for days and months, and "
+ "\n four digits for year: " ) ;
string date_as_string = Console.ReadLine() ;
Date date_of_interest = new Date( date_as_string ) ;
int president_index = 0 ;
int array_search_status = SEARCH_NOT_READY ;
while ( array_search_status == SEARCH_NOT_READY )
{
if ( president_table[ president_index ].
was_president_on( date_of_interest ) )
{
array_search_status = SEARCH_IS_SUCCESSFUL ;
}
else if ( president_index >= number_of_presidents_in_table - 1)
{
array_search_status = SEARCH_NOT_SUCCESSFUL ;
}
else
{
president_index ++ ;
}
}
if ( array_search_status == SEARCH_IS_SUCCESSFUL )
{
Console.Write( "\n\n ON " + date_of_interest
+ ", THE PRESIDENT OF THE UNITED STATES WAS: \n"
+ president_table[ president_index ].
get_full_president_data() ) ;
index_of_last_printing = president_index ;
}
else
{
Console.Write( "\n\n Sorry, no president was on duty on "
+ date_of_interest + ".\n" ) ;
}
}
public void search_presidents_born_in_certain_state()
{
Console.Write( "\n Please, type in a state name: " ) ;
string given_state = Console.ReadLine() ;
Console.Write( "\n The presidents born in " + given_state
+ " are: \n" ) ;
int president_index = 0 ;
while ( president_index < number_of_presidents_in_table )
{
if ( president_table[ president_index ].
was_born_in_state( given_state ) )
{
Console.Write( president_table[ president_index ].
get_brief_president_info() ) ;
}
president_index ++ ;
}
}
public void print_data_of_next_president()
{
index_of_last_printing ++ ;
if ( index_of_last_printing < number_of_presidents_in_table )
{
Console.Write( "\n\n THE #" + ( index_of_last_printing + 1 )
+ " PRESIDENT OF THE UNITED STATES: \n"
+ president_table[ index_of_last_printing ].
get_full_president_data() ) ;
}
else
{
Console.Write( "\n Sorry, no more presidents in table." ) ;
}
}
public void print_data_of_previous_president()
{
if ( index_of_last_printing > 0 )
{
index_of_last_printing -- ;
Console.Write( "\n\n THE #" + ( index_of_last_printing + 1 )
+ " PRESIDENT OF THE UNITED STATES: \n"
+ president_table[ index_of_last_printing ].
get_full_president_data() ) ;
}
else
{
Console.Write( "\n Sorry, no previous presidents." ) ;
}
}
public void print_list_of_all_presidents()
{
int president_index = 0 ;
while ( president_index < number_of_presidents_in_table )
{
Console.Write( president_table[ president_index ].
get_brief_president_info() ) ;
president_index ++ ;
if ( ( president_index % 15 ) == 0 )
{
Console.Write( "\nPress <Enter> to continue ....." ) ;
string any_string_from_keyboard = Console.ReadLine() ;
}
}
}
public void run()
{
string user_selection = "????" ;
Console.Write("\n This program provides information about all"
+ "\n presidents of the U.S.A. Please, select from"
+ "\n the following menu by typing in a letter. ") ;
while ( user_selection[ 0 ] != 'e' &&
user_selection[ 0 ] != 'q' ) // Solution to 11-11.
{
Console.Write("\n\n p Search president by name."
+ "\n d Search president for a given date."
+ "\n s Search presidents born in certain state."
+ "\n n Print data of next president."
+ "\n f Print date of former (previous) president"
+ "\n a Print list of all presidents."
+ "\n e or q Exit the program.\n\n " ) ;
user_selection = Console.ReadLine() ;
// The first "if" is the solution to Exercise 11-4
if ( user_selection.Length == 0 )
{
// The user hit only the Enter key.
user_selection = "????" ;
}
else if ( user_selection[ 0 ] == 'p' )
{
search_president_by_name() ;
}
else if ( user_selection[ 0 ] == 'd' )
{
search_president_for_given_date() ;
}
else if ( user_selection[ 0 ] == 's' )
{
search_presidents_born_in_certain_state() ;
}
else if ( user_selection[ 0 ] == 'n' )
{
print_data_of_next_president() ;
}
else if ( user_selection[ 0 ] == 'f' )
{
print_data_of_previous_president() ;
}
else if ( user_selection[ 0 ] == 'a' )
{
print_list_of_all_presidents() ;
}
}
}
}
class PresidentInfoApplicationRunner
{
static void Main()
{
PresidentInfoApplication this_president_info_application
= new PresidentInfoApplication() ;
this_president_info_application.run() ;
}
}
| |
namespace Onyx.Authorization.Migrations
{
using System.Data.Entity.Migrations;
using System.Linq;
using Onyx.Authorization.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using Onyx.Authorization;
using System.Data.Entity.Core;
using TwoFactorAuthentication.API.Services;
using System.Data.Entity.Validation;
using System.IdentityModel.Claims;
using System.Web;
/// <summary>
/// Class handling configuration of migrations
/// </summary>
internal sealed class Configuration : DbMigrationsConfiguration<AuthorizationDb>
{
/// <summary>
/// Migrations configuration constructor
/// </summary>
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
/// <summary>
/// Adds a default "admin" user to the database with a password of "password"
/// </summary>
/// <param name="context">A datastore access context</param>
/// <returns>Whether adding the user exists in the database</returns>
private bool AddUser(AuthorizationDb context)
{
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
const string roleName = "Admin";
// Identity result objects handle results from non-select operations
// on the user datastore
IdentityResult identityResult = null;
// UserManager handles the management of a certain type of User, and it
// requires a UserStore to handle the actual access to the datastore
//UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
try
{
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new IdentityRole(roleName);
var roleresult = roleManager.Create(role);
}
// Create a new user as a POCO
var user = userManager.FindByName("admin");// new ApplicationUser()
// Check if the user already exists before creating it
if (user == null)
{
user = new ApplicationUser()
{
UserName = "admin",
Email = "m@darocha.com",
TwoFactorEnabled = true,
EmailConfirmed = true,
PSK = TimeSensitivePassCode.GeneratePresharedKey(),
Profile = new Profile()
{
FirstName = "Marcelo",
LastName = "Darocha"
}
};
// Attempt to create the user
identityResult = userManager.Create(user, "Password1!");
}
// Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
var result = userManager.AddToRole(user.Id, role.Name);
}
}
catch (DbEntityValidationException e)
{
var message = e.InnerException.Message;
}
// Pass back the result of attempting to create the user
return identityResult.Succeeded;
}
/// <summary>
/// Add some default sales data to the databse
/// </summary>
/// <param name="context">A datastore access context</param>
private void AddSales(AuthorizationDb context)
{
// Grab some default regions
Region northAmerica = context.Regions.Single(r => r.Name == "North America");
Region europe = context.Regions.Single(r => r.Name == "Europe");
// Create some default sales (amounts need to be unique)
List<Sale> sales = new List<Sale> {
new Sale {
RegionId = northAmerica.Id,
Amount = 500m
},
new Sale {
RegionId = northAmerica.Id,
Amount = 200.58m
},
new Sale {
RegionId = northAmerica.Id,
Amount = 300.75m
},
new Sale {
RegionId = northAmerica.Id,
Amount = 1300.45m
},
new Sale {
RegionId = northAmerica.Id,
Amount = 5000.75m
},
new Sale {
RegionId = northAmerica.Id,
Amount = 800.46m
},
new Sale {
RegionId = northAmerica.Id,
Amount = 400.10m
},
new Sale {
RegionId = northAmerica.Id,
Amount = 1070.67m
},
new Sale {
RegionId = northAmerica.Id,
Amount = 657.25m
},
new Sale {
RegionId = northAmerica.Id,
Amount = 142.25m
},
new Sale {
RegionId = europe.Id,
Amount = 1000.46m
},
new Sale {
RegionId = europe.Id,
Amount = 102.15m
},
new Sale {
RegionId = europe.Id,
Amount = 500.46m
},
new Sale {
RegionId = europe.Id,
Amount = 400.00m
},
new Sale {
RegionId = europe.Id,
Amount = 360.00m
},
new Sale {
RegionId = europe.Id,
Amount = 780.00m
},
new Sale {
RegionId = europe.Id,
Amount = 605.67m
},
new Sale {
RegionId = europe.Id,
Amount = 455.42m
}
};
// Add the sales to the database (unless the amount exists)
sales.ForEach(sale => context.Sales.AddOrUpdate(s => s.Amount, sale));
}
/// <summary>
/// Function that will be run on upwards migrations of the database
/// </summary>
/// <param name="context">A datastpre access context</param>
protected override void Seed(AuthorizationDb context)
{
// Add a default user to the database
AddUser(context);
// Define some default regions
List<Region> regions = new List<Region> {
new Region {
Name = "North America",
SalesTarget = 9000m
},
new Region
{
Name = "Europe",
SalesTarget = 6000m
}
};
// Add them to the context, unless they already exist
regions.ForEach(region => context.Regions.AddOrUpdate(r => r.Name, region));
// Then save them to the database
context.SaveChanges();
// Now grab the database versions
Region northAmerica = context.Regions.Single(r => r.Name == "North America");
Region europe = context.Regions.Single(r => r.Name == "Europe");
// Define some default employees
List<Employee> employees = new List<Employee> {
new Employee
{
FirstName = "Sarah",
LastName = "Doe",
RegionId = northAmerica.Id
},
new Employee
{
FirstName = "John Q.",
LastName = "Public",
RegionId = europe.Id
}
};
// Add them to the context, unless they already exist
employees.ForEach(employee => context.Employees.AddOrUpdate(e => e.LastName, employee));
// Then save them to the database
context.SaveChanges();
// Now grab the database versions
Employee sarahDoe = context.Employees.Single(e => e.FirstName == "Sarah" && e.LastName == "Doe");
Employee johnPublic = context.Employees.Single(e => e.FirstName == "John Q." && e.LastName == "Public");
// And make them sales directors
northAmerica.SalesDirector = sarahDoe;
europe.SalesDirector = johnPublic;
// Save their "promotions" to the database
context.SaveChanges();
// if there aren't any sales in the database currently, add some
if (context.Sales.Count() == 0)
{
AddSales(context);
}
// save any sales that were added
context.SaveChanges();
if (context.Clients.Count() == 0)
{
context.Clients.AddRange(BuildClientsList());
context.SaveChanges();
}
}
private static List<Client> BuildClientsList()
{
List<Client> ClientsList = new List<Client>
{
new Client
{ Id = "ngAuthApp",
Secret= Helper.GetHash("abc@123"),
Name="AngularJS front-end Application",
ApplicationType = Models.ApplicationTypes.JavaScript,
Active = true,
RefreshTokenLifeTime = 7200,
AllowedOrigin = "http://onyximports.com.br"
},
new Client
{ Id = "consoleApp",
Secret=Helper.GetHash("123@abc"),
Name="Console Application",
ApplicationType =Models.ApplicationTypes.NativeConfidential,
Active = true,
RefreshTokenLifeTime = 14400,
AllowedOrigin = "*"
}
};
return ClientsList;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using Internal.Cryptography;
using Internal.Cryptography.Pal;
namespace System.Security.Cryptography.X509Certificates
{
public class X509Certificate : IDisposable
{
public X509Certificate()
{
}
public X509Certificate(byte[] data)
{
if (data != null && data.Length != 0) // For compat reasons, this constructor treats passing a null or empty data set as the same as calling the nullary constructor.
Pal = CertificatePal.FromBlob(data, null, X509KeyStorageFlags.DefaultKeySet);
}
public X509Certificate(byte[] rawData, string password)
: this(rawData, password, X509KeyStorageFlags.DefaultKeySet)
{
}
public X509Certificate(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
if (rawData == null || rawData.Length == 0)
throw new ArgumentException(SR.Arg_EmptyOrNullArray, "rawData");
if ((keyStorageFlags & ~KeyStorageFlagsAll) != 0)
throw new ArgumentException(SR.Argument_InvalidFlag, "keyStorageFlags");
Pal = CertificatePal.FromBlob(rawData, password, keyStorageFlags);
}
public X509Certificate(IntPtr handle)
{
Pal = CertificatePal.FromHandle(handle);
}
internal X509Certificate(ICertificatePal pal)
{
Debug.Assert(pal != null);
Pal = pal;
}
public X509Certificate(string fileName)
: this(fileName, null, X509KeyStorageFlags.DefaultKeySet)
{
}
public X509Certificate(string fileName, string password)
: this(fileName, password, X509KeyStorageFlags.DefaultKeySet)
{
}
public X509Certificate(string fileName, string password, X509KeyStorageFlags keyStorageFlags)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
if ((keyStorageFlags & ~KeyStorageFlagsAll) != 0)
throw new ArgumentException(SR.Argument_InvalidFlag, "keyStorageFlags");
Pal = CertificatePal.FromFile(fileName, password, keyStorageFlags);
}
public IntPtr Handle
{
get
{
if (Pal == null)
return IntPtr.Zero;
else
return Pal.Handle;
}
}
public string Issuer
{
get
{
ThrowIfInvalid();
string issuer = _lazyIssuer;
if (issuer == null)
issuer = _lazyIssuer = Pal.Issuer;
return issuer;
}
}
public string Subject
{
get
{
ThrowIfInvalid();
string subject = _lazySubject;
if (subject == null)
subject = _lazySubject = Pal.Subject;
return subject;
}
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
ICertificatePal pal = Pal;
Pal = null;
if (pal != null)
pal.Dispose();
}
}
public override bool Equals(object obj)
{
X509Certificate other = obj as X509Certificate;
if (other == null)
return false;
return Equals(other);
}
public virtual bool Equals(X509Certificate other)
{
if (other == null)
return false;
if (Pal == null)
return other.Pal == null;
if (!Issuer.Equals(other.Issuer))
return false;
byte[] thisSerialNumber = GetSerialNumber();
byte[] otherSerialNumber = other.GetSerialNumber();
if (thisSerialNumber.Length != otherSerialNumber.Length)
return false;
for (int i = 0; i < thisSerialNumber.Length; i++)
{
if (thisSerialNumber[i] != otherSerialNumber[i])
return false;
}
return true;
}
public virtual byte[] Export(X509ContentType contentType)
{
return Export(contentType, null);
}
public virtual byte[] Export(X509ContentType contentType, string password)
{
if (!(contentType == X509ContentType.Cert || contentType == X509ContentType.SerializedCert || contentType == X509ContentType.Pkcs12))
throw new CryptographicException(SR.Cryptography_X509_InvalidContentType);
if (Pal == null)
throw new CryptographicException(ErrorCode.E_POINTER); // Not the greatest error, but needed for backward compat.
using (IStorePal storePal = StorePal.FromCertificate(Pal))
{
return storePal.Export(contentType, password);
}
}
public virtual byte[] GetCertHash()
{
ThrowIfInvalid();
byte[] certHash = _lazyCertHash;
if (certHash == null)
_lazyCertHash = certHash = Pal.Thumbprint;
return certHash.CloneByteArray();
}
public virtual string GetFormat()
{
return "X509";
}
public override int GetHashCode()
{
if (Pal == null)
return 0;
byte[] thumbPrint = GetCertHash();
int value = 0;
for (int i = 0; i < thumbPrint.Length && i < 4; ++i)
{
value = value << 8 | thumbPrint[i];
}
return value;
}
public virtual string GetKeyAlgorithm()
{
ThrowIfInvalid();
string keyAlgorithm = _lazyKeyAlgorithm;
if (keyAlgorithm == null)
keyAlgorithm = _lazyKeyAlgorithm = Pal.KeyAlgorithm;
return keyAlgorithm;
}
public virtual byte[] GetKeyAlgorithmParameters()
{
ThrowIfInvalid();
byte[] keyAlgorithmParameters = _lazyKeyAlgorithmParameters;
if (keyAlgorithmParameters == null)
keyAlgorithmParameters = _lazyKeyAlgorithmParameters = Pal.KeyAlgorithmParameters;
return keyAlgorithmParameters.CloneByteArray();
}
public virtual string GetKeyAlgorithmParametersString()
{
ThrowIfInvalid();
byte[] keyAlgorithmParameters = GetKeyAlgorithmParameters();
return keyAlgorithmParameters.ToHexStringUpper();
}
public virtual byte[] GetPublicKey()
{
ThrowIfInvalid();
byte[] publicKey = _lazyPublicKey;
if (publicKey == null)
publicKey = _lazyPublicKey = Pal.PublicKeyValue;
return publicKey.CloneByteArray();
}
public virtual byte[] GetSerialNumber()
{
ThrowIfInvalid();
byte[] serialNumber = _lazySerialNumber;
if (serialNumber == null)
serialNumber = _lazySerialNumber = Pal.SerialNumber;
return serialNumber.CloneByteArray();
}
public override string ToString()
{
return ToString(fVerbose: false);
}
public virtual string ToString(bool fVerbose)
{
if (fVerbose == false || Pal == null)
return GetType().ToString();
StringBuilder sb = new StringBuilder();
// Subject
sb.AppendLine("[Subject]");
sb.Append(" ");
sb.AppendLine(Subject);
// Issuer
sb.AppendLine();
sb.AppendLine("[Issuer]");
sb.Append(" ");
sb.AppendLine(Issuer);
// Serial Number
sb.AppendLine();
sb.AppendLine("[Serial Number]");
sb.Append(" ");
byte[] serialNumber = GetSerialNumber();
Array.Reverse(serialNumber);
sb.Append(serialNumber.ToHexArrayUpper());
sb.AppendLine();
// NotBefore
sb.AppendLine();
sb.AppendLine("[Not Before]");
sb.Append(" ");
sb.AppendLine(FormatDate(GetNotBefore()));
// NotAfter
sb.AppendLine();
sb.AppendLine("[Not After]");
sb.Append(" ");
sb.AppendLine(FormatDate(GetNotAfter()));
// Thumbprint
sb.AppendLine();
sb.AppendLine("[Thumbprint]");
sb.Append(" ");
sb.Append(GetCertHash().ToHexArrayUpper());
sb.AppendLine();
return sb.ToString();
}
internal ICertificatePal Pal { get; private set; }
internal DateTime GetNotAfter()
{
ThrowIfInvalid();
DateTime notAfter = _lazyNotAfter;
if (notAfter == DateTime.MinValue)
notAfter = _lazyNotAfter = Pal.NotAfter;
return notAfter;
}
internal DateTime GetNotBefore()
{
ThrowIfInvalid();
DateTime notBefore = _lazyNotBefore;
if (notBefore == DateTime.MinValue)
notBefore = _lazyNotBefore = Pal.NotBefore;
return notBefore;
}
internal void ThrowIfInvalid()
{
if (Pal == null)
throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHandle, "m_safeCertContext")); // Keeping "m_safeCertContext" string for backward compat sake.
}
/// <summary>
/// Convert a date to a string.
///
/// Some cultures, specifically using the Um-AlQura calendar cannot convert dates far into
/// the future into strings. If the expiration date of an X.509 certificate is beyond the range
/// of one of these these cases, we need to fall back to a calendar which can express the dates
/// </summary>
internal static string FormatDate(DateTime date)
{
CultureInfo culture = CultureInfo.CurrentCulture;
if (!culture.DateTimeFormat.Calendar.IsValidDay(date.Year, date.Month, date.Day, 0))
{
// The most common case of culture failing to work is in the Um-AlQuara calendar. In this case,
// we can fall back to the Hijri calendar, otherwise fall back to the invariant culture.
if (culture.DateTimeFormat.Calendar is UmAlQuraCalendar)
{
culture = culture.Clone() as CultureInfo;
culture.DateTimeFormat.Calendar = new HijriCalendar();
}
else
{
culture = CultureInfo.InvariantCulture;
}
}
return date.ToString(culture);
}
private volatile byte[] _lazyCertHash;
private volatile string _lazyIssuer;
private volatile string _lazySubject;
private volatile byte[] _lazySerialNumber;
private volatile string _lazyKeyAlgorithm;
private volatile byte[] _lazyKeyAlgorithmParameters;
private volatile byte[] _lazyPublicKey;
private DateTime _lazyNotBefore = DateTime.MinValue;
private DateTime _lazyNotAfter = DateTime.MinValue;
private const X509KeyStorageFlags KeyStorageFlagsAll = (X509KeyStorageFlags)0x1f;
}
}
| |
// 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.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Microsoft.VisualStudio.SymReaderInterop;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public abstract class ExpressionCompilerTestBase : CSharpTestBase, IDisposable
{
private readonly ArrayBuilder<IDisposable> _runtimeInstances = ArrayBuilder<IDisposable>.GetInstance();
public override void Dispose()
{
base.Dispose();
foreach (var instance in _runtimeInstances)
{
instance.Dispose();
}
_runtimeInstances.Free();
}
internal RuntimeInstance CreateRuntimeInstance(
Compilation compilation,
bool includeSymbols = true)
{
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
return CreateRuntimeInstance(
Guid.NewGuid().ToString("D"),
references,
exeBytes,
includeSymbols ? new SymReader(pdbBytes) : null);
}
internal RuntimeInstance CreateRuntimeInstance(
string assemblyName,
ImmutableArray<MetadataReference> references,
byte[] exeBytes,
ISymUnmanagedReader symReader,
bool includeLocalSignatures = true)
{
var exeReference = AssemblyMetadata.CreateFromImage(exeBytes).GetReference(display: assemblyName);
var modulesBuilder = ArrayBuilder<ModuleInstance>.GetInstance();
// Create modules for the references
modulesBuilder.AddRange(references.Select(r => r.ToModuleInstance(fullImage: null, symReader: null, includeLocalSignatures: includeLocalSignatures)));
// Create a module for the exe.
modulesBuilder.Add(exeReference.ToModuleInstance(exeBytes, symReader, includeLocalSignatures: includeLocalSignatures));
var modules = modulesBuilder.ToImmutableAndFree();
modules.VerifyAllModules();
var instance = new RuntimeInstance(modules);
_runtimeInstances.Add(instance);
return instance;
}
internal static void GetContextState(
RuntimeInstance runtime,
string methodOrTypeName,
out ImmutableArray<MetadataBlock> blocks,
out Guid moduleVersionId,
out ISymUnmanagedReader symReader,
out int methodOrTypeToken,
out int localSignatureToken)
{
var moduleInstances = runtime.Modules;
blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock);
var compilation = blocks.ToCompilation();
var methodOrType = GetMethodOrTypeBySignature(compilation, methodOrTypeName);
var module = (PEModuleSymbol)methodOrType.ContainingModule;
var id = module.Module.GetModuleVersionIdOrThrow();
var moduleInstance = moduleInstances.First(m => m.ModuleVersionId == id);
moduleVersionId = id;
symReader = (ISymUnmanagedReader)moduleInstance.SymReader;
Handle methodOrTypeHandle;
if (methodOrType.Kind == SymbolKind.Method)
{
methodOrTypeHandle = ((PEMethodSymbol)methodOrType).Handle;
localSignatureToken = moduleInstance.GetLocalSignatureToken((MethodDefinitionHandle)methodOrTypeHandle);
}
else
{
methodOrTypeHandle = ((PENamedTypeSymbol)methodOrType).Handle;
localSignatureToken = -1;
}
MetadataReader reader = null; // null should be ok
methodOrTypeToken = reader.GetToken(methodOrTypeHandle);
}
internal static EvaluationContext CreateMethodContext(
RuntimeInstance runtime,
string methodName,
int atLineNumber = -1,
CSharpMetadataContext previous = null)
{
ImmutableArray<MetadataBlock> blocks;
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
int ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber);
return EvaluationContext.CreateMethodContext(
previous,
blocks,
symReader,
moduleVersionId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: ilOffset,
localSignatureToken: localSignatureToken);
}
internal static EvaluationContext CreateTypeContext(
RuntimeInstance runtime,
string typeName)
{
ImmutableArray<MetadataBlock> blocks;
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int typeToken;
int localSignatureToken;
GetContextState(runtime, typeName, out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
return EvaluationContext.CreateTypeContext(
null,
blocks,
moduleVersionId,
typeToken);
}
internal CompilationTestData Evaluate(
string source,
OutputKind outputKind,
string methodName,
string expr,
int atLineNumber = -1,
bool includeSymbols = true)
{
ResultProperties resultProperties;
string error;
var result = Evaluate(source, outputKind, methodName, expr, out resultProperties, out error, atLineNumber, DefaultInspectionContext.Instance, includeSymbols);
Assert.Null(error);
return result;
}
internal CompilationTestData Evaluate(
string source,
OutputKind outputKind,
string methodName,
string expr,
out ResultProperties resultProperties,
out string error,
int atLineNumber = -1,
InspectionContext inspectionContext = null,
bool includeSymbols = true)
{
var compilation0 = CreateCompilationWithMscorlib(
source,
options: (outputKind == OutputKind.DynamicallyLinkedLibrary) ? TestOptions.DebugDll : TestOptions.DebugExe);
var runtime = CreateRuntimeInstance(compilation0, includeSymbols);
var context = CreateMethodContext(runtime, methodName, atLineNumber);
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
inspectionContext ?? DefaultInspectionContext.Instance,
expr,
DkmEvaluationFlags.TreatAsExpression,
DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
return testData;
}
/// <summary>
/// Verify all type parameters from the method
/// are from that method or containing types.
/// </summary>
internal static void VerifyTypeParameters(MethodSymbol method)
{
Assert.True(method.IsContainingSymbolOfAllTypeParameters(method.ReturnType));
AssertEx.All(method.TypeParameters, typeParameter => method.IsContainingSymbolOfAllTypeParameters(typeParameter));
AssertEx.All(method.TypeArguments, typeArgument => method.IsContainingSymbolOfAllTypeParameters(typeArgument));
AssertEx.All(method.Parameters, parameter => method.IsContainingSymbolOfAllTypeParameters(parameter.Type));
VerifyTypeParameters(method.ContainingType);
}
internal static void VerifyLocal(
CompilationTestData testData,
string typeName,
LocalAndMethod localAndMethod,
string expectedMethodName,
string expectedLocalName,
DkmClrCompilationResultFlags expectedFlags = DkmClrCompilationResultFlags.None,
string expectedILOpt = null,
bool expectedGeneric = false,
[CallerFilePath]string expectedValueSourcePath = null,
[CallerLineNumber]int expectedValueSourceLine = 0)
{
ExpressionCompilerTestHelpers.VerifyLocal<MethodSymbol>(
testData,
typeName,
localAndMethod,
expectedMethodName,
expectedLocalName,
expectedFlags,
VerifyTypeParameters,
expectedILOpt,
expectedGeneric,
expectedValueSourcePath,
expectedValueSourceLine);
}
/// <summary>
/// Verify all type parameters from the type
/// are from that type or containing types.
/// </summary>
internal static void VerifyTypeParameters(NamedTypeSymbol type)
{
AssertEx.All(type.TypeParameters, typeParameter => type.IsContainingSymbolOfAllTypeParameters(typeParameter));
AssertEx.All(type.TypeArguments, typeArgument => type.IsContainingSymbolOfAllTypeParameters(typeArgument));
var container = type.ContainingType;
if ((object)container != null)
{
VerifyTypeParameters(container);
}
}
internal static Symbol GetMethodOrTypeBySignature(Compilation compilation, string signature)
{
string methodOrTypeName = signature;
string[] parameterTypeNames = null;
var parameterListStart = methodOrTypeName.IndexOf('(');
if (parameterListStart > -1)
{
parameterTypeNames = methodOrTypeName.Substring(parameterListStart).Trim('(', ')').Split(',');
methodOrTypeName = methodOrTypeName.Substring(0, parameterListStart);
}
var candidates = compilation.GetMembers(methodOrTypeName);
Assert.Equal(parameterTypeNames == null, candidates.Length == 1);
Symbol methodOrType = null;
foreach (var candidate in candidates)
{
methodOrType = candidate;
if ((parameterTypeNames == null) ||
parameterTypeNames.SequenceEqual(methodOrType.GetParameters().Select(p => p.Type.Name)))
{
// Found a match.
break;
}
}
Assert.False(methodOrType == null, "Could not find method or type with signature '" + signature + "'.");
return methodOrType;
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// DialogueScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
#endregion
namespace RolePlaying
{
/// <summary>
/// Display of conversation dialog between the player and the npc
/// </summary>
class DialogueScreen : GameScreen
{
#region Graphics Data
private Texture2D backgroundTexture;
private Vector2 backgroundPosition;
private Texture2D fadeTexture;
private Texture2D selectButtonTexture;
private Vector2 selectPosition;
private Vector2 selectButtonPosition;
private Vector2 backPosition;
private Texture2D backButtonTexture;
private Vector2 backButtonPosition;
private Texture2D scrollTexture;
private Vector2 scrollPosition;
private Texture2D lineTexture;
private Vector2 topLinePosition;
private Vector2 bottomLinePosition;
private Vector2 titlePosition;
private Vector2 dialogueStartPosition;
#endregion
#region Text Data
/// <summary>
/// The title text shown at the top of the screen.
/// </summary>
private string titleText;
/// <summary>
/// The title text shown at the top of the screen.
/// </summary>
public string TitleText
{
get { return titleText; }
set { titleText = value; }
}
/// <summary>
/// The dialogue shown in the main portion of this dialog.
/// </summary>
private string dialogueText;
/// <summary>
/// The dialogue shown in the main portion of this dialog, broken into lines.
/// </summary>
private List<string> dialogueList = new List<string>();
/// <summary>
/// The dialogue shown in the main portion of this dialog.
/// </summary>
public string DialogueText
{
get { return dialogueText; }
set
{
// trim the new value
string trimmedValue = value.Trim();
// if it's a match for what we already have, then this is trivial
if (dialogueText == trimmedValue)
{
return;
}
// assign the new value
dialogueText = trimmedValue;
// break the text into lines
if (String.IsNullOrEmpty(dialogueText))
{
dialogueList.Clear();
}
else
{
dialogueList = Fonts.BreakTextIntoList(dialogueText,
Fonts.DescriptionFont, maxWidth);
}
// set which lines ar edrawn
startIndex = 0;
endIndex = drawMaxLines;
if (endIndex > dialogueList.Count)
{
dialogueStartPosition = new Vector2(271f,
375f - ((dialogueList.Count - startIndex) *
(Fonts.DescriptionFont.LineSpacing) / 2));
endIndex = dialogueList.Count;
}
else
{
dialogueStartPosition = new Vector2(271f, 225f);
}
}
}
/// <summary>
/// The text shown next to the A button, if any.
/// </summary>
private string selectText = "Continue";
/// <summary>
/// The text shown next to the A button, if any.
/// </summary>
public string SelectText
{
get { return selectText; }
set
{
if (selectText != value)
{
selectText = value;
if (selectButtonTexture != null)
{
selectPosition.X = selectButtonPosition.X -
Fonts.ButtonNamesFont.MeasureString(selectText).X - 10f;
selectPosition.Y = selectButtonPosition.Y;
}
}
}
}
/// <summary>
/// The text shown next to the B button, if any.
/// </summary>
private string backText = "Back";
/// <summary>
/// The text shown next to the B button, if any.
/// </summary>
public string BackText
{
get { return backText; }
set { backText = value; }
}
/// <summary>
/// Maximum width of each line in pixels
/// </summary>
private const int maxWidth = 705;
/// <summary>
/// Starting index of the list to be displayed
/// </summary>
private int startIndex = 0;
/// <summary>
/// Ending index of the list to be displayed
/// </summary>
private int endIndex = drawMaxLines;
/// <summary>
/// Maximum number of lines to draw in the screen
/// </summary>
private const int drawMaxLines = 13;
#endregion
#region Initialization
/// <summary>
/// Construct a new DialogueScreen object.
/// </summary>
/// <param name="mapEntry"></param>
public DialogueScreen()
{
this.IsPopup = true;
}
/// <summary>
/// Load the graphics content
/// </summary>
/// <param name="batch">SpriteBatch object</param>
/// <param name="screenWidth">Width of the screen</param>
/// <param name="screenHeight">Height of the screen</param>
public override void LoadContent()
{
ContentManager content = ScreenManager.Game.Content;
fadeTexture =
content.Load<Texture2D>(@"Textures\GameScreens\FadeScreen");
backgroundTexture =
content.Load<Texture2D>(@"Textures\GameScreens\PopupScreen");
scrollTexture =
content.Load<Texture2D>(@"Textures\GameScreens\ScrollButtons");
selectButtonTexture = content.Load<Texture2D>(@"Textures\Buttons\AButton");
backButtonTexture = content.Load<Texture2D>(@"Textures\Buttons\BButton");
lineTexture =
content.Load<Texture2D>(@"Textures\GameScreens\SeparationLine");
Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
backgroundPosition.X = (viewport.Width - backgroundTexture.Width) / 2;
backgroundPosition.Y = (viewport.Height - backgroundTexture.Height) / 2;
selectButtonPosition.X = viewport.Width / 2 + 260;
selectButtonPosition.Y = backgroundPosition.Y + 530f;
selectPosition.X = selectButtonPosition.X -
Fonts.ButtonNamesFont.MeasureString(selectText).X - 10f;
selectPosition.Y = selectButtonPosition.Y;
backPosition.X = viewport.Width / 2 - 250f;
backPosition.Y = backgroundPosition.Y + 530f;
backButtonPosition.X = backPosition.X - backButtonTexture.Width - 10;
backButtonPosition.Y = backPosition.Y;
scrollPosition = backgroundPosition + new Vector2(820f, 200f);
topLinePosition.X = (viewport.Width - lineTexture.Width) / 2 - 30f;
topLinePosition.Y = 200f;
bottomLinePosition.X = topLinePosition.X;
bottomLinePosition.Y = 550f;
titlePosition.X = (viewport.Width -
Fonts.HeaderFont.MeasureString(titleText).X) / 2;
titlePosition.Y = backgroundPosition.Y + 70f;
}
#endregion
#region Updating
/// <summary>
/// Handles user input to the dialog.
/// </summary>
public override void HandleInput()
{
// Press Select or Bback
if (InputManager.IsActionTriggered(InputManager.Action.Ok) ||
InputManager.IsActionTriggered(InputManager.Action.Back))
{
ExitScreen();
return;
}
// Scroll up
if (InputManager.IsActionTriggered(InputManager.Action.CursorUp))
{
if (startIndex > 0)
{
startIndex--;
endIndex--;
}
}
// Scroll down
else if (InputManager.IsActionTriggered(InputManager.Action.CursorDown))
{
if (startIndex < dialogueList.Count - drawMaxLines)
{
endIndex++;
startIndex++;
}
}
}
#endregion
#region Drawing
/// <summary>
/// draws the dialog.
/// </summary>
public override void Draw(GameTime gameTime)
{
Vector2 textPosition = dialogueStartPosition;
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
spriteBatch.Begin();
// draw the fading screen
spriteBatch.Draw(fadeTexture, new Rectangle(0, 0, 1280, 720), Color.White);
// draw popup background
spriteBatch.Draw(backgroundTexture, backgroundPosition, Color.White);
// draw the top line
spriteBatch.Draw(lineTexture, topLinePosition, Color.White);
// draw the bottom line
spriteBatch.Draw(lineTexture, bottomLinePosition, Color.White);
// draw scrollbar
spriteBatch.Draw(scrollTexture, scrollPosition, Color.White);
// draw title
spriteBatch.DrawString(Fonts.HeaderFont, titleText, titlePosition,
Fonts.CountColor);
// draw the dialogue
for (int i = startIndex; i < endIndex; i++)
{
spriteBatch.DrawString(Fonts.DescriptionFont, dialogueList[i],
textPosition, Fonts.CountColor);
textPosition.Y += Fonts.DescriptionFont.LineSpacing;
}
// draw the Back button and adjoining text
if (!String.IsNullOrEmpty(backText))
{
spriteBatch.DrawString(Fonts.ButtonNamesFont, backText, backPosition,
Color.White);
spriteBatch.Draw(backButtonTexture, backButtonPosition, Color.White);
}
// draw the Select button and adjoining text
if (!String.IsNullOrEmpty(selectText))
{
selectPosition.X = selectButtonPosition.X -
Fonts.ButtonNamesFont.MeasureString(selectText).X - 10f;
selectPosition.Y = selectButtonPosition.Y;
spriteBatch.DrawString(Fonts.ButtonNamesFont, selectText, selectPosition,
Color.White);
spriteBatch.Draw(selectButtonTexture, selectButtonPosition, Color.White);
}
spriteBatch.End();
}
#endregion
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A new piece of functionality
/// First published in XenServer 7.2.
/// </summary>
public partial class Feature : XenObject<Feature>
{
#region Constructors
public Feature()
{
}
public Feature(string uuid,
string name_label,
string name_description,
bool enabled,
bool experimental,
string version,
XenRef<Host> host)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.enabled = enabled;
this.experimental = experimental;
this.version = version;
this.host = host;
}
/// <summary>
/// Creates a new Feature from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Feature(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Feature from a Proxy_Feature.
/// </summary>
/// <param name="proxy"></param>
public Feature(Proxy_Feature proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Feature.
/// </summary>
public override void UpdateFrom(Feature update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
enabled = update.enabled;
experimental = update.experimental;
version = update.version;
host = update.host;
}
internal void UpdateFrom(Proxy_Feature proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
enabled = (bool)proxy.enabled;
experimental = (bool)proxy.experimental;
version = proxy.version == null ? null : proxy.version;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
}
public Proxy_Feature ToProxy()
{
Proxy_Feature result_ = new Proxy_Feature();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.enabled = enabled;
result_.experimental = experimental;
result_.version = version ?? "";
result_.host = host ?? "";
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Feature
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("enabled"))
enabled = Marshalling.ParseBool(table, "enabled");
if (table.ContainsKey("experimental"))
experimental = Marshalling.ParseBool(table, "experimental");
if (table.ContainsKey("version"))
version = Marshalling.ParseString(table, "version");
if (table.ContainsKey("host"))
host = Marshalling.ParseRef<Host>(table, "host");
}
public bool DeepEquals(Feature other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._enabled, other._enabled) &&
Helper.AreEqual2(this._experimental, other._experimental) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._host, other._host);
}
internal static List<Feature> ProxyArrayToObjectList(Proxy_Feature[] input)
{
var result = new List<Feature>();
foreach (var item in input)
result.Add(new Feature(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Feature server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given Feature.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_feature">The opaque_ref of the given feature</param>
public static Feature get_record(Session session, string _feature)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.feature_get_record(session.opaque_ref, _feature);
else
return new Feature(session.proxy.feature_get_record(session.opaque_ref, _feature ?? "").parse());
}
/// <summary>
/// Get a reference to the Feature instance with the specified UUID.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Feature> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.feature_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Feature>.Create(session.proxy.feature_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the Feature instances with the given label.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Feature>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.feature_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Feature>.Create(session.proxy.feature_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given Feature.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_feature">The opaque_ref of the given feature</param>
public static string get_uuid(Session session, string _feature)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.feature_get_uuid(session.opaque_ref, _feature);
else
return session.proxy.feature_get_uuid(session.opaque_ref, _feature ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given Feature.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_feature">The opaque_ref of the given feature</param>
public static string get_name_label(Session session, string _feature)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.feature_get_name_label(session.opaque_ref, _feature);
else
return session.proxy.feature_get_name_label(session.opaque_ref, _feature ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given Feature.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_feature">The opaque_ref of the given feature</param>
public static string get_name_description(Session session, string _feature)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.feature_get_name_description(session.opaque_ref, _feature);
else
return session.proxy.feature_get_name_description(session.opaque_ref, _feature ?? "").parse();
}
/// <summary>
/// Get the enabled field of the given Feature.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_feature">The opaque_ref of the given feature</param>
public static bool get_enabled(Session session, string _feature)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.feature_get_enabled(session.opaque_ref, _feature);
else
return (bool)session.proxy.feature_get_enabled(session.opaque_ref, _feature ?? "").parse();
}
/// <summary>
/// Get the experimental field of the given Feature.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_feature">The opaque_ref of the given feature</param>
public static bool get_experimental(Session session, string _feature)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.feature_get_experimental(session.opaque_ref, _feature);
else
return (bool)session.proxy.feature_get_experimental(session.opaque_ref, _feature ?? "").parse();
}
/// <summary>
/// Get the version field of the given Feature.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_feature">The opaque_ref of the given feature</param>
public static string get_version(Session session, string _feature)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.feature_get_version(session.opaque_ref, _feature);
else
return session.proxy.feature_get_version(session.opaque_ref, _feature ?? "").parse();
}
/// <summary>
/// Get the host field of the given Feature.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_feature">The opaque_ref of the given feature</param>
public static XenRef<Host> get_host(Session session, string _feature)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.feature_get_host(session.opaque_ref, _feature);
else
return XenRef<Host>.Create(session.proxy.feature_get_host(session.opaque_ref, _feature ?? "").parse());
}
/// <summary>
/// Return a list of all the Features known to the system.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Feature>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.feature_get_all(session.opaque_ref);
else
return XenRef<Feature>.Create(session.proxy.feature_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the Feature Records at once, in a single XML RPC call
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Feature>, Feature> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.feature_get_all_records(session.opaque_ref);
else
return XenRef<Feature>.Create<Proxy_Feature>(session.proxy.feature_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Indicates whether the feature is enabled
/// </summary>
public virtual bool enabled
{
get { return _enabled; }
set
{
if (!Helper.AreEqual(value, _enabled))
{
_enabled = value;
Changed = true;
NotifyPropertyChanged("enabled");
}
}
}
private bool _enabled = false;
/// <summary>
/// Indicates whether the feature is experimental (as opposed to stable and fully supported)
/// </summary>
public virtual bool experimental
{
get { return _experimental; }
set
{
if (!Helper.AreEqual(value, _experimental))
{
_experimental = value;
Changed = true;
NotifyPropertyChanged("experimental");
}
}
}
private bool _experimental = false;
/// <summary>
/// The version of this feature
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
Changed = true;
NotifyPropertyChanged("version");
}
}
}
private string _version = "1.0";
/// <summary>
/// The host where this feature is available
/// </summary>
[JsonConverter(typeof(XenRefConverter<Host>))]
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host = new XenRef<Host>(Helper.NullOpaqueRef);
}
}
| |
using Common;
using FezEngine;
using FezEngine.Components;
using FezEngine.Effects;
using FezEngine.Effects.Structures;
using FezEngine.Services;
using FezEngine.Structure;
using FezEngine.Tools;
using FezGame.Services;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Graphics.Localization;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using MonoMod;
using FezEngine.Mod;
using FezGame.Mod;
namespace FezGame.Components {
public class patch_SpeechBubble : SpeechBubble, patch_ISpeechBubbleManager {
private static readonly Color DefaultTextSecondaryColor = new Color(1f, 1f, 1f, 0.8f);
[MonoModIgnore]
private const int TextBorder = 4;
[MonoModIgnore]
private string textString;
[MonoModIgnore]
private string originalString;
private RenderTarget2D text;
[MonoModIgnore]
private SpriteFont zuishFont;
[MonoModIgnore]
private SpriteBatch spriteBatch;
[MonoModIgnore]
private GlyphTextRenderer GTR;
[MonoModIgnore]
private float distanceFromCenterAtTextChange;
[MonoModIgnore]
private Vector3 oldCamPos;
[MonoModIgnore]
private RenderTarget2D bTexture;
[MonoModIgnore]
private Vector3 lastUsedOrigin;
[MonoModIgnore]
private Vector3 origin;
[MonoModIgnore]
private bool show;
[MonoModIgnore]
private bool changingText;
[MonoModIgnore]
private Group textGroup;
[MonoModIgnore]
private Group scalableMiddle;
[MonoModIgnore]
private readonly Mesh canvasMesh;
[MonoModIgnore]
private readonly Mesh textMesh;
[MonoModIgnore]
private float sinceShown;
[MonoModIgnore]
private Vector2 scalableMiddleSize;
[MonoModIgnore]
private readonly Color TextColor = Color.White;
[MonoModIgnore]
private Group scalableTop;
[MonoModIgnore]
private Group bGroup;
[MonoModIgnore]
private Group tailGroup;
[MonoModIgnore]
private Group swGroup;
[MonoModIgnore]
private Group seGroup;
[MonoModIgnore]
private Group nwGroup;
[MonoModIgnore]
private Group neGroup;
[MonoModIgnore]
private Group scalableBottom;
public IGameCameraManager CameraManager { [MonoModIgnore] get; [MonoModIgnore] set; }
public IContentManagerProvider CMProvider { [MonoModIgnore] get; [MonoModIgnore] set; }
public SpeechFont Font { [MonoModIgnore] get; [MonoModIgnore] set; }
public IFontManager FontManager { [MonoModIgnore] get; [MonoModIgnore] set; }
public IGameStateManager GameState { [MonoModIgnore] get; [MonoModIgnore] set; }
public bool Hidden { [MonoModIgnore] get; [MonoModIgnore] private set; }
public ILevelManager LevelManager { [MonoModIgnore] get; [MonoModIgnore] set; }
public Vector3 Origin { [MonoModIgnore] get; [MonoModIgnore] set; }
private Color textColor;
public Color ColorFG {
get {
return textColor;
}
set {
textColor = value;
if (!FezMath.AlmostEqual(lastUsedOrigin, origin, 0.0625f) && sinceShown >= 1 && !changingText) {
OnTextChanged(false);
}
}
}
private Color textSecondaryColor;
public Color ColorSecondaryFG {
get {
return textSecondaryColor;
}
set {
textSecondaryColor = value;
if (!FezMath.AlmostEqual(lastUsedOrigin, origin, 0.0625f) && sinceShown >= 1 && !changingText) {
OnTextChanged(false);
}
}
}
private Color lastColorBG;
public Color ColorBG { get; set; }
private string textSpeaker;
public string Speaker {
get {
return textSpeaker;
}
set {
textSpeaker = value;
if (!FezMath.AlmostEqual(lastUsedOrigin, origin, 0.0625f) && sinceShown >= 1 && !changingText) {
OnTextChanged(false);
}
}
}
private Texture2D tailGroupTexture, neGroupTexture, nwGroupTexture, seGroupTexture, swGroupTexture, scalableGroupTexture;
public patch_SpeechBubble(Game game)
: base(game) {
//no-op
}
public extern void orig_Initialize();
public override void Initialize() {
orig_Initialize();
textColor = Color.White;
textSecondaryColor = DefaultTextSecondaryColor;
ColorBG = Color.Black;
}
protected extern void orig_LoadContent();
protected override void LoadContent() {
orig_LoadContent();
//Currently requires custom assets, thus default color is black.
tailGroupTexture = (Texture2D) tailGroup.Texture;
neGroupTexture = (Texture2D) neGroup.Texture;
nwGroupTexture = (Texture2D) nwGroup.Texture;
seGroupTexture = (Texture2D) seGroup.Texture;
swGroupTexture = (Texture2D) swGroup.Texture;
scalableGroupTexture = CMProvider.Global.Load<Texture2D>("Other Textures/FullWhite");
}
protected extern void orig_UnloadContent();
protected override void UnloadContent() {
orig_UnloadContent();
if (!(scalableMiddle.Texture is RenderTarget2D)) {
return;
}
TextureExtensions.Unhook(tailGroup.Texture); tailGroup.Texture.Dispose();
TextureExtensions.Unhook(neGroup.Texture); neGroup.Texture.Dispose();
TextureExtensions.Unhook(nwGroup.Texture); nwGroup.Texture.Dispose();
TextureExtensions.Unhook(seGroup.Texture); seGroup.Texture.Dispose();
TextureExtensions.Unhook(swGroup.Texture); swGroup.Texture.Dispose();
TextureExtensions.Unhook(scalableMiddle.Texture); scalableMiddle.Texture.Dispose();
}
private extern void orig_OnTextChanged(bool update);
private void OnTextChanged(bool update) {
//Holy decompiler code.
string a = textString;
textString = originalString;
SpriteFont spriteFont = (Font != SpeechFont.Pixel) ? zuishFont : FontManager.Big;
SpriteFont spriteFontSpeaker = (Font != SpeechFont.Pixel) ? zuishFont : FontManager.Small;
if (Font == SpeechFont.Zuish) {
textString = textString.Replace(" ", " ");
if (textSpeaker != null) {
textSpeaker = textSpeaker.ToUpperInvariant();
}
}
float fontScale = (!Culture.IsCJK || Font != SpeechFont.Pixel) ? 1f : FontManager.SmallFactor;
float num3 = 0;
if (Font != SpeechFont.Zuish) {
float num4 = (!update) ? 0.85f : 0.9f;
float num5 = (float) GraphicsDevice.Viewport.Width / (1280f * GraphicsDevice.GetViewScale());
num3 = (Origin - CameraManager.InterpolatedCenter).Dot(CameraManager.Viewpoint.RightVector());
float num6 = (GraphicsDevice.DisplayMode.Width >= 1280f) ? (Math.Max(-num3 * 16f * CameraManager.PixelsPerTrixel + 1280f * num5 / 2f * num4, 50f) / (CameraManager.PixelsPerTrixel / 2f)) : (Math.Max(-num3 * 16f * CameraManager.PixelsPerTrixel + 640f * num4, 50f) * 0.6666667f);
if (GameState.InMap) {
num6 = 500f;
}
num6 = Math.Max(num6, 70f);
List<GlyphTextRenderer.FilledInGlyph> list;
string text = GTR.FillInGlyphs(textString, out list);
if (Culture.IsCJK) {
fontScale /= 2f;
}
StringBuilder stringBuilder = new StringBuilder(WordWrap.Split(text, spriteFont, num6 / fontScale));
if (Culture.IsCJK) {
fontScale *= 2f;
}
bool flag2 = true;
int num7 = 0;
for (int i = 0; i < stringBuilder.Length; i++) {
if (flag2 && stringBuilder[i] == '^') {
for (int j = i; j < i + list[num7].Length; j++) {
if (stringBuilder[j] == '\r' || stringBuilder[j] == '\n') {
stringBuilder.Remove(j, 1);
j--;
}
}
stringBuilder.Remove(i, list[num7].Length);
stringBuilder.Insert(i, list[num7].OriginalGlyph);
num7++;
} else {
flag2 = (stringBuilder[i] == ' ' || stringBuilder[i] == '\r' || stringBuilder[i] == '\n');
}
}
textString = stringBuilder.ToString();
if (!update) {
distanceFromCenterAtTextChange = num3;
}
}
if (update && (a == textString || Math.Abs(distanceFromCenterAtTextChange - num3) < 1.5f)) {
textString = a;
return;
}
if (Culture.IsCJK && Font == SpeechFont.Pixel) {
float viewScale = GraphicsDevice.GetViewScale();
if (viewScale < 1.5f) {
spriteFont = FontManager.Small;
} else {
spriteFont = FontManager.Big;
fontScale /= 2f;
}
fontScale *= 2f;
}
bool flag3;
Vector2 value = GTR.MeasureWithGlyphs(spriteFont, textString, fontScale, out flag3);
if (!Culture.IsCJK && flag3) {
spriteFont.LineSpacing += 8;
bool flag4 = flag3;
value = GTR.MeasureWithGlyphs(spriteFont, textString, fontScale, out flag3);
flag3 = flag4;
}
float scaleFactor = 1f;
if (Culture.IsCJK && Font == SpeechFont.Pixel) {
scaleFactor = 2f;
}
scalableMiddleSize = value + Vector2.One * 4f * 2f * scaleFactor + Vector2.UnitX * 4f * 2f * scaleFactor;
if (Font == SpeechFont.Zuish) {
scalableMiddleSize += Vector2.UnitY * 2f;
}
Vector2 textMainSize = new Vector2(scalableMiddleSize.X, scalableMiddleSize.Y);
float fontScaleSpeaker = fontScale * 0.5f;
int speakerHeight = 0;
int speakerOffset = 0;
int speakerHeightAdded = 0;
if (textSpeaker != null) {
speakerHeight = (int) spriteFontSpeaker.MeasureString(textSpeaker).Y;
speakerHeightAdded += 4;
if (Font != SpeechFont.Pixel) {
speakerOffset += 2;
}
scalableMiddleSize.Y += speakerHeightAdded;
}
int width = (int) scalableMiddleSize.X;
int height = (int) scalableMiddleSize.Y;
if (Culture.IsCJK && Font == SpeechFont.Pixel) {
fontScale *= 2f;
fontScaleSpeaker *= 2f;
width *= 2;
height *= 2;
}
if (textSpeaker != null && Font == SpeechFont.Pixel) {
fontScale *= 2f;
fontScaleSpeaker *= 2f;
width *= 2;
height *= 2;
}
if (this.text != null) {
text.Unhook();
text.Dispose();
}
text = new RenderTarget2D(GraphicsDevice, width, height, false, GraphicsDevice.PresentationParameters.BackBufferFormat, GraphicsDevice.PresentationParameters.DepthStencilFormat, 0, RenderTargetUsage.PreserveContents);
GraphicsDevice.SetRenderTarget(text);
GraphicsDevice.PrepareDraw();
GraphicsDevice.Clear(ClearOptions.Target, ColorEx.TransparentWhite, 1, 0);
Vector2 value2 = (!Culture.IsCJK) ? Vector2.Zero : new Vector2(8f);
if (Culture.IsCJK) {
spriteBatch.BeginLinear();
} else {
spriteBatch.BeginPoint();
}
if (Font == SpeechFont.Pixel) {
GTR.DrawString(spriteBatch, spriteFont, textString, (textMainSize / 2 - value / 2 + value2).Round(), textColor, fontScale);
} else {
spriteBatch.DrawString(spriteFont, textString, textMainSize / 2 - value / 2, textColor, 0, Vector2.Zero, 1f, SpriteEffects.None, 0);
}
if (textSpeaker != null) {
GTR.DrawString(spriteBatch, spriteFontSpeaker, textSpeaker, new Vector2((textMainSize / 2 - value / 2 + value2).Round().X, height - speakerHeight * fontScaleSpeaker - speakerOffset), textSecondaryColor, fontScaleSpeaker);
}
spriteBatch.End();
GraphicsDevice.SetRenderTarget(null);
if (Font == SpeechFont.Zuish) {
float x = scalableMiddleSize.X;
scalableMiddleSize.X = scalableMiddleSize.Y;
scalableMiddleSize.Y = x;
}
if (Culture.IsCJK && Font == SpeechFont.Pixel) {
scalableMiddleSize /= 2f;
}
scalableMiddleSize /= 16f;
scalableMiddleSize -= Vector2.One;
textMesh.SamplerState = ((!Culture.IsCJK || Font != SpeechFont.Pixel) ? SamplerState.PointClamp : SamplerState.AnisotropicClamp);
textGroup.Texture = text;
oldCamPos = CameraManager.InterpolatedCenter;
lastUsedOrigin = Origin;
if (!Culture.IsCJK && flag3) {
spriteFont.LineSpacing -= 8;
}
if (lastColorBG != ColorBG) {
lastColorBG = ColorBG;
//Instead of simply drawing the texture tinted.. nope, recolor the texture!
recolorBG(tailGroup, tailGroupTexture);
recolorBG(neGroup, neGroupTexture);
recolorBG(nwGroup, nwGroupTexture);
recolorBG(seGroup, seGroupTexture);
recolorBG(swGroup, swGroupTexture);
recolorBG(scalableMiddle, scalableGroupTexture);
scalableBottom.Texture = scalableTop.Texture = scalableMiddle.Texture;
}
}
private void recolorBG(Group group, Texture2D tex) {
RenderTarget2D rt;
if (group.Texture is RenderTarget2D) {
rt = (RenderTarget2D) group.Texture;
} else {
group.Texture = rt = new RenderTarget2D(GraphicsDevice, tex.Width, tex.Height, false, GraphicsDevice.PresentationParameters.BackBufferFormat, GraphicsDevice.PresentationParameters.DepthStencilFormat, 0, RenderTargetUsage.PreserveContents);
}
GraphicsDevice.SetRenderTarget(rt);
GraphicsDevice.PrepareDraw();
GraphicsDevice.Clear(ClearOptions.Target, ColorEx.TransparentWhite, 1, 0);
spriteBatch.BeginPoint();
spriteBatch.Draw(tex, new Rectangle(0, 0, tex.Width, tex.Height), ColorBG);
spriteBatch.End();
GraphicsDevice.SetRenderTarget(null);
}
public extern void orig_Draw(GameTime gameTime);
public override void Draw(GameTime gameTime) {
orig_Draw(gameTime);
bool flag = show;
if (show && changingText) {
flag = false;
}
if (sinceShown == 0 && !flag && !changingText) {
textSpeaker = null;
textColor = Color.White;
textSecondaryColor = DefaultTextSecondaryColor;
ColorBG = Color.Black;
}
}
}
}
| |
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Reflection;
using NetTopologySuite.Geometries;
using SharpMap.Rendering.Symbolizer;
using Common.Logging;
namespace SharpMap.Styles
{
/// <summary>
/// Defines a style used for rendering vector data
/// </summary>
[Serializable]
public class VectorStyle : Style, ICloneable
{
private static readonly Random _rnd = new Random();
static ILog logger = LogManager.GetLogger(typeof(VectorStyle));
/// <summary>
/// Default Symbol
/// </summary>
public static readonly Image DefaultSymbol;
/// <summary>
/// Static constructor
/// </summary>
static VectorStyle()
{
var rs = Assembly.GetExecutingAssembly().GetManifestResourceStream("SharpMap.Styles.DefaultSymbol.png");
if (rs != null)
DefaultSymbol = Image.FromStream(rs);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public VectorStyle Clone()
{
VectorStyle vs;
lock (this)
{
try
{
vs = (VectorStyle)MemberwiseClone();// new VectorStyle();
if (_fillStyle != null)
vs._fillStyle = _fillStyle.Clone() as Brush;
if (_lineStyle != null)
vs._lineStyle = _lineStyle.Clone() as Pen;
if (_outlineStyle != null)
vs._outlineStyle = _outlineStyle.Clone() as Pen;
if (_pointBrush != null)
vs._pointBrush = _pointBrush.Clone() as Brush;
vs._symbol = (_symbol != null ? _symbol.Clone() as Image : null);
vs._symbolRotation = _symbolRotation;
vs._symbolScale = _symbolScale;
vs.PointSymbolizer = PointSymbolizer;
vs.LineSymbolizer = LineSymbolizer;
vs.PolygonSymbolizer = PolygonSymbolizer;
}
catch (Exception ee)
{
logger.Error("Exception while creating cloned style", ee);
/* if we got an exception, set the style to null and return since we don't know what we got...*/
vs = null;
}
}
return vs;
}
object ICloneable.Clone()
{
return Clone();
}
#region Privates
private Brush _fillStyle;
private Pen _lineStyle;
private bool _outline;
private Pen _outlineStyle;
private Image _symbol;
private float _lineOffset;
#endregion
/// <summary>
/// Initializes a new VectorStyle and sets the default values
/// </summary>
/// <remarks>
/// Default style values when initialized:<br/>
/// *LineStyle: 1px solid black<br/>
/// *FillStyle: Solid black<br/>
/// *Outline: No Outline
/// *Symbol: null-reference
/// </remarks>
public VectorStyle()
{
Outline = new Pen(Color.Black, 1);
Line = new Pen(Color.Black, 1);
Fill = new SolidBrush (Color.FromArgb(192, Color.Black));
EnableOutline = false;
SymbolScale = 1f;
PointColor = new SolidBrush(Color.Red);
PointSize = 10f;
LineOffset = 0;
}
#region Properties
private PointF _symbolOffset;
private float _symbolRotation;
private float _symbolScale;
private float _pointSize;
private Brush _pointBrush;
/// <summary>
/// Linestyle for line geometries
/// </summary>
public Pen Line
{
get { return _lineStyle; }
set { _lineStyle = value; }
}
/// <summary>
/// Outline style for line and polygon geometries
/// </summary>
public Pen Outline
{
get { return _outlineStyle; }
set { _outlineStyle = value; }
}
/// <summary>
/// Specified whether the objects are rendered with or without outlining
/// </summary>
public bool EnableOutline
{
get { return _outline; }
set { _outline = value; }
}
/// <summary>
/// Fillstyle for Polygon geometries
/// </summary>
public Brush Fill
{
get { return _fillStyle; }
set { _fillStyle = value; }
}
/// <summary>
/// Fillstyle for Point geometries (will be used if no Symbol is set)
/// </summary>
public Brush PointColor
{
get { return _pointBrush; }
set { _pointBrush = value; }
}
/// <summary>
/// Size for Point geometries (if drawn with PointColor), will not have affect for Points drawn with Symbol
/// </summary>
public float PointSize
{
get { return _pointSize; }
set { _pointSize= value; }
}
/// <summary>
/// Symbol used for rendering points
/// </summary>
public Image Symbol
{
get { return _symbol; }
set { _symbol = value; }
}
/// <summary>
/// Scale of the symbol (defaults to 1)
/// </summary>
/// <remarks>
/// Setting the symbolscale to '2.0' doubles the size of the symbol, where a scale of 0.5 makes the scale half the size of the original image
/// </remarks>
public float SymbolScale
{
get { return _symbolScale; }
set { _symbolScale = value; }
}
/// <summary>
/// Gets or sets the offset in pixels of the symbol.
/// </summary>
/// <remarks>
/// The symbol offset is scaled with the <see cref="SymbolScale"/> property and refers to the offset af <see cref="SymbolScale"/>=1.0.
/// </remarks>
public PointF SymbolOffset
{
get { return _symbolOffset; }
set { _symbolOffset = value; }
}
/// <summary>
/// Gets or sets the rotation of the symbol in degrees (clockwise is positive)
/// </summary>
public float SymbolRotation
{
get { return _symbolRotation; }
set { _symbolRotation = value; }
}
/// <summary>
/// Gets or sets the offset (in pixel units) by which line will be offset from its original posision (perpendicular).
/// </summary>
/// <remarks>
/// A positive value offsets the line to the right
/// A negative value offsets to the left
/// </remarks>
public float LineOffset
{
get { return _lineOffset; }
set { _lineOffset = value; }
}
/// <summary>
/// Gets or sets the symbolizer for puntal geometries
/// </summary>
/// <remarks>Setting this property will lead to ignorance towards all <see cref="IPuntal"/> related style settings</remarks>
public PointSymbolizer PointSymbolizer { get; set; }
/// <summary>
/// Gets or sets the symbolizer for lineal geometries
/// </summary>
/// <remarks>Setting this property will lead to ignorance towards all <see cref="ILineal"/> related style settings</remarks>
public ILineSymbolizer LineSymbolizer { get; set; }
/// <summary>
/// Gets or sets the symbolizer for IPolygonal geometries
/// </summary>
/// <remarks>Setting this property will lead to ignorance towards all <see cref="IPolygonal"/> related style settings</remarks>
public PolygonSymbolizer PolygonSymbolizer { get; set; }
#endregion
/// <summary>
/// Releases managed resources
/// </summary>
protected override void ReleaseManagedResources()
{
if (IsDisposed)
return;
if (_fillStyle != null)
{
_fillStyle.Dispose();
_fillStyle = null;
}
if (_lineStyle != null)
{
_lineStyle.Dispose();
_lineStyle = null;
}
if (_outlineStyle != null)
{
_outlineStyle.Dispose();
_outlineStyle = null;
}
if (_pointBrush != null)
{
_pointBrush.Dispose();
_pointBrush = null;
}
if (_symbol != null)
{
_symbol.Dispose();
_symbol = null;
}
base.ReleaseManagedResources();
}
/// <summary>
/// Utility function to create a random style
/// </summary>
/// <returns>A vector style</returns>
public static VectorStyle CreateRandomStyle()
{
var res = new VectorStyle();
RandomizePuntalStyle(res);
RandomizeLinealStyle(res);
RandomizeIPolygonalStyle(res);
return res;
}
/// <summary>
/// Factory method to create a random puntal style
/// </summary>
/// <returns>A puntal vector style</returns>
public static VectorStyle CreateRandomPuntalStyle()
{
var res = new VectorStyle();
ClearLinealStyle(res);
ClearIPolygonalStyle(res);
RandomizePuntalStyle(res);
return res;
}
/// <summary>
/// Factory method to create a random puntal style
/// </summary>
/// <returns>A puntal vector style</returns>
public static VectorStyle CreateRandomLinealStyle()
{
var res = new VectorStyle();
ClearPuntalStyle(res);
ClearIPolygonalStyle(res);
RandomizeLinealStyle(res);
return res;
}
/// <summary>
/// Factory method to create a random puntal style
/// </summary>
/// <returns>A puntal vector style</returns>
public static VectorStyle CreateRandomIPolygonalStyle()
{
var res = new VectorStyle();
ClearPuntalStyle(res);
ClearLinealStyle(res);
RandomizeIPolygonalStyle(res);
return res;
}
/// <summary>
/// Utility function to modify <paramref name="style"/> in order to prevent drawing of any puntal components
/// </summary>
/// <param name="style">The style to modify</param>
private static void ClearPuntalStyle(VectorStyle style)
{
style.PointColor = Brushes.Transparent;
style.PointSize = 0f;
style.Symbol = null;
style.PointSymbolizer = null;
}
/// <summary>
/// Utility function to modify <paramref name="style"/> in order to prevent drawing of any puntal components
/// </summary>
/// <param name="style">The style to modify</param>
private static void ClearLinealStyle(VectorStyle style)
{
style.EnableOutline = false;
style.Line = Pens.Transparent;
style.Outline = Pens.Transparent;
}
/// <summary>
/// Utility function to modify <paramref name="style"/> in order to prevent drawing of any puntal components
/// </summary>
/// <param name="style">The style to modify</param>
private static void ClearIPolygonalStyle(VectorStyle style)
{
style.EnableOutline = false;
style.Line = Pens.Transparent;
style.Outline = Pens.Transparent;
style.Fill = Brushes.Transparent;
}
/// <summary>
/// Utility function to randomize puntal settings
/// </summary>
/// <param name="res">The style to randomize</param>
private static void RandomizePuntalStyle(VectorStyle res)
{
switch (_rnd.Next(2))
{
case 0:
res.Symbol = DefaultSymbol;
res.SymbolScale = 0.01f * _rnd.Next(80, 200);
break;
case 1:
res.Symbol = null;
res.PointColor = new SolidBrush(CreateRandomKnownColor(_rnd.Next(67, 256)));
res.PointSize = 0.1f * _rnd.Next(5, 20);
break;
}
}
/// <summary>
/// Utility function to randomize lineal settings
/// </summary>
/// <param name="res">The style to randomize</param>
private static void RandomizeLinealStyle(VectorStyle res)
{
res.Line = new Pen(CreateRandomKnownColor(_rnd.Next(67, 256)), _rnd.Next(1, 3));
res.EnableOutline = _rnd.Next(0, 2) == 1;
if (res.EnableOutline)
res.Outline = new Pen(CreateRandomKnownColor(_rnd.Next(67, 256)), _rnd.Next((int)res.Line.Width, 5));
}
/// <summary>
/// Utility function to randomize IPolygonal settings
/// </summary>
/// <param name="res"></param>
private static void RandomizeIPolygonalStyle(VectorStyle res)
{
switch (_rnd.Next(3))
{
case 0:
res.Fill = new SolidBrush(CreateRandomKnownColor(_rnd.Next(67, 256)));
break;
case 1:
res.Fill = new HatchBrush((HatchStyle)_rnd.Next(0, 53),
CreateRandomKnownColor(), CreateRandomKnownColor(_rnd.Next(67, 256)));
break;
case 2:
var alpha = _rnd.Next(67, 256);
res.Fill = new LinearGradientBrush(new System.Drawing.Point(0, 0), new System.Drawing.Point(_rnd.Next(5, 10), _rnd.Next(5, 10)),
CreateRandomKnownColor(alpha), CreateRandomKnownColor(alpha));
break;
}
}
/// <summary>
/// Factory method to create a random color from the <see cref="KnownColor"/>s enumeration
/// </summary>
/// <param name="alpha">An optional alpha value.</param>
/// <returns></returns>
public static Color CreateRandomKnownColor(int alpha = 255)
{
var kc = (KnownColor)_rnd.Next(28, 168);
return alpha == 255
? Color.FromKnownColor(kc)
: Color.FromArgb(alpha, Color.FromKnownColor(kc));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Scripting.Utils;
namespace Microsoft.Scripting.Runtime {
/// <summary>
/// Abstract base class used for optimized thread-safe dictionaries which have a set
/// of pre-defined string keys.
///
/// Implementers derive from this class and override the GetExtraKeys, TrySetExtraValue,
/// and TryGetExtraValue methods. When looking up a value first the extra keys will be
/// searched using the optimized Try*ExtraValue functions. If the value isn't found there
/// then the value is stored in the underlying .NET dictionary.
///
/// This dictionary can store object values in addition to string values. It also supports
/// null keys.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
public abstract class CustomStringDictionary : IDictionary, IDictionary<object, object> {
private Dictionary<object, object> _data;
private static readonly object _nullObject = new object();
/// <summary>
/// Gets a list of the extra keys that are cached by the the optimized implementation
/// of the module.
/// </summary>
public abstract string[] GetExtraKeys();
/// <summary>
/// Try to set the extra value and return true if the specified key was found in the
/// list of extra values.
/// </summary>
protected internal abstract bool TrySetExtraValue(string key, object value);
/// <summary>
/// Try to get the extra value and returns true if the specified key was found in the
/// list of extra values. Returns true even if the value is Uninitialized.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
protected internal abstract bool TryGetExtraValue(string key, out object value);
private void InitializeData() {
Debug.Assert(_data == null);
_data = new Dictionary<object, object>();
}
#region IDictionary<object, object> Members
void IDictionary<object, object>.Add(object key, object value) {
if (key is string strKey) {
lock (this) {
if (_data == null) InitializeData();
if (TrySetExtraValue(strKey, value))
return;
_data.Add(strKey, value);
}
} else {
AddObjectKey(key, value);
}
}
private void AddObjectKey(object key, object value) {
if (_data == null) {
InitializeData();
}
_data[key] = value;
}
bool IDictionary<object, object>.ContainsKey(object key) {
lock (this) {
if (_data == null) {
return false;
}
object dummy;
return _data.TryGetValue(key, out dummy);
}
}
public ICollection<object> Keys {
get {
List<object> res = new List<object>();
lock (this) {
if (_data != null) {
res.AddRange(_data.Keys);
}
}
foreach (var key in GetExtraKeys()) {
if (TryGetExtraValue(key, out object dummy) && dummy != Uninitialized.Instance) {
res.Add(key);
}
}
return res;
}
}
bool IDictionary<object, object>.Remove(object key) {
if (key is string strKey) {
lock (this) {
if (TrySetExtraValue(strKey, Uninitialized.Instance)) return true;
if (_data == null) return false;
return _data.Remove(strKey);
}
}
return RemoveObjectKey(key);
}
private bool RemoveObjectKey(object key) {
return _data.Remove(key);
}
public bool TryGetValue(object key, out object value) {
if (key is string strKey) {
lock (this) {
if (TryGetExtraValue(strKey, out value) && value != Uninitialized.Instance) return true;
if (_data == null) return false;
return _data.TryGetValue(strKey, out value);
}
}
return TryGetObjectValue(key, out value);
}
private bool TryGetObjectValue(object key, out object value) {
if (_data == null) {
value = null;
return false;
}
return _data.TryGetValue(key, out value);
}
ICollection<object> IDictionary<object, object>.Values {
get {
List<object> res = new List<object>();
lock (this) {
if (_data != null) {
res.AddRange(_data.Values);
}
}
foreach (var key in GetExtraKeys()) {
if (TryGetExtraValue(key, out object value) && value != Uninitialized.Instance) {
res.Add(value);
}
}
return res;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public object this[object key] {
get {
string strKey = key as string;
object res;
if (strKey != null) {
lock (this) {
if (TryGetExtraValue(strKey, out res) && !(res is Uninitialized)) return res;
if (_data == null) {
throw new KeyNotFoundException(strKey);
}
return _data[strKey];
}
}
if (TryGetObjectValue(key, out res))
return res;
throw new KeyNotFoundException(key.ToString());
}
set {
if (key is string strKey) {
lock (this) {
if (TrySetExtraValue(strKey, value)) return;
if (_data == null) InitializeData();
_data[strKey] = value;
}
} else {
AddObjectKey(key, value);
}
}
}
#endregion
#region ICollection<KeyValuePair<string,object>> Members
public void Add(KeyValuePair<object, object> item) {
throw new NotImplementedException();
}
public void Clear() {
lock (this) {
foreach (var key in GetExtraKeys()) {
TrySetExtraValue(key, Uninitialized.Instance);
}
_data = null;
}
}
public bool Contains(KeyValuePair<object, object> item) {
throw new NotImplementedException();
}
public void CopyTo(KeyValuePair<object, object>[] array, int arrayIndex) {
ContractUtils.RequiresNotNull(array, nameof(array));
ContractUtils.RequiresArrayRange(array, arrayIndex, Count, nameof(arrayIndex), nameof(Count));
foreach (KeyValuePair<object, object> kvp in ((IEnumerable<KeyValuePair<object, object>>)this)) {
array[arrayIndex++] = kvp;
}
}
public int Count {
get {
int count = _data?.Count ?? 0;
lock (this) {
foreach (var key in GetExtraKeys()) {
if (TryGetExtraValue(key, out object dummy) && dummy != Uninitialized.Instance) count++;
}
}
return count;
}
}
public bool IsReadOnly => false;
public bool Remove(KeyValuePair<object, object> item) {
throw new NotImplementedException();
}
public bool Remove(object key) {
if (!(key is string strKey))
return RemoveObjectKey(key);
if (TrySetExtraValue(strKey, Uninitialized.Instance)) {
return true;
}
lock (this) {
return _data != null && _data.Remove(strKey);
}
}
#endregion
#region IEnumerable<KeyValuePair<object,object>> Members
IEnumerator<KeyValuePair<object, object>> IEnumerable<KeyValuePair<object, object>>.GetEnumerator() {
if (_data != null) {
foreach (KeyValuePair<object, object> o in _data) {
yield return o;
}
}
foreach (var o in GetExtraKeys()) {
if (TryGetExtraValue(o, out object val) && val != Uninitialized.Instance) {
yield return new KeyValuePair<object, object>(o, val);
}
}
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator() {
List<object> l = new List<object>(this.Keys);
for (int i = 0; i < l.Count; i++) {
object baseVal = l[i];
object nullVal = l[i] = CustomStringDictionary.ObjToNull(l[i]);
if (baseVal != nullVal) {
// we've transformed null, stop looking
break;
}
}
return l.GetEnumerator();
}
#endregion
#region IDictionary Members
void IDictionary.Add(object key, object value) {
((IDictionary<object, object>)this).Add(key, value);
}
public bool Contains(object key) {
object dummy;
return ((IDictionary<object, object>)this).TryGetValue(key, out dummy);
}
IDictionaryEnumerator IDictionary.GetEnumerator() {
List<IDictionaryEnumerator> enums = new List<IDictionaryEnumerator>();
enums.Add(new ExtraKeyEnumerator(this));
if (_data != null) enums.Add(((IDictionary)_data).GetEnumerator());
return new DictionaryUnionEnumerator(enums);
}
public bool IsFixedSize {
get { return false; }
}
ICollection IDictionary.Keys {
get {
return new List<object>(((IDictionary<object, object>)this).Keys);
}
}
void IDictionary.Remove(object key) {
Remove(key);
}
ICollection IDictionary.Values {
get {
return new List<object>(((IDictionary<object, object>)this).Values);
}
}
#endregion
#region IValueEquality Members
public int GetValueHashCode() {
throw Error.DictionaryNotHashable();
}
public virtual bool ValueEquals(object other) {
if (object.ReferenceEquals(this, other)) return true;
IDictionary<object, object> oth = other as IDictionary<object, object>;
IDictionary<object, object> ths = this as IDictionary<object, object>;
if (oth?.Count != ths.Count) return false;
foreach (KeyValuePair<object, object> o in ths) {
if (!oth.TryGetValue(o.Key, out object res))
return false;
if (res != null) {
if (!res.Equals(o.Value)) return false;
} else if (o.Value != null) {
if (!o.Value.Equals(res)) return false;
} // else both null and are equal
}
return true;
}
#endregion
public void CopyTo(Array array, int index) {
throw Error.MethodOrOperatorNotImplemented();
}
public bool IsSynchronized => true;
public object SyncRoot {
get {
// TODO: Sync root shouldn't be this, it should be data.
return this;
}
}
public static object NullToObj(object o) {
if (o == null) return _nullObject;
return o;
}
public static object ObjToNull(object o) {
if (o == _nullObject) return null;
return o;
}
public static bool IsNullObject(object o) {
return o == _nullObject;
}
}
[Obsolete("Derive directly from CustomStringDictionary instead")]
public abstract class CustomSymbolDictionary : CustomStringDictionary {
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine.AssetGraph;
namespace AssetBundleGraph {
public enum NodeKind : int {
LOADER_GUI,
FILTER_GUI,
IMPORTSETTING_GUI,
MODIFIER_GUI,
GROUPING_GUI,
PREFABBUILDER_GUI,
BUNDLECONFIG_GUI,
BUNDLEBUILDER_GUI,
EXPORTER_GUI
}
public enum ExporterExportOption : int {
ErrorIfNoExportDirectoryFound,
AutomaticallyCreateIfNoExportDirectoryFound,
DeleteAndRecreateExportDirectory
}
[Serializable]
public class FilterEntry {
[SerializeField] private string m_filterKeyword;
[SerializeField] private string m_filterKeytype;
[SerializeField] private ConnectionPointData m_point; // deprecated. it is here for compatibility
[SerializeField] private string m_pointId;
public FilterEntry(string keyword, string keytype, ConnectionPointData point) {
m_filterKeyword = keyword;
m_filterKeytype = keytype;
m_pointId = point.Id;
}
public string FilterKeyword {
get {
return m_filterKeyword;
}
set {
m_filterKeyword = value;
}
}
public string FilterKeytype {
get {
return m_filterKeytype;
}
set {
m_filterKeytype = value;
}
}
public string ConnectionPointId {
get {
if(m_pointId == null && m_point != null) {
m_pointId = m_point.Id;
}
return m_pointId;
}
}
public string Hash {
get {
return m_filterKeyword+m_filterKeytype;
}
}
}
[Serializable]
public class Variant {
[SerializeField] private string m_name;
[SerializeField] private ConnectionPointData m_point; // deprecated. it is here for compatibility
[SerializeField] private string m_pointId;
public Variant(string name, ConnectionPointData point) {
m_name = name;
m_pointId = point.Id;
}
public string Name {
get {
return m_name;
}
set {
m_name = value;
}
}
public string ConnectionPointId {
get {
if(m_pointId == null && m_point != null) {
m_pointId = m_point.Id;
}
return m_pointId;
}
}
}
/*
* node data saved in/to Json
*/
[Serializable]
public class NodeData {
private const string NODE_NAME = "name";
private const string NODE_ID = "id";
private const string NODE_KIND = "kind";
private const string NODE_POS = "pos";
private const string NODE_POS_X = "x";
private const string NODE_POS_Y = "y";
private const string NODE_INPUTPOINTS = "inputPoints";
private const string NODE_OUTPUTPOINTS = "outputPoints";
//loader settings
private const string NODE_LOADER_LOAD_PATH = "loadPath";
//exporter settings
private const string NODE_EXPORTER_EXPORT_PATH = "exportTo";
private const string NODE_EXPORTER_EXPORT_OPTION = "exportOption";
//filter settings
private const string NODE_FILTER = "filter";
private const string NODE_FILTER_KEYWORD = "keyword";
private const string NODE_FILTER_KEYTYPE = "keytype";
private const string NODE_FILTER_POINTID = "pointId";
//group settings
private const string NODE_GROUPING_KEYWORD = "groupingKeyword";
//mofidier/prefabBuilder settings
private const string NODE_SCRIPT_CLASSNAME = "scriptClassName";
private const string NODE_SCRIPT_INSTANCE_DATA = "scriptInstanceData";
//bundleconfig settings
private const string NODE_BUNDLECONFIG_BUNDLENAME_TEMPLATE = "bundleNameTemplate";
private const string NODE_BUNDLECONFIG_VARIANTS = "variants";
private const string NODE_BUNDLECONFIG_VARIANTS_NAME = "name";
private const string NODE_BUNDLECONFIG_VARIANTS_POINTID = "pointId";
private const string NODE_BUNDLECONFIG_USE_GROUPASVARIANTS = "useGroupAsVariants";
//bundlebuilder settings
private const string NODE_BUNDLEBUILDER_ENABLEDBUNDLEOPTIONS = "enabledBundleOptions";
//prefabbuilder settings
private const string NODE_PREFABBUILDER_REPLACEPREFABOPTIONS = "replacePrefabOptions";
[SerializeField] private string m_name;
[SerializeField] private string m_id;
[SerializeField] private NodeKind m_kind;
[SerializeField] private float m_x;
[SerializeField] private float m_y;
[SerializeField] private string m_scriptClassName;
[SerializeField] private List<FilterEntry> m_filter;
[SerializeField] private List<ConnectionPointData> m_inputPoints;
[SerializeField] private List<ConnectionPointData> m_outputPoints;
[SerializeField] private SerializableMultiTargetString m_loaderLoadPath;
[SerializeField] private SerializableMultiTargetString m_exporterExportPath;
[SerializeField] private SerializableMultiTargetString m_groupingKeyword;
[SerializeField] private SerializableMultiTargetString m_bundleConfigBundleNameTemplate;
[SerializeField] private SerializableMultiTargetString m_scriptInstanceData;
[SerializeField] private List<Variant> m_variants;
[SerializeField] private bool m_bundleConfigUseGroupAsVariants;
[SerializeField] private SerializableMultiTargetInt m_bundleBuilderEnabledBundleOptions;
[SerializeField] private SerializableMultiTargetInt m_exporterExportOption;
[SerializeField] private int m_prefabBuilderReplacePrefabOptions = (int)UnityEditor.ReplacePrefabOptions.Default;
private bool m_nodeNeedsRevisit;
/*
* Properties
*/
public bool NeedsRevisit {
get {
return m_nodeNeedsRevisit;
}
set {
m_nodeNeedsRevisit = value;
}
}
public string Name {
get {
return m_name;
}
set {
m_name = value;
}
}
public string Id {
get {
return m_id;
}
}
public NodeKind Kind {
get {
return m_kind;
}
}
public string ScriptClassName {
get {
return m_scriptClassName;
}
set {
m_scriptClassName = value;
}
}
public float X {
get {
return m_x;
}
set {
m_x = value;
}
}
public float Y {
get {
return m_y;
}
set {
m_y = value;
}
}
public List<ConnectionPointData> InputPoints {
get {
return m_inputPoints;
}
}
public List<ConnectionPointData> OutputPoints {
get {
return m_outputPoints;
}
}
public SerializableMultiTargetString LoaderLoadPath {
get {
ValidateAccess(
NodeKind.LOADER_GUI
);
return m_loaderLoadPath;
}
}
public SerializableMultiTargetString ExporterExportPath {
get {
ValidateAccess(
NodeKind.EXPORTER_GUI
);
return m_exporterExportPath;
}
}
public SerializableMultiTargetString GroupingKeywords {
get {
ValidateAccess(
NodeKind.GROUPING_GUI
);
return m_groupingKeyword;
}
}
public SerializableMultiTargetString BundleNameTemplate {
get {
ValidateAccess(
NodeKind.BUNDLECONFIG_GUI
);
return m_bundleConfigBundleNameTemplate;
}
}
public bool BundleConfigUseGroupAsVariants {
get {
ValidateAccess(
NodeKind.BUNDLECONFIG_GUI
);
return m_bundleConfigUseGroupAsVariants;
}
set {
ValidateAccess(
NodeKind.BUNDLECONFIG_GUI
);
m_bundleConfigUseGroupAsVariants = value;
}
}
public SerializableMultiTargetString InstanceData {
get {
ValidateAccess(
NodeKind.PREFABBUILDER_GUI,
NodeKind.MODIFIER_GUI
);
return m_scriptInstanceData;
}
}
public List<Variant> Variants {
get {
ValidateAccess(
NodeKind.BUNDLECONFIG_GUI
);
return m_variants;
}
}
public SerializableMultiTargetInt BundleBuilderBundleOptions {
get {
ValidateAccess(
NodeKind.BUNDLEBUILDER_GUI
);
return m_bundleBuilderEnabledBundleOptions;
}
}
public SerializableMultiTargetInt ExporterExportOption {
get {
ValidateAccess(
NodeKind.EXPORTER_GUI
);
return m_exporterExportOption;
}
}
public UnityEditor.ReplacePrefabOptions ReplacePrefabOptions {
get {
ValidateAccess(
NodeKind.PREFABBUILDER_GUI
);
return (UnityEditor.ReplacePrefabOptions)m_prefabBuilderReplacePrefabOptions;
}
set {
ValidateAccess(
NodeKind.PREFABBUILDER_GUI
);
m_prefabBuilderReplacePrefabOptions = (int)value;
}
}
public List<FilterEntry> FilterConditions {
get {
ValidateAccess(
NodeKind.FILTER_GUI
);
return m_filter;
}
}
private Dictionary<string, object> _SafeGet(Dictionary<string, object> jsonData, string key) {
if(jsonData.ContainsKey(key)) {
return jsonData[key] as Dictionary<string, object>;
} else {
return new Dictionary<string, object>();
}
}
/*
* Create NodeData from JSON
*/
public NodeData(Dictionary<string, object> jsonData) {
FromJsonDictionary(jsonData);
}
public void FromJsonDictionary(Dictionary<string, object> jsonData) {
m_name = jsonData[NODE_NAME] as string;
m_id = jsonData[NODE_ID]as string;
m_kind = Settings.NodeKindFromString(jsonData[NODE_KIND] as string);
m_scriptClassName = string.Empty;
m_nodeNeedsRevisit = false;
if(jsonData.ContainsKey(NODE_SCRIPT_CLASSNAME)) {
m_scriptClassName = jsonData[NODE_SCRIPT_CLASSNAME] as string;
}
var pos = jsonData[NODE_POS] as Dictionary<string, object>;
m_x = (float)Convert.ToDouble(pos[NODE_POS_X]);
m_y = (float)Convert.ToDouble(pos[NODE_POS_Y]);
var inputs = jsonData[NODE_INPUTPOINTS] as List<object>;
var outputs = jsonData[NODE_OUTPUTPOINTS] as List<object>;
m_inputPoints = new List<ConnectionPointData>();
m_outputPoints = new List<ConnectionPointData>();
foreach(var obj in inputs) {
var pDic = obj as Dictionary<string, object>;
m_inputPoints.Add(new ConnectionPointData(pDic, this, true));
}
foreach(var obj in outputs) {
var pDic = obj as Dictionary<string, object>;
m_outputPoints.Add(new ConnectionPointData(pDic, this, false));
}
switch (m_kind) {
case NodeKind.IMPORTSETTING_GUI:
// nothing to do
break;
case NodeKind.PREFABBUILDER_GUI:
{
if(jsonData.ContainsKey(NODE_PREFABBUILDER_REPLACEPREFABOPTIONS)) {
m_prefabBuilderReplacePrefabOptions = Convert.ToInt32(jsonData[NODE_PREFABBUILDER_REPLACEPREFABOPTIONS]);
}
if(jsonData.ContainsKey(NODE_SCRIPT_INSTANCE_DATA)) {
m_scriptInstanceData = new SerializableMultiTargetString(_SafeGet(jsonData, NODE_SCRIPT_INSTANCE_DATA));
}
}
break;
case NodeKind.MODIFIER_GUI:
{
if(jsonData.ContainsKey(NODE_SCRIPT_INSTANCE_DATA)) {
m_scriptInstanceData = new SerializableMultiTargetString(_SafeGet(jsonData, NODE_SCRIPT_INSTANCE_DATA));
}
}
break;
case NodeKind.LOADER_GUI:
{
m_loaderLoadPath = new SerializableMultiTargetString(_SafeGet(jsonData, NODE_LOADER_LOAD_PATH));
}
break;
case NodeKind.FILTER_GUI:
{
var filters = jsonData[NODE_FILTER] as List<object>;
m_filter = new List<FilterEntry>();
for(int i=0; i<filters.Count; ++i) {
var f = filters[i] as Dictionary<string, object>;
var keyword = f[NODE_FILTER_KEYWORD] as string;
var keytype = f[NODE_FILTER_KEYTYPE] as string;
var pointId = f[NODE_FILTER_POINTID] as string;
var point = m_outputPoints.Find(p => p.Id == pointId);
UnityEngine.Assertions.Assert.IsNotNull(point, "Output point not found for " + keyword);
var newEntry = new FilterEntry(keyword, keytype, point);
m_filter.Add(newEntry);
UpdateFilterEntry(newEntry);
}
}
break;
case NodeKind.GROUPING_GUI:
{
m_groupingKeyword = new SerializableMultiTargetString(_SafeGet(jsonData, NODE_GROUPING_KEYWORD));
}
break;
case NodeKind.BUNDLECONFIG_GUI:
{
m_bundleConfigBundleNameTemplate = new SerializableMultiTargetString(_SafeGet(jsonData, NODE_BUNDLECONFIG_BUNDLENAME_TEMPLATE));
if(jsonData.ContainsKey(NODE_BUNDLECONFIG_USE_GROUPASVARIANTS)) {
m_bundleConfigUseGroupAsVariants = Convert.ToBoolean(jsonData[NODE_BUNDLECONFIG_USE_GROUPASVARIANTS]);
}
m_variants = new List<Variant>();
if(jsonData.ContainsKey(NODE_BUNDLECONFIG_VARIANTS)){
var variants = jsonData[NODE_BUNDLECONFIG_VARIANTS] as List<object>;
for(int i=0; i<variants.Count; ++i) {
var v = variants[i] as Dictionary<string, object>;
var name = v[NODE_BUNDLECONFIG_VARIANTS_NAME] as string;
var pointId = v[NODE_BUNDLECONFIG_VARIANTS_POINTID] as string;
var point = m_inputPoints.Find(p => p.Id == pointId);
UnityEngine.Assertions.Assert.IsNotNull(point, "Input point not found for " + name);
var newVariant = new Variant(name, point);
m_variants.Add(newVariant);
UpdateVariant(newVariant);
}
}
}
break;
case NodeKind.BUNDLEBUILDER_GUI:
{
m_bundleBuilderEnabledBundleOptions = new SerializableMultiTargetInt(_SafeGet(jsonData, NODE_BUNDLEBUILDER_ENABLEDBUNDLEOPTIONS));
}
break;
case NodeKind.EXPORTER_GUI:
{
m_exporterExportPath = new SerializableMultiTargetString(_SafeGet(jsonData, NODE_EXPORTER_EXPORT_PATH));
m_exporterExportOption = new SerializableMultiTargetInt(_SafeGet(jsonData, NODE_EXPORTER_EXPORT_OPTION));
}
break;
default:
throw new ArgumentOutOfRangeException ();
}
}
/*
* Constructor used to create new node from GUI
*/
public NodeData(string name, NodeKind kind, float x, float y) {
m_id = Guid.NewGuid().ToString();
m_name = name;
m_x = x;
m_y = y;
m_kind = kind;
m_nodeNeedsRevisit = false;
m_scriptClassName = String.Empty;
m_inputPoints = new List<ConnectionPointData>();
m_outputPoints = new List<ConnectionPointData>();
// adding defalut input point.
// Loader does not take input
if(kind != NodeKind.LOADER_GUI) {
m_inputPoints.Add(new ConnectionPointData(Settings.DEFAULT_INPUTPOINT_LABEL, this, true));
}
// adding default output point.
// Filter and Exporter does not have output.
if(kind != NodeKind.FILTER_GUI && kind != NodeKind.EXPORTER_GUI) {
m_outputPoints.Add(new ConnectionPointData(Settings.DEFAULT_OUTPUTPOINT_LABEL, this, false));
}
switch(m_kind) {
case NodeKind.PREFABBUILDER_GUI:
m_prefabBuilderReplacePrefabOptions = (int)UnityEditor.ReplacePrefabOptions.Default;
m_scriptInstanceData = new SerializableMultiTargetString();
break;
case NodeKind.MODIFIER_GUI:
m_scriptInstanceData = new SerializableMultiTargetString();
break;
case NodeKind.IMPORTSETTING_GUI:
break;
case NodeKind.FILTER_GUI:
m_filter = new List<FilterEntry>();
break;
case NodeKind.LOADER_GUI:
m_loaderLoadPath = new SerializableMultiTargetString();
break;
case NodeKind.GROUPING_GUI:
m_groupingKeyword = new SerializableMultiTargetString(Settings.GROUPING_KEYWORD_DEFAULT);
break;
case NodeKind.BUNDLECONFIG_GUI:
m_bundleConfigBundleNameTemplate = new SerializableMultiTargetString(Settings.BUNDLECONFIG_BUNDLENAME_TEMPLATE_DEFAULT);
m_bundleConfigUseGroupAsVariants = false;
m_variants = new List<Variant>();
break;
case NodeKind.BUNDLEBUILDER_GUI:
m_bundleBuilderEnabledBundleOptions = new SerializableMultiTargetInt();
break;
case NodeKind.EXPORTER_GUI:
m_exporterExportPath = new SerializableMultiTargetString();
m_exporterExportOption = new SerializableMultiTargetInt();
break;
default:
throw new AssetGraphException("[FATAL]Unhandled nodekind. unimplmented:"+ m_kind);
}
}
/**
* Duplicate this node with new guid.
*/
public NodeData Duplicate (bool keepGuid = false) {
if(keepGuid) {
return new NodeData( this.ToJsonDictionary() );
}
var newData = new NodeData(m_name, m_kind, m_x, m_y);
newData.m_nodeNeedsRevisit = false;
newData.m_scriptClassName = m_scriptClassName;
switch(m_kind) {
case NodeKind.IMPORTSETTING_GUI:
break;
case NodeKind.PREFABBUILDER_GUI:
newData.m_prefabBuilderReplacePrefabOptions = m_prefabBuilderReplacePrefabOptions;
newData.m_scriptInstanceData = new SerializableMultiTargetString(m_scriptInstanceData);
break;
case NodeKind.MODIFIER_GUI:
newData.m_scriptInstanceData = new SerializableMultiTargetString(m_scriptInstanceData);
break;
case NodeKind.FILTER_GUI:
foreach(var f in m_filter) {
newData.AddFilterCondition(f.FilterKeyword, f.FilterKeytype);
}
break;
case NodeKind.LOADER_GUI:
newData.m_loaderLoadPath = new SerializableMultiTargetString(m_loaderLoadPath);
break;
case NodeKind.GROUPING_GUI:
newData.m_groupingKeyword = new SerializableMultiTargetString(m_groupingKeyword);
break;
case NodeKind.BUNDLECONFIG_GUI:
newData.m_bundleConfigBundleNameTemplate = new SerializableMultiTargetString(m_bundleConfigBundleNameTemplate);
newData.m_bundleConfigUseGroupAsVariants = m_bundleConfigUseGroupAsVariants;
foreach(var v in m_variants) {
newData.AddVariant(v.Name);
}
break;
case NodeKind.BUNDLEBUILDER_GUI:
newData.m_bundleBuilderEnabledBundleOptions = new SerializableMultiTargetInt(m_bundleBuilderEnabledBundleOptions);
break;
case NodeKind.EXPORTER_GUI:
newData.m_exporterExportPath = new SerializableMultiTargetString(m_exporterExportPath);
newData.m_exporterExportOption = new SerializableMultiTargetInt(m_exporterExportOption);
break;
default:
throw new AssetGraphException("[FATAL]Unhandled nodekind. unimplmented:"+ m_kind);
}
return newData;
}
public ConnectionPointData AddInputPoint(string label) {
var p = new ConnectionPointData(label, this, true);
m_inputPoints.Add(p);
return p;
}
public ConnectionPointData AddOutputPoint(string label) {
var p = new ConnectionPointData(label, this, false);
m_outputPoints.Add(p);
return p;
}
public ConnectionPointData FindInputPoint(string id) {
return m_inputPoints.Find(p => p.Id == id);
}
public ConnectionPointData FindOutputPoint(string id) {
return m_outputPoints.Find(p => p.Id == id);
}
public ConnectionPointData FindConnectionPoint(string id) {
var v = FindInputPoint(id);
if(v != null) {
return v;
}
return FindOutputPoint(id);
}
public string GetLoaderFullLoadPath(BuildTarget g) {
return FileUtility.PathCombine(Application.dataPath, LoaderLoadPath[g]);
}
public bool ValidateOverlappingFilterCondition(bool throwException) {
ValidateAccess(NodeKind.FILTER_GUI);
var conditionGroup = FilterConditions.Select(v => v).GroupBy(v => v.Hash).ToList();
var overlap = conditionGroup.Find(v => v.Count() > 1);
if( overlap != null && throwException ) {
var element = overlap.First();
throw new AssetGraphException(String.Format("Duplicated filter condition found for [Keyword:{0} Type:{1}]", element.FilterKeyword, element.FilterKeytype));
}
return overlap != null;
}
public void AddFilterCondition(string keyword, string keytype) {
ValidateAccess(
NodeKind.FILTER_GUI
);
var point = new ConnectionPointData(keyword, this, false);
m_outputPoints.Add(point);
var newEntry = new FilterEntry(keyword, keytype, point);
m_filter.Add(newEntry);
UpdateFilterEntry(newEntry);
}
public void RemoveFilterCondition(FilterEntry f) {
ValidateAccess(
NodeKind.FILTER_GUI
);
m_filter.Remove(f);
m_outputPoints.Remove(GetConnectionPoint(f));
}
public ConnectionPointData GetConnectionPoint(FilterEntry f) {
ConnectionPointData p = m_outputPoints.Find(v => v.Id == f.ConnectionPointId);
UnityEngine.Assertions.Assert.IsNotNull(p);
return p;
}
public void UpdateFilterEntry(FilterEntry f) {
ConnectionPointData p = m_outputPoints.Find(v => v.Id == f.ConnectionPointId);
UnityEngine.Assertions.Assert.IsNotNull(p);
if(f.FilterKeytype == Settings.DEFAULT_FILTER_KEYTYPE) {
p.Label = f.FilterKeyword;
} else {
var pointIndex = f.FilterKeytype.LastIndexOf('.');
var keytypeName = (pointIndex > 0)? f.FilterKeytype.Substring(pointIndex+1):f.FilterKeytype;
p.Label = string.Format("{0}[{1}]", f.FilterKeyword, keytypeName);
}
}
public void AddVariant(string name) {
ValidateAccess(
NodeKind.BUNDLECONFIG_GUI
);
name = name.ToLower();
var point = new ConnectionPointData(name, this, true);
m_inputPoints.Add(point);
var newEntry = new Variant(name, point);
m_variants.Add(newEntry);
UpdateVariant(newEntry);
}
public void RemoveVariant(Variant v) {
ValidateAccess(
NodeKind.BUNDLECONFIG_GUI
);
m_variants.Remove(v);
m_inputPoints.Remove(GetConnectionPoint(v));
}
public ConnectionPointData GetConnectionPoint(Variant v) {
ConnectionPointData p = m_inputPoints.Find(point => point.Id == v.ConnectionPointId);
UnityEngine.Assertions.Assert.IsNotNull(p);
return p;
}
public void UpdateVariant(Variant variant) {
ConnectionPointData p = m_inputPoints.Find(v => v.Id == variant.ConnectionPointId);
UnityEngine.Assertions.Assert.IsNotNull(p);
p.Label = variant.Name;
}
private void ValidateAccess(params NodeKind[] allowedKind) {
foreach(var k in allowedKind) {
if (k == m_kind) {
return;
}
}
throw new AssetGraphException(m_name + ": Tried to access invalid method or property.");
}
public bool Validate (List<NodeData> allNodes, List<ConnectionData> allConnections) {
switch(m_kind) {
case NodeKind.BUNDLEBUILDER_GUI:
{
foreach(var v in m_bundleBuilderEnabledBundleOptions.Values) {
bool isDisableWriteTypeTreeEnabled = 0 < (v.value & (int)BuildAssetBundleOptions.DisableWriteTypeTree);
bool isIgnoreTypeTreeChangesEnabled = 0 < (v.value & (int)BuildAssetBundleOptions.IgnoreTypeTreeChanges);
// If both are marked something is wrong. Clear both flag and save.
if(isDisableWriteTypeTreeEnabled && isIgnoreTypeTreeChangesEnabled) {
int flag = ~((int)BuildAssetBundleOptions.DisableWriteTypeTree + (int)BuildAssetBundleOptions.IgnoreTypeTreeChanges);
v.value = v.value & flag;
LogUtility.Logger.LogWarning(LogUtility.kTag, m_name + ": DisableWriteTypeTree and IgnoreTypeTreeChanges can not be used together. Settings overwritten.");
}
}
}
break;
}
return true;
}
public bool CompareIgnoreGUIChanges (NodeData rhs) {
if(this.m_kind != rhs.m_kind) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Kind");
return false;
}
if(m_scriptClassName != rhs.m_scriptClassName) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Script classname different");
return false;
}
if(m_inputPoints.Count != rhs.m_inputPoints.Count) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Input Count");
return false;
}
if(m_outputPoints.Count != rhs.m_outputPoints.Count) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Output Count");
return false;
}
foreach(var pin in m_inputPoints) {
if(rhs.m_inputPoints.Find(x => pin.Id == x.Id) == null) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Input point not found");
return false;
}
}
foreach(var pout in m_outputPoints) {
if(rhs.m_outputPoints.Find(x => pout.Id == x.Id) == null) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Output point not found");
return false;
}
}
switch (m_kind) {
case NodeKind.PREFABBUILDER_GUI:
if(m_prefabBuilderReplacePrefabOptions != rhs.m_prefabBuilderReplacePrefabOptions) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "ReplacePrefabOptions different");
return false;
}
if(m_scriptInstanceData != rhs.m_scriptInstanceData) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Script instance data different");
return false;
}
break;
case NodeKind.MODIFIER_GUI:
if(m_scriptInstanceData != rhs.m_scriptInstanceData) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Script instance data different");
return false;
}
break;
case NodeKind.LOADER_GUI:
if(m_loaderLoadPath != rhs.m_loaderLoadPath) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Loader load path different");
return false;
}
break;
case NodeKind.FILTER_GUI:
foreach(var f in m_filter) {
if(null == rhs.m_filter.Find(x => x.FilterKeytype == f.FilterKeytype && x.FilterKeyword == f.FilterKeyword)) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Filter entry not found");
return false;
}
}
break;
case NodeKind.GROUPING_GUI:
if(m_groupingKeyword != rhs.m_groupingKeyword) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Grouping keyword different");
return false;
}
break;
case NodeKind.BUNDLECONFIG_GUI:
if(m_bundleConfigBundleNameTemplate != rhs.m_bundleConfigBundleNameTemplate) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "BundleNameTemplate different");
return false;
}
if(m_bundleConfigUseGroupAsVariants != rhs.m_bundleConfigUseGroupAsVariants) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "UseGroupAsVariants different");
return false;
}
foreach(var v in m_variants) {
if(null == rhs.m_variants.Find(x => x.Name == v.Name && x.ConnectionPointId == v.ConnectionPointId)) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "Variants not found");
return false;
}
}
break;
case NodeKind.BUNDLEBUILDER_GUI:
if(m_bundleBuilderEnabledBundleOptions != rhs.m_bundleBuilderEnabledBundleOptions) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "EnabledBundleOptions different");
return false;
}
break;
case NodeKind.EXPORTER_GUI:
if(m_exporterExportPath != rhs.m_exporterExportPath) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "ExporterPath different");
return false;
}
if(m_exporterExportOption != rhs.m_exporterExportOption) {
LogUtility.Logger.LogFormat(LogType.Log, "{0} and {1} was different: {2}", Name, rhs.Name, "ExporterOption different");
return false;
}
break;
case NodeKind.IMPORTSETTING_GUI:
// nothing to do
break;
default:
throw new ArgumentOutOfRangeException ();
}
return true;
}
/**
* Serialize to JSON dictionary
*/
public Dictionary<string, object> ToJsonDictionary() {
var nodeDict = new Dictionary<string, object>();
nodeDict[NODE_NAME] = m_name;
nodeDict[NODE_ID] = m_id;
nodeDict[NODE_KIND] = m_kind.ToString();
if(!string.IsNullOrEmpty(m_scriptClassName)) {
nodeDict[NODE_SCRIPT_CLASSNAME] = m_scriptClassName;
}
var inputs = new List<object>();
var outputs = new List<object>();
foreach(var p in m_inputPoints) {
inputs.Add( p.ToJsonDictionary() );
}
foreach(var p in m_outputPoints) {
outputs.Add( p.ToJsonDictionary() );
}
nodeDict[NODE_INPUTPOINTS] = inputs;
nodeDict[NODE_OUTPUTPOINTS] = outputs;
nodeDict[NODE_POS] = new Dictionary<string, object>() {
{NODE_POS_X, m_x},
{NODE_POS_Y, m_y}
};
switch (m_kind) {
case NodeKind.PREFABBUILDER_GUI:
nodeDict[NODE_PREFABBUILDER_REPLACEPREFABOPTIONS] = m_prefabBuilderReplacePrefabOptions;
nodeDict[NODE_SCRIPT_INSTANCE_DATA] = m_scriptInstanceData.ToJsonDictionary();
break;
case NodeKind.MODIFIER_GUI:
nodeDict[NODE_SCRIPT_INSTANCE_DATA] = m_scriptInstanceData.ToJsonDictionary();
break;
case NodeKind.LOADER_GUI:
nodeDict[NODE_LOADER_LOAD_PATH] = m_loaderLoadPath.ToJsonDictionary();
break;
case NodeKind.FILTER_GUI:
var filterDict = new List<object>();
foreach(var f in m_filter) {
var df = new Dictionary<string, object>();
df[NODE_FILTER_KEYWORD] = f.FilterKeyword;
df[NODE_FILTER_KEYTYPE] = f.FilterKeytype;
df[NODE_FILTER_POINTID] = f.ConnectionPointId;
filterDict.Add(df);
}
nodeDict[NODE_FILTER] = filterDict;
break;
case NodeKind.GROUPING_GUI:
nodeDict[NODE_GROUPING_KEYWORD] = m_groupingKeyword.ToJsonDictionary();
break;
case NodeKind.BUNDLECONFIG_GUI:
nodeDict[NODE_BUNDLECONFIG_BUNDLENAME_TEMPLATE] = m_bundleConfigBundleNameTemplate.ToJsonDictionary();
nodeDict[NODE_BUNDLECONFIG_USE_GROUPASVARIANTS] = m_bundleConfigUseGroupAsVariants;
var variantsDict = new List<object>();
foreach(var v in m_variants) {
var dv = new Dictionary<string, object>();
dv[NODE_BUNDLECONFIG_VARIANTS_NAME] = v.Name;
dv[NODE_BUNDLECONFIG_VARIANTS_POINTID] = v.ConnectionPointId;
variantsDict.Add(dv);
}
nodeDict[NODE_BUNDLECONFIG_VARIANTS] = variantsDict;
break;
case NodeKind.BUNDLEBUILDER_GUI:
nodeDict[NODE_BUNDLEBUILDER_ENABLEDBUNDLEOPTIONS] = m_bundleBuilderEnabledBundleOptions.ToJsonDictionary();
break;
case NodeKind.EXPORTER_GUI:
nodeDict[NODE_EXPORTER_EXPORT_PATH] = m_exporterExportPath.ToJsonDictionary();
nodeDict[NODE_EXPORTER_EXPORT_OPTION] = m_exporterExportOption.ToJsonDictionary();
break;
case NodeKind.IMPORTSETTING_GUI:
// nothing to do
break;
default:
throw new ArgumentOutOfRangeException ();
}
return nodeDict;
}
/**
* Serialize to JSON string
*/
public string ToJsonString() {
return AssetBundleGraph.Json.Serialize(ToJsonDictionary());
}
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SharpNEAT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using SharpNeat.Network;
using System.Threading.Tasks;
namespace SharpNeat.Genomes.Neat
{
// ENHANCEMENT: Consider switching to a SortedList[K,V] - which guarantees item sort order at all times.
/// <summary>
/// Represents a sorted list of NeuronGene objects. The sorting of the items is done on request
/// rather than being strictly enforced at all times (e.g. as part of adding and removing items). This
/// approach is currently more convenient for use in some of the routines that work with NEAT genomes.
///
/// Because we are not using a strictly sorted list such as the generic class SortedList[K,V] a customised
/// BinarySearch() method is provided for fast lookup of items if the list is known to be sorted. If the list is
/// not sorted then the BinarySearch method's behaviour is undefined. This is potentially a source of bugs
/// and thus this class should probably migrate to SortedList[K,V] or be modified to ensure items are sorted
/// prior to a binary search.
///
/// Sort order is with respect to connection gene innovation ID.
/// </summary>
public class NeuronGeneList : List<NeuronGene>, INodeList
{
#region Constructors
/// <summary>
/// Construct an empty list.
/// </summary>
public NeuronGeneList()
{
}
/// <summary>
/// Construct an empty list with the specified capacity.
/// </summary>
public NeuronGeneList(int capacity) : base(capacity)
{
}
/// <summary>
/// Copy constructor. The newly allocated list has a capacity 1 larger than copyFrom
/// allowing for a single add node mutation to occur without reallocation of memory.
/// </summary>
public NeuronGeneList(ICollection<NeuronGene> copyFrom)
: base(copyFrom.Count+1)
{
// ENHANCEMENT: List.Foreach() is potentially faster than a foreach loop.
// http://diditwith.net/2006/10/05/PerformanceOfForeachVsListForEach.aspx
#if true
foreach(NeuronGene srcGene in copyFrom) {
Add(srcGene.CreateCopy());
}
#else
NeuronGene[] srcArr = new NeuronGene[copyFrom.Count];
NeuronGene[] dstArr = new NeuronGene[copyFrom.Count];
int i = 0;
foreach (NeuronGene srcGene in copyFrom)
{
srcArr[i] = srcGene;
i++;
}
Parallel.For(0, copyFrom.Count, idx =>
{
dstArr[idx] = srcArr[idx].CreateCopy();
});
foreach (NeuronGene srcGene in dstArr)
{
Add(srcGene.CreateCopy());
}
#endif
}
#endregion
#region Public Methods
/// <summary>
/// Inserts a NeuronGene into its correct (sorted) location within the gene list.
/// Normally neuron genes can safely be assumed to have a new Innovation ID higher
/// than all existing IDs, and so we can just call Add().
/// This routine handles genes with older IDs that need placing correctly.
/// </summary>
public void InsertIntoPosition(NeuronGene neuronGene)
{
// Determine the insert idx with a linear search, starting from the end
// since mostly we expect to be adding genes that belong only 1 or 2 genes
// from the end at most.
int idx=Count-1;
for(; idx > -1; idx--)
{
if(this[idx].InnovationId < neuronGene.InnovationId)
{ // Insert idx found.
break;
}
}
Insert(idx+1, neuronGene);
}
/// <summary>
/// Remove the neuron gene with the specified innovation ID.
/// Returns the removed gene.
/// </summary>
public NeuronGene Remove(uint neuronId)
{
int idx = BinarySearch(neuronId);
if(idx<0) {
throw new ApplicationException("Attempt to remove neuron with an unknown neuronId");
}
NeuronGene neuronGene = this[idx];
RemoveAt(idx);
return neuronGene;
}
/// <summary>
/// Gets the neuron gene with the specified innovation ID using a fast binary search.
/// Returns null if no such gene is in the list.
/// </summary>
public NeuronGene GetNeuronById(uint neuronId)
{
int idx = BinarySearch(neuronId);
if(idx<0)
{ // Not found.
return null;
}
return this[idx];
}
/// <summary>
/// Sort neuron gene's into ascending order by their innovation IDs.
/// </summary>
public void SortByInnovationId()
{
Sort(delegate(NeuronGene x, NeuronGene y)
{
// Test the most likely cases first.
if(x.InnovationId < y.InnovationId) {
return -1;
}
if(x.InnovationId > y.InnovationId) {
return 1;
}
return 0;
});
}
/// <summary>
/// Obtain the index of the gene with the specified ID by performing a binary search.
/// Binary search is fast and can be performed so long as the genes are sorted by ID.
/// If the genes are not sorted then the behaviour of this method is undefined.
/// </summary>
public int BinarySearch(uint id)
{
int lo = 0;
int hi = Count-1;
while (lo <= hi)
{
int i = (lo + hi) >> 1;
if(this[i].Id < id) {
lo = i + 1;
}
else if(this[i].Id > id) {
hi = i - 1;
}
else {
return i;
}
}
return ~lo;
}
/// <summary>
/// For debug purposes only. Don't call this method in normal circumstances as it is an
/// expensive O(n) operation.
/// </summary>
public bool IsSorted()
{
int count = this.Count;
if(0 == count) {
return true;
}
uint prev = this[0].InnovationId;
for(int i=1; i<count; i++)
{
if(this[i].InnovationId <= prev) {
return false;
}
}
return true;
}
#endregion
#region INodeList<INetworkNode> Members
INetworkNode INodeList.this[int index]
{
get { return this[index]; }
}
int INodeList.Count
{
get { return this.Count; }
}
IEnumerator<INetworkNode> IEnumerable<INetworkNode>.GetEnumerator()
{
foreach(NeuronGene nGene in this) {
yield return nGene;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<INetworkNode>)this).GetEnumerator();
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AbstractMessageListenerContainer.cs" company="The original author or authors.">
// Copyright 2002-2012 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
#region Using Directives
using System;
using System.Threading;
using Common.Logging;
using RabbitMQ.Client;
using Spring.Context;
using Spring.Messaging.Amqp.Core;
using Spring.Messaging.Amqp.Rabbit.Connection;
using Spring.Messaging.Amqp.Rabbit.Core;
using Spring.Objects.Factory;
using Spring.Transaction.Support;
using Spring.Util;
#endregion
namespace Spring.Messaging.Amqp.Rabbit.Listener
{
/// <summary>
/// An abstract message listener container.
/// </summary>
/// <author>Mark Pollack</author>
public abstract class AbstractMessageListenerContainer : RabbitAccessor, IDisposable, IObjectNameAware, ILifecycle, IInitializingObject
{
/// <summary>
/// Logger available to subclasses.
/// </summary>
protected new static readonly ILog Logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// The object name.
/// </summary>
private volatile string objectName;
/// <summary>
/// Flag for auto startup.
/// </summary>
private volatile bool autoStartup = true;
/// <summary>
/// The phase.
/// </summary>
private int phase = int.MaxValue;
/// <summary>
/// Flag for active.
/// </summary>
private volatile bool active;
/// <summary>
/// Flag for running.
/// </summary>
private volatile bool isRunning;
/// <summary>
/// Flag for lifecycle monitor.
/// </summary>
private readonly object lifecycleMonitor = new object();
/// <summary>
/// The queues.
/// </summary>
private volatile string[] queueNames;
/// <summary>
/// The error handler.
/// </summary>
private IErrorHandler errorHandler;
/// <summary>
/// Flag for expose listener channel.
/// </summary>
private bool exposeListenerChannel = true;
/// <summary>
/// The message listener.
/// </summary>
private volatile object messageListener;
/// <summary>
/// The acknowledge mode.
/// </summary>
private volatile AcknowledgeModeUtils.AcknowledgeMode acknowledgeMode = AcknowledgeModeUtils.AcknowledgeMode.Auto;
/// <summary>
/// Flag for initialized.
/// </summary>
private bool initialized;
#region Properties
/// <summary>
/// <para>
/// Gets or sets AcknowledgeMode.
/// Flag controlling the behaviour of the container with respect to message acknowledgement. The most common usage is
/// to let the container handle the acknowledgements (so the listener doesn't need to know about the channel or the
/// message).
/// </para>
/// <para>
/// Set to {@link AcknowledgeMode#Manual} if the listener will send the acknowledgements itself using
/// {@link Channel#basicAck(long, boolean)}. Manual acks are consistent with either a transactional or
/// non-transactional channel, but if you are doing no other work on the channel at the same other than receiving a
/// single message then the transaction is probably unnecessary.
/// </para>
/// <para>
/// Set to {@link AcknowledgeMode#None} to tell the broker not to expect any acknowledgements, and it will assume all
/// messages are acknowledged as soon as they are sent (this is "autoack" in native Rabbit broker terms). If
/// {@link AcknowledgeMode#None} then the channel cannot be transactional (so the container will fail on start up if
/// that flag is accidentally set).
/// </para>
/// <para>
/// @param acknowledgeMode the acknowledge mode to set. Defaults to {@link AcknowledgeMode#Auto}
/// @see AcknowledgeMode
/// </para>
/// </summary>
public AcknowledgeModeUtils.AcknowledgeMode AcknowledgeMode { get { return this.acknowledgeMode; } set { this.acknowledgeMode = value; } }
/// <summary>
/// Gets or sets the name of the queues to receive messages from.
/// </summary>
/// <value>The name of the queues. Can not be null.</value>
public string[] QueueNames { get { return this.queueNames; } set { this.queueNames = value; } }
/// <summary>
/// Sets the queues.
/// </summary>
/// <value>The queues.</value>
public Queue[] Queues
{
set
{
var queueNames = new string[value.Length];
for (var i = 0; i < value.Length; i++)
{
AssertUtils.ArgumentNotNull(value[i], "Queue must not be null.");
queueNames[i] = value[i].Name;
}
this.queueNames = queueNames;
}
}
/// <summary>
/// Gets the required queue names.
/// </summary>
/// <returns>The required queue names.</returns>
public string[] GetRequiredQueueNames()
{
AssertUtils.ArgumentNotNull(this.queueNames, "Queue");
AssertUtils.State(this.queueNames.Length > 0, "Queue names must not be empty.");
return this.queueNames;
}
/// <summary>
/// Gets or sets a value indicating whether ExposeListenerChannel.
/// Exposes the listener channel to a registered
/// <see cref="Spring.Messaging.Amqp.Rabbit.Core.IChannelAwareMessageListener"/> as well as to
/// <see cref="Spring.Messaging.Amqp.Rabbit.Core.RabbitTemplate"/> calls.
/// Default is true, reusing the listener's <see cref="IModel"/>
/// </summary>
/// <value><c>true</c> if expose listener channel; otherwise, <c>false</c>.</value>
/// <see cref="Spring.Messaging.Amqp.Rabbit.Core.IChannelAwareMessageListener"/>
public bool ExposeListenerChannel { get { return this.exposeListenerChannel; } set { this.exposeListenerChannel = value; } }
/// <summary>
/// Gets or sets the message listener to register with the container. This
/// can be either a Spring <see cref="IMessageListener"/> object or
/// a Spring <see cref="IChannelAwareMessageListener"/> object.
/// </summary>
/// <value>The message listener.</value>
/// <exception cref="ArgumentException">If the supplied listener</exception> is not a <see cref="IMessageListener"/> or <see cref="IChannelAwareMessageListener"/> <see cref="IMessageListener"/>
public object MessageListener
{
get { return this.messageListener; }
set
{
this.CheckMessageListener(value);
this.messageListener = value;
}
}
/// <summary>Checks the message listener, throwing an exception
/// if it does not correspond to a supported listener type.
/// By default, only a <see cref="IMessageListener"/> object or a
/// Spring <see cref="IChannelAwareMessageListener"/> object will be accepted.</summary>
/// <param name="messageListener">The message listener.</param>
protected virtual void CheckMessageListener(object messageListener)
{
AssertUtils.ArgumentNotNull(messageListener, "IMessage Listener can not be null");
if (!(messageListener is IMessageListener || messageListener is IChannelAwareMessageListener || messageListener is Action<Message>))
{
throw new ArgumentException("messageListener needs to be of type [" + typeof(IMessageListener).FullName + "] or [" + typeof(IChannelAwareMessageListener).FullName + "] or [" + typeof(Action<Message>) + "]");
}
}
/// <summary>
/// Sets an ErrorHandler to be invoked in case of any uncaught exceptions thrown
/// while processing a Message. By default there will be no ErrorHandler
/// so that error-level logging is the only result.
/// </summary>
/// <value>The error handler.</value>
public IErrorHandler ErrorHandler { set { this.errorHandler = value; } }
/// <summary>
/// Gets or sets a value indicating whether AutoStartup.
/// </summary>
public bool AutoStartup { get { return this.autoStartup; } set { this.autoStartup = value; } }
/// <summary>
/// Gets or sets Phase.
/// </summary>
public int Phase { get { return this.phase; } set { this.phase = value; } }
/// <summary>
/// Gets or sets ObjectName.
/// </summary>
public string ObjectName { get { return this.objectName; } set { this.objectName = value; } }
#endregion
/// <summary>
/// Delegates to {@link #validateConfiguration()} and {@link #initialize()}.
/// </summary>
public override void AfterPropertiesSet()
{
base.AfterPropertiesSet();
AssertUtils.State(
this.exposeListenerChannel || !this.AcknowledgeMode.IsManual(),
"You cannot acknowledge messages manually if the channel is not exposed to the listener " + "(please check your configuration and set exposeListenerChannel=true or acknowledgeMode!=Manual)");
AssertUtils.State(
!(this.AcknowledgeMode.IsAutoAck() && this.ChannelTransacted),
"The acknowledgeMode is None (autoack in Rabbit terms) which is not consistent with having a " + "transactional channel. Either use a different AcknowledgeMode or make sure channelTransacted=false");
this.ValidateConfiguration();
this.Initialize();
}
/// <summary>
/// Validate the configuration of this container. The default implementation is empty. To be overridden in subclasses.
/// </summary>
protected virtual void ValidateConfiguration() { }
/// <summary>
/// Calls {@link #shutdown()} when the ObjectFactory destroys the container instance.
/// </summary>
public void Dispose() { this.Shutdown(); }
#region Lifecycle Methods For Starting and Stopping the Container
/// <summary>
/// Initialize this container.
/// </summary>
public void Initialize()
{
try
{
lock (this.lifecycleMonitor)
{
Monitor.PulseAll(this.lifecycleMonitor);
}
this.DoInitialize();
}
catch (Exception ex)
{
throw this.ConvertRabbitAccessException(ex);
}
}
/// <summary>
/// Stop the shared Connection, call {@link #doShutdown()}, and close this container.
/// </summary>
public void Shutdown()
{
Logger.Debug(m => m("Shutting down Rabbit listener container"));
lock (this.lifecycleMonitor)
{
this.active = false;
Monitor.PulseAll(this.lifecycleMonitor);
}
// Shut down the invokers.
try
{
this.DoShutdown();
}
catch (Exception ex)
{
throw this.ConvertRabbitAccessException(ex);
}
finally
{
lock (this.lifecycleMonitor)
{
this.isRunning = false;
Monitor.PulseAll(this.lifecycleMonitor);
}
}
}
/// <summary>
/// Register any invokers within this container. Subclasses need to implement this method for their specific invoker management process.
/// </summary>
protected abstract void DoInitialize();
/// <summary>
/// Close the registered invokers. Subclasses need to implement this method for their specific invoker management process. A shared Rabbit Connection, if any, will automatically be closed <i>afterwards</i>.
/// </summary>
protected abstract void DoShutdown();
/// <summary>
/// Gets a value indicating whether IsActive.
/// </summary>
public bool IsActive
{
get
{
lock (this.lifecycleMonitor)
{
return this.active;
}
}
}
#region ILifecycle Implementation
/// <summary>
/// Start this container.
/// </summary>
public void Start()
{
if (!this.initialized)
{
lock (this.lifecycleMonitor)
{
if (!this.initialized)
{
this.AfterPropertiesSet();
this.initialized = true;
}
}
}
try
{
Logger.Debug(m => m("Starting Rabbit listener container."));
this.DoStart();
}
catch (Exception ex)
{
throw this.ConvertRabbitAccessException(ex);
}
}
/// <summary>
/// Start this container, and notify all invoker tasks.
/// </summary>
protected virtual void DoStart()
{
// Reschedule paused tasks, if any.
lock (this.lifecycleMonitor)
{
this.active = true;
this.isRunning = true;
Monitor.PulseAll(this.lifecycleMonitor);
}
}
/// <summary>
/// Stop this container.
/// </summary>
/// <exception cref="SystemException">
/// </exception>
public void Stop()
{
try
{
this.DoStop();
}
catch (Exception ex)
{
throw this.ConvertRabbitAccessException(ex);
}
finally
{
lock (this.lifecycleMonitor)
{
this.isRunning = false;
Monitor.PulseAll(this.lifecycleMonitor);
}
}
}
/// <summary>Stop this container.</summary>
/// <param name="callback">The callback.</param>
public void Stop(Action callback)
{
this.Stop();
callback.Invoke();
}
/// <summary>
/// This method is invoked when the container is stopping. The default implementation does nothing, but subclasses may override.
/// </summary>
protected virtual void DoStop() { }
/// <summary>
/// Determine whether this container is currently running, that is, whether it has been started and not stopped yet.
/// </summary>
/// <value><c>true</c> if this component is running; otherwise, <c>false</c>.</value>
public bool IsRunning
{
get
{
lock (this.lifecycleMonitor)
{
return this.isRunning;
}
}
}
#endregion
/// <summary>Invoke the registered ErrorHandler, if any. Log at error level otherwise.</summary>
/// <param name="ex">The ex.</param>
protected void InvokeErrorHandler(Exception ex)
{
if (this.errorHandler != null)
{
this.errorHandler.HandleError(ex);
}
else
{
Logger.Warn(m => m("Execution of Rabbit message listener failed, and no ErrorHandler has been set."), ex);
}
}
#endregion
#region Template methods for listener execution
/// <summary>Executes the specified listener,
/// committing or rolling back the transaction afterwards (if necessary).</summary>
/// <param name="channel">The channel.</param>
/// <param name="message">The received message.</param>
/// <see cref="InvokeListener"/><see cref="CommitIfNecessary"/><see cref="RollbackOnExceptionIfNecessary"/><see cref="HandleListenerException"/>
protected virtual void ExecuteListener(IModel channel, Message message)
{
if (!this.IsRunning)
{
Logger.Warn(m => m("Rejecting received message because the listener container has been stopped: {0}", message));
throw new MessageRejectedWhileStoppingException();
}
try
{
this.InvokeListener(channel, message);
}
catch (Exception ex)
{
this.HandleListenerException(ex);
throw ex;
}
}
/// <summary>Invokes the specified listener</summary>
/// <param name="channel">The channel to operate on.</param>
/// <param name="message">The received message.</param>
/// <see cref="MessageListener"/>
public virtual void InvokeListener(IModel channel, Message message)
{
var listener = this.MessageListener;
if (listener is IChannelAwareMessageListener)
{
this.DoInvokeListener((IChannelAwareMessageListener)listener, channel, message);
}
else if (listener is IMessageListener || listener is Action<Message>)
{
var bindChannel = this.ExposeListenerChannel && this.IsChannelLocallyTransacted(channel);
if (bindChannel)
{
var resourceHolder = new RabbitResourceHolder(channel, false);
resourceHolder.SynchronizedWithTransaction = true;
TransactionSynchronizationManager.BindResource(this.ConnectionFactory, resourceHolder);
}
try
{
if (listener is IMessageListener)
{
this.DoInvokeListener((IMessageListener)listener, message);
}
else if (listener is Action<Message>)
{
this.DoInvokeListener((Action<Message>)listener, message);
}
}
finally
{
if (bindChannel)
{
// unbind if we bound
TransactionSynchronizationManager.UnbindResource(this.ConnectionFactory);
}
}
}
else if (listener != null)
{
throw new ArgumentException("Only MessageListener and SessionAwareMessageListener supported: " + listener);
}
else
{
throw new InvalidOperationException("No message listener specified - see property MessageListener");
}
}
/// <summary>Invoke the specified listener as Spring SessionAwareMessageListener,
/// exposing a new Rabbit Channel (potentially with its own transaction)
/// to the listener if demanded.</summary>
/// <param name="listener">The Spring ISessionAwareMessageListener to invoke.</param>
/// <param name="channel">The channel to operate on.</param>
/// <param name="message">The received message.</param>
/// <see cref="IChannelAwareMessageListener"/><see cref="ExposeListenerChannel"/>
protected virtual void DoInvokeListener(IChannelAwareMessageListener listener, IModel channel, Message message)
{
RabbitResourceHolder resourceHolder = null;
var channelToUse = channel;
var boundHere = false;
try
{
if (!this.ExposeListenerChannel)
{
// We need to expose a separate Channel.
resourceHolder = this.GetTransactionalResourceHolder();
channelToUse = resourceHolder.Channel;
if (this.IsChannelLocallyTransacted(channelToUse) &&
!TransactionSynchronizationManager.ActualTransactionActive)
{
resourceHolder.SynchronizedWithTransaction = true;
TransactionSynchronizationManager.BindResource(
this.ConnectionFactory,
resourceHolder);
boundHere = true;
}
}
else
{
// if locally transacted, bind the current channel to make it available to RabbitTemplate
if (this.IsChannelLocallyTransacted(channel))
{
var localResourceHolder = new RabbitResourceHolder(channelToUse, false);
localResourceHolder.SynchronizedWithTransaction = true;
TransactionSynchronizationManager.BindResource(this.ConnectionFactory, localResourceHolder);
boundHere = true;
}
}
// Actually invoke the message listener
try
{
listener.OnMessage(message, channelToUse);
}
catch (Exception e)
{
throw this.WrapToListenerExecutionFailedExceptionIfNeeded(e);
}
}
finally
{
if (resourceHolder != null && boundHere)
{
// so the channel exposed (because exposeListenerChannel is false) will be closed
resourceHolder.SynchronizedWithTransaction = false;
}
ConnectionFactoryUtils.ReleaseResources(resourceHolder);
if (boundHere)
{
// unbind if we bound
TransactionSynchronizationManager.UnbindResource(this.ConnectionFactory);
if (!this.ExposeListenerChannel && this.IsChannelLocallyTransacted(channelToUse))
{
/*
* commit the temporary channel we exposed; the consumer's channel
* will be committed later. Note that when exposing a different channel
* when there's no transaction manager, the exposed channel is committed
* on each message, and not based on txSize.
*/
RabbitUtils.CommitIfNecessary(channelToUse);
}
}
}
}
/// <summary>Invoke the specified listener a Spring Rabbit MessageListener.</summary>
/// <remarks>Default implementation performs a plain invocation of the
/// <code>OnMessage</code>
/// methods</remarks>
/// <param name="listener">The listener to invoke.</param>
/// <param name="message">The received message.</param>
protected virtual void DoInvokeListener(IMessageListener listener, Message message)
{
try
{
listener.OnMessage(message);
}
catch (Exception e)
{
throw this.WrapToListenerExecutionFailedExceptionIfNeeded(e);
}
}
/// <summary>The do invoke listener.</summary>
/// <param name="listener">The listener.</param>
/// <param name="message">The message.</param>
/// <exception cref="Exception"></exception>
protected virtual void DoInvokeListener(Action<Message> listener, Message message)
{
try
{
listener.Invoke(message);
}
catch (Exception e)
{
throw this.WrapToListenerExecutionFailedExceptionIfNeeded(e);
}
}
/// <summary>Determines whether the given Channel is locally transacted, that is, whether
/// its transaction is managed by this listener container's Channel handling
/// and not by an external transaction coordinator.</summary>
/// <remarks>This method is about finding out whether the Channel's transaction
/// is local or externally coordinated.</remarks>
/// <param name="channel">The channel to check.</param>
/// <returns><c>true</c> if the is channel locally transacted; otherwise, <c>false</c>.</returns>
/// <see cref="RabbitAccessor.ChannelTransacted"/>
protected virtual bool IsChannelLocallyTransacted(IModel channel) { return this.ChannelTransacted; }
/// <summary>Handle the given exception that arose during listener execution.</summary>
/// <remarks>The default implementation logs the exception at error level,
/// not propagating it to the Rabbit provider - assuming that all handling of
/// acknowledgement and/or transactions is done by this listener container.
/// This can be overridden in subclasses.</remarks>
/// <param name="ex">The exception to handle</param>
protected virtual void HandleListenerException(Exception ex)
{
if (this.IsActive)
{
// Regular case: failed while active.
// Invoke ErrorHandler if available.
this.InvokeErrorHandler(ex);
}
else
{
// Rare case: listener thread failed after container shutdown.
// Log at debug level, to avoid spamming the shutdown log.
Logger.Debug(m => m("Listener exception after container shutdown"), ex);
}
}
/// <summary>Wrap listener execution failed exception if needed.</summary>
/// <param name="e">The e.</param>
/// <returns>The exception.</returns>
protected Exception WrapToListenerExecutionFailedExceptionIfNeeded(Exception e)
{
if (!(e is ListenerExecutionFailedException))
{
// Wrap exception to ListenerExecutionFailedException.
return new ListenerExecutionFailedException("Listener threw exception", e);
}
return e;
}
#endregion
}
/// <summary>
/// Exception that indicates that the initial setup of this container's
/// shared Connection failed. This is indicating to invokers that they need
/// to establish the shared Connection themselves on first access.
/// </summary>
public class SharedConnectionNotInitializedException : SystemException
{
/// <summary>Initializes a new instance of the <see cref="SharedConnectionNotInitializedException"/> class.</summary>
/// <param name="message">The message.</param>
public SharedConnectionNotInitializedException(string message) : base(message) { }
}
}
| |
// 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.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.MethodInfos;
using System.Reflection.Runtime.CustomAttributes;
using Internal.Reflection.Core;
using Internal.Reflection.Core.Execution;
using Internal.Reflection.Tracing;
namespace System.Reflection.Runtime.TypeInfos
{
internal abstract class RuntimeGenericParameterTypeInfo : RuntimeTypeInfo
{
protected RuntimeGenericParameterTypeInfo(int position)
{
_position = position;
}
public sealed override bool IsTypeDefinition => false;
public sealed override bool IsGenericTypeDefinition => false;
protected sealed override bool HasElementTypeImpl() => false;
protected sealed override bool IsArrayImpl() => false;
public sealed override bool IsSZArray => false;
public sealed override bool IsVariableBoundArray => false;
protected sealed override bool IsByRefImpl() => false;
protected sealed override bool IsPointerImpl() => false;
public sealed override bool IsConstructedGenericType => false;
public sealed override bool IsGenericParameter => true;
public sealed override Assembly Assembly
{
get
{
return DeclaringType.Assembly;
}
}
public sealed override bool ContainsGenericParameters
{
get
{
return true;
}
}
public abstract override MethodBase DeclaringMethod { get; }
public sealed override Type[] GetGenericParameterConstraints()
{
return ConstraintInfos.CloneTypeArray();
}
public sealed override string FullName
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_FullName(this);
#endif
return null; // We return null as generic parameter types are not roundtrippable through Type.GetType().
}
}
public sealed override int GenericParameterPosition
{
get
{
return _position;
}
}
public sealed override string Namespace
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.TypeInfo_Namespace(this);
#endif
return DeclaringType.Namespace;
}
}
public sealed override StructLayoutAttribute StructLayoutAttribute
{
get
{
return null;
}
}
public sealed override string ToString()
{
return Name;
}
protected sealed override TypeAttributes GetAttributeFlagsImpl()
{
return TypeAttributes.Public;
}
internal sealed override bool CanBrowseWithoutMissingMetadataExceptions => true;
internal sealed override string InternalFullNameOfAssembly
{
get
{
Debug.Fail("Since this class always returns null for FullName, this helper should be unreachable.");
return null;
}
}
internal sealed override RuntimeTypeHandle InternalTypeHandleIfAvailable
{
get
{
return default(RuntimeTypeHandle);
}
}
//
// Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces.
//
internal abstract override TypeContext TypeContext { get; }
//
// Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null.
//
internal sealed override QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType
{
get
{
QTypeDefRefOrSpec[] constraints = Constraints;
TypeInfo[] constraintInfos = ConstraintInfos;
for (int i = 0; i < constraints.Length; i++)
{
TypeInfo constraintInfo = constraintInfos[i];
if (constraintInfo.IsInterface)
continue;
return constraints[i];
}
RuntimeNamedTypeInfo objectTypeInfo = CommonRuntimeTypes.Object.CastToRuntimeNamedTypeInfo();
return objectTypeInfo.TypeDefinitionQHandle;
}
}
//
// Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and
// insertion of the TypeContext.
//
internal sealed override QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces
{
get
{
LowLevelList<QTypeDefRefOrSpec> result = new LowLevelList<QTypeDefRefOrSpec>();
QTypeDefRefOrSpec[] constraints = Constraints;
TypeInfo[] constraintInfos = ConstraintInfos;
for (int i = 0; i < constraints.Length; i++)
{
if (constraintInfos[i].IsInterface)
result.Add(constraints[i]);
}
return result.ToArray();
}
}
protected abstract QTypeDefRefOrSpec[] Constraints { get; }
private TypeInfo[] ConstraintInfos
{
get
{
QTypeDefRefOrSpec[] constraints = Constraints;
if (constraints.Length == 0)
return Array.Empty<TypeInfo>();
TypeInfo[] constraintInfos = new TypeInfo[constraints.Length];
for (int i = 0; i < constraints.Length; i++)
{
constraintInfos[i] = constraints[i].Resolve(TypeContext);
}
return constraintInfos;
}
}
private readonly int _position;
}
}
| |
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Halcyon.HAL.Attributes;
using Halcyon.Web.HAL;
using CustomerOrdersApi.Model;
using System.Net;
using Newtonsoft.Json;
using HalKit;
using System.Threading.Tasks;
using System;
using MongoDB.Driver;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using CustomerOrdersApi.Config;
using System.Threading;
using System.IO;
namespace CustomerOrdersApi
{
[HalModel("http://orders/", true)]
[HalLink("self", "/orders")]
[HalLink("profile", "profile/orders")]
[HalLink("search", "orders/search")]
public class OrdersModel
{
[JsonProperty("page")]
public ResultPage Page { get; set; } = new ResultPage();
[JsonIgnore]
[HalEmbedded("customerOrders")]
public List<CustomerOrder> Orders { get; set; } = new List<CustomerOrder>();
public class ResultPage
{
[JsonProperty("size")]
public int Size { get; set; } = 20;
[JsonProperty("totalElements")]
public int TotalElements { get; set; }
[JsonProperty("totalPages")]
public int TotalPages { get; set; }
[JsonProperty("number")]
public int Number { get; set; }
}
}
[Route("/orders")]
public class ProductsController: Controller
{
private readonly AppSettings AppSettings;
private readonly ILogger<ProductsController> logger;
private HalClient client = new HalClient(new HalConfiguration());
private HALAttributeConverter converter = new HALAttributeConverter();
private MongoClient dbClient;
private IMongoCollection<CustomerOrder> collection;
public ProductsController(IOptions<AppSettings> options, ILogger<ProductsController> logger) : base()
{
this.AppSettings = options.Value;
this.logger = logger;
dbClient = new MongoClient(AppSettings.Data.MongoConnection.ConnectionString);
IMongoDatabase database = dbClient.GetDatabase(AppSettings.Data.MongoConnection.Database);
collection = database.GetCollection<CustomerOrder>("customerOrder");
}
[HttpGet]
public IActionResult Get()
{
IEnumerator<CustomerOrder> enumerator = collection.AsQueryable<CustomerOrder>().GetEnumerator();
OrdersModel model = new OrdersModel();
while (enumerator.MoveNext())
{
model.Orders.Add(enumerator.Current);
}
model.Page.TotalPages = 1;
model.Page.TotalElements = model.Orders.Count;
model.Page.Size = model.Page.TotalElements;
return this.HAL(converter.Convert(model), HttpStatusCode.OK);
}
// GET api/values/5
[HttpGet("{id}", Name = "GetOffer")]
public IActionResult Get(string id)
{
CustomerOrder order = collection.Find(x => x.Id.Equals(id)).First();
if(order == null) {
return NotFound();
}
return this.HAL(converter.Convert(order), HttpStatusCode.OK);
}
[HttpGet, Route("search/customerId/{custId?}/{sort=date}")]
public IActionResult Get(string custId, string sort)
{
List<CustomerOrder> result = new List<CustomerOrder>();
var sortBy = Builders<CustomerOrder>.Sort.Ascending(sort);
var options = new FindOptions<CustomerOrder> { Sort = sortBy };
result = collection.FindSync(x => x.CustomerId.Equals(custId), options).ToList();
OrdersModel model = new OrdersModel();
model.Orders = result;
model.Page.TotalPages = 1;
model.Page.TotalElements = model.Orders.Count;
model.Page.Size = model.Page.TotalElements;
return this.HAL(converter.Convert(model), HttpStatusCode.OK);
}
[HttpPost]
public IActionResult Create([FromBody] NewOrderResource item)
{
if (item == null)
{
return BadRequest();
}
Thread.Sleep(2000);
Address address = null;
Customer customer = null;
Card card = null;
List<Item> items = null;
/* Task.Factory.ContinueWhenAll(
new Task[] {
createHalAsyncTask<Address>(item.Address.AbsoluteUri)
.ContinueWith((task) => { address = task.Result; }),
createHalAsyncTask<Customer>(item.Customer.AbsoluteUri)
.ContinueWith((task) => { customer = task.Result; }),
createHalAsyncTask<Card>(item.Card.AbsoluteUri)
.ContinueWith((task) => { card = task.Result; }),
createHalAsyncTask<List<Item>>(item.Items.AbsoluteUri)
.ContinueWith((task) => { items = task.Result; })
},
_ => {})
.Wait();
*/
WebRequest cartRequest = WebRequest.Create(item.Items.AbsoluteUri);
var cartResponse = cartRequest.GetResponseAsync().Result;
StreamReader cartreader = new StreamReader(cartResponse.GetResponseStream());
string responseFromServer = cartreader.ReadToEnd();
items = JsonConvert.DeserializeObject<List<Item>>(responseFromServer);
WebRequest customerRequest = WebRequest.Create(item.Customer.AbsoluteUri);
var customerResponse = customerRequest.GetResponseAsync().Result;
StreamReader customerreader = new StreamReader(customerResponse.GetResponseStream());
responseFromServer = customerreader.ReadToEnd();
customer = JsonConvert.DeserializeObject<Customer>(responseFromServer);
WebRequest addressRequest = WebRequest.Create(item.Address.AbsoluteUri);
var addressResponse = addressRequest.GetResponseAsync().Result;
StreamReader addressreader = new StreamReader(addressResponse.GetResponseStream());
responseFromServer = addressreader.ReadToEnd();
address = JsonConvert.DeserializeObject<Address>(responseFromServer);
WebRequest cardRequest = WebRequest.Create(item.Card.AbsoluteUri);
var cardsResponse = cardRequest.GetResponseAsync().Result;
StreamReader cardreader = new StreamReader(cardsResponse.GetResponseStream());
responseFromServer = cardreader.ReadToEnd();
card = JsonConvert.DeserializeObject<Card>(responseFromServer);
Thread.Sleep(2000);
PaymentResponse paymentResponse = null;
float amount = CalculateTotal(items);
PaymentRequest paymentRequest = new PaymentRequest() {
Address = address,
Card = card,
Customer = customer,
Amount = amount
};
/*
client.PostAsync<PaymentResponse>(new HalKit.Models.Response.Link {HRef = AppSettings.ServiceEndpoints.PaymentServiceEndpoint, IsTemplated = false}, paymentRequest)
.ContinueWith((task) => {
paymentResponse = task.Result;
})
.Wait(); */
var data = System.Text.Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(paymentRequest).ToString());
WebRequest payRequest = WebRequest.Create(AppSettings.ServiceEndpoints.PaymentServiceEndpoint);
payRequest.Method = "POST";
payRequest.ContentType = "application/json";
Stream reqStream = payRequest.GetRequestStreamAsync().Result;
reqStream.Write(data, 0, data.Length);
var payResponse = payRequest.GetResponseAsync().Result;
StreamReader payreader = new StreamReader(payResponse.GetResponseStream());
responseFromServer = payreader.ReadToEnd();
paymentResponse = JsonConvert.DeserializeObject<PaymentResponse>(responseFromServer);
if(!paymentResponse.Authorised) {
return BadRequest();
}
string ACustomerId = customer.Id;
Shipment Shipment = null;
Shipment AShipment = new Shipment() {
Name = ACustomerId
};
/* client.PostAsync<Shipment>(new HalKit.Models.Response.Link {HRef = AppSettings.ServiceEndpoints.ShippingServiceEndpoint, IsTemplated = false}, AShipment)
.ContinueWith((task) => {
Shipment = task.Result;
})
.Wait(); */
var shipmentData = System.Text.Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(AShipment).ToString());
WebRequest shipmentRequest = WebRequest.Create(AppSettings.ServiceEndpoints.ShippingServiceEndpoint);
shipmentRequest.Method = "POST";
shipmentRequest.ContentType = "application/json";
Stream reqShipmentStream = shipmentRequest.GetRequestStreamAsync().Result;
reqShipmentStream.Write(shipmentData, 0, shipmentData.Length);
var shipmentResponse = shipmentRequest.GetResponseAsync().Result;
StreamReader shipmentReader = new StreamReader(shipmentResponse.GetResponseStream());
responseFromServer = shipmentReader.ReadToEnd();
Shipment = JsonConvert.DeserializeObject<Shipment>(responseFromServer);
CustomerOrder order = new CustomerOrder() {
CustomerId = ACustomerId,
Address = address,
Card = card,
Customer = customer,
Items = items,
Total = amount,
Shipment = Shipment
};
collection.InsertOne(order);
//return CreatedAtRoute("GetOffer", new { id = order.Id }, order);
customer.Id = null;
address.Id = null;
card.Id = null;
return new ObjectResult(order) {
StatusCode = 201
};
}
private float CalculateTotal(List<Item> items) {
float amount = 0F;
float shipping = 4.99F;
items.ForEach(item => amount += item.Quantity * item.UnitPrice);
amount += shipping;
return amount;
}
private string ToStringNullSafe(object value) {
return (value ?? string.Empty).ToString();
}
Task<T> createHalAsyncTask<T>(string link) {
return client.GetAsync<T>(new HalKit.Models.Response.Link {HRef = link, IsTemplated = false}
, new Dictionary<string, string> ()
, new Dictionary<string, IEnumerable<string>>
{
// it's needed to avoid
// org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
// from a spring based server
{"Accept", new[] {"application/hal+json", "application/json"}}
});
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Textures;
using osu.Framework.Testing;
using osu.Game.Audio;
using osu.Game.IO;
using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;
using osu.Game.Tests.Beatmaps;
using osu.Game.Tests.Visual;
using osuTK.Graphics;
namespace osu.Game.Tests.Skins
{
[TestFixture]
[HeadlessTest]
public class TestSceneSkinConfigurationLookup : OsuTestScene
{
private UserSkinSource userSource;
private BeatmapSkinSource beatmapSource;
private SkinRequester requester;
[SetUp]
public void SetUp() => Schedule(() =>
{
Add(new SkinProvidingContainer(userSource = new UserSkinSource())
.WithChild(new SkinProvidingContainer(beatmapSource = new BeatmapSkinSource())
.WithChild(requester = new SkinRequester())));
});
[Test]
public void TestBasicLookup()
{
AddStep("Add config values", () =>
{
userSource.Configuration.ConfigDictionary["Lookup"] = "user skin";
beatmapSource.Configuration.ConfigDictionary["Lookup"] = "beatmap skin";
});
AddAssert("Check lookup finds beatmap skin", () => requester.GetConfig<string, string>("Lookup")?.Value == "beatmap skin");
}
[Test]
public void TestFloatLookup()
{
AddStep("Add config values", () => userSource.Configuration.ConfigDictionary["FloatTest"] = "1.1");
AddAssert("Check float parse lookup", () => requester.GetConfig<string, float>("FloatTest")?.Value == 1.1f);
}
[Test]
public void TestBoolLookup()
{
AddStep("Add config values", () => userSource.Configuration.ConfigDictionary["BoolTest"] = "1");
AddAssert("Check bool parse lookup", () => requester.GetConfig<string, bool>("BoolTest")?.Value == true);
}
[Test]
public void TestEnumLookup()
{
AddStep("Add config values", () => userSource.Configuration.ConfigDictionary["Test"] = "Test2");
AddAssert("Check enum parse lookup", () => requester.GetConfig<LookupType, ValueType>(LookupType.Test)?.Value == ValueType.Test2);
}
[Test]
public void TestLookupFailure()
{
AddAssert("Check lookup failure", () => requester.GetConfig<string, float>("Lookup") == null);
}
[Test]
public void TestLookupNull()
{
AddStep("Add config values", () => userSource.Configuration.ConfigDictionary["Lookup"] = null);
AddAssert("Check lookup null", () =>
{
var bindable = requester.GetConfig<string, string>("Lookup");
return bindable != null && bindable.Value == null;
});
}
[Test]
public void TestColourLookup()
{
AddStep("Add config colour", () => userSource.Configuration.CustomColours["Lookup"] = Color4.Red);
AddAssert("Check colour lookup", () => requester.GetConfig<SkinCustomColourLookup, Color4>(new SkinCustomColourLookup("Lookup"))?.Value == Color4.Red);
}
[Test]
public void TestGlobalLookup()
{
AddAssert("Check combo colours", () => requester.GetConfig<GlobalSkinColours, IReadOnlyList<Color4>>(GlobalSkinColours.ComboColours)?.Value?.Count > 0);
}
[Test]
public void TestWrongColourType()
{
AddStep("Add config colour", () => userSource.Configuration.CustomColours["Lookup"] = Color4.Red);
AddAssert("perform incorrect lookup", () =>
{
try
{
requester.GetConfig<SkinCustomColourLookup, int>(new SkinCustomColourLookup("Lookup"));
return false;
}
catch
{
return true;
}
});
}
[Test]
public void TestEmptyComboColours()
{
AddAssert("Check retrieved combo colours is skin default colours", () =>
requester.GetConfig<GlobalSkinColours, IReadOnlyList<Color4>>(GlobalSkinColours.ComboColours)?.Value?.SequenceEqual(SkinConfiguration.DefaultComboColours) ?? false);
}
[Test]
public void TestEmptyComboColoursNoFallback()
{
AddStep("Add custom combo colours to user skin", () => userSource.Configuration.AddComboColours(
new Color4(100, 150, 200, 255),
new Color4(55, 110, 166, 255),
new Color4(75, 125, 175, 255)
));
AddStep("Disallow default colours fallback in beatmap skin", () => beatmapSource.Configuration.AllowDefaultComboColoursFallback = false);
AddAssert("Check retrieved combo colours from user skin", () =>
requester.GetConfig<GlobalSkinColours, IReadOnlyList<Color4>>(GlobalSkinColours.ComboColours)?.Value?.SequenceEqual(userSource.Configuration.ComboColours) ?? false);
}
[Test]
public void TestNullBeatmapVersionFallsBackToUserSkin()
{
AddStep("Set user skin version 2.3", () => userSource.Configuration.LegacyVersion = 2.3m);
AddStep("Set beatmap skin version null", () => beatmapSource.Configuration.LegacyVersion = null);
AddAssert("Check legacy version lookup", () => requester.GetConfig<LegacySkinConfiguration.LegacySetting, decimal>(LegacySkinConfiguration.LegacySetting.Version)?.Value == 2.3m);
}
[Test]
public void TestSetBeatmapVersionNoFallback()
{
AddStep("Set user skin version 2.3", () => userSource.Configuration.LegacyVersion = 2.3m);
AddStep("Set beatmap skin version null", () => beatmapSource.Configuration.LegacyVersion = 1.7m);
AddAssert("Check legacy version lookup", () => requester.GetConfig<LegacySkinConfiguration.LegacySetting, decimal>(LegacySkinConfiguration.LegacySetting.Version)?.Value == 1.7m);
}
[Test]
public void TestNullBeatmapAndUserVersionFallsBackToLatest()
{
AddStep("Set user skin version 2.3", () => userSource.Configuration.LegacyVersion = null);
AddStep("Set beatmap skin version null", () => beatmapSource.Configuration.LegacyVersion = null);
AddAssert("Check legacy version lookup",
() => requester.GetConfig<LegacySkinConfiguration.LegacySetting, decimal>(LegacySkinConfiguration.LegacySetting.Version)?.Value == LegacySkinConfiguration.LATEST_VERSION);
}
[Test]
public void TestIniWithNoVersionFallsBackTo1()
{
AddStep("Parse skin with no version", () => userSource.Configuration = new LegacySkinDecoder().Decode(new LineBufferedReader(new MemoryStream())));
AddStep("Set beatmap skin version null", () => beatmapSource.Configuration.LegacyVersion = null);
AddAssert("Check legacy version lookup", () => requester.GetConfig<LegacySkinConfiguration.LegacySetting, decimal>(LegacySkinConfiguration.LegacySetting.Version)?.Value == 1.0m);
}
public enum LookupType
{
Test
}
public enum ValueType
{
Test1,
Test2,
Test3
}
public class UserSkinSource : LegacySkin
{
public UserSkinSource()
: base(new SkinInfo(), null, null, string.Empty)
{
}
}
public class BeatmapSkinSource : LegacyBeatmapSkin
{
public BeatmapSkinSource()
: base(new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo, null, null)
{
}
}
public class SkinRequester : Drawable, ISkin
{
private ISkinSource skin;
[BackgroundDependencyLoader]
private void load(ISkinSource skin)
{
this.skin = skin;
}
public Drawable GetDrawableComponent(ISkinComponent component) => skin.GetDrawableComponent(component);
public Texture GetTexture(string componentName) => skin.GetTexture(componentName);
public SampleChannel GetSample(ISampleInfo sampleInfo) => skin.GetSample(sampleInfo);
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => skin.GetConfig<TLookup, TValue>(lookup);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace WebApiBasicAuth.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type EventMultiValueExtendedPropertiesCollectionRequest.
/// </summary>
public partial class EventMultiValueExtendedPropertiesCollectionRequest : BaseRequest, IEventMultiValueExtendedPropertiesCollectionRequest
{
/// <summary>
/// Constructs a new EventMultiValueExtendedPropertiesCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public EventMultiValueExtendedPropertiesCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified MultiValueLegacyExtendedProperty to the collection via POST.
/// </summary>
/// <param name="multiValueLegacyExtendedProperty">The MultiValueLegacyExtendedProperty to add.</param>
/// <returns>The created MultiValueLegacyExtendedProperty.</returns>
public System.Threading.Tasks.Task<MultiValueLegacyExtendedProperty> AddAsync(MultiValueLegacyExtendedProperty multiValueLegacyExtendedProperty)
{
return this.AddAsync(multiValueLegacyExtendedProperty, CancellationToken.None);
}
/// <summary>
/// Adds the specified MultiValueLegacyExtendedProperty to the collection via POST.
/// </summary>
/// <param name="multiValueLegacyExtendedProperty">The MultiValueLegacyExtendedProperty to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created MultiValueLegacyExtendedProperty.</returns>
public System.Threading.Tasks.Task<MultiValueLegacyExtendedProperty> AddAsync(MultiValueLegacyExtendedProperty multiValueLegacyExtendedProperty, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<MultiValueLegacyExtendedProperty>(multiValueLegacyExtendedProperty, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IEventMultiValueExtendedPropertiesCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IEventMultiValueExtendedPropertiesCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<EventMultiValueExtendedPropertiesCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IEventMultiValueExtendedPropertiesCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IEventMultiValueExtendedPropertiesCollectionRequest Expand(Expression<Func<MultiValueLegacyExtendedProperty, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IEventMultiValueExtendedPropertiesCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IEventMultiValueExtendedPropertiesCollectionRequest Select(Expression<Func<MultiValueLegacyExtendedProperty, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IEventMultiValueExtendedPropertiesCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IEventMultiValueExtendedPropertiesCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IEventMultiValueExtendedPropertiesCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IEventMultiValueExtendedPropertiesCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
namespace Gu.Wpf.Geometry
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Windows;
[DebuggerDisplay("{DebuggerDisplay,nq}")]
internal struct Ray
{
internal readonly Point Point;
internal readonly Vector Direction;
internal Ray(Point point, Vector direction)
{
this.Point = point;
this.Direction = direction.Normalized();
}
private string DebuggerDisplay => $"{this.Point.ToString("F1")}, {this.Direction.ToString("F1")} angle: {this.Direction.AngleToPositiveX().ToString("F1", CultureInfo.InvariantCulture)}";
internal static Ray Parse(string text)
{
var strings = text.Split(';');
if (strings.Length != 2)
{
throw new FormatException("Could not parse a Ray from the string.");
}
var p = Point.Parse(strings[0]);
var v = Vector.Parse(strings[1]).Normalized();
return new Ray(p, v);
}
internal Ray Rotate(double angleInDegrees)
{
return new Ray(this.Point, this.Direction.Rotate(angleInDegrees));
}
internal bool IsPointOn(Point p)
{
if (this.Point.DistanceTo(p) < Constants.Tolerance)
{
return true;
}
var angle = this.Point.VectorTo(p).AngleTo(this.Direction);
return Math.Abs(angle) < Constants.Tolerance;
}
internal Ray Flip()
{
return new Ray(this.Point, this.Direction.Negated());
}
internal Point Project(Point p)
{
var toPoint = this.Point.VectorTo(p);
var dotProdcut = toPoint.DotProdcut(this.Direction);
var projected = this.Point + (dotProdcut * this.Direction);
return projected;
}
internal Line? PerpendicularLineTo(Point p)
{
if (this.IsPointOn(p))
{
return null;
}
var startPoint = this.Project(p);
return new Line(startPoint, p);
}
internal Point? FirstIntersectionWith(Rect rectangle)
{
var quadrant = rectangle.Contains(this.Point)
? this.Direction.Quadrant()
: this.Direction.Negated().Quadrant();
return quadrant switch
{
Quadrant.NegativeXPositiveY
=> IntersectionPoint(this, rectangle.LeftLine(), mustBeBetweenStartAndEnd: true) ??
IntersectionPoint(this, rectangle.BottomLine(), mustBeBetweenStartAndEnd: true),
Quadrant.PositiveXPositiveY
=> IntersectionPoint(this, rectangle.RightLine(), mustBeBetweenStartAndEnd: true) ??
IntersectionPoint(this, rectangle.BottomLine(), mustBeBetweenStartAndEnd: true),
Quadrant.PositiveXNegativeY
=> IntersectionPoint(this, rectangle.RightLine(), mustBeBetweenStartAndEnd: true) ??
IntersectionPoint(this, rectangle.TopLine(), mustBeBetweenStartAndEnd: true),
Quadrant.NegativeXNegativeY
=> IntersectionPoint(this, rectangle.LeftLine(), mustBeBetweenStartAndEnd: true) ??
IntersectionPoint(this, rectangle.TopLine(), mustBeBetweenStartAndEnd: true),
_ => throw new InvalidEnumArgumentException("Unhandled Quadrant."),
};
}
internal Point? FirstIntersectionWith(Circle circle)
{
var perp = this.PerpendicularLineTo(circle.Center);
if (perp is null)
{
return this.Point.DistanceTo(circle.Center) < circle.Radius
? circle.Center + (circle.Radius * this.Direction)
: circle.Center - (circle.Radius * this.Direction);
}
var pl = perp.Value.Length;
if (pl > circle.Radius)
{
return null;
}
var tangentLength = Math.Sqrt((circle.Radius * circle.Radius) - (pl * pl));
var result = perp.Value.StartPoint - (tangentLength * this.Direction);
return this.IsPointOn(result)
? (Point?)result
: null;
}
// http://www.mare.ee/indrek/misc/2d.pdf
internal Point? FirstIntersectionWith(Ellipse ellipse)
{
if (Math.Abs(ellipse.CenterPoint.X) < Constants.Tolerance && Math.Abs(ellipse.CenterPoint.Y) < Constants.Tolerance)
{
return FirstIntersectionWithEllipseCenteredAtOrigin(this.Point, this.Direction, ellipse.RadiusX, ellipse.RadiusY);
}
var offset = new Point(0, 0).VectorTo(ellipse.CenterPoint);
var ip = FirstIntersectionWithEllipseCenteredAtOrigin(this.Point - offset, this.Direction, ellipse.RadiusX, ellipse.RadiusY);
return ip + offset;
}
private static Point? FirstIntersectionWithEllipseCenteredAtOrigin(Point startPoint, Vector direction, double a, double b)
{
var nx = direction.X;
var nx2 = nx * nx;
var ny = direction.Y;
var ny2 = ny * ny;
var x0 = startPoint.X;
var x02 = x0 * x0;
var y0 = startPoint.Y;
var y02 = y0 * y0;
var a2 = a * a;
var b2 = b * b;
#pragma warning disable SA1312 // Variable names should begin with lower-case letter
var A = (nx2 * b2) + (ny2 * a2);
if (Math.Abs(A) < Constants.Tolerance)
{
return null;
}
var B = (2 * x0 * nx * b2) + (2 * y0 * ny * a2);
var C = (x02 * b2) + (y02 * a2) - (a2 * b2);
var d = (B * B) - (4 * A * C);
if (d < 0)
{
return null;
}
var sqrt = Math.Sqrt(d);
var s = (-B - sqrt) / (2 * A);
if (s < 0)
{
s = (-B + sqrt) / (2 * A);
return s > 0
? new Point(x0, y0) + (s * direction)
: (Point?)null;
}
return new Point(x0, y0) + (s * direction);
#pragma warning restore SA1312 // Variable names should begin with lower-case letter
}
// http://geomalgorithms.com/a05-_intersect-1.html#intersect2D_2Segments()
private static Point? IntersectionPoint(Ray ray, Line l2, bool mustBeBetweenStartAndEnd)
{
var u = ray.Direction;
var v = l2.Direction;
var w = ray.Point - l2.StartPoint;
var d = Perp(u, v);
if (Math.Abs(d) < Constants.Tolerance)
{
// parallel lines
return null;
}
var sI = Perp(v, w) / d;
var p = ray.Point + (sI * u);
if (mustBeBetweenStartAndEnd)
{
if (ray.IsPointOn(p) && l2.IsPointOnLine(p))
{
return p;
}
return null;
}
return p;
}
private static double Perp(Vector u, Vector v)
{
return (u.X * v.Y) - (u.Y * v.X);
}
}
}
| |
using Umbraco.Core.Configuration;
using System;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Persistence.Caching;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Persistence
{
/// <summary>
/// Used to instantiate each repository type
/// </summary>
public class RepositoryFactory
{
private readonly bool _disableAllCache;
private readonly CacheHelper _cacheHelper;
private readonly IUmbracoSettingsSection _settings;
#region Ctors
public RepositoryFactory()
: this(false, UmbracoConfig.For.UmbracoSettings())
{
}
public RepositoryFactory(CacheHelper cacheHelper)
: this(false, UmbracoConfig.For.UmbracoSettings())
{
if (cacheHelper == null) throw new ArgumentNullException("cacheHelper");
_disableAllCache = false;
_cacheHelper = cacheHelper;
}
public RepositoryFactory(bool disableAllCache, CacheHelper cacheHelper)
: this(disableAllCache, UmbracoConfig.For.UmbracoSettings())
{
if (cacheHelper == null) throw new ArgumentNullException("cacheHelper");
_cacheHelper = cacheHelper;
}
public RepositoryFactory(bool disableAllCache)
: this(disableAllCache, UmbracoConfig.For.UmbracoSettings())
{
}
internal RepositoryFactory(bool disableAllCache, IUmbracoSettingsSection settings)
{
_disableAllCache = disableAllCache;
_settings = settings;
_cacheHelper = _disableAllCache ? CacheHelper.CreateDisabledCacheHelper() : ApplicationContext.Current.ApplicationCache;
}
internal RepositoryFactory(bool disableAllCache, IUmbracoSettingsSection settings, CacheHelper cacheHelper)
{
_disableAllCache = disableAllCache;
_settings = settings;
_cacheHelper = cacheHelper;
}
#endregion
public virtual ITagsRepository CreateTagsRepository(IDatabaseUnitOfWork uow)
{
return new TagsRepository(
uow,
_disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current);
}
public virtual IContentRepository CreateContentRepository(IDatabaseUnitOfWork uow)
{
return new ContentRepository(
uow,
_disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current,
CreateContentTypeRepository(uow),
CreateTemplateRepository(uow),
CreateTagsRepository(uow),
_cacheHelper) { EnsureUniqueNaming = _settings.Content.EnsureUniqueNaming };
}
public virtual IContentTypeRepository CreateContentTypeRepository(IDatabaseUnitOfWork uow)
{
return new ContentTypeRepository(
uow,
_disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current,
new TemplateRepository(uow, NullCacheProvider.Current));
}
public virtual IDataTypeDefinitionRepository CreateDataTypeDefinitionRepository(IDatabaseUnitOfWork uow)
{
return new DataTypeDefinitionRepository(
uow,
NullCacheProvider.Current);
}
public virtual IDictionaryRepository CreateDictionaryRepository(IDatabaseUnitOfWork uow)
{
return new DictionaryRepository(
uow,
_disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current,
CreateLanguageRepository(uow));
}
public virtual ILanguageRepository CreateLanguageRepository(IDatabaseUnitOfWork uow)
{
return new LanguageRepository(
uow,
_disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current);
}
public virtual IMediaRepository CreateMediaRepository(IDatabaseUnitOfWork uow)
{
return new MediaRepository(
uow,
_disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current,
CreateMediaTypeRepository(uow),
CreateTagsRepository(uow)) { EnsureUniqueNaming = _settings.Content.EnsureUniqueNaming };
}
public virtual IMediaTypeRepository CreateMediaTypeRepository(IDatabaseUnitOfWork uow)
{
return new MediaTypeRepository(
uow,
_disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current);
}
public virtual IRelationRepository CreateRelationRepository(IDatabaseUnitOfWork uow)
{
return new RelationRepository(
uow,
NullCacheProvider.Current,
CreateRelationTypeRepository(uow));
}
public virtual IRelationTypeRepository CreateRelationTypeRepository(IDatabaseUnitOfWork uow)
{
return new RelationTypeRepository(
uow,
NullCacheProvider.Current);
}
public virtual IScriptRepository CreateScriptRepository(IUnitOfWork uow)
{
return new ScriptRepository(uow);
}
public virtual IStylesheetRepository CreateStylesheetRepository(IUnitOfWork uow, IDatabaseUnitOfWork db)
{
return new StylesheetRepository(uow, db);
}
public virtual ITemplateRepository CreateTemplateRepository(IDatabaseUnitOfWork uow)
{
return new TemplateRepository(uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current);
}
internal virtual ServerRegistrationRepository CreateServerRegistrationRepository(IDatabaseUnitOfWork uow)
{
return new ServerRegistrationRepository(
uow,
NullCacheProvider.Current);
}
public virtual IUserTypeRepository CreateUserTypeRepository(IDatabaseUnitOfWork uow)
{
return new UserTypeRepository(
uow,
//There's not many user types but we query on users all the time so the result needs to be cached
_disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current);
}
public virtual IUserRepository CreateUserRepository(IDatabaseUnitOfWork uow)
{
return new UserRepository(
uow,
//Need to cache users - we look up user information more than anything in the back office!
_disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current,
CreateUserTypeRepository(uow),
_cacheHelper);
}
internal virtual IMacroRepository CreateMacroRepository(IDatabaseUnitOfWork uow)
{
return new MacroRepository(uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current);
}
public virtual IMemberRepository CreateMemberRepository(IDatabaseUnitOfWork uow)
{
return new MemberRepository(
uow,
_disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current,
CreateMemberTypeRepository(uow),
CreateMemberGroupRepository(uow),
CreateTagsRepository(uow));
}
public virtual IMemberTypeRepository CreateMemberTypeRepository(IDatabaseUnitOfWork uow)
{
return new MemberTypeRepository(uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current);
}
public virtual IMemberGroupRepository CreateMemberGroupRepository(IDatabaseUnitOfWork uow)
{
return new MemberGroupRepository(uow, _disableAllCache ? (IRepositoryCacheProvider)NullCacheProvider.Current : RuntimeCacheProvider.Current, _cacheHelper);
}
public virtual IEntityRepository CreateEntityRepository(IDatabaseUnitOfWork uow)
{
return new EntityRepository(uow);
}
internal virtual RecycleBinRepository CreateRecycleBinRepository(IDatabaseUnitOfWork uow)
{
return new RecycleBinRepository(uow);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Text;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;
namespace Lucene.Net.Classification
{
/**
* Base class for testing <see cref="IClassifier{T}"/>s
*/
public abstract class ClassificationTestBase<T> : Util.LuceneTestCase
{
public readonly static String POLITICS_INPUT = "Here are some interesting questions and answers about Mitt Romney.. " +
"If you don't know the answer to the question about Mitt Romney, then simply click on the answer below the question section.";
public static readonly BytesRef POLITICS_RESULT = new BytesRef("politics");
public static readonly String TECHNOLOGY_INPUT = "Much is made of what the likes of Facebook, Google and Apple know about users." +
" Truth is, Amazon may know more.";
public static readonly BytesRef TECHNOLOGY_RESULT = new BytesRef("technology");
private RandomIndexWriter indexWriter;
private Directory dir;
private FieldType ft;
protected String textFieldName;
protected String categoryFieldName;
String booleanFieldName;
[SetUp]
public override void SetUp()
{
base.SetUp();
dir = NewDirectory();
indexWriter = new RandomIndexWriter(Random(), dir, Similarity, TimeZone);
textFieldName = "text";
categoryFieldName = "cat";
booleanFieldName = "bool";
ft = new FieldType(TextField.TYPE_STORED);
ft.StoreTermVectors = true;
ft.StoreTermVectorOffsets = true;
ft.StoreTermVectorPositions = true;
}
[TearDown]
public override void TearDown()
{
indexWriter.Dispose();
dir.Dispose();
base.TearDown();
}
protected void CheckCorrectClassification(IClassifier<T> classifier, String inputDoc, T expectedResult, Analyzer analyzer, String textFieldName, String classFieldName)
{
CheckCorrectClassification(classifier, inputDoc, expectedResult, analyzer, textFieldName, classFieldName, null);
}
protected void CheckCorrectClassification(IClassifier<T> classifier, String inputDoc, T expectedResult, Analyzer analyzer, String textFieldName, String classFieldName, Query query)
{
AtomicReader atomicReader = null;
try
{
PopulateSampleIndex(analyzer);
atomicReader = SlowCompositeReaderWrapper.Wrap(indexWriter.Reader);
classifier.Train(atomicReader, textFieldName, classFieldName, analyzer, query);
ClassificationResult<T> classificationResult = classifier.AssignClass(inputDoc);
NotNull(classificationResult.AssignedClass);
AreEqual(expectedResult, classificationResult.AssignedClass, "got an assigned class of " + classificationResult.AssignedClass);
IsTrue(classificationResult.Score > 0, "got a not positive score " + classificationResult.Score);
}
finally
{
if (atomicReader != null)
atomicReader.Dispose();
}
}
protected void CheckOnlineClassification(IClassifier<T> classifier, String inputDoc, T expectedResult, Analyzer analyzer, String textFieldName, String classFieldName)
{
CheckOnlineClassification(classifier, inputDoc, expectedResult, analyzer, textFieldName, classFieldName, null);
}
protected void CheckOnlineClassification(IClassifier<T> classifier, String inputDoc, T expectedResult, Analyzer analyzer, String textFieldName, String classFieldName, Query query)
{
AtomicReader atomicReader = null;
try
{
PopulateSampleIndex(analyzer);
atomicReader = SlowCompositeReaderWrapper.Wrap(indexWriter.Reader);
classifier.Train(atomicReader, textFieldName, classFieldName, analyzer, query);
ClassificationResult<T> classificationResult = classifier.AssignClass(inputDoc);
NotNull(classificationResult.AssignedClass);
AreEqual(expectedResult, classificationResult.AssignedClass, "got an assigned class of " + classificationResult.AssignedClass);
IsTrue(classificationResult.Score > 0, "got a not positive score " + classificationResult.Score);
UpdateSampleIndex(analyzer);
ClassificationResult<T> secondClassificationResult = classifier.AssignClass(inputDoc);
Equals(classificationResult.AssignedClass, secondClassificationResult.AssignedClass);
Equals(classificationResult.Score, secondClassificationResult.Score);
}
finally
{
if (atomicReader != null)
atomicReader.Dispose();
}
}
private void PopulateSampleIndex(Analyzer analyzer)
{
indexWriter.DeleteAll();
indexWriter.Commit();
String text;
Document doc = new Document();
text = "The traveling press secretary for Mitt Romney lost his cool and cursed at reporters " +
"who attempted to ask questions of the Republican presidential candidate in a public plaza near the Tomb of " +
"the Unknown Soldier in Warsaw Tuesday.";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "politics", ft));
doc.Add(new Field(booleanFieldName, "true", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "Mitt Romney seeks to assure Israel and Iran, as well as Jewish voters in the United" +
" States, that he will be tougher against Iran's nuclear ambitions than President Barack Obama.";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "politics", ft));
doc.Add(new Field(booleanFieldName, "true", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "And there's a threshold question that he has to answer for the American people and " +
"that's whether he is prepared to be commander-in-chief,\" she continued. \"As we look to the past events, we " +
"know that this raises some questions about his preparedness and we'll see how the rest of his trip goes.\"";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "politics", ft));
doc.Add(new Field(booleanFieldName, "true", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "Still, when it comes to gun policy, many congressional Democrats have \"decided to " +
"keep quiet and not go there,\" said Alan Lizotte, dean and professor at the State University of New York at " +
"Albany's School of Criminal Justice.";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "politics", ft));
doc.Add(new Field(booleanFieldName, "true", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "Standing amongst the thousands of people at the state Capitol, Jorstad, director of " +
"technology at the University of Wisconsin-La Crosse, documented the historic moment and shared it with the " +
"world through the Internet.";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "technology", ft));
doc.Add(new Field(booleanFieldName, "false", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "So, about all those experts and analysts who've spent the past year or so saying " +
"Facebook was going to make a phone. A new expert has stepped forward to say it's not going to happen.";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "technology", ft));
doc.Add(new Field(booleanFieldName, "false", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "More than 400 million people trust Google with their e-mail, and 50 million store files" +
" in the cloud using the Dropbox service. People manage their bank accounts, pay bills, trade stocks and " +
"generally transfer or store huge volumes of personal data online.";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "technology", ft));
doc.Add(new Field(booleanFieldName, "false", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "unlabeled doc";
doc.Add(new Field(textFieldName, text, ft));
indexWriter.AddDocument(doc, analyzer);
indexWriter.Commit();
}
protected void CheckPerformance(IClassifier<T> classifier, Analyzer analyzer, String classFieldName)
{
AtomicReader atomicReader = null;
var stopwatch = new Stopwatch();
stopwatch.Start();
try
{
PopulatePerformanceIndex(analyzer);
atomicReader = SlowCompositeReaderWrapper.Wrap(indexWriter.Reader);
classifier.Train(atomicReader, textFieldName, classFieldName, analyzer);
stopwatch.Stop();
long trainTime = stopwatch.ElapsedMilliseconds;
IsTrue(trainTime < 120000, "training took more than 2 mins : " + trainTime / 1000 + "s");
}
finally
{
if (atomicReader != null)
atomicReader.Dispose();
}
}
private void PopulatePerformanceIndex(Analyzer analyzer)
{
indexWriter.DeleteAll();
indexWriter.Commit();
FieldType ft = new FieldType(TextField.TYPE_STORED);
ft.StoreTermVectors = true;
ft.StoreTermVectorOffsets = true;
ft.StoreTermVectorPositions = true;
int docs = 1000;
Random random = new Random();
for (int i = 0; i < docs; i++)
{
Boolean b = random.NextBoolean();
Document doc = new Document();
doc.Add(new Field(textFieldName, createRandomString(random), ft));
doc.Add(new Field(categoryFieldName, b ? "technology" : "politics", ft));
doc.Add(new Field(booleanFieldName, b.ToString(), ft));
indexWriter.AddDocument(doc, analyzer);
}
indexWriter.Commit();
}
private String createRandomString(Random random)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 20; i++)
{
builder.Append(TestUtil.RandomSimpleString(random, 5));
builder.Append(" ");
}
return builder.ToString();
}
private void UpdateSampleIndex(Analyzer analyzer)
{
String text;
Document doc = new Document();
text = "Warren Bennis says John F. Kennedy grasped a key lesson about the presidency that few have followed.";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "politics", ft));
doc.Add(new Field(booleanFieldName, "true", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "Julian Zelizer says Bill Clinton is still trying to shape his party, years after the White House, while George W. Bush opts for a much more passive role.";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "politics", ft));
doc.Add(new Field(booleanFieldName, "true", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "Crossfire: Sen. Tim Scott passes on Sen. Lindsey Graham endorsement";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "politics", ft));
doc.Add(new Field(booleanFieldName, "true", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "Illinois becomes 16th state to allow same-sex marriage.";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "politics", ft));
doc.Add(new Field(booleanFieldName, "true", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "Apple is developing iPhones with curved-glass screens and enhanced sensors that detect different levels of pressure, according to a new report.";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "technology", ft));
doc.Add(new Field(booleanFieldName, "false", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "The Xbox One is Microsoft's first new gaming console in eight years. It's a quality piece of hardware but it's also noteworthy because Microsoft is using it to make a statement.";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "technology", ft));
doc.Add(new Field(booleanFieldName, "false", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "Google says it will replace a Google Maps image after a California father complained it shows the body of his teen-age son, who was shot to death in 2009.";
doc.Add(new Field(textFieldName, text, ft));
doc.Add(new Field(categoryFieldName, "technology", ft));
doc.Add(new Field(booleanFieldName, "false", ft));
indexWriter.AddDocument(doc, analyzer);
doc = new Document();
text = "second unlabeled doc";
doc.Add(new Field(textFieldName, text, ft));
indexWriter.AddDocument(doc, analyzer);
indexWriter.Commit();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
#nullable enable
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
{
internal partial class HttpProtocol : IFeatureCollection,
IHttpRequestFeature,
IHttpResponseFeature,
IHttpResponseBodyFeature,
IRouteValuesFeature,
IEndpointFeature,
IHttpRequestIdentifierFeature,
IHttpRequestTrailersFeature,
IHttpUpgradeFeature,
IRequestBodyPipeFeature,
IHttpConnectionFeature,
IHttpRequestLifetimeFeature,
IHttpBodyControlFeature,
IHttpMaxRequestBodySizeFeature,
IHttpRequestBodyDetectionFeature,
IBadRequestExceptionFeature
{
// Implemented features
internal protected IHttpRequestFeature? _currentIHttpRequestFeature;
internal protected IHttpResponseFeature? _currentIHttpResponseFeature;
internal protected IHttpResponseBodyFeature? _currentIHttpResponseBodyFeature;
internal protected IRouteValuesFeature? _currentIRouteValuesFeature;
internal protected IEndpointFeature? _currentIEndpointFeature;
internal protected IHttpRequestIdentifierFeature? _currentIHttpRequestIdentifierFeature;
internal protected IHttpRequestTrailersFeature? _currentIHttpRequestTrailersFeature;
internal protected IHttpUpgradeFeature? _currentIHttpUpgradeFeature;
internal protected IRequestBodyPipeFeature? _currentIRequestBodyPipeFeature;
internal protected IHttpConnectionFeature? _currentIHttpConnectionFeature;
internal protected IHttpRequestLifetimeFeature? _currentIHttpRequestLifetimeFeature;
internal protected IHttpBodyControlFeature? _currentIHttpBodyControlFeature;
internal protected IHttpMaxRequestBodySizeFeature? _currentIHttpMaxRequestBodySizeFeature;
internal protected IHttpRequestBodyDetectionFeature? _currentIHttpRequestBodyDetectionFeature;
internal protected IBadRequestExceptionFeature? _currentIBadRequestExceptionFeature;
// Other reserved feature slots
internal protected IServiceProvidersFeature? _currentIServiceProvidersFeature;
internal protected IHttpActivityFeature? _currentIHttpActivityFeature;
internal protected IItemsFeature? _currentIItemsFeature;
internal protected IQueryFeature? _currentIQueryFeature;
internal protected IFormFeature? _currentIFormFeature;
internal protected IHttpAuthenticationFeature? _currentIHttpAuthenticationFeature;
internal protected ISessionFeature? _currentISessionFeature;
internal protected IResponseCookiesFeature? _currentIResponseCookiesFeature;
internal protected IHttpResponseTrailersFeature? _currentIHttpResponseTrailersFeature;
internal protected ITlsConnectionFeature? _currentITlsConnectionFeature;
internal protected IHttpWebSocketFeature? _currentIHttpWebSocketFeature;
internal protected IHttp2StreamIdFeature? _currentIHttp2StreamIdFeature;
internal protected IHttpMinRequestBodyDataRateFeature? _currentIHttpMinRequestBodyDataRateFeature;
internal protected IHttpMinResponseDataRateFeature? _currentIHttpMinResponseDataRateFeature;
internal protected IHttpResetFeature? _currentIHttpResetFeature;
internal protected IPersistentStateFeature? _currentIPersistentStateFeature;
private int _featureRevision;
private List<KeyValuePair<Type, object>>? MaybeExtra;
private void FastReset()
{
_currentIHttpRequestFeature = this;
_currentIHttpResponseFeature = this;
_currentIHttpResponseBodyFeature = this;
_currentIRouteValuesFeature = this;
_currentIEndpointFeature = this;
_currentIHttpRequestIdentifierFeature = this;
_currentIHttpRequestTrailersFeature = this;
_currentIHttpUpgradeFeature = this;
_currentIRequestBodyPipeFeature = this;
_currentIHttpConnectionFeature = this;
_currentIHttpRequestLifetimeFeature = this;
_currentIHttpBodyControlFeature = this;
_currentIHttpMaxRequestBodySizeFeature = this;
_currentIHttpRequestBodyDetectionFeature = this;
_currentIBadRequestExceptionFeature = this;
_currentIServiceProvidersFeature = null;
_currentIHttpActivityFeature = null;
_currentIItemsFeature = null;
_currentIQueryFeature = null;
_currentIFormFeature = null;
_currentIHttpAuthenticationFeature = null;
_currentISessionFeature = null;
_currentIResponseCookiesFeature = null;
_currentIHttpResponseTrailersFeature = null;
_currentITlsConnectionFeature = null;
_currentIHttpWebSocketFeature = null;
_currentIHttp2StreamIdFeature = null;
_currentIHttpMinRequestBodyDataRateFeature = null;
_currentIHttpMinResponseDataRateFeature = null;
_currentIHttpResetFeature = null;
_currentIPersistentStateFeature = null;
}
// Internal for testing
internal void ResetFeatureCollection()
{
FastReset();
MaybeExtra?.Clear();
_featureRevision++;
}
private object? ExtraFeatureGet(Type key)
{
if (MaybeExtra == null)
{
return null;
}
for (var i = 0; i < MaybeExtra.Count; i++)
{
var kv = MaybeExtra[i];
if (kv.Key == key)
{
return kv.Value;
}
}
return null;
}
private void ExtraFeatureSet(Type key, object? value)
{
if (value == null)
{
if (MaybeExtra == null)
{
return;
}
for (var i = 0; i < MaybeExtra.Count; i++)
{
if (MaybeExtra[i].Key == key)
{
MaybeExtra.RemoveAt(i);
return;
}
}
}
else
{
if (MaybeExtra == null)
{
MaybeExtra = new List<KeyValuePair<Type, object>>(2);
}
for (var i = 0; i < MaybeExtra.Count; i++)
{
if (MaybeExtra[i].Key == key)
{
MaybeExtra[i] = new KeyValuePair<Type, object>(key, value);
return;
}
}
MaybeExtra.Add(new KeyValuePair<Type, object>(key, value));
}
}
bool IFeatureCollection.IsReadOnly => false;
int IFeatureCollection.Revision => _featureRevision;
object? IFeatureCollection.this[Type key]
{
get
{
object? feature = null;
if (key == typeof(IHttpRequestFeature))
{
feature = _currentIHttpRequestFeature;
}
else if (key == typeof(IHttpResponseFeature))
{
feature = _currentIHttpResponseFeature;
}
else if (key == typeof(IHttpResponseBodyFeature))
{
feature = _currentIHttpResponseBodyFeature;
}
else if (key == typeof(IRouteValuesFeature))
{
feature = _currentIRouteValuesFeature;
}
else if (key == typeof(IEndpointFeature))
{
feature = _currentIEndpointFeature;
}
else if (key == typeof(IServiceProvidersFeature))
{
feature = _currentIServiceProvidersFeature;
}
else if (key == typeof(IHttpActivityFeature))
{
feature = _currentIHttpActivityFeature;
}
else if (key == typeof(IItemsFeature))
{
feature = _currentIItemsFeature;
}
else if (key == typeof(IQueryFeature))
{
feature = _currentIQueryFeature;
}
else if (key == typeof(IRequestBodyPipeFeature))
{
feature = _currentIRequestBodyPipeFeature;
}
else if (key == typeof(IFormFeature))
{
feature = _currentIFormFeature;
}
else if (key == typeof(IHttpAuthenticationFeature))
{
feature = _currentIHttpAuthenticationFeature;
}
else if (key == typeof(IHttpRequestIdentifierFeature))
{
feature = _currentIHttpRequestIdentifierFeature;
}
else if (key == typeof(IHttpConnectionFeature))
{
feature = _currentIHttpConnectionFeature;
}
else if (key == typeof(ISessionFeature))
{
feature = _currentISessionFeature;
}
else if (key == typeof(IResponseCookiesFeature))
{
feature = _currentIResponseCookiesFeature;
}
else if (key == typeof(IHttpRequestTrailersFeature))
{
feature = _currentIHttpRequestTrailersFeature;
}
else if (key == typeof(IHttpResponseTrailersFeature))
{
feature = _currentIHttpResponseTrailersFeature;
}
else if (key == typeof(ITlsConnectionFeature))
{
feature = _currentITlsConnectionFeature;
}
else if (key == typeof(IHttpUpgradeFeature))
{
feature = _currentIHttpUpgradeFeature;
}
else if (key == typeof(IHttpWebSocketFeature))
{
feature = _currentIHttpWebSocketFeature;
}
else if (key == typeof(IBadRequestExceptionFeature))
{
feature = _currentIBadRequestExceptionFeature;
}
else if (key == typeof(IHttp2StreamIdFeature))
{
feature = _currentIHttp2StreamIdFeature;
}
else if (key == typeof(IHttpRequestLifetimeFeature))
{
feature = _currentIHttpRequestLifetimeFeature;
}
else if (key == typeof(IHttpMaxRequestBodySizeFeature))
{
feature = _currentIHttpMaxRequestBodySizeFeature;
}
else if (key == typeof(IHttpMinRequestBodyDataRateFeature))
{
feature = _currentIHttpMinRequestBodyDataRateFeature;
}
else if (key == typeof(IHttpMinResponseDataRateFeature))
{
feature = _currentIHttpMinResponseDataRateFeature;
}
else if (key == typeof(IHttpBodyControlFeature))
{
feature = _currentIHttpBodyControlFeature;
}
else if (key == typeof(IHttpRequestBodyDetectionFeature))
{
feature = _currentIHttpRequestBodyDetectionFeature;
}
else if (key == typeof(IHttpResetFeature))
{
feature = _currentIHttpResetFeature;
}
else if (key == typeof(IPersistentStateFeature))
{
feature = _currentIPersistentStateFeature;
}
else if (MaybeExtra != null)
{
feature = ExtraFeatureGet(key);
}
return feature ?? ConnectionFeatures?[key];
}
set
{
_featureRevision++;
if (key == typeof(IHttpRequestFeature))
{
_currentIHttpRequestFeature = (IHttpRequestFeature?)value;
}
else if (key == typeof(IHttpResponseFeature))
{
_currentIHttpResponseFeature = (IHttpResponseFeature?)value;
}
else if (key == typeof(IHttpResponseBodyFeature))
{
_currentIHttpResponseBodyFeature = (IHttpResponseBodyFeature?)value;
}
else if (key == typeof(IRouteValuesFeature))
{
_currentIRouteValuesFeature = (IRouteValuesFeature?)value;
}
else if (key == typeof(IEndpointFeature))
{
_currentIEndpointFeature = (IEndpointFeature?)value;
}
else if (key == typeof(IServiceProvidersFeature))
{
_currentIServiceProvidersFeature = (IServiceProvidersFeature?)value;
}
else if (key == typeof(IHttpActivityFeature))
{
_currentIHttpActivityFeature = (IHttpActivityFeature?)value;
}
else if (key == typeof(IItemsFeature))
{
_currentIItemsFeature = (IItemsFeature?)value;
}
else if (key == typeof(IQueryFeature))
{
_currentIQueryFeature = (IQueryFeature?)value;
}
else if (key == typeof(IRequestBodyPipeFeature))
{
_currentIRequestBodyPipeFeature = (IRequestBodyPipeFeature?)value;
}
else if (key == typeof(IFormFeature))
{
_currentIFormFeature = (IFormFeature?)value;
}
else if (key == typeof(IHttpAuthenticationFeature))
{
_currentIHttpAuthenticationFeature = (IHttpAuthenticationFeature?)value;
}
else if (key == typeof(IHttpRequestIdentifierFeature))
{
_currentIHttpRequestIdentifierFeature = (IHttpRequestIdentifierFeature?)value;
}
else if (key == typeof(IHttpConnectionFeature))
{
_currentIHttpConnectionFeature = (IHttpConnectionFeature?)value;
}
else if (key == typeof(ISessionFeature))
{
_currentISessionFeature = (ISessionFeature?)value;
}
else if (key == typeof(IResponseCookiesFeature))
{
_currentIResponseCookiesFeature = (IResponseCookiesFeature?)value;
}
else if (key == typeof(IHttpRequestTrailersFeature))
{
_currentIHttpRequestTrailersFeature = (IHttpRequestTrailersFeature?)value;
}
else if (key == typeof(IHttpResponseTrailersFeature))
{
_currentIHttpResponseTrailersFeature = (IHttpResponseTrailersFeature?)value;
}
else if (key == typeof(ITlsConnectionFeature))
{
_currentITlsConnectionFeature = (ITlsConnectionFeature?)value;
}
else if (key == typeof(IHttpUpgradeFeature))
{
_currentIHttpUpgradeFeature = (IHttpUpgradeFeature?)value;
}
else if (key == typeof(IHttpWebSocketFeature))
{
_currentIHttpWebSocketFeature = (IHttpWebSocketFeature?)value;
}
else if (key == typeof(IBadRequestExceptionFeature))
{
_currentIBadRequestExceptionFeature = (IBadRequestExceptionFeature?)value;
}
else if (key == typeof(IHttp2StreamIdFeature))
{
_currentIHttp2StreamIdFeature = (IHttp2StreamIdFeature?)value;
}
else if (key == typeof(IHttpRequestLifetimeFeature))
{
_currentIHttpRequestLifetimeFeature = (IHttpRequestLifetimeFeature?)value;
}
else if (key == typeof(IHttpMaxRequestBodySizeFeature))
{
_currentIHttpMaxRequestBodySizeFeature = (IHttpMaxRequestBodySizeFeature?)value;
}
else if (key == typeof(IHttpMinRequestBodyDataRateFeature))
{
_currentIHttpMinRequestBodyDataRateFeature = (IHttpMinRequestBodyDataRateFeature?)value;
}
else if (key == typeof(IHttpMinResponseDataRateFeature))
{
_currentIHttpMinResponseDataRateFeature = (IHttpMinResponseDataRateFeature?)value;
}
else if (key == typeof(IHttpBodyControlFeature))
{
_currentIHttpBodyControlFeature = (IHttpBodyControlFeature?)value;
}
else if (key == typeof(IHttpRequestBodyDetectionFeature))
{
_currentIHttpRequestBodyDetectionFeature = (IHttpRequestBodyDetectionFeature?)value;
}
else if (key == typeof(IHttpResetFeature))
{
_currentIHttpResetFeature = (IHttpResetFeature?)value;
}
else if (key == typeof(IPersistentStateFeature))
{
_currentIPersistentStateFeature = (IPersistentStateFeature?)value;
}
else
{
ExtraFeatureSet(key, value);
}
}
}
TFeature? IFeatureCollection.Get<TFeature>() where TFeature : default
{
// Using Unsafe.As for the cast due to https://github.com/dotnet/runtime/issues/49614
// The type of TFeature is confirmed by the typeof() check and the As cast only accepts
// that type; however the Jit does not eliminate a regular cast in a shared generic.
TFeature? feature = default;
if (typeof(TFeature) == typeof(IHttpRequestFeature))
{
feature = Unsafe.As<IHttpRequestFeature?, TFeature?>(ref _currentIHttpRequestFeature);
}
else if (typeof(TFeature) == typeof(IHttpResponseFeature))
{
feature = Unsafe.As<IHttpResponseFeature?, TFeature?>(ref _currentIHttpResponseFeature);
}
else if (typeof(TFeature) == typeof(IHttpResponseBodyFeature))
{
feature = Unsafe.As<IHttpResponseBodyFeature?, TFeature?>(ref _currentIHttpResponseBodyFeature);
}
else if (typeof(TFeature) == typeof(IRouteValuesFeature))
{
feature = Unsafe.As<IRouteValuesFeature?, TFeature?>(ref _currentIRouteValuesFeature);
}
else if (typeof(TFeature) == typeof(IEndpointFeature))
{
feature = Unsafe.As<IEndpointFeature?, TFeature?>(ref _currentIEndpointFeature);
}
else if (typeof(TFeature) == typeof(IServiceProvidersFeature))
{
feature = Unsafe.As<IServiceProvidersFeature?, TFeature?>(ref _currentIServiceProvidersFeature);
}
else if (typeof(TFeature) == typeof(IHttpActivityFeature))
{
feature = Unsafe.As<IHttpActivityFeature?, TFeature?>(ref _currentIHttpActivityFeature);
}
else if (typeof(TFeature) == typeof(IItemsFeature))
{
feature = Unsafe.As<IItemsFeature?, TFeature?>(ref _currentIItemsFeature);
}
else if (typeof(TFeature) == typeof(IQueryFeature))
{
feature = Unsafe.As<IQueryFeature?, TFeature?>(ref _currentIQueryFeature);
}
else if (typeof(TFeature) == typeof(IRequestBodyPipeFeature))
{
feature = Unsafe.As<IRequestBodyPipeFeature?, TFeature?>(ref _currentIRequestBodyPipeFeature);
}
else if (typeof(TFeature) == typeof(IFormFeature))
{
feature = Unsafe.As<IFormFeature?, TFeature?>(ref _currentIFormFeature);
}
else if (typeof(TFeature) == typeof(IHttpAuthenticationFeature))
{
feature = Unsafe.As<IHttpAuthenticationFeature?, TFeature?>(ref _currentIHttpAuthenticationFeature);
}
else if (typeof(TFeature) == typeof(IHttpRequestIdentifierFeature))
{
feature = Unsafe.As<IHttpRequestIdentifierFeature?, TFeature?>(ref _currentIHttpRequestIdentifierFeature);
}
else if (typeof(TFeature) == typeof(IHttpConnectionFeature))
{
feature = Unsafe.As<IHttpConnectionFeature?, TFeature?>(ref _currentIHttpConnectionFeature);
}
else if (typeof(TFeature) == typeof(ISessionFeature))
{
feature = Unsafe.As<ISessionFeature?, TFeature?>(ref _currentISessionFeature);
}
else if (typeof(TFeature) == typeof(IResponseCookiesFeature))
{
feature = Unsafe.As<IResponseCookiesFeature?, TFeature?>(ref _currentIResponseCookiesFeature);
}
else if (typeof(TFeature) == typeof(IHttpRequestTrailersFeature))
{
feature = Unsafe.As<IHttpRequestTrailersFeature?, TFeature?>(ref _currentIHttpRequestTrailersFeature);
}
else if (typeof(TFeature) == typeof(IHttpResponseTrailersFeature))
{
feature = Unsafe.As<IHttpResponseTrailersFeature?, TFeature?>(ref _currentIHttpResponseTrailersFeature);
}
else if (typeof(TFeature) == typeof(ITlsConnectionFeature))
{
feature = Unsafe.As<ITlsConnectionFeature?, TFeature?>(ref _currentITlsConnectionFeature);
}
else if (typeof(TFeature) == typeof(IHttpUpgradeFeature))
{
feature = Unsafe.As<IHttpUpgradeFeature?, TFeature?>(ref _currentIHttpUpgradeFeature);
}
else if (typeof(TFeature) == typeof(IHttpWebSocketFeature))
{
feature = Unsafe.As<IHttpWebSocketFeature?, TFeature?>(ref _currentIHttpWebSocketFeature);
}
else if (typeof(TFeature) == typeof(IBadRequestExceptionFeature))
{
feature = Unsafe.As<IBadRequestExceptionFeature?, TFeature?>(ref _currentIBadRequestExceptionFeature);
}
else if (typeof(TFeature) == typeof(IHttp2StreamIdFeature))
{
feature = Unsafe.As<IHttp2StreamIdFeature?, TFeature?>(ref _currentIHttp2StreamIdFeature);
}
else if (typeof(TFeature) == typeof(IHttpRequestLifetimeFeature))
{
feature = Unsafe.As<IHttpRequestLifetimeFeature?, TFeature?>(ref _currentIHttpRequestLifetimeFeature);
}
else if (typeof(TFeature) == typeof(IHttpMaxRequestBodySizeFeature))
{
feature = Unsafe.As<IHttpMaxRequestBodySizeFeature?, TFeature?>(ref _currentIHttpMaxRequestBodySizeFeature);
}
else if (typeof(TFeature) == typeof(IHttpMinRequestBodyDataRateFeature))
{
feature = Unsafe.As<IHttpMinRequestBodyDataRateFeature?, TFeature?>(ref _currentIHttpMinRequestBodyDataRateFeature);
}
else if (typeof(TFeature) == typeof(IHttpMinResponseDataRateFeature))
{
feature = Unsafe.As<IHttpMinResponseDataRateFeature?, TFeature?>(ref _currentIHttpMinResponseDataRateFeature);
}
else if (typeof(TFeature) == typeof(IHttpBodyControlFeature))
{
feature = Unsafe.As<IHttpBodyControlFeature?, TFeature?>(ref _currentIHttpBodyControlFeature);
}
else if (typeof(TFeature) == typeof(IHttpRequestBodyDetectionFeature))
{
feature = Unsafe.As<IHttpRequestBodyDetectionFeature?, TFeature?>(ref _currentIHttpRequestBodyDetectionFeature);
}
else if (typeof(TFeature) == typeof(IHttpResetFeature))
{
feature = Unsafe.As<IHttpResetFeature?, TFeature?>(ref _currentIHttpResetFeature);
}
else if (typeof(TFeature) == typeof(IPersistentStateFeature))
{
feature = Unsafe.As<IPersistentStateFeature?, TFeature?>(ref _currentIPersistentStateFeature);
}
else if (MaybeExtra != null)
{
feature = (TFeature?)(ExtraFeatureGet(typeof(TFeature)));
}
if (feature == null && ConnectionFeatures != null)
{
feature = ConnectionFeatures.Get<TFeature>();
}
return feature;
}
void IFeatureCollection.Set<TFeature>(TFeature? feature) where TFeature : default
{
// Using Unsafe.As for the cast due to https://github.com/dotnet/runtime/issues/49614
// The type of TFeature is confirmed by the typeof() check and the As cast only accepts
// that type; however the Jit does not eliminate a regular cast in a shared generic.
_featureRevision++;
if (typeof(TFeature) == typeof(IHttpRequestFeature))
{
_currentIHttpRequestFeature = Unsafe.As<TFeature?, IHttpRequestFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpResponseFeature))
{
_currentIHttpResponseFeature = Unsafe.As<TFeature?, IHttpResponseFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpResponseBodyFeature))
{
_currentIHttpResponseBodyFeature = Unsafe.As<TFeature?, IHttpResponseBodyFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IRouteValuesFeature))
{
_currentIRouteValuesFeature = Unsafe.As<TFeature?, IRouteValuesFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IEndpointFeature))
{
_currentIEndpointFeature = Unsafe.As<TFeature?, IEndpointFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IServiceProvidersFeature))
{
_currentIServiceProvidersFeature = Unsafe.As<TFeature?, IServiceProvidersFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpActivityFeature))
{
_currentIHttpActivityFeature = Unsafe.As<TFeature?, IHttpActivityFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IItemsFeature))
{
_currentIItemsFeature = Unsafe.As<TFeature?, IItemsFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IQueryFeature))
{
_currentIQueryFeature = Unsafe.As<TFeature?, IQueryFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IRequestBodyPipeFeature))
{
_currentIRequestBodyPipeFeature = Unsafe.As<TFeature?, IRequestBodyPipeFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IFormFeature))
{
_currentIFormFeature = Unsafe.As<TFeature?, IFormFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpAuthenticationFeature))
{
_currentIHttpAuthenticationFeature = Unsafe.As<TFeature?, IHttpAuthenticationFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpRequestIdentifierFeature))
{
_currentIHttpRequestIdentifierFeature = Unsafe.As<TFeature?, IHttpRequestIdentifierFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpConnectionFeature))
{
_currentIHttpConnectionFeature = Unsafe.As<TFeature?, IHttpConnectionFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(ISessionFeature))
{
_currentISessionFeature = Unsafe.As<TFeature?, ISessionFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IResponseCookiesFeature))
{
_currentIResponseCookiesFeature = Unsafe.As<TFeature?, IResponseCookiesFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpRequestTrailersFeature))
{
_currentIHttpRequestTrailersFeature = Unsafe.As<TFeature?, IHttpRequestTrailersFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpResponseTrailersFeature))
{
_currentIHttpResponseTrailersFeature = Unsafe.As<TFeature?, IHttpResponseTrailersFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(ITlsConnectionFeature))
{
_currentITlsConnectionFeature = Unsafe.As<TFeature?, ITlsConnectionFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpUpgradeFeature))
{
_currentIHttpUpgradeFeature = Unsafe.As<TFeature?, IHttpUpgradeFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpWebSocketFeature))
{
_currentIHttpWebSocketFeature = Unsafe.As<TFeature?, IHttpWebSocketFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IBadRequestExceptionFeature))
{
_currentIBadRequestExceptionFeature = Unsafe.As<TFeature?, IBadRequestExceptionFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttp2StreamIdFeature))
{
_currentIHttp2StreamIdFeature = Unsafe.As<TFeature?, IHttp2StreamIdFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpRequestLifetimeFeature))
{
_currentIHttpRequestLifetimeFeature = Unsafe.As<TFeature?, IHttpRequestLifetimeFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpMaxRequestBodySizeFeature))
{
_currentIHttpMaxRequestBodySizeFeature = Unsafe.As<TFeature?, IHttpMaxRequestBodySizeFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpMinRequestBodyDataRateFeature))
{
_currentIHttpMinRequestBodyDataRateFeature = Unsafe.As<TFeature?, IHttpMinRequestBodyDataRateFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpMinResponseDataRateFeature))
{
_currentIHttpMinResponseDataRateFeature = Unsafe.As<TFeature?, IHttpMinResponseDataRateFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpBodyControlFeature))
{
_currentIHttpBodyControlFeature = Unsafe.As<TFeature?, IHttpBodyControlFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpRequestBodyDetectionFeature))
{
_currentIHttpRequestBodyDetectionFeature = Unsafe.As<TFeature?, IHttpRequestBodyDetectionFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IHttpResetFeature))
{
_currentIHttpResetFeature = Unsafe.As<TFeature?, IHttpResetFeature?>(ref feature);
}
else if (typeof(TFeature) == typeof(IPersistentStateFeature))
{
_currentIPersistentStateFeature = Unsafe.As<TFeature?, IPersistentStateFeature?>(ref feature);
}
else
{
ExtraFeatureSet(typeof(TFeature), feature);
}
}
private IEnumerable<KeyValuePair<Type, object>> FastEnumerable()
{
if (_currentIHttpRequestFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpRequestFeature), _currentIHttpRequestFeature);
}
if (_currentIHttpResponseFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpResponseFeature), _currentIHttpResponseFeature);
}
if (_currentIHttpResponseBodyFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpResponseBodyFeature), _currentIHttpResponseBodyFeature);
}
if (_currentIRouteValuesFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IRouteValuesFeature), _currentIRouteValuesFeature);
}
if (_currentIEndpointFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IEndpointFeature), _currentIEndpointFeature);
}
if (_currentIServiceProvidersFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IServiceProvidersFeature), _currentIServiceProvidersFeature);
}
if (_currentIHttpActivityFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpActivityFeature), _currentIHttpActivityFeature);
}
if (_currentIItemsFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IItemsFeature), _currentIItemsFeature);
}
if (_currentIQueryFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IQueryFeature), _currentIQueryFeature);
}
if (_currentIRequestBodyPipeFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IRequestBodyPipeFeature), _currentIRequestBodyPipeFeature);
}
if (_currentIFormFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IFormFeature), _currentIFormFeature);
}
if (_currentIHttpAuthenticationFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpAuthenticationFeature), _currentIHttpAuthenticationFeature);
}
if (_currentIHttpRequestIdentifierFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpRequestIdentifierFeature), _currentIHttpRequestIdentifierFeature);
}
if (_currentIHttpConnectionFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpConnectionFeature), _currentIHttpConnectionFeature);
}
if (_currentISessionFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(ISessionFeature), _currentISessionFeature);
}
if (_currentIResponseCookiesFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IResponseCookiesFeature), _currentIResponseCookiesFeature);
}
if (_currentIHttpRequestTrailersFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpRequestTrailersFeature), _currentIHttpRequestTrailersFeature);
}
if (_currentIHttpResponseTrailersFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpResponseTrailersFeature), _currentIHttpResponseTrailersFeature);
}
if (_currentITlsConnectionFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(ITlsConnectionFeature), _currentITlsConnectionFeature);
}
if (_currentIHttpUpgradeFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpUpgradeFeature), _currentIHttpUpgradeFeature);
}
if (_currentIHttpWebSocketFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpWebSocketFeature), _currentIHttpWebSocketFeature);
}
if (_currentIBadRequestExceptionFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IBadRequestExceptionFeature), _currentIBadRequestExceptionFeature);
}
if (_currentIHttp2StreamIdFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttp2StreamIdFeature), _currentIHttp2StreamIdFeature);
}
if (_currentIHttpRequestLifetimeFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpRequestLifetimeFeature), _currentIHttpRequestLifetimeFeature);
}
if (_currentIHttpMaxRequestBodySizeFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpMaxRequestBodySizeFeature), _currentIHttpMaxRequestBodySizeFeature);
}
if (_currentIHttpMinRequestBodyDataRateFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpMinRequestBodyDataRateFeature), _currentIHttpMinRequestBodyDataRateFeature);
}
if (_currentIHttpMinResponseDataRateFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpMinResponseDataRateFeature), _currentIHttpMinResponseDataRateFeature);
}
if (_currentIHttpBodyControlFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpBodyControlFeature), _currentIHttpBodyControlFeature);
}
if (_currentIHttpRequestBodyDetectionFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpRequestBodyDetectionFeature), _currentIHttpRequestBodyDetectionFeature);
}
if (_currentIHttpResetFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IHttpResetFeature), _currentIHttpResetFeature);
}
if (_currentIPersistentStateFeature != null)
{
yield return new KeyValuePair<Type, object>(typeof(IPersistentStateFeature), _currentIPersistentStateFeature);
}
if (MaybeExtra != null)
{
foreach (var item in MaybeExtra)
{
yield return item;
}
}
}
IEnumerator<KeyValuePair<Type, object>> IEnumerable<KeyValuePair<Type, object>>.GetEnumerator() => FastEnumerable().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => FastEnumerable().GetEnumerator();
}
}
| |
//---------------------------------------------------------------------
// <copyright file="PropagatorResult.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Data.Metadata.Edm;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics;
using System.Data.Common.Utils;
using System.Data.Objects;
using System.Collections;
using System.Data.Common;
using System.Text;
using System.Linq;
namespace System.Data.Mapping.Update.Internal
{
/// <summary>
/// requires: for structural types, member values are ordinally aligned with the members of the
/// structural type.
///
/// Stores a 'row' (or element within a row) being propagated through the update pipeline, including
/// markup information and metadata. Internally, we maintain several different classes so that we only
/// store the necessary state.
///
/// - StructuralValue (complex types, entities, and association end keys): type and member values,
/// one version for modified structural values and one version for unmodified structural values
/// (a structural type is modified if its _type_ is changed, not its values
/// - SimpleValue (scalar value): flags to describe the state of the value (is it a concurrency value,
/// is it modified) and the value itself
/// - ServerGenSimpleValue: adds back-prop information to the above (record and position in record
/// so that we can set the value on back-prop)
/// - KeyValue: the originating IEntityStateEntry also travels with keys. These entries are used purely for
/// error reporting. We send them with keys so that every row containing an entity (which must also
/// contain the key) has enough context to recover the state entry.
/// </summary>
/// <remarks>
/// Not all memebers of a PropagatorResult are available for all specializations. For instance, GetSimpleValue
/// is available only on simple types
/// </remarks>
internal abstract class PropagatorResult
{
#region Constructors
// private constructor: only nested classes may derive from propagator result
private PropagatorResult()
{
}
#endregion
#region Fields
internal const int NullIdentifier = -1;
internal const int NullOrdinal = -1;
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether this result is null.
/// </summary>
internal abstract bool IsNull { get; }
/// <summary>
/// Gets a value indicating whether this is a simple (scalar) or complex
/// structural) result.
/// </summary>
internal abstract bool IsSimple { get; }
/// <summary>
/// Gets flags describing the behaviors for this element.
/// </summary>
internal virtual PropagatorFlags PropagatorFlags
{
get { return PropagatorFlags.NoFlags; }
}
/// <summary>
/// Gets all state entries from which this result originated. Only set for key
/// values (to ensure every row knows all of its source entries)
/// </summary>
internal virtual IEntityStateEntry StateEntry
{
get { return null; }
}
/// <summary>
/// Gets record from which this result originated. Only set for server generated
/// results (where the record needs to be synchronized).
/// </summary>
internal virtual CurrentValueRecord Record
{
get { return null; }
}
/// <summary>
/// Gets structural type for non simple results. Only available for entity and complex type
/// results.
/// </summary>
internal virtual StructuralType StructuralType
{
get { return null; }
}
/// <summary>
/// Gets the ordinal within the originating record for this result. Only set
/// for server generated results (otherwise, returns -1)
/// </summary>
internal virtual int RecordOrdinal
{
get { return NullOrdinal; }
}
/// <summary>
/// Gets the identifier for this entry if it is a server-gen key value (otherwise
/// returns -1)
/// </summary>
internal virtual int Identifier
{
get { return NullIdentifier; }
}
/// <summary>
/// Where a single result corresponds to multiple key inputs, they are chained using this linked list.
/// By convention, the first entry in the chain is the 'dominant' entry (the principal key).
/// </summary>
internal virtual PropagatorResult Next
{
get { return null; }
}
#endregion
#region Methods
/// <summary>
/// Returns simple value stored in this result. Only valid when <see cref="IsSimple" /> is
/// true.
/// </summary>
///
/// <returns>Concrete value.</returns>
internal virtual object GetSimpleValue()
{
throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "PropagatorResult.GetSimpleValue");
}
/// <summary>
/// Returns nested value. Only valid when <see cref="IsSimple" /> is false.
/// </summary>
/// <param name="ordinal">Ordinal of value to return (ordinal based on type definition)</param>
/// <returns>Nested result.</returns>
internal virtual PropagatorResult GetMemberValue(int ordinal)
{
throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "PropagatorResult.GetMemberValue");
}
/// <summary>
/// Returns nested value. Only valid when <see cref="IsSimple" /> is false.
/// </summary>
/// <param name="member">Member for which to return a value</param>
/// <returns>Nested result.</returns>
internal PropagatorResult GetMemberValue(EdmMember member)
{
int ordinal = TypeHelpers.GetAllStructuralMembers(this.StructuralType).IndexOf(member);
return GetMemberValue(ordinal);
}
/// <summary>
/// Returns all structural values. Only valid when <see cref="IsSimple" /> is false.
/// </summary>
/// <returns>Values of all structural members.</returns>
internal virtual PropagatorResult[] GetMemberValues()
{
throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "PropagatorResult.GetMembersValues");
}
/// <summary>
/// Produces a replica of this propagator result with different flags.
/// </summary>
/// <param name="flags">New flags for the result.</param>
/// <returns>This result with the given flags.</returns>
internal abstract PropagatorResult ReplicateResultWithNewFlags(PropagatorFlags flags);
/// <summary>
/// Copies this result replacing its value. Used for cast. Requires a simple result.
/// </summary>
/// <param name="value">New value for result</param>
/// <returns>Copy of this result with new value.</returns>
internal virtual PropagatorResult ReplicateResultWithNewValue(object value)
{
throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "PropagatorResult.ReplicateResultWithNewValue");
}
/// <summary>
/// Replaces parts of the structured result.
/// </summary>
/// <param name="map">A replace-with map applied to simple (i.e. not structural) values.</param>
/// <returns>Result with requested elements replaced.</returns>
internal abstract PropagatorResult Replace(Func<PropagatorResult, PropagatorResult> map);
/// <summary>
/// A result is merged with another when it is merged as part of an equi-join.
/// </summary>
/// <remarks>
/// In theory, this should only ever be called on two keys (since we only join on
/// keys). We throw in the base implementation, and override in KeyResult. By convention
/// the principal key is always the first result in the chain (in case of an RIC). In
/// addition, entity entries always appear before relationship entries.
/// </remarks>
/// <param name="other">Result to merge with.</param>
/// <returns>Merged result.</returns>
internal virtual PropagatorResult Merge(KeyManager keyManager, PropagatorResult other)
{
throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "PropagatorResult.Merge");
}
#if DEBUG
public override string ToString()
{
StringBuilder builder = new StringBuilder();
if (PropagatorFlags.NoFlags != PropagatorFlags)
{
builder.Append(PropagatorFlags.ToString()).Append(":");
}
if (NullIdentifier != Identifier)
{
builder.Append("id").Append(Identifier.ToString(CultureInfo.InvariantCulture)).Append(":");
}
if (NullOrdinal != RecordOrdinal)
{
builder.Append("ord").Append(RecordOrdinal.ToString(CultureInfo.InvariantCulture)).Append(":");
}
if (IsSimple)
{
builder.AppendFormat(CultureInfo.InvariantCulture, "{0}", GetSimpleValue());
}
else
{
if (!Helper.IsRowType(StructuralType))
{
builder.Append(StructuralType.Name).Append(":");
}
builder.Append("{");
bool first = true;
foreach (KeyValuePair<EdmMember, PropagatorResult> memberValue in Helper.PairEnumerations(
TypeHelpers.GetAllStructuralMembers(this.StructuralType), GetMemberValues()))
{
if (first) { first = false; }
else { builder.Append(", "); }
builder.Append(memberValue.Key.Name).Append("=").Append(memberValue.Value.ToString());
}
builder.Append("}");
}
return builder.ToString();
}
#endif
#endregion
#region Nested types and factory methods
internal static PropagatorResult CreateSimpleValue(PropagatorFlags flags, object value)
{
return new SimpleValue(flags, value);
}
private class SimpleValue : PropagatorResult
{
internal SimpleValue(PropagatorFlags flags, object value)
{
m_flags = flags;
m_value = value ?? DBNull.Value;
}
private readonly PropagatorFlags m_flags;
protected readonly object m_value;
internal override PropagatorFlags PropagatorFlags
{
get { return m_flags; }
}
internal override bool IsSimple
{
get { return true; }
}
internal override bool IsNull
{
get
{
// The result is null if it is not associated with an identifier and
// the value provided by the user is also null.
return NullIdentifier == this.Identifier && DBNull.Value == m_value;
}
}
internal override object GetSimpleValue()
{
return m_value;
}
internal override PropagatorResult ReplicateResultWithNewFlags(PropagatorFlags flags)
{
return new SimpleValue(flags, m_value);
}
internal override PropagatorResult ReplicateResultWithNewValue(object value)
{
return new SimpleValue(PropagatorFlags, value);
}
internal override PropagatorResult Replace(Func<PropagatorResult, PropagatorResult> map)
{
return map(this);
}
}
internal static PropagatorResult CreateServerGenSimpleValue(PropagatorFlags flags, object value, CurrentValueRecord record, int recordOrdinal)
{
return new ServerGenSimpleValue(flags, value, record, recordOrdinal);
}
private class ServerGenSimpleValue : SimpleValue
{
internal ServerGenSimpleValue(PropagatorFlags flags, object value, CurrentValueRecord record, int recordOrdinal)
: base(flags, value)
{
Debug.Assert(null != record);
m_record = record;
m_recordOrdinal = recordOrdinal;
}
private readonly CurrentValueRecord m_record;
private readonly int m_recordOrdinal;
internal override CurrentValueRecord Record
{
get { return m_record; }
}
internal override int RecordOrdinal
{
get { return m_recordOrdinal; }
}
internal override PropagatorResult ReplicateResultWithNewFlags(PropagatorFlags flags)
{
return new ServerGenSimpleValue(flags, m_value, Record, RecordOrdinal);
}
internal override PropagatorResult ReplicateResultWithNewValue(object value)
{
return new ServerGenSimpleValue(PropagatorFlags, value, Record, RecordOrdinal);
}
}
internal static PropagatorResult CreateKeyValue(PropagatorFlags flags, object value, IEntityStateEntry stateEntry, int identifier)
{
return new KeyValue(flags, value, stateEntry, identifier, null);
}
private class KeyValue : SimpleValue
{
internal KeyValue(PropagatorFlags flags, object value, IEntityStateEntry stateEntry, int identifier, KeyValue next)
: base(flags, value)
{
Debug.Assert(null != stateEntry);
m_stateEntry = stateEntry;
m_identifier = identifier;
m_next = next;
}
private readonly IEntityStateEntry m_stateEntry;
private readonly int m_identifier;
protected readonly KeyValue m_next;
internal override IEntityStateEntry StateEntry
{
get { return m_stateEntry; }
}
internal override int Identifier
{
get { return m_identifier; }
}
internal override CurrentValueRecord Record
{
get
{
// delegate to the state entry, which also has the record
return m_stateEntry.CurrentValues;
}
}
internal override PropagatorResult Next
{
get
{
return m_next;
}
}
internal override PropagatorResult ReplicateResultWithNewFlags(PropagatorFlags flags)
{
return new KeyValue(flags, m_value, StateEntry, Identifier, m_next);
}
internal override PropagatorResult ReplicateResultWithNewValue(object value)
{
return new KeyValue(PropagatorFlags, value, StateEntry, Identifier, m_next);
}
internal virtual KeyValue ReplicateResultWithNewNext(KeyValue next)
{
if (m_next != null)
{
// push the next value to the end of the linked list
next = m_next.ReplicateResultWithNewNext(next);
}
return new KeyValue(this.PropagatorFlags, m_value, m_stateEntry, m_identifier, next);
}
internal override PropagatorResult Merge(KeyManager keyManager, PropagatorResult other)
{
KeyValue otherKey = other as KeyValue;
if (null == otherKey)
{
EntityUtil.InternalError(EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "KeyValue.Merge");
}
// Determine which key (this or otherKey) is first in the chain. Principal keys take
// precedence over dependent keys and entities take precedence over relationships.
if (this.Identifier != otherKey.Identifier)
{
// Find principal (if any)
if (keyManager.GetPrincipals(otherKey.Identifier).Contains(this.Identifier))
{
return this.ReplicateResultWithNewNext(otherKey);
}
else
{
return otherKey.ReplicateResultWithNewNext(this);
}
}
else
{
// Entity takes precedence of relationship
if (null == m_stateEntry || m_stateEntry.IsRelationship)
{
return otherKey.ReplicateResultWithNewNext(this);
}
else
{
return this.ReplicateResultWithNewNext(otherKey);
}
}
}
}
internal static PropagatorResult CreateServerGenKeyValue(PropagatorFlags flags, object value, IEntityStateEntry stateEntry, int identifier, int recordOrdinal)
{
return new ServerGenKeyValue(flags, value, stateEntry, identifier, recordOrdinal, null);
}
private class ServerGenKeyValue : KeyValue
{
internal ServerGenKeyValue(PropagatorFlags flags, object value, IEntityStateEntry stateEntry, int identifier, int recordOrdinal, KeyValue next)
: base(flags, value, stateEntry, identifier, next)
{
m_recordOrdinal = recordOrdinal;
}
private readonly int m_recordOrdinal;
internal override int RecordOrdinal
{
get { return m_recordOrdinal; }
}
internal override PropagatorResult ReplicateResultWithNewFlags(PropagatorFlags flags)
{
return new ServerGenKeyValue(flags, m_value, this.StateEntry, this.Identifier, this.RecordOrdinal, m_next);
}
internal override PropagatorResult ReplicateResultWithNewValue(object value)
{
return new ServerGenKeyValue(this.PropagatorFlags, value, this.StateEntry, this.Identifier, this.RecordOrdinal, m_next);
}
internal override KeyValue ReplicateResultWithNewNext(KeyValue next)
{
if (m_next != null)
{
// push the next value to the end of the linked list
next = m_next.ReplicateResultWithNewNext(next);
}
return new ServerGenKeyValue(PropagatorFlags, m_value, StateEntry, Identifier, RecordOrdinal, next);
}
}
internal static PropagatorResult CreateStructuralValue(PropagatorResult[] values, StructuralType structuralType, bool isModified)
{
if (isModified)
{
return new StructuralValue(values, structuralType);
}
else
{
return new UnmodifiedStructuralValue(values, structuralType);
}
}
private class StructuralValue : PropagatorResult
{
internal StructuralValue(PropagatorResult[] values, StructuralType structuralType)
{
Debug.Assert(null != structuralType);
Debug.Assert(null != values);
Debug.Assert(values.Length == TypeHelpers.GetAllStructuralMembers(structuralType).Count);
m_values = values;
m_structuralType = structuralType;
}
private readonly PropagatorResult[] m_values;
protected readonly StructuralType m_structuralType;
internal override bool IsSimple
{
get { return false; }
}
internal override bool IsNull
{
get { return false; }
}
internal override StructuralType StructuralType
{
get { return m_structuralType; }
}
internal override PropagatorResult GetMemberValue(int ordinal)
{
return m_values[ordinal];
}
internal override PropagatorResult[] GetMemberValues()
{
return m_values;
}
internal override PropagatorResult ReplicateResultWithNewFlags(PropagatorFlags flags)
{
throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "StructuralValue.ReplicateResultWithNewFlags");
}
internal override PropagatorResult Replace(Func<PropagatorResult, PropagatorResult> map)
{
PropagatorResult[] newValues = ReplaceValues(map);
return null == newValues ? this : new StructuralValue(newValues, m_structuralType);
}
protected PropagatorResult[] ReplaceValues(Func<PropagatorResult, PropagatorResult> map)
{
PropagatorResult[] newValues = new PropagatorResult[m_values.Length];
bool hasChange = false;
for (int i = 0; i < newValues.Length; i++)
{
PropagatorResult newValue = m_values[i].Replace(map);
if (!object.ReferenceEquals(newValue, m_values[i]))
{
hasChange = true;
}
newValues[i] = newValue;
}
return hasChange ? newValues : null;
}
}
private class UnmodifiedStructuralValue : StructuralValue
{
internal UnmodifiedStructuralValue(PropagatorResult[] values, StructuralType structuralType)
: base(values, structuralType)
{
}
internal override PropagatorFlags PropagatorFlags
{
get
{
return PropagatorFlags.Preserve;
}
}
internal override PropagatorResult Replace(Func<PropagatorResult, PropagatorResult> map)
{
PropagatorResult[] newValues = ReplaceValues(map);
return null == newValues ? this : new UnmodifiedStructuralValue(newValues, m_structuralType);
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml.Schema;
namespace System.Xml.Xsl
{
/// <summary>
/// XmlQueryType contains static type information that describes the structure and possible values of dynamic
/// instances of the Xml data model.
///
/// Every XmlQueryType is composed of a Prime type and a cardinality. The Prime type itself may be a union
/// between several item types. The XmlQueryType IList<XmlQueryType/> implementation allows callers
/// to enumerate the item types. Other properties expose other information about the type.
/// </summary>
internal abstract class XmlQueryType : ListBase<XmlQueryType>
{
private static readonly BitMatrix s_typeCodeDerivation;
private int _hashCode;
//-----------------------------------------------
// Static Constructor
//-----------------------------------------------
static XmlQueryType()
{
s_typeCodeDerivation = new BitMatrix(s_baseTypeCodes.Length);
// Build derivation matrix
for (int i = 0; i < s_baseTypeCodes.Length; i++)
{
int nextAncestor = i;
while (true)
{
s_typeCodeDerivation[i, nextAncestor] = true;
if ((int)s_baseTypeCodes[nextAncestor] == nextAncestor)
break;
nextAncestor = (int)s_baseTypeCodes[nextAncestor];
}
}
}
//-----------------------------------------------
// ItemType, OccurrenceIndicator Properties
//-----------------------------------------------
/// <summary>
/// Static data type code. The dynamic type is guaranteed to be this type or a subtype of this code.
/// This type code includes support for XQuery types that are not part of Xsd, such as Item,
/// Node, AnyAtomicType, and Comment.
/// </summary>
public abstract XmlTypeCode TypeCode { get; }
/// <summary>
/// Set of allowed names for element, document{element}, attribute and PI
/// Returns XmlQualifiedName.Wildcard for all other types
/// </summary>
public abstract XmlQualifiedNameTest NameTest { get; }
/// <summary>
/// Static Xsd schema type. The dynamic type is guaranteed to be this type or a subtype of this type.
/// SchemaType will follow these rules:
/// 1. If TypeCode is an atomic type code, then SchemaType will be the corresponding non-null simple type
/// 2. If TypeCode is Element or Attribute, then SchemaType will be the non-null content type
/// 3. If TypeCode is Item, Node, Comment, PI, Text, Document, Namespace, None, then SchemaType will be AnyType
/// </summary>
public abstract XmlSchemaType SchemaType { get; }
/// <summary>
/// Permits the element or document{element} node to have the nilled property.
/// Returns false for all other types
/// </summary>
public abstract bool IsNillable { get; }
/// <summary>
/// This property is always XmlNodeKindFlags.None unless TypeCode = XmlTypeCode.Node, in which case this
/// property lists all node kinds that instances of this type may be.
/// </summary>
public abstract XmlNodeKindFlags NodeKinds { get; }
/// <summary>
/// If IsStrict is true, then the dynamic type is guaranteed to be the exact same as the static type, and
/// will therefore never be a subtype of the static type.
/// </summary>
public abstract bool IsStrict { get; }
/// <summary>
/// This property specifies the possible cardinalities that instances of this type may have.
/// </summary>
public abstract XmlQueryCardinality Cardinality { get; }
/// <summary>
/// This property returns this type's Prime type, which is always cardinality One.
/// </summary>
public abstract XmlQueryType Prime { get; }
/// <summary>
/// True if dynamic data type of all items in this sequence is guaranteed to be not a subtype of Rtf.
/// </summary>
public abstract bool IsNotRtf { get; }
/// <summary>
/// True if items in the sequence are guaranteed to be nodes in document order with no duplicates.
/// </summary>
public abstract bool IsDod { get; }
/// <summary>
/// The XmlValueConverter maps each XmlQueryType to various Clr types which are capable of representing it.
/// </summary>
public abstract XmlValueConverter ClrMapping { get; }
//-----------------------------------------------
// Type Operations
//-----------------------------------------------
/// <summary>
/// Returns true if every possible dynamic instance of this type is also an instance of "baseType".
/// </summary>
public bool IsSubtypeOf(XmlQueryType baseType)
{
XmlQueryType thisPrime, basePrime;
// Check cardinality sub-typing rules
if (!(Cardinality <= baseType.Cardinality) || (!IsDod && baseType.IsDod))
return false;
if (!IsDod && baseType.IsDod)
return false;
// Check early for common case that two types are the same object
thisPrime = Prime;
basePrime = baseType.Prime;
if ((object)thisPrime == (object)basePrime)
return true;
// Check early for common case that two prime types are item types
if (thisPrime.Count == 1 && basePrime.Count == 1)
return thisPrime.IsSubtypeOfItemType(basePrime);
// Check that each item type in this type is a subtype of some item type in "baseType"
foreach (XmlQueryType thisItem in thisPrime)
{
bool match = false;
foreach (XmlQueryType baseItem in basePrime)
{
if (thisItem.IsSubtypeOfItemType(baseItem))
{
match = true;
break;
}
}
if (match == false)
return false;
}
return true;
}
/// <summary>
/// Returns true if a dynamic instance (type None never has an instance) of this type can never be a subtype of "baseType".
/// </summary>
public bool NeverSubtypeOf(XmlQueryType baseType)
{
// Check cardinalities
if (Cardinality.NeverSubset(baseType.Cardinality))
return true;
// If both this type and "other" type might be empty, it doesn't matter what the prime types are
if (MaybeEmpty && baseType.MaybeEmpty)
return false;
// None is subtype of every other type
if (Count == 0)
return false;
// Check item types
foreach (XmlQueryType typThis in this)
{
foreach (XmlQueryType typThat in baseType)
{
if (typThis.HasIntersectionItemType(typThat))
return false;
}
}
return true;
}
/// <summary>
/// Strongly-typed Equals that returns true if this type and "that" type are equivalent.
/// </summary>
public bool Equals(XmlQueryType that)
{
if (that == null)
return false;
// Check cardinality and DocOrderDistinct property
if (Cardinality != that.Cardinality || IsDod != that.IsDod)
return false;
// Check early for common case that two types are the same object
XmlQueryType thisPrime = Prime;
XmlQueryType thatPrime = that.Prime;
if ((object)thisPrime == (object)thatPrime)
return true;
// Check that count of item types is equal
if (thisPrime.Count != thatPrime.Count)
return false;
// Check early for common case that two prime types are item types
if (thisPrime.Count == 1)
{
return (thisPrime.TypeCode == thatPrime.TypeCode &&
thisPrime.NameTest == thatPrime.NameTest &&
thisPrime.SchemaType == thatPrime.SchemaType &&
thisPrime.IsStrict == thatPrime.IsStrict &&
thisPrime.IsNotRtf == thatPrime.IsNotRtf);
}
// Check that each item type in this type is equal to some item type in "baseType"
// (string | int) should be the same type as (int | string)
foreach (XmlQueryType thisItem in this)
{
bool match = false;
foreach (XmlQueryType thatItem in that)
{
if (thisItem.TypeCode == thatItem.TypeCode &&
thisItem.NameTest == thatItem.NameTest &&
thisItem.SchemaType == thatItem.SchemaType &&
thisItem.IsStrict == thatItem.IsStrict &&
thisItem.IsNotRtf == thatItem.IsNotRtf)
{
// Found match so proceed to next type
match = true;
break;
}
}
if (match == false)
return false;
}
return true;
}
/// <summary>
/// Overload == operator to call Equals rather than do reference equality.
/// </summary>
public static bool operator ==(XmlQueryType left, XmlQueryType right)
{
if ((object)left == null)
return ((object)right == null);
return left.Equals(right);
}
/// <summary>
/// Overload != operator to call Equals rather than do reference inequality.
/// </summary>
public static bool operator !=(XmlQueryType left, XmlQueryType right)
{
if ((object)left == null)
return ((object)right != null);
return !left.Equals(right);
}
//-----------------------------------------------
// Convenience Properties
//-----------------------------------------------
/// <summary>
/// True if dynamic cardinality of this sequence is guaranteed to be 0.
/// </summary>
public bool IsEmpty
{
get { return Cardinality <= XmlQueryCardinality.Zero; }
}
/// <summary>
/// True if dynamic cardinality of this sequence is guaranteed to be 1.
/// </summary>
public bool IsSingleton
{
get { return Cardinality <= XmlQueryCardinality.One; }
}
/// <summary>
/// True if dynamic cardinality of this sequence might be 0.
/// </summary>
public bool MaybeEmpty
{
get { return XmlQueryCardinality.Zero <= Cardinality; }
}
/// <summary>
/// True if dynamic cardinality of this sequence might be >1.
/// </summary>
public bool MaybeMany
{
get { return XmlQueryCardinality.More <= Cardinality; }
}
/// <summary>
/// True if dynamic data type of all items in this sequence is guaranteed to be a subtype of Node.
/// Equivalent to calling IsSubtypeOf(TypeFactory.NodeS).
/// </summary>
public bool IsNode
{
get { return (s_typeCodeToFlags[(int)TypeCode] & TypeFlags.IsNode) != 0; }
}
/// <summary>
/// True if dynamic data type of all items in this sequence is guaranteed to be a subtype of AnyAtomicType.
/// Equivalent to calling IsSubtypeOf(TypeFactory.AnyAtomicTypeS).
/// </summary>
public bool IsAtomicValue
{
get { return (s_typeCodeToFlags[(int)TypeCode] & TypeFlags.IsAtomicValue) != 0; }
}
/// <summary>
/// True if dynamic data type of all items in this sequence is guaranteed to be a subtype of Decimal, Double, or Float.
/// Equivalent to calling IsSubtypeOf(TypeFactory.NumericS).
/// </summary>
public bool IsNumeric
{
get { return (s_typeCodeToFlags[(int)TypeCode] & TypeFlags.IsNumeric) != 0; }
}
//-----------------------------------------------
// System.Object implementation
//-----------------------------------------------
/// <summary>
/// True if "obj" is an XmlQueryType, and this type is the exact same static type.
/// </summary>
public override bool Equals(object obj)
{
XmlQueryType that = obj as XmlQueryType;
if (that == null)
return false;
return Equals(that);
}
/// <summary>
/// Return hash code of this instance.
/// </summary>
public override int GetHashCode()
{
if (_hashCode == 0)
{
int hash;
XmlSchemaType schemaType;
hash = (int)TypeCode;
schemaType = SchemaType;
unchecked
{
if (schemaType != null)
hash += (hash << 7) ^ schemaType.GetHashCode();
hash += (hash << 7) ^ (int)NodeKinds;
hash += (hash << 7) ^ Cardinality.GetHashCode();
hash += (hash << 7) ^ (IsStrict ? 1 : 0);
// Mix hash code a bit more
hash -= hash >> 17;
hash -= hash >> 11;
hash -= hash >> 5;
}
// Save hashcode. Don't save 0, so that it won't ever be recomputed.
_hashCode = (hash == 0) ? 1 : hash;
}
return _hashCode;
}
/// <summary>
/// Return a user-friendly string representation of the XmlQueryType.
/// </summary>
public override string ToString()
{
return ToString("G");
}
/// <summary>
/// Return a string representation of the XmlQueryType using the specified format. The following formats are
/// supported:
///
/// "G" (General): This is the default mode, and is used if no other format is recognized. This format is
/// easier to read than the canonical format, since it excludes redundant information.
/// (e.g. element instead of element(*, xs:anyType))
///
/// "X" (XQuery): Return the canonical XQuery representation, which excludes Qil specific information and
/// includes extra, redundant information, such as fully specified types.
/// (e.g. element(*, xs:anyType) instead of element)
///
/// "S" (Serialized): This format is used to serialize parts of the type which can be serialized easily, in
/// a format that is easy to parse. Only the cardinality, type code, and strictness flag
/// are serialized. User-defined type information and element/attribute content types
/// are lost.
/// (e.g. One;Attribute|String|Int;true)
///
/// </summary>
public string ToString(string format)
{
string[] sa;
StringBuilder sb;
bool isXQ;
if (format == "S")
{
sb = new StringBuilder();
sb.Append(Cardinality.ToString(format));
sb.Append(';');
for (int i = 0; i < Count; i++)
{
if (i != 0)
sb.Append("|");
sb.Append(this[i].TypeCode.ToString());
}
sb.Append(';');
sb.Append(IsStrict);
return sb.ToString();
}
isXQ = (format == "X");
if (Cardinality == XmlQueryCardinality.None)
{
return "none";
}
else if (Cardinality == XmlQueryCardinality.Zero)
{
return "empty";
}
sb = new StringBuilder();
switch (Count)
{
case 0:
// This assert depends on the way we are going to represent None
// Debug.Assert(false);
sb.Append("none");
break;
case 1:
sb.Append(this[0].ItemTypeToString(isXQ));
break;
default:
sa = new string[Count];
for (int i = 0; i < Count; i++)
sa[i] = this[i].ItemTypeToString(isXQ);
Array.Sort(sa);
sb = new StringBuilder();
sb.Append('(');
sb.Append(sa[0]);
for (int i = 1; i < sa.Length; i++)
{
sb.Append(" | ");
sb.Append(sa[i]);
}
sb.Append(')');
break;
}
sb.Append(Cardinality.ToString());
if (!isXQ && IsDod)
sb.Append('#');
return sb.ToString();
}
//-----------------------------------------------
// Serialization
//-----------------------------------------------
/// <summary>
/// Serialize the object to BinaryWriter.
/// </summary>
public abstract void GetObjectData(BinaryWriter writer);
//-----------------------------------------------
// Helpers
//-----------------------------------------------
/// <summary>
/// Returns true if this item type is a subtype of another item type.
/// </summary>
private bool IsSubtypeOfItemType(XmlQueryType baseType)
{
Debug.Assert(Count == 1 && IsSingleton, "This method should only be called for item types.");
Debug.Assert(baseType.Count == 1 && baseType.IsSingleton, "This method should only be called for item types.");
Debug.Assert(!IsDod && !baseType.IsDod, "Singleton types may not have DocOrderDistinct property");
XmlSchemaType baseSchemaType = baseType.SchemaType;
if (TypeCode != baseType.TypeCode)
{
// If "baseType" is strict, then IsSubtypeOf must be false
if (baseType.IsStrict)
return false;
// If type codes are not the same, then IsSubtypeOf can return true *only* if "baseType" is a built-in type
XmlSchemaType builtInType = XmlSchemaType.GetBuiltInSimpleType(baseType.TypeCode);
if (builtInType != null && baseSchemaType != builtInType)
return false;
// Now check whether TypeCode is derived from baseType.TypeCode
return s_typeCodeDerivation[TypeCode, baseType.TypeCode];
}
else if (baseType.IsStrict)
{
// only atomic values can be strict
Debug.Assert(IsAtomicValue && baseType.IsAtomicValue);
// If schema types are not the same, then IsSubtype is false if "baseType" is strict
return IsStrict && SchemaType == baseSchemaType;
}
else
{
// Otherwise, check derivation tree
return (IsNotRtf || !baseType.IsNotRtf) && NameTest.IsSubsetOf(baseType.NameTest) &&
(baseSchemaType == XmlSchemaComplexType.AnyType || XmlSchemaType.IsDerivedFrom(SchemaType, baseSchemaType, /* except:*/XmlSchemaDerivationMethod.Empty)) &&
(!IsNillable || baseType.IsNillable);
}
}
/// <summary>
/// Returns true if the intersection between this item type and "other" item type is not empty.
/// </summary>
private bool HasIntersectionItemType(XmlQueryType other)
{
Debug.Assert(this.Count == 1 && this.IsSingleton, "this should be an item");
Debug.Assert(other.Count == 1 && other.IsSingleton, "other should be an item");
if (this.TypeCode == other.TypeCode && (this.NodeKinds & (XmlNodeKindFlags.Document | XmlNodeKindFlags.Element | XmlNodeKindFlags.Attribute)) != 0)
{
if (this.TypeCode == XmlTypeCode.Node)
return true;
// Intersect name tests
if (!this.NameTest.HasIntersection(other.NameTest))
return false;
if (!XmlSchemaType.IsDerivedFrom(this.SchemaType, other.SchemaType, /* except:*/XmlSchemaDerivationMethod.Empty) &&
!XmlSchemaType.IsDerivedFrom(other.SchemaType, this.SchemaType, /* except:*/XmlSchemaDerivationMethod.Empty))
{
return false;
}
return true;
}
else if (this.IsSubtypeOf(other) || other.IsSubtypeOf(this))
{
return true;
}
return false;
}
/// <summary>
/// Return the string representation of an item type (cannot be a union or a sequence).
/// </summary>
private string ItemTypeToString(bool isXQ)
{
string s;
Debug.Assert(Count == 1, "Do not pass a Union type to this method.");
Debug.Assert(IsSingleton, "Do not pass a Sequence type to this method.");
if (IsNode)
{
// Map TypeCode to string
s = s_typeNames[(int)TypeCode];
switch (TypeCode)
{
case XmlTypeCode.Document:
if (!isXQ)
goto case XmlTypeCode.Element;
s += "{(element" + NameAndType(true) + "?&text?&comment?&processing-instruction?)*}";
break;
case XmlTypeCode.Element:
case XmlTypeCode.Attribute:
s += NameAndType(isXQ);
break;
}
}
else if (SchemaType != XmlSchemaComplexType.AnyType)
{
// Get QualifiedName from SchemaType
if (SchemaType.QualifiedName.IsEmpty)
s = "<:" + s_typeNames[(int)TypeCode];
else
s = QNameToString(SchemaType.QualifiedName);
}
else
{
// Map TypeCode to string
s = s_typeNames[(int)TypeCode];
}
if (!isXQ && IsStrict)
s += "=";
return s;
}
/// <summary>
/// Return "(name-test, type-name)" for this type. If isXQ is false, normalize xs:anySimpleType and
/// xs:anyType to "*".
/// </summary>
private string NameAndType(bool isXQ)
{
string nodeName = NameTest.ToString();
string typeName = "*";
if (SchemaType.QualifiedName.IsEmpty)
{
typeName = "typeof(" + nodeName + ")";
}
else
{
if (isXQ || (SchemaType != XmlSchemaComplexType.AnyType && SchemaType != DatatypeImplementation.AnySimpleType))
typeName = QNameToString(SchemaType.QualifiedName);
}
if (IsNillable)
typeName += " nillable";
// Normalize "(*, *)" to ""
if (nodeName == "*" && typeName == "*")
return "";
return "(" + nodeName + ", " + typeName + ")";
}
/// <summary>
/// Convert an XmlQualifiedName to a string, using somewhat different rules than XmlQualifiedName.ToString():
/// 1. Empty QNames are assumed to be wildcard names, so return "*"
/// 2. Recognize the built-in xs: and xdt: namespaces and print the short prefix rather than the long namespace
/// 3. Use brace characters "{", "}" around the namespace portion of the QName
/// </summary>
private static string QNameToString(XmlQualifiedName name)
{
if (name.IsEmpty)
{
return "*";
}
else if (name.Namespace.Length == 0)
{
return name.Name;
}
else if (name.Namespace == XmlReservedNs.NsXs)
{
return "xs:" + name.Name;
}
else if (name.Namespace == XmlReservedNs.NsXQueryDataType)
{
return "xdt:" + name.Name;
}
else
{
return "{" + name.Namespace + "}" + name.Name;
}
}
#region TypeFlags
private enum TypeFlags
{
None = 0,
IsNode = 1,
IsAtomicValue = 2,
IsNumeric = 4,
}
#endregion
#region TypeCodeToFlags
private static readonly TypeFlags[] s_typeCodeToFlags = {
/* XmlTypeCode.None */ TypeFlags.IsNode | TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.Item */ TypeFlags.None,
/* XmlTypeCode.Node */ TypeFlags.IsNode,
/* XmlTypeCode.Document */ TypeFlags.IsNode,
/* XmlTypeCode.Element */ TypeFlags.IsNode,
/* XmlTypeCode.Attribute */ TypeFlags.IsNode,
/* XmlTypeCode.Namespace */ TypeFlags.IsNode,
/* XmlTypeCode.ProcessingInstruction */ TypeFlags.IsNode,
/* XmlTypeCode.Comment */ TypeFlags.IsNode,
/* XmlTypeCode.Text */ TypeFlags.IsNode,
/* XmlTypeCode.AnyAtomicType */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.UntypedAtomic */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.String */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Boolean */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Decimal */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.Float */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.Double */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.Duration */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.DateTime */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Time */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Date */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.GYearMonth */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.GYear */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.GMonthDay */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.GDay */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.GMonth */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.HexBinary */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Base64Binary */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.AnyUri */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.QName */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Notation */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.NormalizedString */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Token */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Language */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.NmToken */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Name */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.NCName */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Id */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Idref */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Entity */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.Integer */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.NonPositiveInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.NegativeInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.Long */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.Int */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.Short */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.Byte */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.NonNegativeInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.UnsignedLong */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.UnsignedInt */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.UnsignedShort */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.UnsignedByte */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.PositiveInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric,
/* XmlTypeCode.YearMonthDuration */ TypeFlags.IsAtomicValue,
/* XmlTypeCode.DayTimeDuration */ TypeFlags.IsAtomicValue,
};
private static readonly XmlTypeCode[] s_baseTypeCodes = {
/* None */ XmlTypeCode.None,
/* Item */ XmlTypeCode.Item,
/* Node */ XmlTypeCode.Item,
/* Document */ XmlTypeCode.Node,
/* Element */ XmlTypeCode.Node,
/* Attribute */ XmlTypeCode.Node,
/* Namespace */ XmlTypeCode.Node,
/* ProcessingInstruction */ XmlTypeCode.Node,
/* Comment */ XmlTypeCode.Node,
/* Text */ XmlTypeCode.Node,
/* AnyAtomicType */ XmlTypeCode.Item,
/* UntypedAtomic */ XmlTypeCode.AnyAtomicType,
/* String */ XmlTypeCode.AnyAtomicType,
/* Boolean */ XmlTypeCode.AnyAtomicType,
/* Decimal */ XmlTypeCode.AnyAtomicType,
/* Float */ XmlTypeCode.AnyAtomicType,
/* Double */ XmlTypeCode.AnyAtomicType,
/* Duration */ XmlTypeCode.AnyAtomicType,
/* DateTime */ XmlTypeCode.AnyAtomicType,
/* Time */ XmlTypeCode.AnyAtomicType,
/* Date */ XmlTypeCode.AnyAtomicType,
/* GYearMonth */ XmlTypeCode.AnyAtomicType,
/* GYear */ XmlTypeCode.AnyAtomicType,
/* GMonthDay */ XmlTypeCode.AnyAtomicType,
/* GDay */ XmlTypeCode.AnyAtomicType,
/* GMonth */ XmlTypeCode.AnyAtomicType,
/* HexBinary */ XmlTypeCode.AnyAtomicType,
/* Base64Binary */ XmlTypeCode.AnyAtomicType,
/* AnyUri */ XmlTypeCode.AnyAtomicType,
/* QName */ XmlTypeCode.AnyAtomicType,
/* Notation */ XmlTypeCode.AnyAtomicType,
/* NormalizedString */ XmlTypeCode.String,
/* Token */ XmlTypeCode.NormalizedString,
/* Language */ XmlTypeCode.Token,
/* NmToken */ XmlTypeCode.Token,
/* Name */ XmlTypeCode.Token,
/* NCName */ XmlTypeCode.Name,
/* Id */ XmlTypeCode.NCName,
/* Idref */ XmlTypeCode.NCName,
/* Entity */ XmlTypeCode.NCName,
/* Integer */ XmlTypeCode.Decimal,
/* NonPositiveInteger */ XmlTypeCode.Integer,
/* NegativeInteger */ XmlTypeCode.NonPositiveInteger,
/* Long */ XmlTypeCode.Integer,
/* Int */ XmlTypeCode.Long,
/* Short */ XmlTypeCode.Int,
/* Byte */ XmlTypeCode.Short,
/* NonNegativeInteger */ XmlTypeCode.Integer,
/* UnsignedLong */ XmlTypeCode.NonNegativeInteger,
/* UnsignedInt */ XmlTypeCode.UnsignedLong,
/* UnsignedShort */ XmlTypeCode.UnsignedInt,
/* UnsignedByte */ XmlTypeCode.UnsignedShort,
/* PositiveInteger */ XmlTypeCode.NonNegativeInteger,
/* YearMonthDuration */ XmlTypeCode.Duration,
/* DayTimeDuration */ XmlTypeCode.Duration,
};
private static readonly string[] s_typeNames = {
/* None */ "none",
/* Item */ "item",
/* Node */ "node",
/* Document */ "document",
/* Element */ "element",
/* Attribute */ "attribute",
/* Namespace */ "namespace",
/* ProcessingInstruction */ "processing-instruction",
/* Comment */ "comment",
/* Text */ "text",
/* AnyAtomicType */ "xdt:anyAtomicType",
/* UntypedAtomic */ "xdt:untypedAtomic",
/* String */ "xs:string",
/* Boolean */ "xs:boolean",
/* Decimal */ "xs:decimal",
/* Float */ "xs:float",
/* Double */ "xs:double",
/* Duration */ "xs:duration",
/* DateTime */ "xs:dateTime",
/* Time */ "xs:time",
/* Date */ "xs:date",
/* GYearMonth */ "xs:gYearMonth",
/* GYear */ "xs:gYear",
/* GMonthDay */ "xs:gMonthDay",
/* GDay */ "xs:gDay",
/* GMonth */ "xs:gMonth",
/* HexBinary */ "xs:hexBinary",
/* Base64Binary */ "xs:base64Binary",
/* AnyUri */ "xs:anyUri",
/* QName */ "xs:QName",
/* Notation */ "xs:NOTATION",
/* NormalizedString */ "xs:normalizedString",
/* Token */ "xs:token",
/* Language */ "xs:language",
/* NmToken */ "xs:NMTOKEN",
/* Name */ "xs:Name",
/* NCName */ "xs:NCName",
/* Id */ "xs:ID",
/* Idref */ "xs:IDREF",
/* Entity */ "xs:ENTITY",
/* Integer */ "xs:integer",
/* NonPositiveInteger */ "xs:nonPositiveInteger",
/* NegativeInteger */ "xs:negativeInteger",
/* Long */ "xs:long",
/* Int */ "xs:int",
/* Short */ "xs:short",
/* Byte */ "xs:byte",
/* NonNegativeInteger */ "xs:nonNegativeInteger",
/* UnsignedLong */ "xs:unsignedLong",
/* UnsignedInt */ "xs:unsignedInt",
/* UnsignedShort */ "xs:unsignedShort",
/* UnsignedByte */ "xs:unsignedByte",
/* PositiveInteger */ "xs:positiveInteger",
/* YearMonthDuration */ "xdt:yearMonthDuration",
/* DayTimeDuration */ "xdt:dayTimeDuration",
};
#endregion
/// <summary>
/// Implements an NxN bit matrix.
/// </summary>
private sealed class BitMatrix
{
private ulong[] _bits;
/// <summary>
/// Create NxN bit matrix, where N = count.
/// </summary>
public BitMatrix(int count)
{
Debug.Assert(count < 64, "BitMatrix currently only handles up to 64x64 matrix.");
_bits = new ulong[count];
}
// /// <summary>
// /// Return the number of rows and columns in the matrix.
// /// </summary>
// public int Size {
// get { return bits.Length; }
// }
//
/// <summary>
/// Get or set a bit in the matrix at position (index1, index2).
/// </summary>
public bool this[int index1, int index2]
{
get
{
Debug.Assert(index1 < _bits.Length && index2 < _bits.Length, "Index out of range.");
return (_bits[index1] & ((ulong)1 << index2)) != 0;
}
set
{
Debug.Assert(index1 < _bits.Length && index2 < _bits.Length, "Index out of range.");
if (value == true)
{
_bits[index1] |= (ulong)1 << index2;
}
else
{
_bits[index1] &= ~((ulong)1 << index2);
}
}
}
/// <summary>
/// Strongly typed indexer.
/// </summary>
public bool this[XmlTypeCode index1, XmlTypeCode index2]
{
get
{
return this[(int)index1, (int)index2];
}
// set {
// this[(int)index1, (int)index2] = value;
// }
}
}
}
}
| |
using System;
using System.Xml;
using Google.GData.Client;
namespace Google.GData.Extensions
{
/// <summary>
/// GData schema extension describing a nested entry link.
/// </summary>
public class EntryLink : IExtensionElementFactory
{
/// <summary>holds the AtomEntry property of the EntryLink element</summary>
private AtomEntry entry;
/// <summary>holds the href property of the EntryLink element</summary>
private string href;
/// <summary>holds the readOnlySet property of the EntryLink element</summary>
private bool readOnly;
private bool readOnlySet;
/// <summary>holds the rel attribute of the EntyrLink element</summary>
private string rel;
/// <summary>
/// Entry URI
/// </summary>
public string Href
{
get { return href; }
set { href = value; }
}
/// <summary>
/// Read only flag.
/// </summary>
public bool ReadOnly
{
get { return readOnly; }
set
{
readOnly = value;
readOnlySet = true;
}
}
/// <summary>
/// Nested entry (optional).
/// </summary>
public AtomEntry Entry
{
get { return entry; }
set { entry = value; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string Rel</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Rel
{
get { return rel; }
set { rel = value; }
}
/////////////////////////////////////////////////////////////////////////////
#region EntryLink Parser
//////////////////////////////////////////////////////////////////////
/// <summary>parses an xml node to create an EntryLink object</summary>
/// <param name="node">entrylink node</param>
/// <param name="parser">AtomFeedParser to use</param>
/// <returns> the created EntryLink object</returns>
//////////////////////////////////////////////////////////////////////
public static EntryLink ParseEntryLink(XmlNode node, AtomFeedParser parser)
{
Tracing.TraceCall();
EntryLink link = null;
Tracing.Assert(node != null, "node should not be null");
if (node == null)
{
throw new ArgumentNullException("node");
}
object localname = node.LocalName;
if (localname.Equals(GDataParserNameTable.XmlEntryLinkElement))
{
link = new EntryLink();
if (node.Attributes != null)
{
if (node.Attributes[GDataParserNameTable.XmlAttributeHref] != null)
{
link.Href = node.Attributes[GDataParserNameTable.XmlAttributeHref].Value;
}
if (node.Attributes[GDataParserNameTable.XmlAttributeReadOnly] != null)
{
link.ReadOnly =
node.Attributes[GDataParserNameTable.XmlAttributeReadOnly].Value.Equals(Utilities.XSDTrue);
}
if (node.Attributes[GDataParserNameTable.XmlAttributeRel] != null)
{
link.Rel = node.Attributes[GDataParserNameTable.XmlAttributeRel].Value;
}
}
if (node.HasChildNodes)
{
XmlNode entryChild = node.FirstChild;
while (entryChild != null && entryChild is XmlElement)
{
if (entryChild.LocalName == AtomParserNameTable.XmlAtomEntryElement &&
entryChild.NamespaceURI == BaseNameTable.NSAtom)
{
if (link.Entry == null)
{
XmlReader reader = new XmlNodeReader(entryChild);
// move the reader to the first node
reader.Read();
AtomFeedParser p = new AtomFeedParser();
p.NewAtomEntry += link.OnParsedNewEntry;
p.ParseEntry(reader);
}
else
{
throw new ArgumentException("Only one entry is allowed inside the g:entryLink");
}
}
entryChild = entryChild.NextSibling;
}
}
}
return link;
}
//////////////////////////////////////////////////////////////////////
/// <summary>Event chaining. We catch this from the AtomFeedParser
/// we want to set this to our property, and do not add the entry to the collection
/// </summary>
/// <param name="sender"> the object which send the event</param>
/// <param name="e">FeedParserEventArguments, holds the feed entry</param>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
internal void OnParsedNewEntry(object sender, FeedParserEventArgs e)
{
// by default, if our event chain is not hooked, add it to the collection
Tracing.TraceCall("received new item notification");
Tracing.Assert(e != null, "e should not be null");
if (e == null)
{
throw new ArgumentNullException("e");
}
if (!e.CreatingEntry)
{
if (e.Entry != null)
{
// add it to the collection
Tracing.TraceMsg("\t new EventEntry found");
Entry = e.Entry;
e.DiscardEntry = true;
}
}
}
/////////////////////////////////////////////////////////////////////////////
#endregion
#region overloaded for persistence
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public static string XmlName
{
get { return GDataParserNameTable.XmlEntryLinkElement; }
}
/// <summary>
/// Used to save the EntryLink instance into the passed in xmlwriter
/// </summary>
/// <param name="writer">the XmlWriter to write into</param>
public void Save(XmlWriter writer)
{
if (Utilities.IsPersistable(Href) ||
readOnlySet ||
entry != null)
{
writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace);
if (Utilities.IsPersistable(Href))
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeHref, Href);
}
if (Utilities.IsPersistable(Rel))
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeRel, Rel);
}
if (readOnlySet)
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeReadOnly,
Utilities.ConvertBooleanToXSDString(ReadOnly));
}
if (entry != null)
{
entry.SaveToXml(writer);
}
writer.WriteEndElement();
}
}
#endregion
#region IExtensionElementFactory Members
/// <summary>
/// returns the xml local name for this element
/// </summary>
string IExtensionElementFactory.XmlName
{
get { return XmlName; }
}
/// <summary>
/// returns the xml namespace for this element
/// </summary>
public string XmlNameSpace
{
get { return BaseNameTable.gNamespace; }
}
/// <summary>
/// returns the xml prefix to be used for this element
/// </summary>
public string XmlPrefix
{
get { return BaseNameTable.gDataPrefix; }
}
/// <summary>
/// factory method to create an instance of a batchinterrupt during parsing
/// </summary>
/// <param name="node">the xmlnode that is going to be parsed</param>
/// <param name="parser">the feedparser that is used right now</param>
/// <returns></returns>
public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser)
{
return ParseEntryLink(node, parser);
}
#endregion
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using IBits = Lucene.Net.Util.IBits;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using Field = Field;
using FixedBitSet = Lucene.Net.Util.FixedBitSet;
using IndexReader = Lucene.Net.Index.IndexReader;
using IOUtils = Lucene.Net.Util.IOUtils;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using SerialMergeScheduler = Lucene.Net.Index.SerialMergeScheduler;
using SlowCompositeReaderWrapper = Lucene.Net.Index.SlowCompositeReaderWrapper;
using StringField = StringField;
using Term = Lucene.Net.Index.Term;
[TestFixture]
public class TestCachingWrapperFilter : LuceneTestCase
{
private Directory dir;
private DirectoryReader ir;
private IndexSearcher @is;
private RandomIndexWriter iw;
[SetUp]
public override void SetUp()
{
base.SetUp();
dir = NewDirectory();
iw = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
Document doc = new Document();
Field idField = new StringField("id", "", Field.Store.NO);
doc.Add(idField);
// add 500 docs with id 0..499
for (int i = 0; i < 500; i++)
{
idField.SetStringValue(Convert.ToString(i));
iw.AddDocument(doc);
}
// delete 20 of them
for (int i = 0; i < 20; i++)
{
iw.DeleteDocuments(new Term("id", Convert.ToString(Random.Next(iw.MaxDoc))));
}
ir = iw.GetReader();
@is = NewSearcher(ir);
}
[TearDown]
public override void TearDown()
{
IOUtils.Dispose(iw, ir, dir);
base.TearDown();
}
private void AssertFilterEquals(Filter f1, Filter f2)
{
Query query = new MatchAllDocsQuery();
TopDocs hits1 = @is.Search(query, f1, ir.MaxDoc);
TopDocs hits2 = @is.Search(query, f2, ir.MaxDoc);
Assert.AreEqual(hits1.TotalHits, hits2.TotalHits);
CheckHits.CheckEqual(query, hits1.ScoreDocs, hits2.ScoreDocs);
// now do it again to confirm caching works
TopDocs hits3 = @is.Search(query, f1, ir.MaxDoc);
TopDocs hits4 = @is.Search(query, f2, ir.MaxDoc);
Assert.AreEqual(hits3.TotalHits, hits4.TotalHits);
CheckHits.CheckEqual(query, hits3.ScoreDocs, hits4.ScoreDocs);
}
/// <summary>
/// test null iterator </summary>
[Test]
public virtual void TestEmpty()
{
Query query = new BooleanQuery();
Filter expected = new QueryWrapperFilter(query);
Filter actual = new CachingWrapperFilter(expected);
AssertFilterEquals(expected, actual);
}
/// <summary>
/// test iterator returns NO_MORE_DOCS </summary>
[Test]
public virtual void TestEmpty2()
{
BooleanQuery query = new BooleanQuery();
query.Add(new TermQuery(new Term("id", "0")), Occur.MUST);
query.Add(new TermQuery(new Term("id", "0")), Occur.MUST_NOT);
Filter expected = new QueryWrapperFilter(query);
Filter actual = new CachingWrapperFilter(expected);
AssertFilterEquals(expected, actual);
}
/// <summary>
/// test null docidset </summary>
[Test]
public virtual void TestEmpty3()
{
Filter expected = new PrefixFilter(new Term("bogusField", "bogusVal"));
Filter actual = new CachingWrapperFilter(expected);
AssertFilterEquals(expected, actual);
}
/// <summary>
/// test iterator returns single document </summary>
[Test]
public virtual void TestSingle()
{
for (int i = 0; i < 10; i++)
{
int id = Random.Next(ir.MaxDoc);
Query query = new TermQuery(new Term("id", Convert.ToString(id)));
Filter expected = new QueryWrapperFilter(query);
Filter actual = new CachingWrapperFilter(expected);
AssertFilterEquals(expected, actual);
}
}
/// <summary>
/// test sparse filters (match single documents) </summary>
[Test]
public virtual void TestSparse()
{
for (int i = 0; i < 10; i++)
{
int id_start = Random.Next(ir.MaxDoc - 1);
int id_end = id_start + 1;
Query query = TermRangeQuery.NewStringRange("id", Convert.ToString(id_start), Convert.ToString(id_end), true, true);
Filter expected = new QueryWrapperFilter(query);
Filter actual = new CachingWrapperFilter(expected);
AssertFilterEquals(expected, actual);
}
}
/// <summary>
/// test dense filters (match entire index) </summary>
[Test]
public virtual void TestDense()
{
Query query = new MatchAllDocsQuery();
Filter expected = new QueryWrapperFilter(query);
Filter actual = new CachingWrapperFilter(expected);
AssertFilterEquals(expected, actual);
}
[Test]
public virtual void TestCachingWorks()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
writer.Dispose();
IndexReader reader = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir));
AtomicReaderContext context = (AtomicReaderContext)reader.Context;
MockFilter filter = new MockFilter();
CachingWrapperFilter cacher = new CachingWrapperFilter(filter);
// first time, nested filter is called
DocIdSet strongRef = cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs);
Assert.IsTrue(filter.WasCalled(), "first time");
// make sure no exception if cache is holding the wrong docIdSet
cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs);
// second time, nested filter should not be called
filter.Clear();
cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs);
Assert.IsFalse(filter.WasCalled(), "second time");
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestNullDocIdSet()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
writer.Dispose();
IndexReader reader = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir));
AtomicReaderContext context = (AtomicReaderContext)reader.Context;
Filter filter = new FilterAnonymousInnerClassHelper(this, context);
CachingWrapperFilter cacher = new CachingWrapperFilter(filter);
// the caching filter should return the empty set constant
//Assert.IsNull(cacher.GetDocIdSet(context, "second time", (context.AtomicReader).LiveDocs));
Assert.IsNull(cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs));
reader.Dispose();
dir.Dispose();
}
private class FilterAnonymousInnerClassHelper : Filter
{
private readonly TestCachingWrapperFilter outerInstance;
private AtomicReaderContext context;
public FilterAnonymousInnerClassHelper(TestCachingWrapperFilter outerInstance, AtomicReaderContext context)
{
this.outerInstance = outerInstance;
this.context = context;
}
public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs)
{
return null;
}
}
[Test]
public virtual void TestNullDocIdSetIterator()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
writer.Dispose();
IndexReader reader = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir));
AtomicReaderContext context = (AtomicReaderContext)reader.Context;
Filter filter = new FilterAnonymousInnerClassHelper2(this, context);
CachingWrapperFilter cacher = new CachingWrapperFilter(filter);
// the caching filter should return the empty set constant
Assert.IsNull(cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs));
reader.Dispose();
dir.Dispose();
}
private class FilterAnonymousInnerClassHelper2 : Filter
{
private readonly TestCachingWrapperFilter outerInstance;
private AtomicReaderContext context;
public FilterAnonymousInnerClassHelper2(TestCachingWrapperFilter outerInstance, AtomicReaderContext context)
{
this.outerInstance = outerInstance;
this.context = context;
}
public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs)
{
return new DocIdSetAnonymousInnerClassHelper(this);
}
private class DocIdSetAnonymousInnerClassHelper : DocIdSet
{
private readonly FilterAnonymousInnerClassHelper2 outerInstance;
public DocIdSetAnonymousInnerClassHelper(FilterAnonymousInnerClassHelper2 outerInstance)
{
this.outerInstance = outerInstance;
}
public override DocIdSetIterator GetIterator()
{
return null;
}
}
}
private static void AssertDocIdSetCacheable(IndexReader reader, Filter filter, bool shouldCacheable)
{
Assert.IsTrue(reader.Context is AtomicReaderContext);
AtomicReaderContext context = (AtomicReaderContext)reader.Context;
CachingWrapperFilter cacher = new CachingWrapperFilter(filter);
DocIdSet originalSet = filter.GetDocIdSet(context, (context.AtomicReader).LiveDocs);
DocIdSet cachedSet = cacher.GetDocIdSet(context, (context.AtomicReader).LiveDocs);
if (originalSet == null)
{
Assert.IsNull(cachedSet);
}
if (cachedSet == null)
{
Assert.IsTrue(originalSet == null || originalSet.GetIterator() == null);
}
else
{
Assert.IsTrue(cachedSet.IsCacheable);
Assert.AreEqual(shouldCacheable, originalSet.IsCacheable);
//System.out.println("Original: "+originalSet.getClass().getName()+" -- cached: "+cachedSet.getClass().getName());
if (originalSet.IsCacheable)
{
Assert.AreEqual(originalSet.GetType(), cachedSet.GetType(), "Cached DocIdSet must be of same class like uncached, if cacheable");
}
else
{
Assert.IsTrue(cachedSet is FixedBitSet || cachedSet == null, "Cached DocIdSet must be an FixedBitSet if the original one was not cacheable");
}
}
}
[Test]
public virtual void TestIsCacheAble()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
writer.AddDocument(new Document());
writer.Dispose();
IndexReader reader = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(dir));
// not cacheable:
AssertDocIdSetCacheable(reader, new QueryWrapperFilter(new TermQuery(new Term("test", "value"))), false);
// returns default empty docidset, always cacheable:
AssertDocIdSetCacheable(reader, NumericRangeFilter.NewInt32Range("test", Convert.ToInt32(10000), Convert.ToInt32(-10000), true, true), true);
// is cacheable:
AssertDocIdSetCacheable(reader, FieldCacheRangeFilter.NewInt32Range("test", Convert.ToInt32(10), Convert.ToInt32(20), true, true), true);
// a fixedbitset filter is always cacheable
AssertDocIdSetCacheable(reader, new FilterAnonymousInnerClassHelper3(this), true);
reader.Dispose();
dir.Dispose();
}
private class FilterAnonymousInnerClassHelper3 : Filter
{
private readonly TestCachingWrapperFilter outerInstance;
public FilterAnonymousInnerClassHelper3(TestCachingWrapperFilter outerInstance)
{
this.outerInstance = outerInstance;
}
public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs)
{
return new FixedBitSet(context.Reader.MaxDoc);
}
}
[Test]
public virtual void TestEnforceDeletions()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergeScheduler(new SerialMergeScheduler()).SetMergePolicy(NewLogMergePolicy(10)));
// asserts below requires no unexpected merges:
// NOTE: cannot use writer.getReader because RIW (on
// flipping a coin) may give us a newly opened reader,
// but we use .reopen on this reader below and expect to
// (must) get an NRT reader:
DirectoryReader reader = DirectoryReader.Open(writer.IndexWriter, true);
// same reason we don't wrap?
IndexSearcher searcher = NewSearcher(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
reader, false);
// add a doc, refresh the reader, and check that it's there
Document doc = new Document();
doc.Add(NewStringField("id", "1", Field.Store.YES));
writer.AddDocument(doc);
reader = RefreshReader(reader);
searcher = NewSearcher(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
reader, false);
TopDocs docs = searcher.Search(new MatchAllDocsQuery(), 1);
Assert.AreEqual(1, docs.TotalHits, "Should find a hit...");
Filter startFilter = new QueryWrapperFilter(new TermQuery(new Term("id", "1")));
CachingWrapperFilter filter = new CachingWrapperFilter(startFilter);
docs = searcher.Search(new MatchAllDocsQuery(), filter, 1);
Assert.IsTrue(filter.GetSizeInBytes() > 0);
Assert.AreEqual(1, docs.TotalHits, "[query + filter] Should find a hit...");
Query constantScore = new ConstantScoreQuery(filter);
docs = searcher.Search(constantScore, 1);
Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit...");
// make sure we get a cache hit when we reopen reader
// that had no change to deletions
// fake delete (deletes nothing):
writer.DeleteDocuments(new Term("foo", "bar"));
IndexReader oldReader = reader;
reader = RefreshReader(reader);
Assert.IsTrue(reader == oldReader);
int missCount = filter.missCount;
docs = searcher.Search(constantScore, 1);
Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit...");
// cache hit:
Assert.AreEqual(missCount, filter.missCount);
// now delete the doc, refresh the reader, and see that it's not there
writer.DeleteDocuments(new Term("id", "1"));
// NOTE: important to hold ref here so GC doesn't clear
// the cache entry! Else the assert below may sometimes
// fail:
oldReader = reader;
reader = RefreshReader(reader);
searcher = NewSearcher(reader, false);
missCount = filter.missCount;
docs = searcher.Search(new MatchAllDocsQuery(), filter, 1);
Assert.AreEqual(0, docs.TotalHits, "[query + filter] Should *not* find a hit...");
// cache hit
Assert.AreEqual(missCount, filter.missCount);
docs = searcher.Search(constantScore, 1);
Assert.AreEqual(0, docs.TotalHits, "[just filter] Should *not* find a hit...");
// apply deletes dynamically:
filter = new CachingWrapperFilter(startFilter);
writer.AddDocument(doc);
reader = RefreshReader(reader);
searcher = NewSearcher(reader, false);
docs = searcher.Search(new MatchAllDocsQuery(), filter, 1);
Assert.AreEqual(1, docs.TotalHits, "[query + filter] Should find a hit...");
missCount = filter.missCount;
Assert.IsTrue(missCount > 0);
constantScore = new ConstantScoreQuery(filter);
docs = searcher.Search(constantScore, 1);
Assert.AreEqual(1, docs.TotalHits, "[just filter] Should find a hit...");
Assert.AreEqual(missCount, filter.missCount);
writer.AddDocument(doc);
// NOTE: important to hold ref here so GC doesn't clear
// the cache entry! Else the assert below may sometimes
// fail:
oldReader = reader;
reader = RefreshReader(reader);
searcher = NewSearcher(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
reader, false);
docs = searcher.Search(new MatchAllDocsQuery(), filter, 1);
Assert.AreEqual(2, docs.TotalHits, "[query + filter] Should find 2 hits...");
Assert.IsTrue(filter.missCount > missCount);
missCount = filter.missCount;
constantScore = new ConstantScoreQuery(filter);
docs = searcher.Search(constantScore, 1);
Assert.AreEqual(2, docs.TotalHits, "[just filter] Should find a hit...");
Assert.AreEqual(missCount, filter.missCount);
// now delete the doc, refresh the reader, and see that it's not there
writer.DeleteDocuments(new Term("id", "1"));
reader = RefreshReader(reader);
searcher = NewSearcher(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
reader, false);
docs = searcher.Search(new MatchAllDocsQuery(), filter, 1);
Assert.AreEqual(0, docs.TotalHits, "[query + filter] Should *not* find a hit...");
// CWF reused the same entry (it dynamically applied the deletes):
Assert.AreEqual(missCount, filter.missCount);
docs = searcher.Search(constantScore, 1);
Assert.AreEqual(0, docs.TotalHits, "[just filter] Should *not* find a hit...");
// CWF reused the same entry (it dynamically applied the deletes):
Assert.AreEqual(missCount, filter.missCount);
// NOTE: silliness to make sure JRE does not eliminate
// our holding onto oldReader to prevent
// CachingWrapperFilter's WeakHashMap from dropping the
// entry:
Assert.IsTrue(oldReader != null);
reader.Dispose();
writer.Dispose();
dir.Dispose();
}
private static DirectoryReader RefreshReader(DirectoryReader reader)
{
DirectoryReader oldReader = reader;
reader = DirectoryReader.OpenIfChanged(reader);
if (reader != null)
{
oldReader.Dispose();
return reader;
}
else
{
return oldReader;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.Protocols.TestTools.Messages.Marshaling;
using System.IO;
using System.Net.Security;
namespace Microsoft.Protocols.TestTools.Messages
{
/// <summary>
/// An interface which TCP adapters should derive from.
/// </summary>
public interface ITcpAdapter : IAdapter
{
/// <summary>
/// Establishes the connection to the configured endpoint.
/// </summary>
void Connect();
}
/// <summary>
/// An abstract base class for TCP adapters.
/// </summary>
public abstract class TcpAdapterBase : ManagedAdapterBase, ITcpAdapter
{
string adapterName;
TcpClient tcpClient;
/// <summary>
/// Gets the underlying TcpClient.
/// </summary>
public virtual TcpClient TcpClient
{
get
{
if (tcpClient == null)
{
tcpClient = new TcpClient(NetworkAddressFamily);
tcpClient.NoDelay = true;
}
return tcpClient;
}
}
/// <summary>
/// Gets the end point which is used for TcpClient connection.
/// </summary>
public virtual IPEndPoint IPEndPoint
{
get
{
IPEndPoint endPoint = null;
string hostName = GetRequiredProperty(HostPropertyName);
int port = GetRequiredIntProperty(PortPropertyName);
try
{
foreach (IPAddress ipAddress in Dns.GetHostAddresses(hostName))
{
if (ipAddress.AddressFamily == this.NetworkAddressFamily)
{
endPoint = new IPEndPoint(ipAddress, port);
break;
}
}
}
catch (ArgumentOutOfRangeException e)
{
Site.Assume.Fail(e.Message);
}
catch (SocketException e)
{
Site.Assume.Fail(e.Message);
}
if (endPoint == null)
{
throw new InvalidOperationException(
"Cannot get the host address for the configured address family.");
}
return endPoint;
}
}
/// <summary>
/// Gets the underlying NetworkStream. The property can be overrode.
/// If visit the NetworkStream before connection or after close,
/// null value will be returned.
/// </summary>
public virtual NetworkStream NetworkStream
{
get
{
if (TcpClient == null || !TcpClient.Connected)
{
return null;
}
return TcpClient.GetStream();
}
}
/// <summary>
/// Gets the underlying Stream. The property can be overrided.
/// If visit the Stream before connection or after close,
/// null value will be returned.
/// </summary>
public virtual Stream Stream
{
get
{
return NetworkStream;
}
}
Channel channel;
MarshalingConfiguration marshalingConfig;
Thread listener;
/// <summary>
/// Constructs a TCP adapter.
/// The parameter adapterName is used for constructing default PTF property names in the configuration.
/// </summary>
/// <param name="adapterName">The adapter name</param>
protected TcpAdapterBase(string adapterName)
{
this.adapterName = adapterName;
this.marshalingConfig = BlockMarshalingConfiguration.Configuration;
}
/// <summary>
/// Constructs a TCP adapter with given marshaling configuration.
/// The parameter adapterName is used for constructing default PTF property names in the configuration.
/// </summary>
/// <param name="adapterName">The adapter name</param>
/// <param name="config">The marshaling configuration</param>
protected TcpAdapterBase(string adapterName, MarshalingConfiguration config)
{
this.adapterName = adapterName;
this.marshalingConfig = config;
}
/// <summary>
/// Gets the PTF property name to be used for looking up the hostname of the TCP connection.
/// The default format is adapterName.hostname.
/// </summary>
public virtual string HostPropertyName
{
get
{
return String.Format("{0}.hostname", adapterName);
}
}
/// <summary>
/// Gets the PTF property name to be used for looking up the port of the TCP connection.
/// The default format is adapterName.port.
/// </summary>
public virtual string PortPropertyName
{
get
{
return String.Format("{0}.port", adapterName);
}
}
/// <summary>
/// Gets the PTF property name to be used for looking up the address family of the UDP connection.
/// The default format is adapterName.addressfamily.
/// </summary>
public virtual string AddressFamilyPropertyName
{
get
{
return String.Format("{0}.addressfamily", adapterName);
}
}
/// <summary>
/// Initializes the adapter.
/// This method does not include setting up a connection.
/// </summary>
/// <param name="testSite">The test site</param>
public override void Initialize(ITestSite testSite)
{
base.Initialize(testSite);
}
/// <summary>
/// Resets the adapter.
/// This method closes opened connection, if any.
/// </summary>
public override void Reset()
{
base.Reset();
CloseConnection();
}
/// <summary>
/// Disposes the adapter.
/// This method closes opened connection, if any.
/// </summary>
/// <param name="disposing">Indicates whether Dispose is called by user</param>
protected override void Dispose(bool disposing)
{
try
{
if (!IsDisposed)
{
if (disposing)
{
CloseConnection();
}
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Gets the Channel which is associated with this TcpAdapterBase.
/// The Channel is used for reading and writing to the TCP connection.
/// The Channel property is null if no connection is established.
/// </summary>
public virtual Channel Channel
{
get
{
if (channel == null && Stream != null)
{
if (DisableValidation)
{
channel = new Channel(Site, Stream, this.marshalingConfig);
}
else
{
channel = new ValidationChannel(Site, Stream, this.marshalingConfig);
}
}
return channel;
}
}
/// <summary>
/// A virtual method which implements reading from the channel.
/// This method is executed in an asynchronous thread within TcpAdapterBase
/// when a connection is established. It should not return until receiving
/// finished. This method should only use Checkers of ITestSite to report errors.
/// </summary>
protected virtual void ReceiveLoop()
{
}
/// <summary>
/// Invokes ReceiveLoop() and processes the exceptions thrown by the method ReceiveLoop().
/// </summary>
// The following suppression is adopted because any exception thrown in ReceiveLoop() must be caught by TcpAdapterBase.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal void InternalReceive()
{
try
{
ReceiveLoop();
}
catch (ThreadAbortException)
{
throw;
}
catch (Exception e)
{
ExtensionHelper.HandleVSException(e, Site);
string msg = e != null ? e.ToString() : "unexpected internal error";
Site.Assert.Fail("unexpected exception in receive loop: {0}", msg);
}
}
/// <summary>
/// Closes the connection and releases all resources.
/// This method releases the resources including Thread, Channel, Stream and TcpClient orderly.
/// The method can be overrided, and users should close Stream, NetworkStream before
/// closing TcpClient in the overrided CloseConnection method.
/// </summary>
protected virtual void CloseConnection()
{
try
{
//ignore the thread abort exception
//and release all resourcese.
if (listener != null)
{
listener.Abort();
}
}
finally
{
listener = null;
if (Channel != null)
{
Channel.Dispose();
}
if (channel != null)
{
channel.Dispose();
channel = null;
}
if (Stream != null)
{
Stream.Close();
}
if (TcpClient != null)
{
TcpClient.Client.Close();
TcpClient.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
tcpClient = null;
}
}
}
/// <summary>
/// Establishes the connection to the configured endpoint. Including
/// connect TcpClient with spceified end point and start the receive loop
/// in a stand-alone thread.
/// This method must be called before any communication in the channel or
/// before visit the underlying stream or network stream.
/// </summary>
public void Connect()
{
CloseConnection();
try
{
TcpClient.Connect(IPEndPoint);
}
catch (ArgumentOutOfRangeException e)
{
Site.Assume.Fail(e.Message);
}
catch (SocketException e)
{
Site.Assume.Fail(e.Message);
}
listener = new Thread(InternalReceive);
listener.Start();
}
/// <summary>
/// Returns the value of address family for this tcp adapter.
/// </summary>
AddressFamily NetworkAddressFamily
{
get
{
AddressFamily addressFamily = AddressFamily.InterNetwork;
string addressFamilyName = Site.Properties[AddressFamilyPropertyName];
if (!string.IsNullOrEmpty(addressFamilyName))
{
try
{
addressFamily = (AddressFamily)Enum.Parse(typeof(AddressFamily), addressFamilyName);
}
catch (ArgumentException)
{
throw new InvalidOperationException(
String.Format("The address family '{0}' in PTF config is invalid.", addressFamilyName));
}
}
return addressFamily;
}
}
/// <summary>
/// Returns the String value of required property.
/// </summary>
/// <param name="name">The property name</param>
/// <returns>The string value of the property</returns>
string GetRequiredProperty(string name)
{
string value = Site.Properties[name];
if (value == null)
throw new InvalidOperationException(
String.Format("Required PTF property '{0}' undefined",
name));
return value;
}
/// <summary>
/// Returns the value to indicate whether the validation is disabled.
/// </summary>
bool DisableValidation
{
get
{
if (Site == null)
{
return false;
}
bool disableValidation = false;
string disableValidationName = "disablevalidation";
string disableValidationValue = Site.Properties[disableValidationName];
if (!string.IsNullOrEmpty(disableValidationValue))
{
try
{
disableValidationValue = disableValidationValue.Trim().ToLower();
disableValidation = bool.Parse(disableValidationValue);
}
catch (ArgumentException)
{
throw new InvalidOperationException(
String.Format("The property '{0}' in PTF config is invalid.", disableValidationName));
}
}
return disableValidation;
}
}
/// <summary>
/// Returns the integer value of required property
/// </summary>
/// <param name="name">The property name</param>
/// <returns>The integer value of the property</returns>
int GetRequiredIntProperty(string name)
{
string value = GetRequiredProperty(name);
try
{
return Int32.Parse(value);
}
catch (FormatException)
{
throw new InvalidOperationException(
String.Format("Required PTF property'{0}' not assigned to a valid number",
name));
}
}
}
}
| |
using Discord;
using Discord.Net;
using Discord.WebSocket;
using NadekoBot.Extensions;
using NadekoBot.Services;
using NLog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Games.Trivia
{
public class TriviaGame
{
private readonly SemaphoreSlim _guessLock = new SemaphoreSlim(1, 1);
private Logger _log { get; }
public IGuild guild { get; }
public ITextChannel channel { get; }
private int QuestionDurationMiliseconds { get; } = 30000;
private int HintTimeoutMiliseconds { get; } = 6000;
public bool ShowHints { get; } = true;
private CancellationTokenSource triviaCancelSource { get; set; }
public TriviaQuestion CurrentQuestion { get; private set; }
public HashSet<TriviaQuestion> oldQuestions { get; } = new HashSet<TriviaQuestion>();
public ConcurrentDictionary<IGuildUser, int> Users { get; } = new ConcurrentDictionary<IGuildUser, int>();
public bool GameActive { get; private set; } = false;
public bool ShouldStopGame { get; private set; }
public int WinRequirement { get; } = 10;
public TriviaGame(IGuild guild, ITextChannel channel, bool showHints, int winReq)
{
this._log = LogManager.GetCurrentClassLogger();
this.ShowHints = showHints;
this.guild = guild;
this.channel = channel;
this.WinRequirement = winReq;
}
public async Task StartGame()
{
while (!ShouldStopGame)
{
// reset the cancellation source
triviaCancelSource = new CancellationTokenSource();
// load question
CurrentQuestion = TriviaQuestionPool.Instance.GetRandomQuestion(oldQuestions);
if (CurrentQuestion == null ||
string.IsNullOrWhiteSpace(CurrentQuestion.Answer) ||
string.IsNullOrWhiteSpace(CurrentQuestion.Question))
{
await channel.SendErrorAsync("Trivia Game", "Failed loading a question.").ConfigureAwait(false);
return;
}
oldQuestions.Add(CurrentQuestion); //add it to exclusion list so it doesn't show up again
EmbedBuilder questionEmbed;
IUserMessage questionMessage;
try
{
questionEmbed = new EmbedBuilder().WithOkColor()
.WithTitle("Trivia Game")
.AddField(eab => eab.WithName("Category").WithValue(CurrentQuestion.Category))
.AddField(eab => eab.WithName("Question").WithValue(CurrentQuestion.Question));
questionMessage = await channel.EmbedAsync(questionEmbed).ConfigureAwait(false);
}
catch (HttpException ex) when (ex.HttpCode == System.Net.HttpStatusCode.NotFound ||
ex.HttpCode == System.Net.HttpStatusCode.Forbidden ||
ex.HttpCode == System.Net.HttpStatusCode.BadRequest)
{
return;
}
catch (Exception ex)
{
_log.Warn(ex);
await Task.Delay(2000).ConfigureAwait(false);
continue;
}
//receive messages
try
{
NadekoBot.Client.MessageReceived += PotentialGuess;
//allow people to guess
GameActive = true;
try
{
//hint
await Task.Delay(HintTimeoutMiliseconds, triviaCancelSource.Token).ConfigureAwait(false);
if (ShowHints)
try
{
await questionMessage.ModifyAsync(m => m.Embed = questionEmbed.WithFooter(efb => efb.WithText(CurrentQuestion.GetHint())).Build())
.ConfigureAwait(false);
}
catch (HttpException ex) when (ex.HttpCode == System.Net.HttpStatusCode.NotFound || ex.HttpCode == System.Net.HttpStatusCode.Forbidden)
{
break;
}
catch (Exception ex) { _log.Warn(ex); }
//timeout
await Task.Delay(QuestionDurationMiliseconds - HintTimeoutMiliseconds, triviaCancelSource.Token).ConfigureAwait(false);
}
catch (TaskCanceledException) { } //means someone guessed the answer
}
finally
{
GameActive = false;
NadekoBot.Client.MessageReceived -= PotentialGuess;
}
if (!triviaCancelSource.IsCancellationRequested)
try { await channel.SendErrorAsync("Trivia Game", $"**Time's up!** The correct answer was **{CurrentQuestion.Answer}**").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); }
await Task.Delay(2000).ConfigureAwait(false);
}
}
public async Task EnsureStopped()
{
ShouldStopGame = true;
await channel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithAuthor(eab => eab.WithName("Trivia Game Ended"))
.WithTitle("Final Results")
.WithDescription(GetLeaderboard())).ConfigureAwait(false);
}
public async Task StopGame()
{
var old = ShouldStopGame;
ShouldStopGame = true;
if (!old)
try { await channel.SendConfirmAsync("Trivia Game", "Stopping after this question.").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); }
}
private async Task PotentialGuess(SocketMessage imsg)
{
try
{
if (imsg.Author.IsBot)
return;
var umsg = imsg as SocketUserMessage;
if (umsg == null)
return;
var textChannel = umsg.Channel as ITextChannel;
if (textChannel == null || textChannel.Guild != guild)
return;
var guildUser = (IGuildUser)umsg.Author;
var guess = false;
await _guessLock.WaitAsync().ConfigureAwait(false);
try
{
if (GameActive && CurrentQuestion.IsAnswerCorrect(umsg.Content) && !triviaCancelSource.IsCancellationRequested)
{
Users.AddOrUpdate(guildUser, 1, (gu, old) => ++old);
guess = true;
}
}
finally { _guessLock.Release(); }
if (!guess) return;
triviaCancelSource.Cancel();
if (Users[guildUser] == WinRequirement)
{
ShouldStopGame = true;
try { await channel.SendConfirmAsync("Trivia Game", $"{guildUser.Mention} guessed it and WON the game! The answer was: **{CurrentQuestion.Answer}**").ConfigureAwait(false); } catch { }
var reward = NadekoBot.BotConfig.TriviaCurrencyReward;
if (reward > 0)
await CurrencyHandler.AddCurrencyAsync(guildUser, "Won trivia", reward, true).ConfigureAwait(false);
return;
}
await channel.SendConfirmAsync("Trivia Game", $"{guildUser.Mention} guessed it! The answer was: **{CurrentQuestion.Answer}**").ConfigureAwait(false);
}
catch (Exception ex) { _log.Warn(ex); }
}
public string GetLeaderboard()
{
if (Users.Count == 0)
return "No results.";
var sb = new StringBuilder();
foreach (var kvp in Users.OrderByDescending(kvp => kvp.Value))
{
sb.AppendLine($"**{kvp.Key.Username}** has {kvp.Value} points".ToString().SnPl(kvp.Value));
}
return sb.ToString();
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityModel;
using IdentityModel.Client;
using IdentityServer.IntegrationTests.Clients.Setup;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
namespace IdentityServer.IntegrationTests.Clients
{
public class UserInfoEndpointClient
{
private const string TokenEndpoint = "https://server/connect/token";
private const string UserInfoEndpoint = "https://server/connect/userinfo";
private readonly HttpClient _client;
public UserInfoEndpointClient()
{
var builder = new WebHostBuilder()
.UseStartup<Startup>();
var server = new TestServer(builder);
_client = server.CreateClient();
}
[Fact]
public async Task Valid_client_with_GET_should_succeed()
{
var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = TokenEndpoint,
ClientId = "roclient",
ClientSecret = "secret",
Scope = "openid email api1",
UserName = "bob",
Password = "bob"
});
response.IsError.Should().BeFalse();
var userInfo = await _client.GetUserInfoAsync(new UserInfoRequest
{
Address = UserInfoEndpoint,
Token = response.AccessToken
});
userInfo.IsError.Should().BeFalse();
userInfo.Claims.Count().Should().Be(3);
userInfo.Claims.Should().Contain(c => c.Type == "sub" && c.Value == "88421113");
userInfo.Claims.Should().Contain(c => c.Type == "email" && c.Value == "BobSmith@email.com");
userInfo.Claims.Should().Contain(c => c.Type == "email_verified" && c.Value == "true");
}
[Fact]
public async Task Request_address_scope_should_return_expected_response()
{
var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = TokenEndpoint,
ClientId = "roclient",
ClientSecret = "secret",
Scope = "openid address",
UserName = "bob",
Password = "bob"
});
response.IsError.Should().BeFalse();
var userInfo = await _client.GetUserInfoAsync(new UserInfoRequest
{
Address = UserInfoEndpoint,
Token = response.AccessToken
});
userInfo.IsError.Should().BeFalse();
userInfo.Raw.Should().Be("{\"address\":{\"street_address\":\"One Hacker Way\",\"locality\":\"Heidelberg\",\"postal_code\":69118,\"country\":\"Germany\"},\"sub\":\"88421113\"}");
}
[Fact]
public async Task Using_a_token_with_no_identity_scope_should_fail()
{
var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = TokenEndpoint,
ClientId = "roclient",
ClientSecret = "secret",
Scope = "api1",
UserName = "bob",
Password = "bob"
});
response.IsError.Should().BeFalse();
var userInfo = await _client.GetUserInfoAsync(new UserInfoRequest
{
Address = UserInfoEndpoint,
Token = response.AccessToken
});
userInfo.IsError.Should().BeTrue();
userInfo.HttpStatusCode.Should().Be(HttpStatusCode.Forbidden);
}
[Fact]
public async Task Using_a_token_with_an_identity_scope_but_no_openid_should_fail()
{
var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = TokenEndpoint,
ClientId = "roclient",
ClientSecret = "secret",
Scope = "email api1",
UserName = "bob",
Password = "bob"
});
response.IsError.Should().BeFalse();
var userInfo = await _client.GetUserInfoAsync(new UserInfoRequest
{
Address = UserInfoEndpoint,
Token = response.AccessToken
});
userInfo.IsError.Should().BeTrue();
userInfo.HttpStatusCode.Should().Be(HttpStatusCode.Forbidden);
}
[Fact]
public async Task Invalid_token_should_fail()
{
var userInfo = await _client.GetUserInfoAsync(new UserInfoRequest
{
Address = UserInfoEndpoint,
Token = "invalid"
});
userInfo.IsError.Should().BeTrue();
userInfo.HttpStatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Complex_json_should_be_correct()
{
var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = TokenEndpoint,
ClientId = "roclient",
ClientSecret = "secret",
Scope = "openid email api1 api4.with.roles roles",
UserName = "bob",
Password = "bob"
});
response.IsError.Should().BeFalse();
var payload = GetPayload(response);
var scopes = ((JArray)payload["scope"]).Select(x => x.ToString()).ToArray();
scopes.Length.Should().Be(5);
scopes.Should().Contain("openid");
scopes.Should().Contain("email");
scopes.Should().Contain("api1");
scopes.Should().Contain("api4.with.roles");
scopes.Should().Contain("roles");
var roles = ((JArray)payload["role"]).Select(x => x.ToString()).ToArray();
roles.Length.Should().Be(2);
roles.Should().Contain("Geek");
roles.Should().Contain("Developer");
var userInfo = await _client.GetUserInfoAsync(new UserInfoRequest
{
Address = UserInfoEndpoint,
Token = response.AccessToken
});
roles = ((JArray)userInfo.Json["role"]).Select(x => x.ToString()).ToArray();
roles.Length.Should().Be(2);
roles.Should().Contain("Geek");
roles.Should().Contain("Developer");
}
private Dictionary<string, object> GetPayload(TokenResponse response)
{
var token = response.AccessToken.Split('.').Skip(1).Take(1).First();
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(
Encoding.UTF8.GetString(Base64Url.Decode(token)));
return dictionary;
}
}
}
| |
/*
* 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 Nini.Config;
using log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.UserAccounts
{
public class UserAccountServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IUserAccountService m_UserAccountService;
public UserAccountServerPostHandler(IUserAccountService service) :
base("POST", "/accounts")
{
m_UserAccountService = service;
}
public override byte[] Handle(string path, Stream requestData,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
// We need to check the authorization header
//httpRequest.Headers["authorization"] ...
//m_log.DebugFormat("[XXX]: query String: {0}", body);
string method = string.Empty;
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
method = request["METHOD"].ToString();
switch (method)
{
case "getaccount":
return GetAccount(request);
case "getaccounts":
return GetAccounts(request);
case "setaccount":
return StoreAccount(request);
}
m_log.DebugFormat("[USER SERVICE HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.DebugFormat("[USER SERVICE HANDLER]: Exception in method {0}: {1}", method, e);
}
return FailureResult();
}
byte[] GetAccount(Dictionary<string, object> request)
{
UserAccount account = null;
UUID scopeID = UUID.Zero;
Dictionary<string, object> result = new Dictionary<string, object>();
if (!request.ContainsKey("ScopeID"))
{
result["result"] = "null";
return ResultToBytes(result);
}
if (!UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
{
result["result"] = "null";
return ResultToBytes(result);
}
if (request.ContainsKey("UserID") && request["UserID"] != null)
{
UUID userID;
if (UUID.TryParse(request["UserID"].ToString(), out userID))
account = m_UserAccountService.GetUserAccount(scopeID, userID);
}
else if (request.ContainsKey("Email") && request["Email"] != null)
account = m_UserAccountService.GetUserAccount(scopeID, request["Email"].ToString());
else if (request.ContainsKey("FirstName") && request.ContainsKey("LastName") &&
request["FirstName"] != null && request["LastName"] != null)
account = m_UserAccountService.GetUserAccount(scopeID, request["FirstName"].ToString(), request["LastName"].ToString());
if (account == null)
result["result"] = "null";
else
{
result["result"] = account.ToKeyValuePairs();
}
return ResultToBytes(result);
}
byte[] GetAccounts(Dictionary<string, object> request)
{
if (!request.ContainsKey("ScopeID") || !request.ContainsKey("query"))
return FailureResult();
UUID scopeID = UUID.Zero;
if (!UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
return FailureResult();
string query = request["query"].ToString();
List<UserAccount> accounts = m_UserAccountService.GetUserAccounts(scopeID, query);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((accounts == null) || ((accounts != null) && (accounts.Count == 0)))
result["result"] = "null";
else
{
int i = 0;
foreach (UserAccount acc in accounts)
{
Dictionary<string, object> rinfoDict = acc.ToKeyValuePairs();
result["account" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] StoreAccount(Dictionary<string, object> request)
{
// No can do. No changing user accounts from remote sims
return FailureResult();
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] FailureResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
}
private byte[] ResultToBytes(Dictionary<string, object> result)
{
string xmlString = ServerUtils.BuildXmlResponse(result);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A bus stop.
/// </summary>
public class BusStop_Core : TypeCore, ICivicStructure
{
public BusStop_Core()
{
this._TypeId = 48;
this._Id = "BusStop";
this._Schema_Org_Url = "http://schema.org/BusStop";
string label = "";
GetLabel(out label, "BusStop", typeof(BusStop_Core));
this._Label = label;
this._Ancestors = new int[]{266,206,62};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{62};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.IO;
using Umbraco.Core.Events;
using Umbraco.Core.IO;
using umbraco.DataLayer;
namespace umbraco.BusinessLogic
{
/// <summary>
/// umbraco.BusinessLogic.ApplicationTree provides access to the application tree structure in umbraco.
/// An application tree is a collection of nodes belonging to one or more application(s).
/// Through this class new application trees can be created, modified and deleted.
/// </summary>
public class ApplicationTree
{
internal const string TreeConfigFileName = "trees.config";
private static string _treeConfig;
private static readonly object Locker = new object();
/// <summary>
/// gets/sets the trees.config file path
/// </summary>
/// <remarks>
/// The setter is generally only going to be used in unit tests, otherwise it will attempt to resolve it using the IOHelper.MapPath
/// </remarks>
internal static string TreeConfigFilePath
{
get
{
if (string.IsNullOrWhiteSpace(_treeConfig))
{
_treeConfig = IOHelper.MapPath(SystemDirectories.Config + "/" + TreeConfigFileName);
}
return _treeConfig;
}
set { _treeConfig = value; }
}
/// <summary>
/// The cache storage for all application trees
/// </summary>
private static List<ApplicationTree> AppTrees
{
get
{
return ApplicationContext.Current.ApplicationCache.GetCacheItem(
CacheKeys.ApplicationTreeCacheKey,
() =>
{
var list = new List<ApplicationTree>();
LoadXml(doc =>
{
foreach (var addElement in doc.Root.Elements("add").OrderBy(x =>
{
var sortOrderAttr = x.Attribute("sortOrder");
return sortOrderAttr != null ? Convert.ToInt32(sortOrderAttr.Value) : 0;
}))
{
var applicationAlias = (string)addElement.Attribute("application");
var type = (string)addElement.Attribute("type");
var assembly = (string)addElement.Attribute("assembly");
//check if the tree definition (applicationAlias + type + assembly) is already in the list
if (!list.Any(tree => tree.ApplicationAlias.InvariantEquals(applicationAlias)
&& tree.Type.InvariantEquals(type)
&& tree.AssemblyName.InvariantEquals(assembly)))
{
list.Add(new ApplicationTree(
addElement.Attribute("silent") != null ? Convert.ToBoolean(addElement.Attribute("silent").Value) : false,
addElement.Attribute("initialize") != null ? Convert.ToBoolean(addElement.Attribute("initialize").Value) : true,
addElement.Attribute("sortOrder") != null ? Convert.ToByte(addElement.Attribute("sortOrder").Value) : (byte)0,
addElement.Attribute("application").Value,
addElement.Attribute("alias").Value,
addElement.Attribute("title").Value,
addElement.Attribute("iconClosed").Value,
addElement.Attribute("iconOpen").Value,
(string)addElement.Attribute("assembly"), //this could be empty: http://issues.umbraco.org/issue/U4-1360
addElement.Attribute("type").Value,
addElement.Attribute("action") != null ? addElement.Attribute("action").Value : ""));
}
}
}, false);
return list;
});
}
}
/// <summary>
/// Gets the SQL helper.
/// </summary>
/// <value>The SQL helper.</value>
public static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ApplicationTree"/> is silent.
/// </summary>
/// <value><c>true</c> if silent; otherwise, <c>false</c>.</value>
public bool Silent { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ApplicationTree"/> should initialize.
/// </summary>
/// <value><c>true</c> if initialize; otherwise, <c>false</c>.</value>
public bool Initialize { get; set; }
/// <summary>
/// Gets or sets the sort order.
/// </summary>
/// <value>The sort order.</value>
public byte SortOrder { get; set; }
/// <summary>
/// Gets the application alias.
/// </summary>
/// <value>The application alias.</value>
public string ApplicationAlias { get; private set; }
/// <summary>
/// Gets the tree alias.
/// </summary>
/// <value>The alias.</value>
public string Alias { get; private set; }
/// <summary>
/// Gets or sets the tree title.
/// </summary>
/// <value>The title.</value>
public string Title { get; set; }
/// <summary>
/// Gets or sets the icon closed.
/// </summary>
/// <value>The icon closed.</value>
public string IconClosed { get; set; }
/// <summary>
/// Gets or sets the icon opened.
/// </summary>
/// <value>The icon opened.</value>
public string IconOpened { get; set; }
/// <summary>
/// Gets or sets the name of the assembly.
/// </summary>
/// <value>The name of the assembly.</value>
public string AssemblyName { get; set; }
/// <summary>
/// Gets or sets the tree type.
/// </summary>
/// <value>The type.</value>
public string Type { get; set; }
/// <summary>
/// Gets or sets the default tree action.
/// </summary>
/// <value>The action.</value>
public string Action { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationTree"/> class.
/// </summary>
public ApplicationTree() { }
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationTree"/> class.
/// </summary>
/// <param name="silent">if set to <c>true</c> [silent].</param>
/// <param name="initialize">if set to <c>true</c> [initialize].</param>
/// <param name="sortOrder">The sort order.</param>
/// <param name="applicationAlias">The application alias.</param>
/// <param name="alias">The tree alias.</param>
/// <param name="title">The tree title.</param>
/// <param name="iconClosed">The icon closed.</param>
/// <param name="iconOpened">The icon opened.</param>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="type">The tree type.</param>
/// <param name="action">The default tree action.</param>
public ApplicationTree(bool silent, bool initialize, byte sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string assemblyName, string type, string action)
{
this.Silent = silent;
this.Initialize = initialize;
this.SortOrder = sortOrder;
this.ApplicationAlias = applicationAlias;
this.Alias = alias;
this.Title = title;
this.IconClosed = iconClosed;
this.IconOpened = iconOpened;
this.AssemblyName = assemblyName;
this.Type = type;
this.Action = action;
}
/// <summary>
/// Creates a new application tree.
/// </summary>
/// <param name="silent">if set to <c>true</c> [silent].</param>
/// <param name="initialize">if set to <c>true</c> [initialize].</param>
/// <param name="sortOrder">The sort order.</param>
/// <param name="applicationAlias">The application alias.</param>
/// <param name="alias">The alias.</param>
/// <param name="title">The title.</param>
/// <param name="iconClosed">The icon closed.</param>
/// <param name="iconOpened">The icon opened.</param>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="type">The type.</param>
/// <param name="action">The action.</param>
public static void MakeNew(bool silent, bool initialize, byte sortOrder, string applicationAlias, string alias, string title, string iconClosed, string iconOpened, string assemblyName, string type, string action)
{
LoadXml(doc =>
{
var el = doc.Root.Elements("add").SingleOrDefault(x => x.Attribute("alias").Value == alias && x.Attribute("application").Value == applicationAlias);
if (el == null)
{
doc.Root.Add(new XElement("add",
new XAttribute("silent", silent),
new XAttribute("initialize", initialize),
new XAttribute("sortOrder", sortOrder),
new XAttribute("alias", alias),
new XAttribute("application", applicationAlias),
new XAttribute("title", title),
new XAttribute("iconClosed", iconClosed),
new XAttribute("iconOpen", iconOpened),
new XAttribute("assembly", assemblyName),
new XAttribute("type", type),
new XAttribute("action", string.IsNullOrEmpty(action) ? "" : action)));
}
}, true);
OnNew(new ApplicationTree(silent, initialize, sortOrder, applicationAlias, alias, title, iconClosed, iconOpened, assemblyName, type, action), new EventArgs());
}
/// <summary>
/// Saves this instance.
/// </summary>
public void Save()
{
LoadXml(doc =>
{
var el = doc.Root.Elements("add").SingleOrDefault(x => x.Attribute("alias").Value == this.Alias && x.Attribute("application").Value == this.ApplicationAlias);
if (el != null)
{
el.RemoveAttributes();
el.Add(new XAttribute("silent", this.Silent));
el.Add(new XAttribute("initialize", this.Initialize));
el.Add(new XAttribute("sortOrder", this.SortOrder));
el.Add(new XAttribute("alias", this.Alias));
el.Add(new XAttribute("application", this.ApplicationAlias));
el.Add(new XAttribute("title", this.Title));
el.Add(new XAttribute("iconClosed", this.IconClosed));
el.Add(new XAttribute("iconOpen", this.IconOpened));
el.Add(new XAttribute("assembly", this.AssemblyName));
el.Add(new XAttribute("type", this.Type));
el.Add(new XAttribute("action", string.IsNullOrEmpty(this.Action) ? "" : this.Action));
}
}, true);
OnUpdated(this, new EventArgs());
}
/// <summary>
/// Deletes this instance.
/// </summary>
public void Delete()
{
//SqlHelper.ExecuteNonQuery("delete from umbracoAppTree where appAlias = @appAlias AND treeAlias = @treeAlias",
// SqlHelper.CreateParameter("@appAlias", this.ApplicationAlias), SqlHelper.CreateParameter("@treeAlias", this.Alias));
LoadXml(doc =>
{
doc.Root.Elements("add").Where(x => x.Attribute("application") != null && x.Attribute("application").Value == this.ApplicationAlias &&
x.Attribute("alias") != null && x.Attribute("alias").Value == this.Alias).Remove();
}, true);
OnDeleted(this, new EventArgs());
}
/// <summary>
/// Gets an ApplicationTree by it's tree alias.
/// </summary>
/// <param name="treeAlias">The tree alias.</param>
/// <returns>An ApplicationTree instance</returns>
public static ApplicationTree getByAlias(string treeAlias)
{
return AppTrees.Find(t => (t.Alias == treeAlias));
}
/// <summary>
/// Gets all applicationTrees registered in umbraco from the umbracoAppTree table..
/// </summary>
/// <returns>Returns a ApplicationTree Array</returns>
public static ApplicationTree[] getAll()
{
return AppTrees.OrderBy(x => x.SortOrder).ToArray();
}
/// <summary>
/// Gets the application tree for the applcation with the specified alias
/// </summary>
/// <param name="applicationAlias">The application alias.</param>
/// <returns>Returns a ApplicationTree Array</returns>
public static ApplicationTree[] getApplicationTree(string applicationAlias)
{
return getApplicationTree(applicationAlias, false);
}
/// <summary>
/// Gets the application tree for the applcation with the specified alias
/// </summary>
/// <param name="applicationAlias">The application alias.</param>
/// <param name="onlyInitializedApplications"></param>
/// <returns>Returns a ApplicationTree Array</returns>
public static ApplicationTree[] getApplicationTree(string applicationAlias, bool onlyInitializedApplications)
{
var list = AppTrees.FindAll(
t =>
{
if (onlyInitializedApplications)
return (t.ApplicationAlias == applicationAlias && t.Initialize);
return (t.ApplicationAlias == applicationAlias);
}
);
return list.OrderBy(x => x.SortOrder).ToArray();
}
internal static void LoadXml(Action<XDocument> callback, bool saveAfterCallback)
{
lock (Locker)
{
var doc = File.Exists(TreeConfigFilePath)
? XDocument.Load(TreeConfigFilePath)
: XDocument.Parse("<?xml version=\"1.0\"?><trees />");
if (doc.Root != null)
{
callback.Invoke(doc);
if (saveAfterCallback)
{
Directory.CreateDirectory(Path.GetDirectoryName(TreeConfigFilePath));
doc.Save(TreeConfigFilePath);
//remove the cache now that it has changed SD: I'm leaving this here even though it
// is taken care of by events as well, I think unit tests may rely on it being cleared here.
ApplicationContext.Current.ApplicationCache.ClearCacheItem(CacheKeys.ApplicationTreeCacheKey);
}
}
}
}
internal static event TypedEventHandler<ApplicationTree, EventArgs> Deleted;
private static void OnDeleted(ApplicationTree app, EventArgs args)
{
if (Deleted != null)
{
Deleted(app, args);
}
}
internal static event TypedEventHandler<ApplicationTree, EventArgs> New;
private static void OnNew(ApplicationTree app, EventArgs args)
{
if (New != null)
{
New(app, args);
}
}
internal static event TypedEventHandler<ApplicationTree, EventArgs> Updated;
private static void OnUpdated(ApplicationTree app, EventArgs args)
{
if (Updated != null)
{
Updated(app, args);
}
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// 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.Text;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using Alachisoft.NCache.Storage.Util;
using Alachisoft.NCache.Storage.Mmf;
using Alachisoft.NCache.Storage.Interop;
namespace Alachisoft.NCache.Storage.Mmf
{
internal class ViewManager
{
class ViewIDComparer : IComparer
{
int IComparer.Compare(object x, object y)
{
return ((View)x).ID.CompareTo(((View)y).ID);
}
}
private readonly uint RESERVED = (uint)SysUtil.AllignViewSize(0);
private MmfFile _mmf;
private ArrayList _viewsOpen;
private ArrayList _viewsClosed;
private uint _maxViews;
private uint _viewSize;
/// <summary>
/// Initializes the ViewManager.
/// </summary>
/// <param name="mapper"></param>
public ViewManager(MmfFile mmf, uint viewSize)
{
_mmf = mmf;
_viewSize = viewSize;
_viewsOpen = new ArrayList();
_viewsClosed = new ArrayList();
}
/// <summary>
///
/// </summary>
public int ViewCount
{
get { return _viewsClosed.Count + _viewsOpen.Count; }
}
/// <summary>
/// Initializes the ViewManager.
/// </summary>
/// <param name="mapper"></param>
public void CreateInitialViews(uint initial)
{
_maxViews = initial;
ulong maxSize = _mmf.MaxLength;
int totalViews = (int)(maxSize / _viewSize);
if (maxSize % _viewSize > 0)
{
totalViews ++;
_mmf.SetMaxLength((ulong)(totalViews * _viewSize));
}
for (uint i = 0; i < totalViews; i++)
{
View view = new View(_mmf, i, _viewSize);
OpenView(view);
CloseView(view);
}
ReOpenViews();
}
/// <summary>
/// Maps the view of the file into the memory.
/// </summary>
/// <param name="viewId">Id of the view to be mapped</param>
public View OpenView(View view)
{
if (view == null || view.IsOpen) return view;
try
{
bool scavengeMem = _viewsOpen.Count >= _maxViews;
do
{
// If there isnt enough mem or more than required views are open
// we need to close some views.
if (scavengeMem)
{
View v = GetLeastUsedOpenView();
CloseView(v);
}
try
{
view.Open();
}
catch (OutOfMemoryException)
{
}
scavengeMem = !view.IsOpen;
}
while (scavengeMem && _viewsOpen.Count > 0);
// View still not open so bail out.
if (scavengeMem) return null;
if (!view.HasValidHeader) view.Format();
_viewsClosed.Remove(view);
_viewsOpen.Add(view);
return view;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Maps the view of the file into the memory.
/// </summary>
/// <param name="viewId">Id of the view to be mapped</param>
public View CloseView(View view)
{
if (view == null || !view.IsOpen) return view;
try
{
view.Close();
_viewsOpen.Remove(view);
_viewsClosed.Add(view);
return view;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Unmaps all the views of the file mapped into memory of process.
/// </summary>
public void CloseAllViews()
{
for (int i = _viewsOpen.Count - 1; i >= 0; i--)
{
CloseView((View)_viewsOpen[i]);
}
_viewsClosed.Sort(new ViewIDComparer());
}
/// <summary>
/// Unmaps all the views of the file mapped into memory of process.
/// </summary>
public void ClearAllViews()
{
CloseAllViews();
for (int i = _viewsClosed.Count - 1; i >= 0; i--)
{
View v = OpenView((View)_viewsClosed[i]);
v.Format();
if (i >= _maxViews)
CloseView(v);
}
}
/// <summary>
/// Initializes the ViewManager.
/// </summary>
/// <param name="mapper"></param>
public void ExtendViewsBucket(int numViews)
{
if (numViews < 1) return;
uint viewCount = (uint)(_viewsClosed.Count + _viewsOpen.Count);
try
{
for (uint i = 0; i < numViews; i++)
{
View view = new View(_mmf, viewCount + i, _viewSize);
OpenView(view);
}
}
catch (Exception e)
{
Trace.error("MmfStorage.ExtendViewsBucket" + "Error:", e.ToString());
}
}
/// <summary>
/// Initializes the ViewManager.
/// </summary>
/// <param name="mapper"></param>
public void ShrinkViewsBucket(int numViews)
{
if (numViews < 1) return;
uint viewCount = (uint)(_viewsClosed.Count + _viewsOpen.Count);
CloseAllViews();
for (uint i = 0; i < numViews; i++)
{
_viewsClosed.RemoveAt(_viewsClosed.Count - 1);
if (_viewsClosed.Count < 2) break;
}
_viewsClosed.TrimToSize();
ReOpenViews();
}
/// <summary>
/// Initializes the ViewManager.
/// </summary>
/// <param name="mapper"></param>
public void ReOpenViews()
{
_viewsClosed.Sort(new ViewIDComparer());
for (uint i = 0; i < _maxViews && i < _viewsClosed.Count; i++)
{
OpenView((View)_viewsClosed[0]);
}
}
/// <summary>
/// Gets the view, if not mapped then it mapps the view.
/// </summary>
/// <param name="id">view to be mapped</param>
/// <returns></returns>
private View GetFreeView()
{
if(_viewsClosed.Count > 0)
return (View)_viewsClosed[0];
return null;
}
/// <summary>
/// Gets the view, if not mapped then it mapps the view.
/// </summary>
/// <param name="id">view to be mapped</param>
/// <returns></returns>
public View GetViewByID(uint viewID)
{
for (int i = 0; i < _viewsOpen.Count; i++)
{
View v = (View)_viewsOpen[i];
if (v.ID == viewID)
return v;
}
for (int i = 0; i < _viewsClosed.Count; i++)
{
View v = (View)_viewsClosed[i];
if (v.ID == viewID)
return v;
}
return null;
}
/// <summary>
/// Gets the view, if not mapped then it mapps the view.
/// </summary>
/// <param name="id">view to be mapped</param>
/// <returns></returns>
private View GetLeastUsedFreeView()
{
View minUsed = null;
for (int i = 0; i < _viewsClosed.Count; i++)
{
View v = (View)_viewsClosed[i];
if (minUsed == null)
{
minUsed = v;
continue;
}
if (v.Usage < minUsed.Usage)
minUsed = v;
}
return minUsed;
}
/// <summary>
/// Gets the view, if not mapped then it mapps the view.
/// </summary>
/// <param name="id">view to be mapped</param>
/// <returns></returns>
private View GetLeastUsedOpenView()
{
View minUsed = null;
for (int i = 0; i < _viewsOpen.Count; i++)
{
View v = (View)_viewsOpen[i];
if (minUsed == null)
{
minUsed = v;
continue;
}
if (v.Usage < minUsed.Usage)
minUsed = v;
}
return minUsed;
}
/// <summary>
/// Gets the view, if not mapped then it mapps the view.
/// </summary>
/// <param name="id">view to be mapped</param>
/// <returns></returns>
public View GetMatchingView(uint memRequirements)
{
for (int i = 0; i < _viewsOpen.Count; i++)
{
View v = (View)_viewsOpen[i];
if (v.FreeSpace >= memRequirements)
return v;
}
for (int i = 0; i < _viewsClosed.Count; i++)
{
View v = (View)_viewsClosed[i];
if (v.FreeSpace >= memRequirements)
return OpenView(v);
}
return null;
}
public override string ToString()
{
StringBuilder b = new StringBuilder(1024);
b.Append("Views Open:\r\n");
for(int i=0; i <_viewsOpen.Count; i++)
b.Append(_viewsOpen[i]);
b.Append("Views Closed:\r\n");
for (int i = 0; i < _viewsClosed.Count; i++)
b.Append(_viewsClosed[i]);
return b.ToString();
}
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//* At: 29/08/2012 03:59:42 p.m.
//***************************************************
using SharpKit.JavaScript;
namespace Ext.ux.@event
{
#region Driver
/// <inheritdocs />
/// <summary>
/// <p>This is the base class for <see cref="Ext.ux.event.Recorder">Ext.ux.event.Recorder</see> and <see cref="Ext.ux.event.Player">Ext.ux.event.Player</see>.</p>
/// </summary>
[JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
public partial class Driver : Ext.Base, Ext.util.Observable
{
/// <summary>
/// A config object containing one or more event handlers to be added to this object during initialization. This
/// should be a valid listeners config object as specified in the addListener example for attaching multiple
/// handlers at once.
/// <strong>DOM events from Ext JS <see cref="Ext.Component">Components</see></strong>
/// While <em>some</em> Ext JS Component classes export selected DOM events (e.g. "click", "mouseover" etc), this is usually
/// only done when extra value can be added. For example the <see cref="Ext.view.View">DataView</see>'s <strong><c><see cref="Ext.view.ViewEvents.itemclick">itemclick</see></c></strong> event passing the node clicked on. To access DOM events directly from a
/// child element of a Component, we need to specify the <c>element</c> option to identify the Component property to add a
/// DOM listener to:
/// <code>new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({
/// width: 400,
/// height: 200,
/// dockedItems: [{
/// xtype: 'toolbar'
/// }],
/// listeners: {
/// click: {
/// element: 'el', //bind to the underlying el property on the panel
/// fn: function(){ console.log('click el'); }
/// },
/// dblclick: {
/// element: 'body', //bind to the underlying body property on the panel
/// fn: function(){ console.log('dblclick body'); }
/// }
/// }
/// });
/// </code>
/// </summary>
public JsObject listeners;
/// <summary>
/// Initial suspended call count. Incremented when suspendEvents is called, decremented when resumeEvents is called.
/// Defaults to: <c>0</c>
/// </summary>
public JsNumber eventsSuspended{get;set;}
/// <summary>
/// This object holds a key for any event that has a listener. The listener may be set
/// directly on the instance, or on its class or a super class (via observe) or
/// on the MVC EventBus. The values of this object are truthy
/// (a non-zero number) and falsy (0 or undefined). They do not represent an exact count
/// of listeners. The value for an event is truthy if the event must be fired and is
/// falsy if there is no need to fire the event.
/// The intended use of this property is to avoid the expense of fireEvent calls when
/// there are no listeners. This can be particularly helpful when one would otherwise
/// have to call fireEvent hundreds or thousands of times. It is used like this:
/// <code> if (this.hasListeners.foo) {
/// this.fireEvent('foo', this, arg1);
/// }
/// </code>
/// </summary>
public JsObject hasListeners{get;set;}
/// <summary>
/// true in this class to identify an object as an instantiated Observable, or subclass thereof.
/// Defaults to: <c>true</c>
/// </summary>
public bool isObservable{get;set;}
/// <summary>
/// Adds the specified events to the list of events which this Observable may fire.
/// </summary>
/// <param name="eventNames"><p>Either an object with event names as properties with
/// a value of <c>true</c>. For example:</p>
/// <pre><code>this.addEvents({
/// storeloaded: true,
/// storecleared: true
/// });
/// </code></pre>
/// <p>Or any number of event names as separate parameters. For example:</p>
/// <pre><code>this.addEvents('storeloaded', 'storecleared');
/// </code></pre>
/// </param>
public virtual void addEvents(object eventNames){}
/// <summary>
/// Appends an event handler to this object. For example:
/// <code>myGridPanel.on("mouseover", this.onMouseOver, this);
/// </code>
/// The method also allows for a single argument to be passed which is a config object
/// containing properties which specify multiple events. For example:
/// <code>myGridPanel.on({
/// cellClick: this.onCellClick,
/// mouseover: this.onMouseOver,
/// mouseout: this.onMouseOut,
/// scope: this // Important. Ensure "this" is correct during handler execution
/// });
/// </code>
/// One can also specify options for each event handler separately:
/// <code>myGridPanel.on({
/// cellClick: {fn: this.onCellClick, scope: this, single: true},
/// mouseover: {fn: panel.onMouseOver, scope: panel}
/// });
/// </code>
/// <em>Names</em> of methods in a specified scope may also be used. Note that
/// <c>scope</c> MUST be specified to use this option:
/// <code>myGridPanel.on({
/// cellClick: {fn: 'onCellClick', scope: this, single: true},
/// mouseover: {fn: 'onMouseOver', scope: panel}
/// });
/// </code>
/// </summary>
/// <param name="eventName"><p>The name of the event to listen for.
/// May also be an object who's property names are event names.</p>
/// </param>
/// <param name="fn"><p>The method the event invokes, or <em>if <c>scope</c> is specified, the </em>name* of the method within
/// the specified <c>scope</c>. Will be called with arguments
/// given to <see cref="Ext.util.Observable.fireEvent">fireEvent</see> plus the <c>options</c> parameter described below.</p>
/// </param>
/// <param name="scope"><p>The scope (<c>this</c> reference) in which the handler function is
/// executed. <strong>If omitted, defaults to the object which fired the event.</strong></p>
/// </param>
/// <param name="options"><p>An object containing handler configuration.</p>
/// <p><strong>Note:</strong> Unlike in ExtJS 3.x, the options object will also be passed as the last
/// argument to every event handler.</p>
/// <p>This object may contain any of the following properties:</p>
/// <ul><li><span>scope</span> : <see cref="Object">Object</see><div><p>The scope (<c>this</c> reference) in which the handler function is executed. <strong>If omitted,
/// defaults to the object which fired the event.</strong></p>
/// </div></li><li><span>delay</span> : <see cref="Number">Number</see><div><p>The number of milliseconds to delay the invocation of the handler after the event fires.</p>
/// </div></li><li><span>single</span> : <see cref="bool">Boolean</see><div><p>True to add a handler to handle just the next firing of the event, and then remove itself.</p>
/// </div></li><li><span>buffer</span> : <see cref="Number">Number</see><div><p>Causes the handler to be scheduled to run in an <see cref="Ext.util.DelayedTask">Ext.util.DelayedTask</see> delayed
/// by the specified number of milliseconds. If the event fires again within that time,
/// the original handler is <em>not</em> invoked, but the new handler is scheduled in its place.</p>
/// </div></li><li><span>target</span> : <see cref="Ext.util.Observable">Ext.util.Observable</see><div><p>Only call the handler if the event was fired on the target Observable, <em>not</em> if the event
/// was bubbled up from a child Observable.</p>
/// </div></li><li><span>element</span> : <see cref="String">String</see><div><p><strong>This option is only valid for listeners bound to <see cref="Ext.Component">Components</see>.</strong>
/// The name of a Component property which references an element to add a listener to.</p>
/// <p> This option is useful during Component construction to add DOM event listeners to elements of
/// <see cref="Ext.Component">Components</see> which will exist only after the Component is rendered.
/// For example, to add a click listener to a Panel's body:</p>
/// <pre><code> new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({
/// title: 'The title',
/// listeners: {
/// click: this.handlePanelClick,
/// element: 'body'
/// }
/// });
/// </code></pre>
/// <p><strong>Combining Options</strong></p>
/// <p>Using the options argument, it is possible to combine different types of listeners:</p>
/// <p>A delayed, one-time listener.</p>
/// <pre><code>myPanel.on('hide', this.handleClick, this, {
/// single: true,
/// delay: 100
/// });
/// </code></pre>
/// </div></li></ul></param>
public virtual void addListener(object eventName, System.Delegate fn=null, object scope=null, object options=null){}
/// <summary>
/// Adds listeners to any Observable object (or Ext.Element) which are automatically removed when this Component is
/// destroyed.
/// </summary>
/// <param name="item"><p>The item to which to add a listener/listeners.</p>
/// </param>
/// <param name="ename"><p>The event name, or an object containing event name properties.</p>
/// </param>
/// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p>
/// </param>
/// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference)
/// in which the handler function is executed.</p>
/// </param>
/// <param name="opt"><p>If the <c>ename</c> parameter was an event name, this is the
/// <see cref="Ext.util.Observable.addListener">addListener</see> options.</p>
/// </param>
public virtual void addManagedListener(object item, object ename, System.Delegate fn=null, object scope=null, object opt=null){}
/// <summary>
/// Removes all listeners for this object including the managed listeners
/// </summary>
public virtual void clearListeners(){}
/// <summary>
/// Removes all managed listeners for this object.
/// </summary>
public virtual void clearManagedListeners(){}
/// <summary>
/// Continue to fire event.
/// </summary>
/// <param name="eventName">
/// </param>
/// <param name="args">
/// </param>
/// <param name="bubbles">
/// </param>
public virtual void continueFireEvent(JsString eventName, object args=null, object bubbles=null){}
/// <summary>
/// Creates an event handling function which refires the event from this object as the passed event name.
/// </summary>
/// <param name="newName">
/// </param>
/// <param name="beginEnd"><p>The caller can specify on which indices to slice</p>
/// </param>
/// <returns>
/// <span><see cref="Function">Function</see></span><div>
/// </div>
/// </returns>
public virtual System.Delegate createRelayer(object newName, object beginEnd=null){return null;}
/// <summary>
/// Enables events fired by this Observable to bubble up an owner hierarchy by calling this.getBubbleTarget() if
/// present. There is no implementation in the Observable base class.
/// This is commonly used by Ext.Components to bubble events to owner Containers.
/// See <see cref="Ext.Component.getBubbleTarget">Ext.Component.getBubbleTarget</see>. The default implementation in <see cref="Ext.Component">Ext.Component</see> returns the
/// Component's immediate owner. But if a known target is required, this can be overridden to access the
/// required target more quickly.
/// Example:
/// <code><see cref="Ext.ExtContext.override">Ext.override</see>(<see cref="Ext.form.field.Base">Ext.form.field.Base</see>, {
/// // Add functionality to Field's initComponent to enable the change event to bubble
/// initComponent : <see cref="Ext.Function.createSequence">Ext.Function.createSequence</see>(Ext.form.field.Base.prototype.initComponent, function() {
/// this.enableBubble('change');
/// }),
/// // We know that we want Field's events to bubble directly to the FormPanel.
/// getBubbleTarget : function() {
/// if (!this.formPanel) {
/// this.formPanel = this.findParentByType('form');
/// }
/// return this.formPanel;
/// }
/// });
/// var myForm = new Ext.formPanel({
/// title: 'User Details',
/// items: [{
/// ...
/// }],
/// listeners: {
/// change: function() {
/// // Title goes red if form has been modified.
/// myForm.header.setStyle('color', 'red');
/// }
/// }
/// });
/// </code>
/// </summary>
/// <param name="eventNames"><p>The event name to bubble, or an Array of event names.</p>
/// </param>
public virtual void enableBubble(object eventNames){}
/// <summary>
/// Fires the specified event with the passed parameters (minus the event name, plus the options object passed
/// to addListener).
/// An event may be set to bubble up an Observable parent hierarchy (See <see cref="Ext.Component.getBubbleTarget">Ext.Component.getBubbleTarget</see>) by
/// calling <see cref="Ext.util.Observable.enableBubble">enableBubble</see>.
/// </summary>
/// <param name="eventName"><p>The name of the event to fire.</p>
/// </param>
/// <param name="args"><p>Variable number of parameters are passed to handlers.</p>
/// </param>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div><p>returns false if any of the handlers return false otherwise it returns true.</p>
/// </div>
/// </returns>
public virtual bool fireEvent(JsString eventName, params object[] args){return false;}
/// <summary>
/// Gets the bubbling parent for an Observable
/// </summary>
/// <returns>
/// <span><see cref="Ext.util.Observable">Ext.util.Observable</see></span><div><p>The bubble parent. null is returned if no bubble target exists</p>
/// </div>
/// </returns>
public virtual Ext.util.Observable getBubbleParent(){return null;}
/// <summary>
/// Returns the number of milliseconds since start was called.
/// </summary>
public void getTimestamp(){}
/// <summary>
/// Checks to see if this object has any listeners for a specified event, or whether the event bubbles. The answer
/// indicates whether the event needs firing or not.
/// </summary>
/// <param name="eventName"><p>The name of the event to check for</p>
/// </param>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div><p><c>true</c> if the event is being listened for or bubbles, else <c>false</c></p>
/// </div>
/// </returns>
public virtual bool hasListener(JsString eventName){return false;}
/// <summary>
/// Shorthand for addManagedListener.
/// Adds listeners to any Observable object (or <see cref="Ext.dom.Element">Ext.Element</see>) which are automatically removed when this Component is
/// destroyed.
/// </summary>
/// <param name="item"><p>The item to which to add a listener/listeners.</p>
/// </param>
/// <param name="ename"><p>The event name, or an object containing event name properties.</p>
/// </param>
/// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p>
/// </param>
/// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference)
/// in which the handler function is executed.</p>
/// </param>
/// <param name="opt"><p>If the <c>ename</c> parameter was an event name, this is the
/// <see cref="Ext.util.Observable.addListener">addListener</see> options.</p>
/// </param>
public virtual void mon(object item, object ename, System.Delegate fn=null, object scope=null, object opt=null){}
/// <summary>
/// Shorthand for removeManagedListener.
/// Removes listeners that were added by the <see cref="Ext.util.Observable.mon">mon</see> method.
/// </summary>
/// <param name="item"><p>The item from which to remove a listener/listeners.</p>
/// </param>
/// <param name="ename"><p>The event name, or an object containing event name properties.</p>
/// </param>
/// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p>
/// </param>
/// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference)
/// in which the handler function is executed.</p>
/// </param>
public virtual void mun(object item, object ename, System.Delegate fn=null, object scope=null){}
/// <summary>
/// Shorthand for addListener.
/// Appends an event handler to this object. For example:
/// <code>myGridPanel.on("mouseover", this.onMouseOver, this);
/// </code>
/// The method also allows for a single argument to be passed which is a config object
/// containing properties which specify multiple events. For example:
/// <code>myGridPanel.on({
/// cellClick: this.onCellClick,
/// mouseover: this.onMouseOver,
/// mouseout: this.onMouseOut,
/// scope: this // Important. Ensure "this" is correct during handler execution
/// });
/// </code>
/// One can also specify options for each event handler separately:
/// <code>myGridPanel.on({
/// cellClick: {fn: this.onCellClick, scope: this, single: true},
/// mouseover: {fn: panel.onMouseOver, scope: panel}
/// });
/// </code>
/// <em>Names</em> of methods in a specified scope may also be used. Note that
/// <c>scope</c> MUST be specified to use this option:
/// <code>myGridPanel.on({
/// cellClick: {fn: 'onCellClick', scope: this, single: true},
/// mouseover: {fn: 'onMouseOver', scope: panel}
/// });
/// </code>
/// </summary>
/// <param name="eventName"><p>The name of the event to listen for.
/// May also be an object who's property names are event names.</p>
/// </param>
/// <param name="fn"><p>The method the event invokes, or <em>if <c>scope</c> is specified, the </em>name* of the method within
/// the specified <c>scope</c>. Will be called with arguments
/// given to <see cref="Ext.util.Observable.fireEvent">fireEvent</see> plus the <c>options</c> parameter described below.</p>
/// </param>
/// <param name="scope"><p>The scope (<c>this</c> reference) in which the handler function is
/// executed. <strong>If omitted, defaults to the object which fired the event.</strong></p>
/// </param>
/// <param name="options"><p>An object containing handler configuration.</p>
/// <p><strong>Note:</strong> Unlike in ExtJS 3.x, the options object will also be passed as the last
/// argument to every event handler.</p>
/// <p>This object may contain any of the following properties:</p>
/// <ul><li><span>scope</span> : <see cref="Object">Object</see><div><p>The scope (<c>this</c> reference) in which the handler function is executed. <strong>If omitted,
/// defaults to the object which fired the event.</strong></p>
/// </div></li><li><span>delay</span> : <see cref="Number">Number</see><div><p>The number of milliseconds to delay the invocation of the handler after the event fires.</p>
/// </div></li><li><span>single</span> : <see cref="bool">Boolean</see><div><p>True to add a handler to handle just the next firing of the event, and then remove itself.</p>
/// </div></li><li><span>buffer</span> : <see cref="Number">Number</see><div><p>Causes the handler to be scheduled to run in an <see cref="Ext.util.DelayedTask">Ext.util.DelayedTask</see> delayed
/// by the specified number of milliseconds. If the event fires again within that time,
/// the original handler is <em>not</em> invoked, but the new handler is scheduled in its place.</p>
/// </div></li><li><span>target</span> : <see cref="Ext.util.Observable">Ext.util.Observable</see><div><p>Only call the handler if the event was fired on the target Observable, <em>not</em> if the event
/// was bubbled up from a child Observable.</p>
/// </div></li><li><span>element</span> : <see cref="String">String</see><div><p><strong>This option is only valid for listeners bound to <see cref="Ext.Component">Components</see>.</strong>
/// The name of a Component property which references an element to add a listener to.</p>
/// <p> This option is useful during Component construction to add DOM event listeners to elements of
/// <see cref="Ext.Component">Components</see> which will exist only after the Component is rendered.
/// For example, to add a click listener to a Panel's body:</p>
/// <pre><code> new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({
/// title: 'The title',
/// listeners: {
/// click: this.handlePanelClick,
/// element: 'body'
/// }
/// });
/// </code></pre>
/// <p><strong>Combining Options</strong></p>
/// <p>Using the options argument, it is possible to combine different types of listeners:</p>
/// <p>A delayed, one-time listener.</p>
/// <pre><code>myPanel.on('hide', this.handleClick, this, {
/// single: true,
/// delay: 100
/// });
/// </code></pre>
/// </div></li></ul></param>
public virtual void on(object eventName, System.Delegate fn=null, object scope=null, object options=null){}
/// <summary>
/// Prepares a given class for observable instances. This method is called when a
/// class derives from this class or uses this class as a mixin.
/// </summary>
/// <param name="T"><p>The class constructor to prepare.</p>
/// </param>
public virtual void prepareClass(System.Delegate T){}
/// <summary>
/// Relays selected events from the specified Observable as if the events were fired by this.
/// For example if you are extending Grid, you might decide to forward some events from store.
/// So you can do this inside your initComponent:
/// <code>this.relayEvents(this.getStore(), ['load']);
/// </code>
/// The grid instance will then have an observable 'load' event which will be passed the
/// parameters of the store's load event and any function fired with the grid's load event
/// would have access to the grid using the <c>this</c> keyword.
/// </summary>
/// <param name="origin"><p>The Observable whose events this object is to relay.</p>
/// </param>
/// <param name="events"><p>Array of event names to relay.</p>
/// </param>
/// <param name="prefix"><p>A common prefix to prepend to the event names. For example:</p>
/// <pre><code>this.relayEvents(this.getStore(), ['load', 'clear'], 'store');
/// </code></pre>
/// <p>Now the grid will forward 'load' and 'clear' events of store as 'storeload' and 'storeclear'.</p>
/// </param>
public virtual void relayEvents(object origin, JsArray<String> events, object prefix=null){}
/// <summary>
/// Removes an event handler.
/// </summary>
/// <param name="eventName"><p>The type of event the handler was associated with.</p>
/// </param>
/// <param name="fn"><p>The handler to remove. <strong>This must be a reference to the function passed into the
/// <see cref="Ext.util.Observable.addListener">addListener</see> call.</strong></p>
/// </param>
/// <param name="scope"><p>The scope originally specified for the handler. It must be the same as the
/// scope argument specified in the original call to <see cref="Ext.util.Observable.addListener">addListener</see> or the listener will not be removed.</p>
/// </param>
public virtual void removeListener(JsString eventName, System.Delegate fn, object scope=null){}
/// <summary>
/// Removes listeners that were added by the mon method.
/// </summary>
/// <param name="item"><p>The item from which to remove a listener/listeners.</p>
/// </param>
/// <param name="ename"><p>The event name, or an object containing event name properties.</p>
/// </param>
/// <param name="fn"><p>If the <c>ename</c> parameter was an event name, this is the handler function.</p>
/// </param>
/// <param name="scope"><p>If the <c>ename</c> parameter was an event name, this is the scope (<c>this</c> reference)
/// in which the handler function is executed.</p>
/// </param>
public virtual void removeManagedListener(object item, object ename, System.Delegate fn=null, object scope=null){}
/// <summary>
/// Remove a single managed listener item
/// </summary>
/// <param name="isClear"><p>True if this is being called during a clear</p>
/// </param>
/// <param name="managedListener"><p>The managed listener item
/// See removeManagedListener for other args</p>
/// </param>
public virtual void removeManagedListenerItem(bool isClear, object managedListener){}
/// <summary>
/// Resumes firing events (see suspendEvents).
/// If events were suspended using the <c>queueSuspended</c> parameter, then all events fired
/// during event suspension will be sent to any listeners now.
/// </summary>
public virtual void resumeEvents(){}
/// <summary>
/// Starts this object. If this object is already started, nothing happens.
/// </summary>
public void start(){}
/// <summary>
/// Stops this object. If this object is not started, nothing happens.
/// </summary>
public void stop(){}
/// <summary>
/// Suspends the firing of all events. (see resumeEvents)
/// </summary>
/// <param name="queueSuspended"><p>Pass as true to queue up suspended events to be fired
/// after the <see cref="Ext.util.Observable.resumeEvents">resumeEvents</see> call instead of discarding all suspended events.</p>
/// </param>
public virtual void suspendEvents(bool queueSuspended){}
/// <summary>
/// Shorthand for removeListener.
/// Removes an event handler.
/// </summary>
/// <param name="eventName"><p>The type of event the handler was associated with.</p>
/// </param>
/// <param name="fn"><p>The handler to remove. <strong>This must be a reference to the function passed into the
/// <see cref="Ext.util.Observable.addListener">addListener</see> call.</strong></p>
/// </param>
/// <param name="scope"><p>The scope originally specified for the handler. It must be the same as the
/// scope argument specified in the original call to <see cref="Ext.util.Observable.addListener">addListener</see> or the listener will not be removed.</p>
/// </param>
public virtual void un(JsString eventName, System.Delegate fn, object scope=null){}
public Driver(DriverConfig config){}
public Driver(){}
public Driver(params object[] args){}
}
#endregion
#region DriverConfig
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class DriverConfig : Ext.BaseConfig
{
/// <summary>
/// A config object containing one or more event handlers to be added to this object during initialization. This
/// should be a valid listeners config object as specified in the addListener example for attaching multiple
/// handlers at once.
/// <strong>DOM events from Ext JS <see cref="Ext.Component">Components</see></strong>
/// While <em>some</em> Ext JS Component classes export selected DOM events (e.g. "click", "mouseover" etc), this is usually
/// only done when extra value can be added. For example the <see cref="Ext.view.View">DataView</see>'s <strong><c><see cref="Ext.view.ViewEvents.itemclick">itemclick</see></c></strong> event passing the node clicked on. To access DOM events directly from a
/// child element of a Component, we need to specify the <c>element</c> option to identify the Component property to add a
/// DOM listener to:
/// <code>new <see cref="Ext.panel.Panel">Ext.panel.Panel</see>({
/// width: 400,
/// height: 200,
/// dockedItems: [{
/// xtype: 'toolbar'
/// }],
/// listeners: {
/// click: {
/// element: 'el', //bind to the underlying el property on the panel
/// fn: function(){ console.log('click el'); }
/// },
/// dblclick: {
/// element: 'body', //bind to the underlying body property on the panel
/// fn: function(){ console.log('dblclick body'); }
/// }
/// }
/// });
/// </code>
/// </summary>
public JsObject listeners;
public DriverConfig(params object[] args){}
}
#endregion
#region DriverEvents
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class DriverEvents : Ext.BaseEvents
{
/// <summary>
/// Fires when this object is started.
/// </summary>
/// <param name="this">
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void start(Driver @this, object eOpts){}
/// <summary>
/// Fires when this object is stopped.
/// </summary>
/// <param name="this">
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void stop(Driver @this, object eOpts){}
public DriverEvents(params object[] args){}
}
#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.Runtime.CompilerServices;
namespace System.Numerics
{
// This file contains the definitions for all of the JIT intrinsic methods and properties that are recognized by the current x64 JIT compiler.
// The implementation defined here is used in any circumstance where the JIT fails to recognize these members as intrinsic.
// The JIT recognizes these methods and properties by name and signature: if either is changed, the JIT will no longer recognize the member.
// Some methods declared here are not strictly intrinsic, but delegate to an intrinsic method. For example, only one overload of CopyTo()
// is actually recognized by the JIT, but both are here for simplicity.
public partial struct Vector3
{
/// <summary>
/// The X component of the vector.
/// </summary>
public Single X;
/// <summary>
/// The Y component of the vector.
/// </summary>
public Single Y;
/// <summary>
/// The Z component of the vector.
/// </summary>
public Single Z;
#region Constructors
/// <summary>
/// Constructs a vector whose elements are all the single specified value.
/// </summary>
/// <param name="value">The element to fill the vector with.</param>
[JitIntrinsic]
public Vector3(Single value) : this(value, value, value) { }
/// <summary>
/// Constructs a Vector3 from the given Vector2 and a third value.
/// </summary>
/// <param name="value">The Vector to extract X and Y components from.</param>
/// <param name="z">The Z component.</param>
public Vector3(Vector2 value, float z) : this(value.X, value.Y, z) { }
/// <summary>
/// Constructs a vector with the given individual elements.
/// </summary>
/// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param>
/// <param name="z">The Z component.</param>
[JitIntrinsic]
public Vector3(Single x, Single y, Single z)
{
X = x;
Y = y;
Z = z;
}
#endregion Constructors
#region Public Instance Methods
/// <summary>
/// Copies the contents of the vector into the given array.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array)
{
CopyTo(array, 0);
}
/// <summary>
/// Copies the contents of the vector into the given array, starting from index.
/// </summary>
/// <exception cref="ArgumentNullException">If array is null.</exception>
/// <exception cref="RankException">If array is multidimensional.</exception>
/// <exception cref="ArgumentOutOfRangeException">If index is greater than end of the array or index is less than zero.</exception>
/// <exception cref="ArgumentException">If number of elements in source vector is greater than those available in destination array.</exception>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array, int index)
{
if (array == null)
{
// Match the JIT's exception type here. For perf, a NullReference is thrown instead of an ArgumentNull.
throw new NullReferenceException(SR.Arg_NullArgumentNullRef);
}
if (index < 0 || index >= array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.Arg_ArgumentOutOfRangeException, index));
}
if ((array.Length - index) < 3)
{
throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index));
}
array[index] = X;
array[index + 1] = Y;
array[index + 2] = Z;
}
/// <summary>
/// Returns a boolean indicating whether the given Vector3 is equal to this Vector3 instance.
/// </summary>
/// <param name="other">The Vector3 to compare this instance to.</param>
/// <returns>True if the other Vector3 is equal to this instance; False otherwise.</returns>
[JitIntrinsic]
public bool Equals(Vector3 other)
{
return X == other.X &&
Y == other.Y &&
Z == other.Z;
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="vector1">The first vector.</param>
/// <param name="vector2">The second vector.</param>
/// <returns>The dot product.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector3 vector1, Vector3 vector2)
{
return vector1.X * vector2.X +
vector1.Y * vector2.Y +
vector1.Z * vector2.Z;
}
/// <summary>
/// Returns a vector whose elements are the minimum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The minimized vector.</returns>
[JitIntrinsic]
public static Vector3 Min(Vector3 value1, Vector3 value2)
{
return new Vector3(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y,
(value1.Z < value2.Z) ? value1.Z : value2.Z);
}
/// <summary>
/// Returns a vector whose elements are the maximum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The maximized vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Max(Vector3 value1, Vector3 value2)
{
return new Vector3(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y,
(value1.Z > value2.Z) ? value1.Z : value2.Z);
}
/// <summary>
/// Returns a vector whose elements are the absolute values of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The absolute value vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Abs(Vector3 value)
{
return new Vector3(MathF.Abs(value.X), MathF.Abs(value.Y), MathF.Abs(value.Z));
}
/// <summary>
/// Returns a vector whose elements are the square root of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The square root vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 SquareRoot(Vector3 value)
{
return new Vector3(MathF.Sqrt(value.X), MathF.Sqrt(value.Y), MathF.Sqrt(value.Z));
}
#endregion Public Static Methods
#region Public Static Operators
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator +(Vector3 left, Vector3 right)
{
return new Vector3(left.X + right.X, left.Y + right.Y, left.Z + right.Z);
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator -(Vector3 left, Vector3 right)
{
return new Vector3(left.X - right.X, left.Y - right.Y, left.Z - right.Z);
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Vector3 left, Vector3 right)
{
return new Vector3(left.X * right.X, left.Y * right.Y, left.Z * right.Z);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Vector3 left, Single right)
{
return left * new Vector3(right);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Single left, Vector3 right)
{
return new Vector3(left) * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator /(Vector3 left, Vector3 right)
{
return new Vector3(left.X / right.X, left.Y / right.Y, left.Z / right.Z);
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator /(Vector3 value1, float value2)
{
float invDiv = 1.0f / value2;
return new Vector3(
value1.X * invDiv,
value1.Y * invDiv,
value1.Z * invDiv);
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator -(Vector3 value)
{
return Zero - value;
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are equal; False otherwise.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector3 left, Vector3 right)
{
return (left.X == right.X &&
left.Y == right.Y &&
left.Z == right.Z);
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are not equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are not equal; False if they are equal.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Vector3 left, Vector3 right)
{
return (left.X != right.X ||
left.Y != right.Y ||
left.Z != right.Z);
}
#endregion Public Static Operators
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
#pragma warning disable 1634, 1691
#pragma warning disable 56517
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Runspaces
{
internal delegate void RunspaceConfigurationEntryUpdateEventHandler();
/// <summary>
/// Define class for runspace configuration entry collection.
/// </summary>
/// <!--
/// Runspace configuration entry collection is used for handling following
/// problems for runspace configuration entries.
///
/// 1. synchronization. Since multiple runspaces may be sharing the same
/// runspace configuration, it is essential all the entry collections
/// (cmdlets, providers, assemblies, types, formats) are thread-safe.
/// 2. prepending/appending. Data for types and formats are order
/// sensitive. It is required for supporting prepending/appending to
/// the list and ability to remove the prepended/appended items.
/// 3. update. Update to the data needs to be communicated to other monad
/// components. For example, if cmdlets/providers list is updated, it
/// has to be communicated to engine.
/// -->
#if CORECLR
internal
#else
public
#endif
sealed class RunspaceConfigurationEntryCollection<T> : IEnumerable<T> where T : RunspaceConfigurationEntry
{
/// <summary>
/// Constructor
/// </summary>
public RunspaceConfigurationEntryCollection()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="items"></param>
public RunspaceConfigurationEntryCollection(IEnumerable<T> items)
{
if (items == null)
{
throw PSTraceSource.NewArgumentNullException("item");
}
AddBuiltInItem(items);
}
private Collection<T> _data = new Collection<T>();
private int _builtInEnd = 0; // this is the index of first after item.
private Collection<T> _updateList = new Collection<T>();
internal Collection<T> UpdateList
{
get
{
return _updateList;
}
}
/// <summary>
/// Get items at a index position.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public T this[int index]
{
get
{
lock (_syncObject)
{
return _data[index];
}
}
}
/// <summary>
/// Get number of items in the collection.
/// </summary>
public int Count
{
get
{
lock (_syncObject)
{
return _data.Count;
}
}
}
/// <summary>
/// Reset items in the collection
/// </summary>
public void Reset()
{
lock (_syncObject)
{
for (int i = _data.Count - 1; i >= 0; i--)
{
if (!_data[i].BuiltIn)
{
RecordRemove(_data[i]);
_data.RemoveAt(i);
}
}
_builtInEnd = _data.Count;
}
}
/// <summary>
/// Remove one item from the collection
/// </summary>
/// <param name="index"></param>
/// <exception cref="PSArgumentOutOfRangeException">when <paramref name="index"/> is out of range.</exception>
public void RemoveItem(int index)
{
lock (_syncObject)
{
if (index < 0 || index >= _data.Count)
{
throw PSTraceSource.NewArgumentOutOfRangeException("index", index);
}
RecordRemove(_data[index]);
_data.RemoveAt(index);
if (index < _builtInEnd)
_builtInEnd--;
return;
}
}
/// <summary>
/// Remove multiple items in the collection.
/// </summary>
/// <param name="index"></param>
/// <param name="count"></param>
/// <exception cref="PSArgumentOutOfRangeException">when <paramref name="index"/> is out of range.</exception>
public void RemoveItem(int index, int count)
{
lock (_syncObject)
{
if (index < 0 || index + count > _data.Count)
{
throw PSTraceSource.NewArgumentOutOfRangeException("index", index);
}
for (int i = index + count - 1; i >= index; i--)
{
RecordRemove(_data[i]);
_data.RemoveAt(i);
}
int _numBeforeBuiltInEnd = Math.Min(count, _builtInEnd - index);
if (_numBeforeBuiltInEnd > 0)
_builtInEnd -= _numBeforeBuiltInEnd;
return;
}
}
/// <summary>
/// Remove one item from the collection
/// </summary>
/// <param name="item"></param>
internal void Remove(T item)
{
lock (_syncObject)
{
int index = _data.IndexOf(item);
if (index < 0 || index >= _data.Count)
{
Dbg.Assert(false, "Index from which to remove the item is out of range.");
throw PSTraceSource.NewArgumentOutOfRangeException("index", index);
}
RecordRemove(item);
_data.Remove(item);
if (index < _builtInEnd)
_builtInEnd--;
return;
}
}
/// <summary>
/// Prepend an item to the collection.
/// </summary>
/// <param name="item"></param>
public void Prepend(T item)
{
lock (_syncObject)
{
RecordAdd(item);
item._builtIn = false;
_data.Insert(0, item);
_builtInEnd++;
}
}
/// <summary>
/// Prepend items into the collection
/// </summary>
/// <param name="items"></param>
public void Prepend(IEnumerable<T> items)
{
if (items == null)
{
throw new ArgumentNullException("items");
}
lock (_syncObject)
{
int i = 0;
foreach (T t in items)
{
RecordAdd(t);
t._builtIn = false;
_data.Insert(i++, t);
_builtInEnd++;
}
}
}
/// <summary>
/// Append one item to the collection
/// </summary>
/// <param name="item"></param>
public void Append(T item)
{
lock (_syncObject)
{
RecordAdd(item);
item._builtIn = false;
_data.Add(item);
}
}
/// <summary>
/// Append items to the collection.
/// </summary>
/// <param name="items"></param>
public void Append(IEnumerable<T> items)
{
if (items == null)
{
throw new ArgumentNullException("items");
}
lock (_syncObject)
{
foreach (T t in items)
{
RecordAdd(t);
t._builtIn = false;
_data.Add(t);
}
}
}
internal void AddBuiltInItem(T item)
{
lock (_syncObject)
{
item._builtIn = true;
RecordAdd(item);
_data.Insert(_builtInEnd, item);
_builtInEnd++;
}
}
internal void AddBuiltInItem(IEnumerable<T> items)
{
lock (_syncObject)
{
foreach (T t in items)
{
t._builtIn = true;
RecordAdd(t);
_data.Insert(_builtInEnd, t);
_builtInEnd++;
}
}
}
internal void RemovePSSnapIn(string PSSnapinName)
{
lock (_syncObject)
{
for (int i = _data.Count - 1; i >= 0; i--)
{
if (_data[i].PSSnapIn != null)
{
if (_data[i].PSSnapIn.Name.Equals(PSSnapinName, StringComparison.Ordinal))
{
RecordRemove(_data[i]);
_data.RemoveAt(i);
if (i < _builtInEnd)
_builtInEnd--;
}
}
}
}
}
/// <summary>
/// Get enumerator for this collection.
/// </summary>
/// <returns></returns>
/// <!--
/// Enumerator work is not thread safe by default. Any code trying
/// to do enumeration on this collection should lock it first.
///
/// Need to document this.
/// -->
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _data.GetEnumerator();
}
/// <summary>
/// Get enumerator for this collection.
/// </summary>
/// <returns></returns>
/// <!--
/// Enumerator work is not thread safe by default. Any code trying
/// to do enumeration on this collection should lock it first.
///
/// Need to document this.
/// -->
IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator()
{
return _data.GetEnumerator();
}
/// <summary>
/// Update others about the collection change.
/// </summary>
public void Update()
{
Update(false);
}
internal void Update(bool force)
{
lock (_syncObject)
{
if (OnUpdate != null && (force || _updateList.Count > 0))
{
OnUpdate();
// Here we need to clear the Action for each item
// since _updateList is sharing data with _data.
foreach (T t in _updateList)
{
t._action = UpdateAction.None;
}
_updateList.Clear();
}
}
}
private void RecordRemove(T t)
{
// if this item was added recently, simply remove the add action.
if (t.Action == UpdateAction.Add)
{
t._action = UpdateAction.None;
_updateList.Remove(t);
}
else
{
t._action = UpdateAction.Remove;
_updateList.Add(t);
}
}
private void RecordAdd(T t)
{
// if this item was removed recently, simply remove the add action.
if (t.Action == UpdateAction.Remove)
{
t._action = UpdateAction.None;
_updateList.Remove(t);
}
else
{
t._action = UpdateAction.Add;
_updateList.Add(t);
}
}
//object to use for locking
private object _syncObject = new object();
/// <summary>
/// OnUpdate handler should lock the object itself.
/// </summary>
internal event RunspaceConfigurationEntryUpdateEventHandler OnUpdate;
}
}
#pragma warning restore 56517
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\TestMultiBlockStreamer.tcl
// output file is AVTestMultiBlockStreamer.cs
/// <summary>
/// The testing class derived from AVTestMultiBlockStreamer
/// </summary>
public class AVTestMultiBlockStreamerClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVTestMultiBlockStreamer(String [] argv)
{
//Prefix Content is: ""
// we need to use composite data pipeline with multiblock datasets[]
alg = new vtkAlgorithm();
pip = new vtkCompositeDataPipeline();
vtkAlgorithm.SetDefaultExecutivePrototype((vtkExecutive)pip);
//skipping Delete pip
Ren1 = vtkRenderer.New();
Ren1.SetBackground((double)0.33,(double)0.35,(double)0.43);
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)Ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
Plot3D0 = new vtkMultiBlockPLOT3DReader();
Plot3D0.SetFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combxyz.bin");
Plot3D0.SetQFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combq.bin");
Plot3D0.SetBinaryFile((int)1);
Plot3D0.SetMultiGrid((int)0);
Plot3D0.SetHasByteCount((int)0);
Plot3D0.SetIBlanking((int)0);
Plot3D0.SetTwoDimensionalGeometry((int)0);
Plot3D0.SetForceRead((int)0);
Plot3D0.SetByteOrder((int)0);
Plot3D0.Update();
Geometry5 = new vtkStructuredGridOutlineFilter();
Geometry5.SetInputData((vtkDataSet)Plot3D0.GetOutput().GetBlock(0));
Mapper5 = vtkPolyDataMapper.New();
Mapper5.SetInputConnection((vtkAlgorithmOutput)Geometry5.GetOutputPort());
Mapper5.SetImmediateModeRendering((int)1);
Mapper5.UseLookupTableScalarRangeOn();
Mapper5.SetScalarVisibility((int)0);
Mapper5.SetScalarModeToDefault();
Actor5 = new vtkActor();
Actor5.SetMapper((vtkMapper)Mapper5);
Actor5.GetProperty().SetRepresentationToSurface();
Actor5.GetProperty().SetInterpolationToGouraud();
Actor5.GetProperty().SetAmbient((double)0.15);
Actor5.GetProperty().SetDiffuse((double)0.85);
Actor5.GetProperty().SetSpecular((double)0.1);
Actor5.GetProperty().SetSpecularPower((double)100);
Actor5.GetProperty().SetSpecularColor((double)1,(double)1,(double)1);
Actor5.GetProperty().SetColor((double)1,(double)1,(double)1);
Ren1.AddActor((vtkProp)Actor5);
ExtractGrid[0] = new vtkExtractGrid();
ExtractGrid[0].SetInputData((vtkDataSet)Plot3D0.GetOutput().GetBlock(0));
ExtractGrid[0].SetVOI((int)0,(int)14,(int)0,(int)32,(int)0,(int)24);
ExtractGrid[0].SetSampleRate((int)1,(int)1,(int)1);
ExtractGrid[0].SetIncludeBoundary((int)0);
ExtractGrid[1] = new vtkExtractGrid();
ExtractGrid[1].SetInputData((vtkDataSet)Plot3D0.GetOutput().GetBlock(0));
ExtractGrid[1].SetVOI((int)14,(int)29,(int)0,(int)32,(int)0,(int)24);
ExtractGrid[1].SetSampleRate((int)1,(int)1,(int)1);
ExtractGrid[1].SetIncludeBoundary((int)0);
ExtractGrid[2] = new vtkExtractGrid();
ExtractGrid[2].SetInputData((vtkDataSet)Plot3D0.GetOutput().GetBlock(0));
ExtractGrid[2].SetVOI((int)29,(int)56,(int)0,(int)32,(int)0,(int)24);
ExtractGrid[2].SetSampleRate((int)1,(int)1,(int)1);
ExtractGrid[2].SetIncludeBoundary((int)0);
LineSourceWidget0 = new vtkLineSource();
LineSourceWidget0.SetPoint1((double)3.05638,(double)-3.00497,(double)28.2211);
LineSourceWidget0.SetPoint2((double)3.05638,(double)3.95916,(double)28.2211);
LineSourceWidget0.SetResolution((int)20);
mbds = new vtkMultiBlockDataSet();
mbds.SetNumberOfBlocks((uint)3);
i = 0;
while((i) < 3)
{
ExtractGrid[i].Update();
sg[i] = vtkStructuredGrid.New();
sg[i].ShallowCopy(ExtractGrid[i].GetOutput());
mbds.SetBlock((uint)i, sg[i]);
//skipping Delete sg[i]
i = i + 1;
}
Stream0 = new vtkStreamTracer();
Stream0.SetInputData((vtkDataObject)mbds);
Stream0.SetSourceConnection(LineSourceWidget0.GetOutputPort());
Stream0.SetIntegrationStepUnit(2);
Stream0.SetMaximumPropagation((double)20);
Stream0.SetInitialIntegrationStep((double)0.5);
Stream0.SetIntegrationDirection((int)0);
Stream0.SetIntegratorType((int)0);
Stream0.SetMaximumNumberOfSteps((int)2000);
Stream0.SetTerminalSpeed((double)1e-12);
//skipping Delete mbds
aa = new vtkAssignAttribute();
aa.SetInputConnection((vtkAlgorithmOutput)Stream0.GetOutputPort());
aa.Assign((string)"Normals",(string)"NORMALS",(string)"POINT_DATA");
Ribbon0 = new vtkRibbonFilter();
Ribbon0.SetInputConnection((vtkAlgorithmOutput)aa.GetOutputPort());
Ribbon0.SetWidth((double)0.1);
Ribbon0.SetAngle((double)0);
Ribbon0.SetDefaultNormal((double)0,(double)0,(double)1);
Ribbon0.SetVaryWidth((int)0);
LookupTable1 = new vtkLookupTable();
LookupTable1.SetNumberOfTableValues((int)256);
LookupTable1.SetHueRange((double)0,(double)0.66667);
LookupTable1.SetSaturationRange((double)1,(double)1);
LookupTable1.SetValueRange((double)1,(double)1);
LookupTable1.SetTableRange((double)0.197813,(double)0.710419);
LookupTable1.SetVectorComponent((int)0);
LookupTable1.Build();
Mapper10 = vtkPolyDataMapper.New();
Mapper10.SetInputConnection((vtkAlgorithmOutput)Ribbon0.GetOutputPort());
Mapper10.SetImmediateModeRendering((int)1);
Mapper10.UseLookupTableScalarRangeOn();
Mapper10.SetScalarVisibility((int)1);
Mapper10.SetScalarModeToUsePointFieldData();
Mapper10.SelectColorArray((string)"Density");
Mapper10.SetLookupTable((vtkScalarsToColors)LookupTable1);
Actor10 = new vtkActor();
Actor10.SetMapper((vtkMapper)Mapper10);
Actor10.GetProperty().SetRepresentationToSurface();
Actor10.GetProperty().SetInterpolationToGouraud();
Actor10.GetProperty().SetAmbient((double)0.15);
Actor10.GetProperty().SetDiffuse((double)0.85);
Actor10.GetProperty().SetSpecular((double)0);
Actor10.GetProperty().SetSpecularPower((double)1);
Actor10.GetProperty().SetSpecularColor((double)1,(double)1,(double)1);
Ren1.AddActor((vtkProp)Actor10);
// enable user interface interactor[]
iren.Initialize();
// prevent the tk window from showing up then start the event loop[]
vtkAlgorithm.SetDefaultExecutivePrototype(null);
//skipping Delete alg
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkAlgorithm alg;
static vtkCompositeDataPipeline pip;
static vtkRenderer Ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkMultiBlockPLOT3DReader Plot3D0;
static vtkStructuredGridOutlineFilter Geometry5;
static vtkPolyDataMapper Mapper5;
static vtkActor Actor5;
static vtkExtractGrid[] ExtractGrid = new vtkExtractGrid[100];
static vtkLineSource LineSourceWidget0;
static vtkMultiBlockDataSet mbds;
static int i;
static vtkStructuredGrid[] sg = new vtkStructuredGrid[100];
static vtkStreamTracer Stream0;
static vtkAssignAttribute aa;
static vtkRibbonFilter Ribbon0;
static vtkLookupTable LookupTable1;
static vtkPolyDataMapper Mapper10;
static vtkActor Actor10;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkAlgorithm Getalg()
{
return alg;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setalg(vtkAlgorithm toSet)
{
alg = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCompositeDataPipeline Getpip()
{
return pip;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setpip(vtkCompositeDataPipeline toSet)
{
pip = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer GetRen1()
{
return Ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetRen1(vtkRenderer toSet)
{
Ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkMultiBlockPLOT3DReader GetPlot3D0()
{
return Plot3D0;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetPlot3D0(vtkMultiBlockPLOT3DReader toSet)
{
Plot3D0 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStructuredGridOutlineFilter GetGeometry5()
{
return Geometry5;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetGeometry5(vtkStructuredGridOutlineFilter toSet)
{
Geometry5 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetMapper5()
{
return Mapper5;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetMapper5(vtkPolyDataMapper toSet)
{
Mapper5 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetActor5()
{
return Actor5;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetActor5(vtkActor toSet)
{
Actor5 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkExtractGrid GetExtractGrid0()
{
return ExtractGrid[0];
}
///<summary> A Set Method for Static Variables </summary>
public static void SetExtractGrid0(vtkExtractGrid toSet)
{
ExtractGrid[0] = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkExtractGrid GetExtractGrid1()
{
return ExtractGrid[1];
}
///<summary> A Set Method for Static Variables </summary>
public static void SetExtractGrid1(vtkExtractGrid toSet)
{
ExtractGrid[1] = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkExtractGrid GetExtractGrid2()
{
return ExtractGrid[2];
}
///<summary> A Set Method for Static Variables </summary>
public static void SetExtractGrid2(vtkExtractGrid toSet)
{
ExtractGrid[2] = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkLineSource GetLineSourceWidget0()
{
return LineSourceWidget0;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetLineSourceWidget0(vtkLineSource toSet)
{
LineSourceWidget0 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkMultiBlockDataSet Getmbds()
{
return mbds;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmbds(vtkMultiBlockDataSet toSet)
{
mbds = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Geti()
{
return i;
}
///<summary> A Set Method for Static Variables </summary>
public static void Seti(int toSet)
{
i = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStructuredGrid[] Getsg()
{
return sg;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setsg(vtkStructuredGrid[] toSet)
{
sg = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStreamTracer GetStream0()
{
return Stream0;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetStream0(vtkStreamTracer toSet)
{
Stream0 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkAssignAttribute Getaa()
{
return aa;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setaa(vtkAssignAttribute toSet)
{
aa = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRibbonFilter GetRibbon0()
{
return Ribbon0;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetRibbon0(vtkRibbonFilter toSet)
{
Ribbon0 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkLookupTable GetLookupTable1()
{
return LookupTable1;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetLookupTable1(vtkLookupTable toSet)
{
LookupTable1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetMapper10()
{
return Mapper10;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetMapper10(vtkPolyDataMapper toSet)
{
Mapper10 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetActor10()
{
return Actor10;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetActor10(vtkActor toSet)
{
Actor10 = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(alg!= null){alg.Dispose();}
if(pip!= null){pip.Dispose();}
if(Ren1!= null){Ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(Plot3D0!= null){Plot3D0.Dispose();}
if(Geometry5!= null){Geometry5.Dispose();}
if(Mapper5!= null){Mapper5.Dispose();}
if(Actor5!= null){Actor5.Dispose();}
if(ExtractGrid[0]!= null){ExtractGrid[0].Dispose();}
if(ExtractGrid[1]!= null){ExtractGrid[1].Dispose();}
if(ExtractGrid[2]!= null){ExtractGrid[2].Dispose();}
if(LineSourceWidget0!= null){LineSourceWidget0.Dispose();}
if(mbds!= null){mbds.Dispose();}
if(Stream0!= null){Stream0.Dispose();}
if(aa!= null){aa.Dispose();}
if(Ribbon0!= null){Ribbon0.Dispose();}
if(LookupTable1!= null){LookupTable1.Dispose();}
if(Mapper10!= null){Mapper10.Dispose();}
if(Actor10!= null){Actor10.Dispose();}
}
}
//--- end of script --//
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Projection;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public partial class TestWorkspace : Workspace
{
public const string WorkspaceName = TestWorkspaceName.Name;
public ExportProvider ExportProvider { get; }
public bool CanApplyChangeDocument { get; set; }
internal override bool CanChangeActiveContextDocument { get { return true; } }
public IList<TestHostProject> Projects { get; }
public IList<TestHostDocument> Documents { get; }
public IList<TestHostDocument> AdditionalDocuments { get; }
public IList<TestHostDocument> ProjectionDocuments { get; }
private readonly BackgroundCompiler _backgroundCompiler;
private readonly BackgroundParser _backgroundParser;
public TestWorkspace()
: this(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, WorkspaceName)
{
}
public TestWorkspace(ExportProvider exportProvider, string workspaceKind = null, bool disablePartialSolutions = true)
: base(MefV1HostServices.Create(exportProvider.AsExportProvider()), workspaceKind ?? WorkspaceName)
{
ResetThreadAffinity();
this.TestHookPartialSolutionsDisabled = disablePartialSolutions;
this.ExportProvider = exportProvider;
this.Projects = new List<TestHostProject>();
this.Documents = new List<TestHostDocument>();
this.AdditionalDocuments = new List<TestHostDocument>();
this.ProjectionDocuments = new List<TestHostDocument>();
this.CanApplyChangeDocument = true;
_backgroundCompiler = new BackgroundCompiler(this);
_backgroundParser = new BackgroundParser(this);
_backgroundParser.Start();
}
/// <summary>
/// Reset the thread affinity, in particular the designated foreground thread, to the active
/// thread.
/// </summary>
internal static void ResetThreadAffinity(ForegroundThreadData foregroundThreadData = null)
{
foregroundThreadData = foregroundThreadData ?? ForegroundThreadAffinitizedObject.CurrentForegroundThreadData;
// HACK: When the platform team took over several of our components they created a copy
// of ForegroundThreadAffinitizedObject. This needs to be reset in the same way as our copy
// does. Reflection is the only choice at the moment.
foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies())
{
var type = assembly.GetType("Microsoft.VisualStudio.Language.Intellisense.Implementation.ForegroundThreadAffinitizedObject", throwOnError: false);
if (type != null)
{
type.GetField("foregroundThread", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, foregroundThreadData.Thread);
type.GetField("ForegroundTaskScheduler", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, foregroundThreadData.TaskScheduler);
break;
}
}
}
protected internal override bool PartialSemanticsEnabled
{
get { return _backgroundCompiler != null; }
}
public TestHostDocument DocumentWithCursor
=> Documents.Single(d => d.CursorPosition.HasValue && !d.IsLinkFile);
protected override void OnDocumentTextChanged(Document document)
{
if (_backgroundParser != null)
{
_backgroundParser.Parse(document);
}
}
protected override void OnDocumentClosing(DocumentId documentId)
{
if (_backgroundParser != null)
{
_backgroundParser.CancelParse(documentId);
}
}
public new void RegisterText(SourceTextContainer text)
{
base.RegisterText(text);
}
protected override void Dispose(bool finalize)
{
var metadataAsSourceService = ExportProvider.GetExportedValues<IMetadataAsSourceFileService>().FirstOrDefault();
if (metadataAsSourceService != null)
{
metadataAsSourceService.CleanupGeneratedFiles();
}
this.ClearSolutionData();
foreach (var document in Documents)
{
document.CloseTextView();
}
foreach (var document in AdditionalDocuments)
{
document.CloseTextView();
}
foreach (var document in ProjectionDocuments)
{
document.CloseTextView();
}
var exceptions = ExportProvider.GetExportedValue<TestExtensionErrorHandler>().GetExceptions();
if (exceptions.Count == 1)
{
throw exceptions.Single();
}
else if (exceptions.Count > 1)
{
throw new AggregateException(exceptions);
}
if (SynchronizationContext.Current != null)
{
Dispatcher.CurrentDispatcher.DoEvents();
}
if (_backgroundParser != null)
{
_backgroundParser.CancelAllParses();
}
base.Dispose(finalize);
}
internal void AddTestSolution(TestHostSolution solution)
{
this.OnSolutionAdded(SolutionInfo.Create(solution.Id, solution.Version, solution.FilePath, projects: solution.Projects.Select(p => p.ToProjectInfo())));
}
public void AddTestProject(TestHostProject project)
{
if (!this.Projects.Contains(project))
{
this.Projects.Add(project);
foreach (var doc in project.Documents)
{
this.Documents.Add(doc);
}
foreach (var doc in project.AdditionalDocuments)
{
this.AdditionalDocuments.Add(doc);
}
}
this.OnProjectAdded(project.ToProjectInfo());
}
public new void OnProjectRemoved(ProjectId projectId)
{
base.OnProjectRemoved(projectId);
}
public new void OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
{
base.OnProjectReferenceAdded(projectId, projectReference);
}
public new void OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
{
base.OnProjectReferenceRemoved(projectId, projectReference);
}
public new void OnDocumentOpened(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext = true)
{
base.OnDocumentOpened(documentId, textContainer, isCurrentContext);
}
public void OnDocumentClosed(DocumentId documentId)
{
var testDocument = this.GetTestDocument(documentId);
this.OnDocumentClosed(documentId, testDocument.Loader);
}
public new void OnParseOptionsChanged(ProjectId projectId, ParseOptions parseOptions)
{
base.OnParseOptionsChanged(projectId, parseOptions);
}
public void OnDocumentRemoved(DocumentId documentId, bool closeDocument = false)
{
if (closeDocument && this.IsDocumentOpen(documentId))
{
this.CloseDocument(documentId);
}
base.OnDocumentRemoved(documentId);
}
public new void OnDocumentSourceCodeKindChanged(DocumentId documentId, SourceCodeKind sourceCodeKind)
{
base.OnDocumentSourceCodeKindChanged(documentId, sourceCodeKind);
}
public DocumentId GetDocumentId(TestHostDocument hostDocument)
{
if (!Documents.Contains(hostDocument) && !AdditionalDocuments.Contains(hostDocument))
{
return null;
}
return hostDocument.Id;
}
public TestHostDocument GetTestDocument(DocumentId documentId)
{
return this.Documents.FirstOrDefault(d => d.Id == documentId);
}
public TestHostDocument GetTestAdditionalDocument(DocumentId documentId)
{
return this.AdditionalDocuments.FirstOrDefault(d => d.Id == documentId);
}
public TestHostProject GetTestProject(DocumentId documentId)
{
return GetTestProject(documentId.ProjectId);
}
public TestHostProject GetTestProject(ProjectId projectId)
{
return this.Projects.FirstOrDefault(p => p.Id == projectId);
}
public TServiceInterface GetService<TServiceInterface>()
{
return ExportProvider.GetExportedValue<TServiceInterface>();
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
switch (feature)
{
case ApplyChangesKind.AddDocument:
case ApplyChangesKind.RemoveDocument:
case ApplyChangesKind.AddAdditionalDocument:
case ApplyChangesKind.RemoveAdditionalDocument:
return true;
case ApplyChangesKind.ChangeDocument:
case ApplyChangesKind.ChangeAdditionalDocument:
return this.CanApplyChangeDocument;
case ApplyChangesKind.AddProjectReference:
case ApplyChangesKind.AddMetadataReference:
return true;
default:
return false;
}
}
protected override void ApplyDocumentTextChanged(DocumentId document, SourceText newText)
{
var testDocument = this.GetTestDocument(document);
testDocument.Update(newText);
}
protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text)
{
var hostProject = this.GetTestProject(info.Id.ProjectId);
var hostDocument = new TestHostDocument(
text.ToString(), info.Name, info.SourceCodeKind,
info.Id, folders: info.Folders);
hostProject.AddDocument(hostDocument);
this.OnDocumentAdded(hostDocument.ToDocumentInfo());
}
protected override void ApplyDocumentRemoved(DocumentId documentId)
{
var hostProject = this.GetTestProject(documentId.ProjectId);
var hostDocument = this.GetTestDocument(documentId);
hostProject.RemoveDocument(hostDocument);
this.OnDocumentRemoved(documentId, closeDocument: true);
}
protected override void ApplyAdditionalDocumentTextChanged(DocumentId document, SourceText newText)
{
var testDocument = this.GetTestAdditionalDocument(document);
testDocument.Update(newText);
}
protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text)
{
var hostProject = this.GetTestProject(info.Id.ProjectId);
var hostDocument = new TestHostDocument(text.ToString(), info.Name, id: info.Id);
hostProject.AddAdditionalDocument(hostDocument);
this.OnAdditionalDocumentAdded(hostDocument.ToDocumentInfo());
}
protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId)
{
var hostProject = this.GetTestProject(documentId.ProjectId);
var hostDocument = this.GetTestAdditionalDocument(documentId);
hostProject.RemoveAdditionalDocument(hostDocument);
this.OnAdditionalDocumentRemoved(documentId);
}
internal override void SetDocumentContext(DocumentId documentId)
{
OnDocumentContextUpdated(documentId);
}
/// <summary>
/// Creates a TestHostDocument backed by a projection buffer. The surface buffer is
/// described by a markup string with {|name:|} style pointers to annotated spans that can
/// be found in one of a set of provided documents. Unnamed spans in the documents (which
/// must have both endpoints inside an annotated spans) and in the surface buffer markup are
/// mapped and included in the resulting document.
///
/// If the markup string has the caret indicator "$$", then the caret will be placed at the
/// corresponding position. If it does not, then the first span mapped into the projection
/// buffer that contains the caret from its document is used.
///
/// The result is a new TestHostDocument backed by a projection buffer including tracking
/// spans from any number of documents and inert text from the markup itself.
///
/// As an example, consider surface buffer markup
/// ABC [|DEF|] [|GHI[|JKL|]|]{|S1:|} [|MNO{|S2:|}PQR S$$TU|] {|S4:|}{|S5:|}{|S3:|}
///
/// This contains 4 unnamed spans and references to 5 spans that should be found and
/// included. Consider an included base document created from the following markup:
///
/// public class C
/// {
/// public void M1()
/// {
/// {|S1:int [|abc[|d$$ef|]|] = foo;|}
/// int y = foo;
/// {|S2:int [|def|] = foo;|}
/// int z = {|S3:123|} + {|S4:456|} + {|S5:789|};
/// }
/// }
///
/// The resulting projection buffer (with unnamed span markup preserved) would look like:
/// ABC [|DEF|] [|GHI[|JKL|]|]int [|abc[|d$$ef|]|] = foo; [|MNOint [|def|] = foo;PQR S$$TU|] 456789123
///
/// The union of unnamed spans from the surface buffer markup and each of the projected
/// spans is sorted as it would have been sorted by MarkupTestFile had it parsed the entire
/// projection buffer as one file, which it would do in a stack-based manner. In our example,
/// the order of the unnamed spans would be as follows:
///
/// ABC [|DEF|] [|GHI[|JKL|]|]int [|abc[|d$$ef|]|] = foo; [|MNOint [|def|] = foo;PQR S$$TU|] 456789123
/// -----1 -----2 -------4 -----6
/// ------------3 --------------5 --------------------------------7
/// </summary>
/// <param name="markup">Describes the surface buffer, and contains a mix of inert text,
/// named spans and unnamed spans. Any named spans must contain only the name portion
/// (e.g. {|Span1:|} which must match the name of a span in one of the baseDocuments.
/// Annotated spans cannot be nested but they can be adjacent, in which case order will be
/// preserved. The markup may also contain the caret indicator.</param>
/// <param name="baseDocuments">The set of documents from which the projection buffer
/// document will be composed.</param>
/// <returns></returns>
public TestHostDocument CreateProjectionBufferDocument(string markup, IList<TestHostDocument> baseDocuments, string languageName, string path = "projectionbufferdocumentpath", ProjectionBufferOptions options = ProjectionBufferOptions.None, IProjectionEditResolver editResolver = null)
{
GetSpansAndCaretFromSurfaceBufferMarkup(markup, baseDocuments,
out var projectionBufferSpans, out Dictionary<string, ImmutableArray<TextSpan>> mappedSpans, out var mappedCaretLocation);
var projectionBufferFactory = this.GetService<IProjectionBufferFactoryService>();
var projectionBuffer = projectionBufferFactory.CreateProjectionBuffer(editResolver, projectionBufferSpans, options);
// Add in mapped spans from each of the base documents
foreach (var document in baseDocuments)
{
mappedSpans[string.Empty] = mappedSpans.ContainsKey(string.Empty)
? mappedSpans[string.Empty]
: ImmutableArray<TextSpan>.Empty;
foreach (var span in document.SelectedSpans)
{
var snapshotSpan = span.ToSnapshotSpan(document.TextBuffer.CurrentSnapshot);
var mappedSpan = projectionBuffer.CurrentSnapshot.MapFromSourceSnapshot(snapshotSpan).Single();
mappedSpans[string.Empty] = mappedSpans[string.Empty].Add(mappedSpan.ToTextSpan());
}
// Order unnamed spans as they would be ordered by the normal span finding
// algorithm in MarkupTestFile
mappedSpans[string.Empty] = mappedSpans[string.Empty].OrderBy(s => s.End).ThenBy(s => -s.Start).ToImmutableArray();
foreach (var kvp in document.AnnotatedSpans)
{
mappedSpans[kvp.Key] = mappedSpans.ContainsKey(kvp.Key)
? mappedSpans[kvp.Key]
: ImmutableArray<TextSpan>.Empty;
foreach (var span in kvp.Value)
{
var snapshotSpan = span.ToSnapshotSpan(document.TextBuffer.CurrentSnapshot);
var mappedSpan = projectionBuffer.CurrentSnapshot.MapFromSourceSnapshot(snapshotSpan).Single();
mappedSpans[kvp.Key] = mappedSpans[kvp.Key].Add(mappedSpan.ToTextSpan());
}
}
}
var languageServices = this.Services.GetLanguageServices(languageName);
var projectionDocument = new TestHostDocument(
TestExportProvider.ExportProviderWithCSharpAndVisualBasic,
languageServices,
projectionBuffer,
path,
mappedCaretLocation,
mappedSpans);
this.ProjectionDocuments.Add(projectionDocument);
return projectionDocument;
}
private void GetSpansAndCaretFromSurfaceBufferMarkup(
string markup, IList<TestHostDocument> baseDocuments,
out IList<object> projectionBufferSpans,
out Dictionary<string, ImmutableArray<TextSpan>> mappedMarkupSpans, out int? mappedCaretLocation)
{
projectionBufferSpans = new List<object>();
var projectionBufferSpanStartingPositions = new List<int>();
mappedCaretLocation = null;
string inertText;
int? markupCaretLocation;
MarkupTestFile.GetPositionAndSpans(markup,
out inertText, out markupCaretLocation, out var markupSpans);
var namedSpans = markupSpans.Where(kvp => kvp.Key != string.Empty);
var sortedAndNamedSpans = namedSpans.OrderBy(kvp => kvp.Value.Single().Start)
.ThenBy(kvp => markup.IndexOf("{|" + kvp.Key + ":|}", StringComparison.Ordinal));
var currentPositionInInertText = 0;
var currentPositionInProjectionBuffer = 0;
// If the markup points to k spans, these k spans divide the inert text into k + 1
// possibly empty substrings. When handling each span, also handle the inert text that
// immediately precedes it. At the end, handle the trailing inert text
foreach (var spanNameToListMap in sortedAndNamedSpans)
{
var spanName = spanNameToListMap.Key;
var spanLocation = spanNameToListMap.Value.Single().Start;
// Get any inert text between this and the previous span
if (currentPositionInInertText < spanLocation)
{
var textToAdd = inertText.Substring(currentPositionInInertText, spanLocation - currentPositionInInertText);
projectionBufferSpans.Add(textToAdd);
projectionBufferSpanStartingPositions.Add(currentPositionInProjectionBuffer);
// If the caret is in the markup and in this substring, calculate the final
// caret location
if (mappedCaretLocation == null &&
markupCaretLocation != null &&
currentPositionInInertText + textToAdd.Length >= markupCaretLocation)
{
var caretOffsetInCurrentText = markupCaretLocation.Value - currentPositionInInertText;
mappedCaretLocation = currentPositionInProjectionBuffer + caretOffsetInCurrentText;
}
currentPositionInInertText += textToAdd.Length;
currentPositionInProjectionBuffer += textToAdd.Length;
}
// Find and insert the span from the corresponding document
var documentWithSpan = baseDocuments.FirstOrDefault(d => d.AnnotatedSpans.ContainsKey(spanName));
if (documentWithSpan == null)
{
continue;
}
markupSpans.Remove(spanName);
var matchingSpan = documentWithSpan.AnnotatedSpans[spanName].Single();
var span = new Span(matchingSpan.Start, matchingSpan.Length);
var trackingSpan = documentWithSpan.TextBuffer.CurrentSnapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeExclusive);
projectionBufferSpans.Add(trackingSpan);
projectionBufferSpanStartingPositions.Add(currentPositionInProjectionBuffer);
// If the caret is not in markup but is in this span, then calculate the final
// caret location. Note - if we find the caret marker in this document, then
// we DO want to map it up, even if it's at the end of the span for this document.
// This is not ambiguous for us, since we have explicit delimiters between the buffer
// so it's clear which document the caret is in.
if (mappedCaretLocation == null &&
markupCaretLocation == null &&
documentWithSpan.CursorPosition.HasValue &&
(matchingSpan.Contains(documentWithSpan.CursorPosition.Value) || matchingSpan.End == documentWithSpan.CursorPosition.Value))
{
var caretOffsetInSpan = documentWithSpan.CursorPosition.Value - matchingSpan.Start;
mappedCaretLocation = currentPositionInProjectionBuffer + caretOffsetInSpan;
}
currentPositionInProjectionBuffer += matchingSpan.Length;
}
// Handle any inert text after the final projected span
if (currentPositionInInertText < inertText.Length - 1)
{
projectionBufferSpans.Add(inertText.Substring(currentPositionInInertText));
projectionBufferSpanStartingPositions.Add(currentPositionInProjectionBuffer);
if (mappedCaretLocation == null && markupCaretLocation != null && markupCaretLocation >= currentPositionInInertText)
{
var caretOffsetInCurrentText = markupCaretLocation.Value - currentPositionInInertText;
mappedCaretLocation = currentPositionInProjectionBuffer + caretOffsetInCurrentText;
}
}
MapMarkupSpans(markupSpans, out mappedMarkupSpans, projectionBufferSpans, projectionBufferSpanStartingPositions);
}
private void MapMarkupSpans(
IDictionary<string, ImmutableArray<TextSpan>> markupSpans,
out Dictionary<string, ImmutableArray<TextSpan>> mappedMarkupSpans,
IList<object> projectionBufferSpans, IList<int> projectionBufferSpanStartingPositions)
{
var tempMappedMarkupSpans = new Dictionary<string, ArrayBuilder<TextSpan>>();
foreach (string key in markupSpans.Keys)
{
tempMappedMarkupSpans[key] = ArrayBuilder<TextSpan>.GetInstance();
foreach (var markupSpan in markupSpans[key])
{
var positionInMarkup = 0;
var spanIndex = 0;
var markupSpanStart = markupSpan.Start;
var markupSpanEndExclusive = markupSpan.Start + markupSpan.Length;
int? spanStartLocation = null;
int? spanEndLocationExclusive = null;
foreach (var projectionSpan in projectionBufferSpans)
{
var text = projectionSpan as string;
if (text != null)
{
if (spanStartLocation == null && positionInMarkup <= markupSpanStart && markupSpanStart <= positionInMarkup + text.Length)
{
var offsetInText = markupSpanStart - positionInMarkup;
spanStartLocation = projectionBufferSpanStartingPositions[spanIndex] + offsetInText;
}
if (spanEndLocationExclusive == null && positionInMarkup <= markupSpanEndExclusive && markupSpanEndExclusive <= positionInMarkup + text.Length)
{
var offsetInText = markupSpanEndExclusive - positionInMarkup;
spanEndLocationExclusive = projectionBufferSpanStartingPositions[spanIndex] + offsetInText;
break;
}
positionInMarkup += text.Length;
}
spanIndex++;
}
tempMappedMarkupSpans[key].Add(new TextSpan(spanStartLocation.Value, spanEndLocationExclusive.Value - spanStartLocation.Value));
}
}
mappedMarkupSpans = tempMappedMarkupSpans.ToDictionary(
kvp => kvp.Key, kvp => kvp.Value.ToImmutableAndFree());
}
public override void OpenDocument(DocumentId documentId, bool activate = true)
{
OnDocumentOpened(documentId, this.CurrentSolution.GetDocument(documentId).GetTextAsync().Result.Container);
}
public override void CloseDocument(DocumentId documentId)
{
var currentDoc = this.CurrentSolution.GetDocument(documentId);
OnDocumentClosed(documentId,
TextLoader.From(TextAndVersion.Create(currentDoc.GetTextAsync().Result, currentDoc.GetTextVersionAsync().Result)));
}
public void ChangeDocument(DocumentId documentId, SourceText text)
{
var oldSolution = this.CurrentSolution;
var newSolution = this.SetCurrentSolution(oldSolution.WithDocumentText(documentId, text));
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId.ProjectId, documentId);
}
public void ChangeAdditionalDocument(DocumentId documentId, SourceText text)
{
var oldSolution = this.CurrentSolution;
var newSolution = this.SetCurrentSolution(oldSolution.WithAdditionalDocumentText(documentId, text));
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.AdditionalDocumentChanged, oldSolution, newSolution, documentId.ProjectId, documentId);
}
public void ChangeProject(ProjectId projectId, Solution solution)
{
var oldSolution = this.CurrentSolution;
var newSolution = this.SetCurrentSolution(solution);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectChanged, oldSolution, newSolution, projectId);
}
public new void ClearSolution()
{
base.ClearSolution();
}
public void ChangeSolution(Solution solution)
{
var oldSolution = this.CurrentSolution;
var newSolution = this.SetCurrentSolution(solution);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionChanged, oldSolution, newSolution);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** File: StackBuilderSink.cs
**
**
** Purpose: Terminating sink which will build a stack and
** make a method call on an object
**
**
===========================================================*/
namespace System.Runtime.Remoting.Messaging {
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Metadata;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Principal;
/* Assembly Access */
using System;
using System.Globalization;
using System.Threading;
[Serializable]
internal class StackBuilderSink : IMessageSink
{
//+============================================================
//
// Method: Constructor, public
//
// Synopsis: Store server object
//
// History: 06-May-1999 <EMAIL>MattSmit</EMAIL> Created
//-============================================================
public StackBuilderSink(MarshalByRefObject server)
{
_server = server;
}
public StackBuilderSink(Object server)
{
_server = server;
if (_server==null)
{
_bStatic = true;
}
}
[System.Security.SecurityCritical] // auto-generated
public virtual IMessage SyncProcessMessage(IMessage msg)
{
// Validate message here
IMessage errMsg = InternalSink.ValidateMessage(msg);
if (errMsg != null)
{
return errMsg;
}
IMethodCallMessage mcMsg = msg as IMethodCallMessage;
IMessage retMessage;
LogicalCallContext oldCallCtx = null;
LogicalCallContext lcc = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
object xADCall = lcc.GetData(CrossAppDomainSink.LCC_DATA_KEY);
bool isCallContextSet = false;
try
{
Object server = _server;
BCLDebug.Assert((server!=null) == (!_bStatic),
"Invalid state in stackbuilder sink?");
// validate the method base if necessary
VerifyIsOkToCallMethod(server, mcMsg);
// install call context onto the thread, holding onto
// the one that is currently on the thread
LogicalCallContext messageCallContext = null;
if (mcMsg != null)
{
messageCallContext = mcMsg.LogicalCallContext;
}
else
{
messageCallContext = (LogicalCallContext)msg.Properties["__CallContext"];
}
oldCallCtx = CallContext.SetLogicalCallContext(messageCallContext);
isCallContextSet = true;
messageCallContext.PropagateIncomingHeadersToCallContext(msg);
PreserveThreadPrincipalIfNecessary(messageCallContext, oldCallCtx);
// NOTE: target for dispatch will be NULL when the StackBuilderSink
// is used for async delegates on static methods.
// *** NOTE ***
// Although we always pass _server to these calls in the EE,
// when we execute using Message::Dispatch we are using TP as
// the this-ptr ... (what the call site thinks is the this-ptr)
// when we execute using StackBuilderSink::PrivatePM we use
// _server as the this-ptr (which could be different if there
// is interception for strictly MBR types in the same AD).
// ************
if (IsOKToStackBlt(mcMsg, server)
&& ((Message)mcMsg).Dispatch(server))
{
//retMessage = StackBasedReturnMessage.GetObjectFromPool((Message)mcMsg);
retMessage = new StackBasedReturnMessage();
((StackBasedReturnMessage)retMessage).InitFields((Message)mcMsg);
// call context could be different then the one from before the call.
LogicalCallContext latestCallContext = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
// retrieve outgoing response headers
latestCallContext.PropagateOutgoingHeadersToMessage(retMessage);
// Install call context back into Message (from the thread)
((StackBasedReturnMessage)retMessage).SetLogicalCallContext(latestCallContext);
}
else
{
MethodBase mb = GetMethodBase(mcMsg);
Object[] outArgs = null;
Object ret = null;
RemotingMethodCachedData methodCache =
InternalRemotingServices.GetReflectionCachedData(mb);
Message.DebugOut("StackBuilderSink::Calling PrivateProcessMessage\n");
Object[] args = Message.CoerceArgs(mcMsg, methodCache.Parameters);
ret = PrivateProcessMessage(
mb.MethodHandle,
args,
server,
out outArgs);
CopyNonByrefOutArgsFromOriginalArgs(methodCache, args, ref outArgs);
// call context could be different then the one from before the call.
LogicalCallContext latestCallContext = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
if (xADCall != null && ((bool)xADCall) == true && latestCallContext != null)
{
// Special case Principal since if might not be serializable before returning
// ReturnMessage
latestCallContext.RemovePrincipalIfNotSerializable();
}
retMessage = new ReturnMessage(
ret,
outArgs,
(outArgs == null ? 0 : outArgs.Length),
latestCallContext,
mcMsg);
// retrieve outgoing response headers
latestCallContext.PropagateOutgoingHeadersToMessage(retMessage);
// restore the call context on the thread
CallContext.SetLogicalCallContext(oldCallCtx);
}
} catch (Exception e)
{
Message.DebugOut(
"StackBuilderSink::The server object probably threw an exception " +
e.Message + e.StackTrace + "\n" );
retMessage = new ReturnMessage(e, mcMsg);
((ReturnMessage)retMessage).SetLogicalCallContext(mcMsg.LogicalCallContext);
if (isCallContextSet)
CallContext.SetLogicalCallContext(oldCallCtx);
}
return retMessage;
}
[System.Security.SecurityCritical] // auto-generated
public virtual IMessageCtrl AsyncProcessMessage(
IMessage msg, IMessageSink replySink)
{
IMethodCallMessage mcMsg = (IMethodCallMessage)msg;
IMessageCtrl retCtrl = null;
IMessage retMessage = null;
LogicalCallContext oldCallCtx = null;
bool isCallContextSet = false;
try{
try
{
LogicalCallContext callCtx = (LogicalCallContext)
mcMsg.Properties[Message.CallContextKey];
Object server = _server;
// validate the method base if necessary
VerifyIsOkToCallMethod(server, mcMsg);
// install call context onto the thread, holding onto
// the one that is currently on the thread
oldCallCtx = CallContext.SetLogicalCallContext(callCtx);
isCallContextSet = true;
// retrieve incoming headers
callCtx.PropagateIncomingHeadersToCallContext(msg);
PreserveThreadPrincipalIfNecessary(callCtx, oldCallCtx);
// see if this is a server message that was dispatched asynchronously
ServerChannelSinkStack sinkStack =
msg.Properties["__SinkStack"] as ServerChannelSinkStack;
if (sinkStack != null)
sinkStack.ServerObject = server;
BCLDebug.Assert((server!=null)==(!_bStatic),
"Invalid state in stackbuilder sink?");
MethodBase mb = GetMethodBase(mcMsg);
Object[] outArgs = null;
Object ret = null;
RemotingMethodCachedData methodCache =
InternalRemotingServices.GetReflectionCachedData(mb);
Object[] args = Message.CoerceArgs(mcMsg, methodCache.Parameters);
ret = PrivateProcessMessage(mb.MethodHandle,
args,
server,
out outArgs);
CopyNonByrefOutArgsFromOriginalArgs(methodCache, args, ref outArgs);
if(replySink != null)
{
// call context could be different then the one from before the call.
LogicalCallContext latestCallContext = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
if (latestCallContext != null)
{
// Special case Principal since if might not be serializable before returning
// ReturnMessage
latestCallContext.RemovePrincipalIfNotSerializable();
}
retMessage = new ReturnMessage(
ret,
outArgs,
(outArgs == null ? 0 : outArgs.Length),
latestCallContext,
mcMsg);
// retrieve outgoing response headers
latestCallContext.PropagateOutgoingHeadersToMessage(retMessage);
}
}
catch (Exception e)
{
if(replySink != null)
{
retMessage = new ReturnMessage(e, mcMsg);
((ReturnMessage)retMessage).SetLogicalCallContext(
(LogicalCallContext)
mcMsg.Properties[Message.CallContextKey]);
}
}
finally
{
if (replySink != null)
{
// Call the reply sink without catching the exceptions
// in it. In v2.0 any exceptions in the callback for example
// would probably bring down the process
replySink.SyncProcessMessage(retMessage);
}
}
}
finally {
// restore the call context on the thread
if (isCallContextSet)
CallContext.SetLogicalCallContext(oldCallCtx);
}
return retCtrl;
} // AsyncProcessMessage
public IMessageSink NextSink
{
[System.Security.SecurityCritical] // auto-generated
get
{
// there is no nextSink for the StackBuilderSink
return null;
}
}
// This check if the call-site on the TP is in our own AD
// It also handles the special case where the TP is on
// a well-known object and we cannot do stack-blting
[System.Security.SecurityCritical] // auto-generated
internal bool IsOKToStackBlt(IMethodMessage mcMsg, Object server)
{
bool bOK = false;
Message msg = mcMsg as Message;
if(null != msg)
{
IInternalMessage iiMsg = (IInternalMessage) msg;
// If there is a frame in the message we can always
// Blt it (provided it is not a proxy to a well-known
// object in our own appDomain)!
// The GetThisPtr == server test allows for people to wrap
// our proxy with their own interception .. in that case
// we should not blt the stack.
if (msg.GetFramePtr() != IntPtr.Zero
&& msg.GetThisPtr() == server
&&
( iiMsg.IdentityObject == null ||
( iiMsg.IdentityObject != null
&& iiMsg.IdentityObject == iiMsg.ServerIdentityObject
)
)
)
{
bOK = true;
}
}
return bOK;
}
[System.Security.SecurityCritical] // auto-generated
private static MethodBase GetMethodBase(IMethodMessage msg)
{
MethodBase mb = msg.MethodBase;
if(null == mb)
{
BCLDebug.Trace("REMOTE", "Method missing w/name ", msg.MethodName);
throw new RemotingException(
String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString(
"Remoting_Message_MethodMissing"),
msg.MethodName,
msg.TypeName));
}
return mb;
}
[System.Security.SecurityCritical] // auto-generated
private static void VerifyIsOkToCallMethod(Object server, IMethodMessage msg)
{
bool bTypeChecked = false;
MarshalByRefObject mbr = server as MarshalByRefObject;
if (mbr != null)
{
bool fServer;
Identity id = MarshalByRefObject.GetIdentity(mbr, out fServer);
if (id != null)
{
ServerIdentity srvId = id as ServerIdentity;
if ((srvId != null) && srvId.MarshaledAsSpecificType)
{
Type srvType = srvId.ServerType;
if (srvType != null)
{
MethodBase mb = GetMethodBase(msg);
RuntimeType declaringType = (RuntimeType)mb.DeclaringType;
// make sure that srvType is not more restrictive than method base
// (i.e. someone marshaled with a specific type or interface exposed)
if ((declaringType != srvType) &&
!declaringType.IsAssignableFrom(srvType))
{
throw new RemotingException(
String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_InvalidCallingType"),
mb.DeclaringType.FullName, srvType.FullName));
}
// Set flag so we don't repeat this work below.
if (declaringType.IsInterface)
{
VerifyNotIRemoteDispatch(declaringType);
}
bTypeChecked = true;
}
}
}
// We must always verify that the type corresponding to
// the method being invoked is compatible with the real server
// type.
if (!bTypeChecked)
{
MethodBase mb = GetMethodBase(msg);
RuntimeType reflectedType = (RuntimeType)mb.ReflectedType;
if (!reflectedType.IsInterface)
{
if (!reflectedType.IsInstanceOfType(mbr))
{
throw new RemotingException(
String.Format(
CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_InvalidCallingType"),
reflectedType.FullName,
mbr.GetType().FullName));
}
}
// This code prohibits calls made to System.EnterpriseServices.IRemoteDispatch
// so that remote call cannot bypass lowFilterLevel logic in the serializers.
// This special casing should be removed in the future
else
{
VerifyNotIRemoteDispatch(reflectedType);
}
}
}
} // VerifyIsOkToCallMethod
// This code prohibits calls made to System.EnterpriseServices.IRemoteDispatch
// so that remote call cannot bypass lowFilterLevel logic in the serializers.
// This special casing should be removed in the future
// Check whether we are calling IRemoteDispatch
[System.Security.SecurityCritical] // auto-generated
private static void VerifyNotIRemoteDispatch(RuntimeType reflectedType)
{
if(reflectedType.FullName.Equals(sIRemoteDispatch) &&
reflectedType.GetRuntimeAssembly().GetSimpleName().Equals(sIRemoteDispatchAssembly))
{
throw new RemotingException(
Environment.GetResourceString("Remoting_CantInvokeIRemoteDispatch"));
}
}
// copies references of non-byref [In, Out] args from the input args to
// the output args array.
internal void CopyNonByrefOutArgsFromOriginalArgs(RemotingMethodCachedData methodCache,
Object[] args,
ref Object[] marshalResponseArgs)
{
int[] map = methodCache.NonRefOutArgMap;
if (map.Length > 0)
{
if (marshalResponseArgs == null)
marshalResponseArgs = new Object[methodCache.Parameters.Length];
foreach (int pos in map)
{
marshalResponseArgs[pos] = args[pos];
}
}
}
// For the incoming call, we sometimes need to preserve the thread principal from
// the executing thread, instead of blindly bashing it with the one from the message.
// For instance, in cross process calls, the principal will always be null
// in the incoming message. However, when we are hosted in ASP.Net, ASP.Net will handle
// authentication and set up the thread principal. We should dispatch the call
// using the identity that it set up.
[System.Security.SecurityCritical] // auto-generated
internal static void PreserveThreadPrincipalIfNecessary(
LogicalCallContext messageCallContext,
LogicalCallContext threadCallContext)
{
BCLDebug.Assert(messageCallContext != null, "message should always have a call context");
if (threadCallContext != null)
{
if (messageCallContext.Principal == null)
{
IPrincipal currentPrincipal = threadCallContext.Principal;
if (currentPrincipal != null)
{
messageCallContext.Principal = currentPrincipal;
}
}
}
} // PreserveThreadPrincipalIfNecessary
internal Object ServerObject
{
get { return _server; }
}
//+============================================================
//
// Method: PrivateProcessMessage, public
//
// Synopsis: does the actual work of building the stack,
// finding the correct code address and calling it.
//
// History: 06-May-1999 <EMAIL>MattSmit</EMAIL> Created
//-============================================================
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Object _PrivateProcessMessage(
IntPtr md, Object[] args, Object server,
out Object[] outArgs);
[System.Security.SecurityCritical] // auto-generated
public Object PrivateProcessMessage(
RuntimeMethodHandle md, Object[] args, Object server,
out Object[] outArgs)
{
return _PrivateProcessMessage(md.Value, args, server, out outArgs);
}
private Object _server; // target object
private static string sIRemoteDispatch = "System.EnterpriseServices.IRemoteDispatch";
private static string sIRemoteDispatchAssembly = "System.EnterpriseServices";
bool _bStatic;
}
}
| |
// 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.Configuration.Assemblies;
using StackCrawlMark = System.Threading.StackCrawlMark;
using System.Runtime.Serialization;
using System.Runtime.Loader;
namespace System.Reflection
{
public abstract partial class Assembly : ICustomAttributeProvider, ISerializable
{
private static volatile bool s_LoadFromResolveHandlerSetup = false;
private static object s_syncRootLoadFrom = new object();
private static List<string> s_LoadFromAssemblyList = new List<string>();
private static object s_syncLoadFromAssemblyList = new object();
private static Assembly LoadFromResolveHandler(object sender, ResolveEventArgs args)
{
Assembly requestingAssembly = args.RequestingAssembly;
if (requestingAssembly == null)
{
return null;
}
// Requesting assembly for LoadFrom is always loaded in defaultContext - proceed only if that
// is the case.
if (AssemblyLoadContext.Default != AssemblyLoadContext.GetLoadContext(requestingAssembly))
return null;
// Get the path where requesting assembly lives and check if it is in the list
// of assemblies for which LoadFrom was invoked.
bool fRequestorLoadedViaLoadFrom = false;
string requestorPath = Path.GetFullPath(requestingAssembly.Location);
if (string.IsNullOrEmpty(requestorPath))
return null;
lock(s_syncLoadFromAssemblyList)
{
fRequestorLoadedViaLoadFrom = s_LoadFromAssemblyList.Contains(requestorPath);
}
// If the requestor assembly was not loaded using LoadFrom, exit.
if (!fRequestorLoadedViaLoadFrom)
return null;
// Requestor assembly was loaded using loadFrom, so look for its dependencies
// in the same folder as it.
// Form the name of the assembly using the path of the assembly that requested its load.
AssemblyName requestedAssemblyName = new AssemblyName(args.Name);
string requestedAssemblyPath = Path.Combine(Path.GetDirectoryName(requestorPath), requestedAssemblyName.Name+".dll");
// Load the dependency via LoadFrom so that it goes through the same path of being in the LoadFrom list.
Assembly resolvedAssembly = null;
try
{
resolvedAssembly = Assembly.LoadFrom(requestedAssemblyPath);
}
catch(FileNotFoundException)
{
// Catch FileNotFoundException when attempting to resolve assemblies via this handler to account for missing assemblies.
resolvedAssembly = null;
}
return resolvedAssembly;
}
public static Assembly LoadFrom(String assemblyFile)
{
if (assemblyFile == null)
throw new ArgumentNullException(nameof(assemblyFile));
string fullPath = Path.GetFullPath(assemblyFile);
if (!s_LoadFromResolveHandlerSetup)
{
lock (s_syncRootLoadFrom)
{
if (!s_LoadFromResolveHandlerSetup)
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromResolveHandler);
s_LoadFromResolveHandlerSetup = true;
}
}
}
// Add the path to the LoadFrom path list which we will consult
// before handling the resolves in our handler.
lock(s_syncLoadFromAssemblyList)
{
if (!s_LoadFromAssemblyList.Contains(fullPath))
{
s_LoadFromAssemblyList.Add(fullPath);
}
}
return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath);
}
public static Assembly LoadFrom(String assemblyFile,
byte[] hashValue,
AssemblyHashAlgorithm hashAlgorithm)
{
throw new NotSupportedException(SR.NotSupported_AssemblyLoadFromHash);
}
// Locate an assembly by the long form of the assembly name.
// eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890"
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly Load(String assemblyString)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeAssembly.InternalLoad(assemblyString, ref stackMark);
}
// Returns type from the assembly while keeping compatibility with Assembly.Load(assemblyString).GetType(typeName) for managed types.
// Calls Type.GetType for WinRT types.
// Note: Type.GetType fails for assembly names that start with weird characters like '['. By calling it for managed types we would
// break AppCompat.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
internal static Type GetType_Compat(String assemblyString, String typeName)
{
// Normally we would get the stackMark only in public APIs. This is internal API, but it is AppCompat replacement of public API
// call Assembly.Load(assemblyString).GetType(typeName), therefore we take the stackMark here as well, to be fully compatible with
// the call sequence.
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
RuntimeAssembly assembly;
AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(
assemblyString,
out assembly);
if (assembly == null)
{
if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime)
{
return Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, false /*ignoreCase*/);
}
assembly = RuntimeAssembly.InternalLoadAssemblyName(
assemblyName, null, ref stackMark,
true /*thrownOnFileNotFound*/);
}
return assembly.GetType(typeName, true /*throwOnError*/, false /*ignoreCase*/);
}
// Locate an assembly by its name. The name can be strong or
// weak. The assembly is loaded into the domain of the caller.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly Load(AssemblyName assemblyRef)
{
AssemblyName modifiedAssemblyRef = null;
if (assemblyRef != null && assemblyRef.CodeBase != null)
{
modifiedAssemblyRef = (AssemblyName)assemblyRef.Clone();
modifiedAssemblyRef.CodeBase = null;
}
else
{
modifiedAssemblyRef = assemblyRef;
}
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeAssembly.InternalLoadAssemblyName(modifiedAssemblyRef, null, ref stackMark, true /*thrownOnFileNotFound*/);
}
// Locate an assembly by its name. The name can be strong or
// weak. The assembly is loaded into the domain of the caller.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
internal static Assembly Load(AssemblyName assemblyRef, IntPtr ptrLoadContextBinder)
{
AssemblyName modifiedAssemblyRef = null;
if (assemblyRef != null && assemblyRef.CodeBase != null)
{
modifiedAssemblyRef = (AssemblyName)assemblyRef.Clone();
modifiedAssemblyRef.CodeBase = null;
}
else
{
modifiedAssemblyRef = assemblyRef;
}
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeAssembly.InternalLoadAssemblyName(modifiedAssemblyRef, null, ref stackMark, true /*thrownOnFileNotFound*/, ptrLoadContextBinder);
}
// Loads the assembly with a COFF based IMAGE containing
// an emitted assembly. The assembly is loaded into the domain
// of the caller. The second parameter is the raw bytes
// representing the symbol store that matches the assembly.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly Load(byte[] rawAssembly,
byte[] rawSymbolStore)
{
AppDomain.CheckLoadByteArraySupported();
if (rawAssembly == null)
throw new ArgumentNullException(nameof(rawAssembly));
AssemblyLoadContext alc = new IndividualAssemblyLoadContext();
MemoryStream assemblyStream = new MemoryStream(rawAssembly);
MemoryStream symbolStream = (rawSymbolStore != null) ? new MemoryStream(rawSymbolStore) : null;
return alc.LoadFromStream(assemblyStream, symbolStream);
}
private static Dictionary<string, Assembly> s_loadfile = new Dictionary<string, Assembly>();
public static Assembly LoadFile(String path)
{
AppDomain.CheckLoadFileSupported();
Assembly result = null;
if (path == null)
throw new ArgumentNullException(nameof(path));
if (PathInternal.IsPartiallyQualified(path))
{
throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(path));
}
string normalizedPath = Path.GetFullPath(path);
lock (s_loadfile)
{
if (s_loadfile.TryGetValue(normalizedPath, out result))
return result;
AssemblyLoadContext alc = new IndividualAssemblyLoadContext();
result = alc.LoadFromAssemblyPath(normalizedPath);
s_loadfile.Add(normalizedPath, result);
}
return result;
}
/*
* Get the assembly that the current code is running from.
*/
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly GetExecutingAssembly()
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeAssembly.GetExecutingAssembly(ref stackMark);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly GetCallingAssembly()
{
// LookForMyCallersCaller is not guarantee to return the correct stack frame
// because of inlining, tail calls, etc. As a result GetCallingAssembly is not
// ganranteed to return the correct result. We should document it as such.
StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;
return RuntimeAssembly.GetExecutingAssembly(ref stackMark);
}
public static Assembly GetEntryAssembly()
{
AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
if (domainManager == null)
domainManager = new AppDomainManager();
return domainManager.EntryAssembly;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using VideoAnalyzer.Tests.Helpers;
using Microsoft.Azure.Management.VideoAnalyzer;
using Microsoft.Azure.Management.VideoAnalyzer.Models;
using Microsoft.Azure.Management.Resources;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Xunit;
namespace VideoAnalyzer.Tests.ScenarioTests
{
public class VideoAnalyzerTests : VideoAnalyzerTestBase
{
[Fact]
public void VideoAnalyzerCheckNameAvailabiltyTest()
{
using (MockContext context = this.StartMockContextAndInitializeClients(this.GetType()))
{
try
{
var videoAnalyzers = VideoAnalyzerClient.VideoAnalyzers.List(ResourceGroup);
Assert.Empty(videoAnalyzers.Value);
var location = VideoAnalyzerManagementTestUtilities.TryGetLocation(ResourceClient, VideoAnalyzerManagementTestUtilities.DefaultLocation);
var lowerCaseLocationWithoutSpaces = location.Replace(" ", string.Empty).ToLowerInvariant();
string videoAnalyzerType = "Microsoft.Media/VideoAnalyzers";
CreateVideoAnalyzerAccount();
videoAnalyzers = VideoAnalyzerClient.VideoAnalyzers.List(ResourceGroup);
Assert.Single(videoAnalyzers.Value);
// check name availabilty
var checkNameAvailabilityOutput = VideoAnalyzerClient.Locations.CheckNameAvailability(lowerCaseLocationWithoutSpaces, AccountName, videoAnalyzerType);
Assert.False(checkNameAvailabilityOutput.NameAvailable);
}
finally
{
DeleteVideoAnalyzerAccount();
}
}
}
[Fact]
public void VideoAnalyzerListByResourceGroupTest()
{
using (MockContext context = this.StartMockContextAndInitializeClients(this.GetType()))
{
try
{
var videoAnalyzers = VideoAnalyzerClient.VideoAnalyzers.List(ResourceGroup);
Assert.Empty(videoAnalyzers.Value);
CreateVideoAnalyzerAccount();
var location = VideoAnalyzerManagementTestUtilities.TryGetLocation(ResourceClient, VideoAnalyzerManagementTestUtilities.DefaultLocation);
var lowerCaseLocationWithoutSpaces = location.Replace(" ", string.Empty).ToLowerInvariant(); // TODO: Fix this once the bug is addressed
videoAnalyzers = VideoAnalyzerClient.VideoAnalyzers.List(ResourceGroup);
Assert.Single(videoAnalyzers.Value);
}
finally
{
DeleteVideoAnalyzerAccount();
}
}
}
[Fact]
public void VideoAnalyzerGetTest()
{
using (MockContext context = this.StartMockContextAndInitializeClients(this.GetType()))
{
try
{
var videoAnalyzers = VideoAnalyzerClient.VideoAnalyzers.List(ResourceGroup);
Assert.Empty(videoAnalyzers.Value);
CreateVideoAnalyzerAccount();
var location = VideoAnalyzerManagementTestUtilities.TryGetLocation(ResourceClient, VideoAnalyzerManagementTestUtilities.DefaultLocation);
var lowerCaseLocationWithoutSpaces = location.Replace(" ", string.Empty).ToLowerInvariant(); // TODO: Fix this once the bug is addressed
videoAnalyzers = VideoAnalyzerClient.VideoAnalyzers.List(ResourceGroup);
Assert.Single(videoAnalyzers.Value);
var VideoAnalyzerGet = VideoAnalyzerClient.VideoAnalyzers.Get(ResourceGroup, AccountName);
Assert.NotNull(VideoAnalyzerGet);
Assert.Equal(AccountName, VideoAnalyzerGet.Name);
Assert.Equal(new Dictionary<string, string>
{
{ "key1","value1"},
{ "key2","value2"}
}, VideoAnalyzerGet.Tags);
Assert.Equal(1, VideoAnalyzerGet.StorageAccounts.Count);
Assert.Equal(StorageAccount.Id, VideoAnalyzerGet.StorageAccounts.ElementAt(0).Id);
}
finally
{
DeleteVideoAnalyzerAccount();
}
}
}
[Fact]
public void VideoAnalyzerCreateTest()
{
var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler3 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler4 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler5 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType()))
{
// Create clients
var videoAnalyzerClient = VideoAnalyzerManagementTestUtilities.GetVideoAnalyzerManagementClient(context, handler1);
var resourceClient = VideoAnalyzerManagementTestUtilities.GetResourceManagementClient(context, handler2);
var storageClient = VideoAnalyzerManagementTestUtilities.GetStorageManagementClient(context, handler3);
var identityManagementClient = VideoAnalyzerManagementTestUtilities.GetManagedIdentityClient(context, handler4);
var authorizationManagementClient = VideoAnalyzerManagementTestUtilities.GetAuthorizationManagementClient(context, handler5);
var location = VideoAnalyzerManagementTestUtilities.TryGetLocation(resourceClient, VideoAnalyzerManagementTestUtilities.DefaultLocation);
var resourceGroup = VideoAnalyzerManagementTestUtilities.CreateResourceGroup(resourceClient, location);
// Create storage account
var storageAccount = VideoAnalyzerManagementTestUtilities.CreateStorageAccount(storageClient, resourceGroup, location);
var managedIdentity = VideoAnalyzerManagementTestUtilities.CreateManagedIdentity(identityManagementClient, resourceGroup, location);
VideoAnalyzerManagementTestUtilities.AddRoleAssignment(authorizationManagementClient, storageAccount.Id, "Storage Blob Data Contributor", TestUtilities.GenerateGuid().ToString(), managedIdentity.PrincipalId.ToString());
VideoAnalyzerManagementTestUtilities.AddRoleAssignment(authorizationManagementClient, storageAccount.Id, "Reader", TestUtilities.GenerateGuid().ToString(), managedIdentity.PrincipalId.ToString());
// Create a video analyzer account
var accountName = TestUtilities.GenerateName("media");
var tagsCreate = new Dictionary<string, string>
{
{ "key1","value1"},
{ "key2","value2"}
};
var storageAccountsCreate = new List<StorageAccount>
{
new StorageAccount
{
Id = storageAccount.Id,
Identity= new ResourceIdentity
{
UserAssignedIdentity = managedIdentity.Id
}
}
};
var VideoAnalyzer = new VideoAnalyzerAccount
{
Location = VideoAnalyzerManagementTestUtilities.DefaultLocation,
Tags = tagsCreate,
StorageAccounts = storageAccountsCreate,
Identity = new VideoAnalyzerIdentity
{
Type = "UserAssigned",
UserAssignedIdentities = new Dictionary<string, UserAssignedManagedIdentity>()
{
{
managedIdentity.Id, new UserAssignedManagedIdentity()
}
}
}
};
videoAnalyzerClient.VideoAnalyzers.CreateOrUpdate(resourceGroup, accountName, VideoAnalyzer);
var VideoAnalyzerGet = videoAnalyzerClient.VideoAnalyzers.Get(resourceGroup, accountName);
Assert.NotNull(VideoAnalyzerGet);
Assert.Equal(accountName, VideoAnalyzerGet.Name);
Assert.Equal(tagsCreate, VideoAnalyzerGet.Tags);
Assert.Equal(1, VideoAnalyzerGet.StorageAccounts.Count);
Assert.Equal(storageAccount.Id, VideoAnalyzerGet.StorageAccounts.ElementAt(0).Id);
videoAnalyzerClient.VideoAnalyzers.Delete(resourceGroup, accountName);
VideoAnalyzerManagementTestUtilities.DeleteStorageAccount(storageClient, resourceGroup, storageAccount.Name);
VideoAnalyzerManagementTestUtilities.DeleteResourceGroup(resourceClient, resourceGroup);
}
}
[Fact]
public void VideoAnalyzerUpdateTest()
{
using (MockContext context = this.StartMockContextAndInitializeClients(this.GetType()))
{
try
{
var videoAnalyzers = VideoAnalyzerClient.VideoAnalyzers.List(ResourceGroup);
Assert.Empty(videoAnalyzers.Value);
CreateVideoAnalyzerAccount();
var location = VideoAnalyzerManagementTestUtilities.TryGetLocation(ResourceClient, VideoAnalyzerManagementTestUtilities.DefaultLocation);
var lowerCaseLocationWithoutSpaces = location.Replace(" ", string.Empty).ToLowerInvariant(); // TODO: Fix this once the bug is addressed
videoAnalyzers = VideoAnalyzerClient.VideoAnalyzers.List(ResourceGroup);
Assert.Single(videoAnalyzers.Value);
var VideoAnalyzerGet = VideoAnalyzerClient.VideoAnalyzers.Get(ResourceGroup, AccountName);
Assert.NotNull(VideoAnalyzerGet);
Assert.Equal(AccountName, VideoAnalyzerGet.Name);
var tagsUpdated = new Dictionary<string, string>
{
{ "key3","value3"},
{ "key4","value4"}
};
VideoAnalyzerClient.VideoAnalyzers.Update(ResourceGroup, AccountName, new VideoAnalyzerUpdate
{
Tags = tagsUpdated
});
VideoAnalyzerGet = VideoAnalyzerClient.VideoAnalyzers.Get(ResourceGroup, AccountName);
Assert.NotNull(VideoAnalyzerGet);
Assert.Equal(AccountName, VideoAnalyzerGet.Name);
Assert.Equal(tagsUpdated, VideoAnalyzerGet.Tags);
}
finally
{
if (!string.IsNullOrEmpty(StorageAccount.Name))
{
VideoAnalyzerManagementTestUtilities.DeleteStorageAccount(StorageClient, ResourceGroup, StorageAccount.Name);
}
if (ManagedIdentity != null)
{
VideoAnalyzerManagementTestUtilities.DeleteManagedIdentity(IdentityManagementClient, ResourceGroup, ManagedIdentity.Name);
}
if (!string.IsNullOrEmpty(ResourceGroup))
{
VideoAnalyzerManagementTestUtilities.DeleteResourceGroup(ResourceClient, ResourceGroup);
}
}
}
}
[Fact]
public void VideoAnalyzerDeleteTest()
{
using (MockContext context = this.StartMockContextAndInitializeClients(this.GetType()))
{
try
{
var videoAnalyzers = VideoAnalyzerClient.VideoAnalyzers.List(ResourceGroup);
Assert.Empty(videoAnalyzers.Value);
CreateVideoAnalyzerAccount();
var location = VideoAnalyzerManagementTestUtilities.TryGetLocation(ResourceClient, VideoAnalyzerManagementTestUtilities.DefaultLocation);
var lowerCaseLocationWithoutSpaces = location.Replace(" ", string.Empty).ToLowerInvariant(); // TODO: Fix this once the bug is addressed
videoAnalyzers = VideoAnalyzerClient.VideoAnalyzers.List(ResourceGroup);
Assert.Single(videoAnalyzers.Value);
VideoAnalyzerClient.VideoAnalyzers.Delete(ResourceGroup, AccountName);
videoAnalyzers = VideoAnalyzerClient.VideoAnalyzers.List(ResourceGroup);
Assert.Empty(videoAnalyzers.Value);
}
finally
{
DeleteVideoAnalyzerAccount();
}
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// Describes the SDN controller that is to connect with the pool
/// First published in XenServer 7.2.
/// </summary>
public partial class SDN_controller : XenObject<SDN_controller>
{
#region Constructors
public SDN_controller()
{
}
public SDN_controller(string uuid,
sdn_controller_protocol protocol,
string address,
long port)
{
this.uuid = uuid;
this.protocol = protocol;
this.address = address;
this.port = port;
}
/// <summary>
/// Creates a new SDN_controller from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public SDN_controller(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new SDN_controller from a Proxy_SDN_controller.
/// </summary>
/// <param name="proxy"></param>
public SDN_controller(Proxy_SDN_controller proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given SDN_controller.
/// </summary>
public override void UpdateFrom(SDN_controller update)
{
uuid = update.uuid;
protocol = update.protocol;
address = update.address;
port = update.port;
}
internal void UpdateFrom(Proxy_SDN_controller proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
protocol = proxy.protocol == null ? (sdn_controller_protocol) 0 : (sdn_controller_protocol)Helper.EnumParseDefault(typeof(sdn_controller_protocol), (string)proxy.protocol);
address = proxy.address == null ? null : proxy.address;
port = proxy.port == null ? 0 : long.Parse(proxy.port);
}
public Proxy_SDN_controller ToProxy()
{
Proxy_SDN_controller result_ = new Proxy_SDN_controller();
result_.uuid = uuid ?? "";
result_.protocol = sdn_controller_protocol_helper.ToString(protocol);
result_.address = address ?? "";
result_.port = port.ToString();
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this SDN_controller
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("protocol"))
protocol = (sdn_controller_protocol)Helper.EnumParseDefault(typeof(sdn_controller_protocol), Marshalling.ParseString(table, "protocol"));
if (table.ContainsKey("address"))
address = Marshalling.ParseString(table, "address");
if (table.ContainsKey("port"))
port = Marshalling.ParseLong(table, "port");
}
public bool DeepEquals(SDN_controller other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._protocol, other._protocol) &&
Helper.AreEqual2(this._address, other._address) &&
Helper.AreEqual2(this._port, other._port);
}
internal static List<SDN_controller> ProxyArrayToObjectList(Proxy_SDN_controller[] input)
{
var result = new List<SDN_controller>();
foreach (var item in input)
result.Add(new SDN_controller(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, SDN_controller server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given SDN_controller.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static SDN_controller get_record(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_record(session.opaque_ref, _sdn_controller);
else
return new SDN_controller(session.proxy.sdn_controller_get_record(session.opaque_ref, _sdn_controller ?? "").parse());
}
/// <summary>
/// Get a reference to the SDN_controller instance with the specified UUID.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<SDN_controller> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<SDN_controller>.Create(session.proxy.sdn_controller_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given SDN_controller.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static string get_uuid(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_uuid(session.opaque_ref, _sdn_controller);
else
return session.proxy.sdn_controller_get_uuid(session.opaque_ref, _sdn_controller ?? "").parse();
}
/// <summary>
/// Get the protocol field of the given SDN_controller.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static sdn_controller_protocol get_protocol(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_protocol(session.opaque_ref, _sdn_controller);
else
return (sdn_controller_protocol)Helper.EnumParseDefault(typeof(sdn_controller_protocol), (string)session.proxy.sdn_controller_get_protocol(session.opaque_ref, _sdn_controller ?? "").parse());
}
/// <summary>
/// Get the address field of the given SDN_controller.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static string get_address(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_address(session.opaque_ref, _sdn_controller);
else
return session.proxy.sdn_controller_get_address(session.opaque_ref, _sdn_controller ?? "").parse();
}
/// <summary>
/// Get the port field of the given SDN_controller.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static long get_port(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_port(session.opaque_ref, _sdn_controller);
else
return long.Parse(session.proxy.sdn_controller_get_port(session.opaque_ref, _sdn_controller ?? "").parse());
}
/// <summary>
/// Introduce an SDN controller to the pool.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_protocol">Protocol to connect with the controller.</param>
/// <param name="_address">IP address of the controller.</param>
/// <param name="_port">TCP port of the controller.</param>
public static XenRef<SDN_controller> introduce(Session session, sdn_controller_protocol _protocol, string _address, long _port)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_introduce(session.opaque_ref, _protocol, _address, _port);
else
return XenRef<SDN_controller>.Create(session.proxy.sdn_controller_introduce(session.opaque_ref, sdn_controller_protocol_helper.ToString(_protocol), _address ?? "", _port.ToString()).parse());
}
/// <summary>
/// Introduce an SDN controller to the pool.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_protocol">Protocol to connect with the controller.</param>
/// <param name="_address">IP address of the controller.</param>
/// <param name="_port">TCP port of the controller.</param>
public static XenRef<Task> async_introduce(Session session, sdn_controller_protocol _protocol, string _address, long _port)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_sdn_controller_introduce(session.opaque_ref, _protocol, _address, _port);
else
return XenRef<Task>.Create(session.proxy.async_sdn_controller_introduce(session.opaque_ref, sdn_controller_protocol_helper.ToString(_protocol), _address ?? "", _port.ToString()).parse());
}
/// <summary>
/// Remove the OVS manager of the pool and destroy the db record.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static void forget(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.sdn_controller_forget(session.opaque_ref, _sdn_controller);
else
session.proxy.sdn_controller_forget(session.opaque_ref, _sdn_controller ?? "").parse();
}
/// <summary>
/// Remove the OVS manager of the pool and destroy the db record.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param>
public static XenRef<Task> async_forget(Session session, string _sdn_controller)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_sdn_controller_forget(session.opaque_ref, _sdn_controller);
else
return XenRef<Task>.Create(session.proxy.async_sdn_controller_forget(session.opaque_ref, _sdn_controller ?? "").parse());
}
/// <summary>
/// Return a list of all the SDN_controllers known to the system.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<SDN_controller>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_all(session.opaque_ref);
else
return XenRef<SDN_controller>.Create(session.proxy.sdn_controller_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the SDN_controller Records at once, in a single XML RPC call
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<SDN_controller>, SDN_controller> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.sdn_controller_get_all_records(session.opaque_ref);
else
return XenRef<SDN_controller>.Create<Proxy_SDN_controller>(session.proxy.sdn_controller_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// Protocol to connect with SDN controller
/// </summary>
[JsonConverter(typeof(sdn_controller_protocolConverter))]
public virtual sdn_controller_protocol protocol
{
get { return _protocol; }
set
{
if (!Helper.AreEqual(value, _protocol))
{
_protocol = value;
Changed = true;
NotifyPropertyChanged("protocol");
}
}
}
private sdn_controller_protocol _protocol = sdn_controller_protocol.ssl;
/// <summary>
/// IP address of the controller
/// </summary>
public virtual string address
{
get { return _address; }
set
{
if (!Helper.AreEqual(value, _address))
{
_address = value;
Changed = true;
NotifyPropertyChanged("address");
}
}
}
private string _address = "";
/// <summary>
/// TCP port of the controller
/// </summary>
public virtual long port
{
get { return _port; }
set
{
if (!Helper.AreEqual(value, _port))
{
_port = value;
Changed = true;
NotifyPropertyChanged("port");
}
}
}
private long _port = 0;
}
}
| |
using System;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;
using System.Diagnostics;
using System.Windows.Documents;
using System.Windows.Media;
using SyNet.GuiHelpers.Adorners;
namespace SyNet.GuiHelpers
{
/// <summary>
/// EditBox is a customized cotrol that can switch between two modes: editing and normal.
/// when it is in editing mode, a TextBox will show up to enable editing. When in normal mode, it
/// displays content as a TextBlock.
///
/// This control can only be used in GridView to enable editing.
/// </summary>
public class EditBox : Control
{
#region Static Constructor
/// <summary>
/// Static constructor
/// </summary>
static EditBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(EditBox), new FrameworkPropertyMetadata(typeof(EditBox)));
}
#endregion
#region Public Methods
/// <summary>
/// Called when the Template's tree has been generated
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
TextBlock textBlock = GetTemplateChild("PART_TextBlockPart") as TextBlock;
Debug.Assert(textBlock != null, "No TextBlock!");
_textBox = new TextBox();
_adorner = new EditBoxAdorner(textBlock, _textBox);
AdornerLayer layer = AdornerLayer.GetAdornerLayer(textBlock); ;
layer.Add(_adorner);
_textBox.KeyDown += new KeyEventHandler(OnTextBoxKeyDown);
_textBox.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(OnTextBoxLostKeyboardFocus);
//hook resize event to handle the the column resize.
HookTemplateParentResizeEvent();
//hook the resize event to handle ListView resize cases.
HookItemsControlEvents();
_listViewItem = GetDependencyObjectFromVisualTree(this, typeof(ListViewItem)) as ListViewItem;
Debug.Assert(_listViewItem != null, "No ListViewItem found");
}
#endregion
#region Protected Methods
/// <summary>
/// If the ListView that contains EditBox is selected, when Mouse enters it, it can switch to editale mode now.
/// </summary>
protected override void OnMouseEnter(MouseEventArgs e)
{
base.OnMouseEnter(e);
if (!IsEditing && IsParentSelected)
{
_canBeEdit = true;
}
}
/// <summary>
/// If mouse leave it, no matter wheher the ListViewItem that contains it is selected or not,
/// it can not switch into Editable mode.
/// </summary>
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
_isMouseWithinScope = false;
_canBeEdit = false;
}
/// <summary>
/// When ListViewItem that contains EditBox is selected and this event happens, if one of the following conditions is satisified, EditBox will be switched EditBox into editable mode.
/// 1. A MouseEnter happened before this.
/// 2. Mouse never move out of it since the ListViewItem was selected.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
if (e.ChangedButton == MouseButton.Right || e.ChangedButton == MouseButton.Middle)
return;
if (!IsEditing)
{
if (!e.Handled && (_canBeEdit || _isMouseWithinScope))
{
IsEditing = true;
}
//Handle a specific case: After a ListViewItem was selected by clicking it,
// Clicking the EditBox again should switch into Editable mode.
if (IsParentSelected)
_isMouseWithinScope = true;
}
}
#endregion
#region Public Properties
#region Value
/// <summary>
/// ValueProperty DependencyProperty.
/// </summary>
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register(
"Value",
typeof(object),
typeof(EditBox),
new FrameworkPropertyMetadata(null));
/// <summary>
/// The value of the EditBox
/// </summary>
public object Value
{
get { return GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
#endregion
#region IsEditing
/// <summary>
/// IsEditingProperty DependencyProperty
/// </summary>
public static DependencyProperty IsEditingProperty =
DependencyProperty.Register(
"IsEditing",
typeof(bool),
typeof(EditBox),
new FrameworkPropertyMetadata(false));
/// <summary>
/// True if the control is in editing mode
/// </summary>
public bool IsEditing
{
get { return (bool)GetValue(IsEditingProperty); }
private set
{
SetValue(IsEditingProperty, value);
_adorner.UpdateVisibilty(value);
}
}
#endregion
#region IsParentSelected
/// <summary>
/// Whether the ListViewItem that contains it is selected.
/// </summary>
private bool IsParentSelected
{
get
{
if (_listViewItem == null)
return false;
else
return _listViewItem.IsSelected;
}
}
#endregion
#endregion
#region Private Methods
/// <summary>
/// When in editable mode,Pressing Enter Key and F2 Key make it switch into normal model
/// </summary>
private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
{
if (IsEditing && (e.Key == Key.Enter || e.Key == Key.F2))
{
IsEditing = false;
_canBeEdit = false;
}
}
/// <summary>
/// When in editable mode, losing focus make it switch into normal mode.
/// </summary>
private void OnTextBoxLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
IsEditing = false;
}
/// <summary>
/// Set IsEditing to false when parent has changed its size
/// </summary>
private void OnCouldSwitchToNormalMode(object sender, RoutedEventArgs e)
{
IsEditing = false;
}
/// <summary>
/// Walk the visual tree to find the ItemsControl and hook its some events on it.
/// </summary>
private void HookItemsControlEvents()
{
_itemsControl = GetDependencyObjectFromVisualTree(this, typeof(ItemsControl)) as ItemsControl;
if (_itemsControl != null)
{
//The reason of hooking Resize/ScrollChange/MouseWheel event is :
//when one of these event happens, the EditBox should be switched into editable mode.
_itemsControl.SizeChanged += new SizeChangedEventHandler(OnCouldSwitchToNormalMode);
_itemsControl.AddHandler(ScrollViewer.ScrollChangedEvent, new RoutedEventHandler(OnScrollViewerChanged));
_itemsControl.AddHandler(ScrollViewer.MouseWheelEvent, new RoutedEventHandler(OnCouldSwitchToNormalMode), true);
}
}
/// <summary>
/// If EditBox is in editable mode, scrolling ListView should switch it into normal mode.
/// </summary>
private void OnScrollViewerChanged(object sender, RoutedEventArgs args)
{
if (IsEditing && Mouse.PrimaryDevice.LeftButton == MouseButtonState.Pressed)
{
IsEditing = false;
}
}
/// <summary>
/// Walk visual tree to find the first DependencyObject of the specific type.
/// </summary>
private DependencyObject GetDependencyObjectFromVisualTree(DependencyObject startObject, Type type)
{
//Iterate the visual tree to get the parent(ItemsControl) of this control
DependencyObject parent = startObject;
while (parent != null)
{
if (type.IsInstanceOfType(parent))
break;
else
parent = VisualTreeHelper.GetParent(parent);
}
return parent;
}
/// <summary>
/// Get the TemplatedParent and hook its resize event.
/// The reason of hooking this event is that when resize a column, the EditBox should switch editable mode.
/// </summary>
private void HookTemplateParentResizeEvent()
{
FrameworkElement parent = TemplatedParent as FrameworkElement;
if (parent != null)
{
parent.SizeChanged += new SizeChangedEventHandler(OnCouldSwitchToNormalMode);
}
}
#endregion
#region private variable
private EditBoxAdorner _adorner; //The AdornerLayer on the TextBlock
private FrameworkElement _textBox; //TextBox in visual tree.
private bool _canBeEdit = false; //Whether EditBox can swithc into Editable mode. If the ListViewItem that contain the EditBox is selected, when mouse enter the EditBox, it becomes true
private bool _isMouseWithinScope = false; //whether can swithc into Editable mode. If the ListViewItem that contain the EditBox is selected, when mouse is over the EditBox, it becomes true.
private ItemsControl _itemsControl; //The ListView that contains it.
private ListViewItem _listViewItem; //The ListViewItem that contains it.
#endregion
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using Encog.MathUtil.RBF;
using Encog.Util;
namespace Encog.Neural.SOM.Training.Neighborhood
{
/// <summary>
/// Implements a multi-dimensional RBF neighborhood function.
/// </summary>
///
public class NeighborhoodRBF : INeighborhoodFunction
{
/// <summary>
/// The radial basis function to use.
/// </summary>
///
private readonly IRadialBasisFunction _rbf;
/// <summary>
/// The size of each dimension.
/// </summary>
///
private readonly int[] _size;
/// <summary>
/// The displacement of each dimension, when mapping the dimensions
/// to a 1d array.
/// </summary>
///
private int[] _displacement;
/// <summary>
/// Construct a 2d neighborhood function based on the sizes for the
/// x and y dimensions.
/// </summary>
///
/// <param name="type">The RBF type to use.</param>
/// <param name="x">The size of the x-dimension.</param>
/// <param name="y">The size of the y-dimension.</param>
public NeighborhoodRBF(RBFEnum type, int x, int y)
{
var size = new int[2];
size[0] = x;
size[1] = y;
var centerArray = new double[2];
centerArray[0] = 0;
centerArray[1] = 0;
var widthArray = new double[2];
widthArray[0] = 1;
widthArray[1] = 1;
switch (type)
{
case RBFEnum.Gaussian:
_rbf = new GaussianFunction(2);
break;
case RBFEnum.InverseMultiquadric:
_rbf = new InverseMultiquadricFunction(2);
break;
case RBFEnum.Multiquadric:
_rbf = new MultiquadricFunction(2);
break;
case RBFEnum.MexicanHat:
_rbf = new MexicanHatFunction(2);
break;
}
_rbf.Width = 1;
EngineArray.ArrayCopy(centerArray, _rbf.Centers);
_size = size;
CalculateDisplacement();
}
/// <summary>
/// Construct a multi-dimensional neighborhood function.
/// </summary>
///
/// <param name="size">The sizes of each dimension.</param>
/// <param name="type">The RBF type to use.</param>
public NeighborhoodRBF(int[] size, RBFEnum type)
{
switch (type)
{
case RBFEnum.Gaussian:
_rbf = new GaussianFunction(2);
break;
case RBFEnum.InverseMultiquadric:
_rbf = new InverseMultiquadricFunction(2);
break;
case RBFEnum.Multiquadric:
_rbf = new MultiquadricFunction(2);
break;
case RBFEnum.MexicanHat:
_rbf = new MexicanHatFunction(2);
break;
}
_size = size;
CalculateDisplacement();
}
/// <value>The RBF to use.</value>
public IRadialBasisFunction RBF
{
get { return _rbf; }
}
#region INeighborhoodFunction Members
/// <summary>
/// Calculate the value for the multi RBF function.
/// </summary>
///
/// <param name="currentNeuron">The current neuron.</param>
/// <param name="bestNeuron">The best neuron.</param>
/// <returns>A percent that determines the amount of training the current
/// neuron should get. Usually 100% when it is the bestNeuron.</returns>
public virtual double Function(int currentNeuron, int bestNeuron)
{
var vector = new double[_displacement.Length];
int[] vectorCurrent = TranslateCoordinates(currentNeuron);
int[] vectorBest = TranslateCoordinates(bestNeuron);
for (int i = 0; i < vectorCurrent.Length; i++)
{
vector[i] = vectorCurrent[i] - vectorBest[i];
}
return _rbf.Calculate(vector);
}
/// <summary>
/// Set the radius.
/// </summary>
public virtual double Radius
{
get { return _rbf.Width; }
set { _rbf.Width = value; }
}
#endregion
/// <summary>
/// Calculate all of the displacement values.
/// </summary>
///
private void CalculateDisplacement()
{
_displacement = new int[_size.Length];
for (int i = 0; i < _size.Length; i++)
{
int v;
if (i == 0)
{
v = 0;
}
else if (i == 1)
{
v = _size[0];
}
else
{
v = _displacement[i - 1]*_size[i - 1];
}
_displacement[i] = v;
}
}
/// <summary>
/// Translate the specified index into a set of multi-dimensional
/// coordinates that represent the same index. This is how the
/// multi-dimensional coordinates are translated into a one dimensional
/// index for the input neurons.
/// </summary>
///
/// <param name="index">The index to translate.</param>
/// <returns>The multi-dimensional coordinates.</returns>
private int[] TranslateCoordinates(int index)
{
var result = new int[_displacement.Length];
int countingIndex = index;
for (int i = _displacement.Length - 1; i >= 0; i--)
{
int v;
if (_displacement[i] > 0)
{
v = countingIndex/_displacement[i];
}
else
{
v = countingIndex;
}
countingIndex -= _displacement[i]*v;
result[i] = v;
}
return result;
}
}
}
| |
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 DurandalAuth.Web.Areas.HelpPage.ModelDescriptions;
using DurandalAuth.Web.Areas.HelpPage.Models;
namespace DurandalAuth.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// 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.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Elasticsearch.Net;
//Generated File Please Do Not Edit Manually
namespace Nest
{
///<summary>
///Raw operations with elasticsearch
///</summary>
internal static class Dispatcher
{
internal static ElasticsearchResponse<T> WatcherAckWatchDispatch<T>(this IElasticsearchClient client, ElasticsearchPathInfo<AcknowledgeWatchRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.PUT:
//PUT /_watcher/watch/{watch_id}/{action_id}/_ack
if (!pathInfo.WatchId.IsNullOrEmpty() && !pathInfo.ActionId.IsNullOrEmpty())
return client.WatcherAckWatch<T>(pathInfo.WatchId,pathInfo.ActionId,u => pathInfo.RequestParameters);
//PUT /_watcher/watch/{watch_id}/_ack
if (!pathInfo.WatchId.IsNullOrEmpty())
return client.WatcherAckWatch<T>(pathInfo.WatchId,u => pathInfo.RequestParameters);
break;
case PathInfoHttpMethod.POST:
//POST /_watcher/watch/{watch_id}/{action_id}/_ack
if (!pathInfo.WatchId.IsNullOrEmpty() && !pathInfo.ActionId.IsNullOrEmpty())
return client.WatcherAckWatchPost<T>(pathInfo.WatchId,pathInfo.ActionId,u => pathInfo.RequestParameters);
//POST /_watcher/watch/{watch_id}/_ack
if (!pathInfo.WatchId.IsNullOrEmpty())
return client.WatcherAckWatchPost<T>(pathInfo.WatchId,u => pathInfo.RequestParameters);
break;
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherAckWatch() into any of the following paths: \r\n - /_watcher/watch/{watch_id}/_ack\r\n - /_watcher/watch/{watch_id}/{action_id}/_ack");
}
internal static Task<ElasticsearchResponse<T>> WatcherAckWatchDispatchAsync<T>(this IElasticsearchClient client, ElasticsearchPathInfo<AcknowledgeWatchRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.PUT:
//PUT /_watcher/watch/{watch_id}/{action_id}/_ack
if (!pathInfo.WatchId.IsNullOrEmpty() && !pathInfo.ActionId.IsNullOrEmpty())
return client.WatcherAckWatchAsync<T>(pathInfo.WatchId,pathInfo.ActionId,u => pathInfo.RequestParameters);
//PUT /_watcher/watch/{watch_id}/_ack
if (!pathInfo.WatchId.IsNullOrEmpty())
return client.WatcherAckWatchAsync<T>(pathInfo.WatchId,u => pathInfo.RequestParameters);
break;
case PathInfoHttpMethod.POST:
//POST /_watcher/watch/{watch_id}/{action_id}/_ack
if (!pathInfo.WatchId.IsNullOrEmpty() && !pathInfo.ActionId.IsNullOrEmpty())
return client.WatcherAckWatchPostAsync<T>(pathInfo.WatchId,pathInfo.ActionId,u => pathInfo.RequestParameters);
//POST /_watcher/watch/{watch_id}/_ack
if (!pathInfo.WatchId.IsNullOrEmpty())
return client.WatcherAckWatchPostAsync<T>(pathInfo.WatchId,u => pathInfo.RequestParameters);
break;
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherAckWatch() into any of the following paths: \r\n - /_watcher/watch/{watch_id}/_ack\r\n - /_watcher/watch/{watch_id}/{action_id}/_ack");
}
internal static ElasticsearchResponse<T> WatcherDeleteWatchDispatch<T>(this IElasticsearchClient client, ElasticsearchPathInfo<DeleteWatchRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.DELETE:
//DELETE /_watcher/watch/{id}
if (!pathInfo.Id.IsNullOrEmpty())
return client.WatcherDeleteWatch<T>(pathInfo.Id,u => pathInfo.RequestParameters);
break;
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherDeleteWatch() into any of the following paths: \r\n - /_watcher/watch/{id}");
}
internal static Task<ElasticsearchResponse<T>> WatcherDeleteWatchDispatchAsync<T>(this IElasticsearchClient client, ElasticsearchPathInfo<DeleteWatchRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.DELETE:
//DELETE /_watcher/watch/{id}
if (!pathInfo.Id.IsNullOrEmpty())
return client.WatcherDeleteWatchAsync<T>(pathInfo.Id,u => pathInfo.RequestParameters);
break;
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherDeleteWatch() into any of the following paths: \r\n - /_watcher/watch/{id}");
}
internal static ElasticsearchResponse<T> WatcherExecuteWatchDispatch<T>(this IElasticsearchClient client, ElasticsearchPathInfo<ExecuteWatchRequestParameters> elasticsearchPathInfo, object body, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.PUT:
//PUT /_watcher/watch/{id}/_execute
if (!pathInfo.Id.IsNullOrEmpty() && body != null)
return client.WatcherExecuteWatch<T>(pathInfo.Id,body,u => pathInfo.RequestParameters);
//PUT /_watcher/watch/_execute
if (body != null)
return client.WatcherExecuteWatch<T>(body,u => pathInfo.RequestParameters);
break;
case PathInfoHttpMethod.POST:
//POST /_watcher/watch/{id}/_execute
if (!pathInfo.Id.IsNullOrEmpty() && body != null)
return client.WatcherExecuteWatchPost<T>(pathInfo.Id,body,u => pathInfo.RequestParameters);
//POST /_watcher/watch/_execute
if (body != null)
return client.WatcherExecuteWatchPost<T>(body,u => pathInfo.RequestParameters);
break;
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherExecuteWatch() into any of the following paths: \r\n - /_watcher/watch/{id}/_execute\r\n - /_watcher/watch/_execute");
}
internal static Task<ElasticsearchResponse<T>> WatcherExecuteWatchDispatchAsync<T>(this IElasticsearchClient client, ElasticsearchPathInfo<ExecuteWatchRequestParameters> elasticsearchPathInfo, object body, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.PUT:
//PUT /_watcher/watch/{id}/_execute
if (!pathInfo.Id.IsNullOrEmpty() && body != null)
return client.WatcherExecuteWatchAsync<T>(pathInfo.Id,body,u => pathInfo.RequestParameters);
//PUT /_watcher/watch/_execute
if (body != null)
return client.WatcherExecuteWatchAsync<T>(body,u => pathInfo.RequestParameters);
break;
case PathInfoHttpMethod.POST:
//POST /_watcher/watch/{id}/_execute
if (!pathInfo.Id.IsNullOrEmpty() && body != null)
return client.WatcherExecuteWatchPostAsync<T>(pathInfo.Id,body,u => pathInfo.RequestParameters);
//POST /_watcher/watch/_execute
if (body != null)
return client.WatcherExecuteWatchPostAsync<T>(body,u => pathInfo.RequestParameters);
break;
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherExecuteWatch() into any of the following paths: \r\n - /_watcher/watch/{id}/_execute\r\n - /_watcher/watch/_execute");
}
internal static ElasticsearchResponse<T> WatcherGetWatchDispatch<T>(this IElasticsearchClient client, ElasticsearchPathInfo<GetWatchRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.GET:
//GET /_watcher/watch/{id}
if (!pathInfo.Id.IsNullOrEmpty())
return client.WatcherGetWatch<T>(pathInfo.Id,u => pathInfo.RequestParameters);
break;
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherGetWatch() into any of the following paths: \r\n - /_watcher/watch/{id}");
}
internal static Task<ElasticsearchResponse<T>> WatcherGetWatchDispatchAsync<T>(this IElasticsearchClient client, ElasticsearchPathInfo<GetWatchRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.GET:
//GET /_watcher/watch/{id}
if (!pathInfo.Id.IsNullOrEmpty())
return client.WatcherGetWatchAsync<T>(pathInfo.Id,u => pathInfo.RequestParameters);
break;
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherGetWatch() into any of the following paths: \r\n - /_watcher/watch/{id}");
}
internal static ElasticsearchResponse<T> WatcherInfoDispatch<T>(this IElasticsearchClient client, ElasticsearchPathInfo<WatcherInfoRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.GET:
//GET /_watcher/
return client.WatcherInfo<T>(u => pathInfo.RequestParameters);
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherInfo() into any of the following paths: \r\n - /_watcher/");
}
internal static Task<ElasticsearchResponse<T>> WatcherInfoDispatchAsync<T>(this IElasticsearchClient client, ElasticsearchPathInfo<WatcherInfoRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.GET:
//GET /_watcher/
return client.WatcherInfoAsync<T>(u => pathInfo.RequestParameters);
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherInfo() into any of the following paths: \r\n - /_watcher/");
}
internal static ElasticsearchResponse<T> WatcherPutWatchDispatch<T>(this IElasticsearchClient client, ElasticsearchPathInfo<PutWatchRequestParameters> elasticsearchPathInfo, object body, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.PUT:
//PUT /_watcher/watch/{id}
if (!pathInfo.Id.IsNullOrEmpty() && body != null)
return client.WatcherPutWatch<T>(pathInfo.Id,body,u => pathInfo.RequestParameters);
break;
case PathInfoHttpMethod.POST:
//POST /_watcher/watch/{id}
if (!pathInfo.Id.IsNullOrEmpty() && body != null)
return client.WatcherPutWatchPost<T>(pathInfo.Id,body,u => pathInfo.RequestParameters);
break;
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherPutWatch() into any of the following paths: \r\n - /_watcher/watch/{id}");
}
internal static Task<ElasticsearchResponse<T>> WatcherPutWatchDispatchAsync<T>(this IElasticsearchClient client, ElasticsearchPathInfo<PutWatchRequestParameters> elasticsearchPathInfo, object body, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.PUT:
//PUT /_watcher/watch/{id}
if (!pathInfo.Id.IsNullOrEmpty() && body != null)
return client.WatcherPutWatchAsync<T>(pathInfo.Id,body,u => pathInfo.RequestParameters);
break;
case PathInfoHttpMethod.POST:
//POST /_watcher/watch/{id}
if (!pathInfo.Id.IsNullOrEmpty() && body != null)
return client.WatcherPutWatchPostAsync<T>(pathInfo.Id,body,u => pathInfo.RequestParameters);
break;
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherPutWatch() into any of the following paths: \r\n - /_watcher/watch/{id}");
}
internal static ElasticsearchResponse<T> WatcherRestartDispatch<T>(this IElasticsearchClient client, ElasticsearchPathInfo<RestartWatcherRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.PUT:
//PUT /_watcher/_restart
return client.WatcherRestart<T>(u => pathInfo.RequestParameters);
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherRestart() into any of the following paths: \r\n - /_watcher/_restart");
}
internal static Task<ElasticsearchResponse<T>> WatcherRestartDispatchAsync<T>(this IElasticsearchClient client, ElasticsearchPathInfo<RestartWatcherRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.PUT:
//PUT /_watcher/_restart
return client.WatcherRestartAsync<T>(u => pathInfo.RequestParameters);
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherRestart() into any of the following paths: \r\n - /_watcher/_restart");
}
internal static ElasticsearchResponse<T> WatcherStartDispatch<T>(this IElasticsearchClient client, ElasticsearchPathInfo<StartWatcherRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.PUT:
//PUT /_watcher/_start
return client.WatcherStart<T>(u => pathInfo.RequestParameters);
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherStart() into any of the following paths: \r\n - /_watcher/_start");
}
internal static Task<ElasticsearchResponse<T>> WatcherStartDispatchAsync<T>(this IElasticsearchClient client, ElasticsearchPathInfo<StartWatcherRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.PUT:
//PUT /_watcher/_start
return client.WatcherStartAsync<T>(u => pathInfo.RequestParameters);
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherStart() into any of the following paths: \r\n - /_watcher/_start");
}
internal static ElasticsearchResponse<T> WatcherStatsDispatch<T>(this IElasticsearchClient client, ElasticsearchPathInfo<WatcherStatsRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.GET:
//GET /_watcher/stats/{metric}
if (pathInfo.Metric != null)
return client.WatcherStats<T>(pathInfo.Metric,u => pathInfo.RequestParameters);
//GET /_watcher/stats
return client.WatcherStats<T>(u => pathInfo.RequestParameters);
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherStats() into any of the following paths: \r\n - /_watcher/stats\r\n - /_watcher/stats/{metric}");
}
internal static Task<ElasticsearchResponse<T>> WatcherStatsDispatchAsync<T>(this IElasticsearchClient client, ElasticsearchPathInfo<WatcherStatsRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.GET:
//GET /_watcher/stats/{metric}
if (pathInfo.Metric != null)
return client.WatcherStatsAsync<T>(pathInfo.Metric,u => pathInfo.RequestParameters);
//GET /_watcher/stats
return client.WatcherStatsAsync<T>(u => pathInfo.RequestParameters);
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherStats() into any of the following paths: \r\n - /_watcher/stats\r\n - /_watcher/stats/{metric}");
}
internal static ElasticsearchResponse<T> WatcherStopDispatch<T>(this IElasticsearchClient client, ElasticsearchPathInfo<StopWatcherRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.PUT:
//PUT /_watcher/_stop
return client.WatcherStop<T>(u => pathInfo.RequestParameters);
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherStop() into any of the following paths: \r\n - /_watcher/_stop");
}
internal static Task<ElasticsearchResponse<T>> WatcherStopDispatchAsync<T>(this IElasticsearchClient client, ElasticsearchPathInfo<StopWatcherRequestParameters> elasticsearchPathInfo, string watchId = null, string actionId = null, Metric metric = Metric.All)
{
var pathInfo = elasticsearchPathInfo.ToWatcherPathInfo(watchId, actionId, metric);
switch(pathInfo.HttpMethod)
{
case PathInfoHttpMethod.PUT:
//PUT /_watcher/_stop
return client.WatcherStopAsync<T>(u => pathInfo.RequestParameters);
}
throw new DispatchException("Could not dispatch IElasticClient.WatcherStop() into any of the following paths: \r\n - /_watcher/_stop");
}
}
}
| |
// DeflaterHuffman.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace TvdbLib.SharpZipLib.Zip.Compression
{
/// <summary>
/// This is the DeflaterHuffman class.
///
/// This class is <i>not</i> thread safe. This is inherent in the API, due
/// to the split of Deflate and SetInput.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class DeflaterHuffman
{
const int BUFSIZE = 1 << (DeflaterConstants.DEFAULT_MEM_LEVEL + 6);
const int LITERAL_NUM = 286;
// Number of distance codes
const int DIST_NUM = 30;
// Number of codes used to transfer bit lengths
const int BITLEN_NUM = 19;
// repeat previous bit length 3-6 times (2 bits of repeat count)
const int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
const int REP_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
const int REP_11_138 = 18;
const int EOF_SYMBOL = 256;
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit length codes.
static readonly int[] BL_ORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
static readonly byte[] bit4Reverse = {
0,
8,
4,
12,
2,
10,
6,
14,
1,
9,
5,
13,
3,
11,
7,
15
};
static short[] staticLCodes;
static byte[] staticLLength;
static short[] staticDCodes;
static byte[] staticDLength;
class Tree
{
#region Instance Fields
public short[] freqs;
public byte[] length;
public int minNumCodes;
public int numCodes;
short[] codes;
int[] bl_counts;
int maxLength;
DeflaterHuffman dh;
#endregion
#region Constructors
public Tree(DeflaterHuffman dh, int elems, int minCodes, int maxLength)
{
this.dh = dh;
this.minNumCodes = minCodes;
this.maxLength = maxLength;
freqs = new short[elems];
bl_counts = new int[maxLength];
}
#endregion
/// <summary>
/// Resets the internal state of the tree
/// </summary>
public void Reset()
{
for (int i = 0; i < freqs.Length; i++) {
freqs[i] = 0;
}
codes = null;
length = null;
}
public void WriteSymbol(int code)
{
// if (DeflaterConstants.DEBUGGING) {
// freqs[code]--;
// // Console.Write("writeSymbol("+freqs.length+","+code+"): ");
// }
dh.pending.WriteBits(codes[code] & 0xffff, length[code]);
}
/// <summary>
/// Check that all frequencies are zero
/// </summary>
/// <exception cref="SharpZipBaseException">
/// At least one frequency is non-zero
/// </exception>
public void CheckEmpty()
{
bool empty = true;
for (int i = 0; i < freqs.Length; i++) {
if (freqs[i] != 0) {
//Console.WriteLine("freqs[" + i + "] == " + freqs[i]);
empty = false;
}
}
if (!empty) {
throw new SharpZipBaseException("!Empty");
}
}
/// <summary>
/// Set static codes and length
/// </summary>
/// <param name="staticCodes">new codes</param>
/// <param name="staticLengths">length for new codes</param>
public void SetStaticCodes(short[] staticCodes, byte[] staticLengths)
{
codes = staticCodes;
length = staticLengths;
}
/// <summary>
/// Build dynamic codes and lengths
/// </summary>
public void BuildCodes()
{
int numSymbols = freqs.Length;
int[] nextCode = new int[maxLength];
int code = 0;
codes = new short[freqs.Length];
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("buildCodes: "+freqs.Length);
// }
for (int bits = 0; bits < maxLength; bits++) {
nextCode[bits] = code;
code += bl_counts[bits] << (15 - bits);
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("bits: " + ( bits + 1) + " count: " + bl_counts[bits]
// +" nextCode: "+code);
// }
}
#if DebugDeflation
if ( DeflaterConstants.DEBUGGING && (code != 65536) )
{
throw new SharpZipBaseException("Inconsistent bl_counts!");
}
#endif
for (int i=0; i < numCodes; i++) {
int bits = length[i];
if (bits > 0) {
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("codes["+i+"] = rev(" + nextCode[bits-1]+"),
// +bits);
// }
codes[i] = BitReverse(nextCode[bits-1]);
nextCode[bits-1] += 1 << (16 - bits);
}
}
}
public void BuildTree()
{
int numSymbols = freqs.Length;
/* heap is a priority queue, sorted by frequency, least frequent
* nodes first. The heap is a binary tree, with the property, that
* the parent node is smaller than both child nodes. This assures
* that the smallest node is the first parent.
*
* The binary tree is encoded in an array: 0 is root node and
* the nodes 2*n+1, 2*n+2 are the child nodes of node n.
*/
int[] heap = new int[numSymbols];
int heapLen = 0;
int maxCode = 0;
for (int n = 0; n < numSymbols; n++) {
int freq = freqs[n];
if (freq != 0) {
// Insert n into heap
int pos = heapLen++;
int ppos;
while (pos > 0 && freqs[heap[ppos = (pos - 1) / 2]] > freq) {
heap[pos] = heap[ppos];
pos = ppos;
}
heap[pos] = n;
maxCode = n;
}
}
/* We could encode a single literal with 0 bits but then we
* don't see the literals. Therefore we force at least two
* literals to avoid this case. We don't care about order in
* this case, both literals get a 1 bit code.
*/
while (heapLen < 2) {
int node = maxCode < 2 ? ++maxCode : 0;
heap[heapLen++] = node;
}
numCodes = Math.Max(maxCode + 1, minNumCodes);
int numLeafs = heapLen;
int[] childs = new int[4 * heapLen - 2];
int[] values = new int[2 * heapLen - 1];
int numNodes = numLeafs;
for (int i = 0; i < heapLen; i++) {
int node = heap[i];
childs[2 * i] = node;
childs[2 * i + 1] = -1;
values[i] = freqs[node] << 8;
heap[i] = i;
}
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
do {
int first = heap[0];
int last = heap[--heapLen];
// Propagate the hole to the leafs of the heap
int ppos = 0;
int path = 1;
while (path < heapLen) {
if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) {
path++;
}
heap[ppos] = heap[path];
ppos = path;
path = path * 2 + 1;
}
/* Now propagate the last element down along path. Normally
* it shouldn't go too deep.
*/
int lastVal = values[last];
while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) {
heap[path] = heap[ppos];
}
heap[path] = last;
int second = heap[0];
// Create a new node father of first and second
last = numNodes++;
childs[2 * last] = first;
childs[2 * last + 1] = second;
int mindepth = Math.Min(values[first] & 0xff, values[second] & 0xff);
values[last] = lastVal = values[first] + values[second] - mindepth + 1;
// Again, propagate the hole to the leafs
ppos = 0;
path = 1;
while (path < heapLen) {
if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) {
path++;
}
heap[ppos] = heap[path];
ppos = path;
path = ppos * 2 + 1;
}
// Now propagate the new element down along path
while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) {
heap[path] = heap[ppos];
}
heap[path] = last;
} while (heapLen > 1);
if (heap[0] != childs.Length / 2 - 1) {
throw new SharpZipBaseException("Heap invariant violated");
}
BuildLength(childs);
}
/// <summary>
/// Get encoded length
/// </summary>
/// <returns>Encoded length, the sum of frequencies * lengths</returns>
public int GetEncodedLength()
{
int len = 0;
for (int i = 0; i < freqs.Length; i++) {
len += freqs[i] * length[i];
}
return len;
}
/// <summary>
/// Scan a literal or distance tree to determine the frequencies of the codes
/// in the bit length tree.
/// </summary>
public void CalcBLFreq(Tree blTree)
{
int max_count; /* max repeat count */
int min_count; /* min repeat count */
int count; /* repeat count of the current code */
int curlen = -1; /* length of current code */
int i = 0;
while (i < numCodes) {
count = 1;
int nextlen = length[i];
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else {
max_count = 6;
min_count = 3;
if (curlen != nextlen) {
blTree.freqs[nextlen]++;
count = 0;
}
}
curlen = nextlen;
i++;
while (i < numCodes && curlen == length[i]) {
i++;
if (++count >= max_count) {
break;
}
}
if (count < min_count) {
blTree.freqs[curlen] += (short)count;
} else if (curlen != 0) {
blTree.freqs[REP_3_6]++;
} else if (count <= 10) {
blTree.freqs[REP_3_10]++;
} else {
blTree.freqs[REP_11_138]++;
}
}
}
/// <summary>
/// Write tree values
/// </summary>
/// <param name="blTree">Tree to write</param>
public void WriteTree(Tree blTree)
{
int max_count; // max repeat count
int min_count; // min repeat count
int count; // repeat count of the current code
int curlen = -1; // length of current code
int i = 0;
while (i < numCodes) {
count = 1;
int nextlen = length[i];
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else {
max_count = 6;
min_count = 3;
if (curlen != nextlen) {
blTree.WriteSymbol(nextlen);
count = 0;
}
}
curlen = nextlen;
i++;
while (i < numCodes && curlen == length[i]) {
i++;
if (++count >= max_count) {
break;
}
}
if (count < min_count) {
while (count-- > 0) {
blTree.WriteSymbol(curlen);
}
} else if (curlen != 0) {
blTree.WriteSymbol(REP_3_6);
dh.pending.WriteBits(count - 3, 2);
} else if (count <= 10) {
blTree.WriteSymbol(REP_3_10);
dh.pending.WriteBits(count - 3, 3);
} else {
blTree.WriteSymbol(REP_11_138);
dh.pending.WriteBits(count - 11, 7);
}
}
}
void BuildLength(int[] childs)
{
this.length = new byte [freqs.Length];
int numNodes = childs.Length / 2;
int numLeafs = (numNodes + 1) / 2;
int overflow = 0;
for (int i = 0; i < maxLength; i++) {
bl_counts[i] = 0;
}
// First calculate optimal bit lengths
int[] lengths = new int[numNodes];
lengths[numNodes-1] = 0;
for (int i = numNodes - 1; i >= 0; i--) {
if (childs[2 * i + 1] != -1) {
int bitLength = lengths[i] + 1;
if (bitLength > maxLength) {
bitLength = maxLength;
overflow++;
}
lengths[childs[2 * i]] = lengths[childs[2 * i + 1]] = bitLength;
} else {
// A leaf node
int bitLength = lengths[i];
bl_counts[bitLength - 1]++;
this.length[childs[2*i]] = (byte) lengths[i];
}
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Tree "+freqs.Length+" lengths:");
// for (int i=0; i < numLeafs; i++) {
// //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]]
// + " len: "+length[childs[2*i]]);
// }
// }
if (overflow == 0) {
return;
}
int incrBitLen = maxLength - 1;
do {
// Find the first bit length which could increase:
while (bl_counts[--incrBitLen] == 0)
;
// Move this node one down and remove a corresponding
// number of overflow nodes.
do {
bl_counts[incrBitLen]--;
bl_counts[++incrBitLen]++;
overflow -= 1 << (maxLength - 1 - incrBitLen);
} while (overflow > 0 && incrBitLen < maxLength - 1);
} while (overflow > 0);
/* We may have overshot above. Move some nodes from maxLength to
* maxLength-1 in that case.
*/
bl_counts[maxLength-1] += overflow;
bl_counts[maxLength-2] -= overflow;
/* Now recompute all bit lengths, scanning in increasing
* frequency. It is simpler to reconstruct all lengths instead of
* fixing only the wrong ones. This idea is taken from 'ar'
* written by Haruhiko Okumura.
*
* The nodes were inserted with decreasing frequency into the childs
* array.
*/
int nodePtr = 2 * numLeafs;
for (int bits = maxLength; bits != 0; bits--) {
int n = bl_counts[bits-1];
while (n > 0) {
int childPtr = 2*childs[nodePtr++];
if (childs[childPtr + 1] == -1) {
// We found another leaf
length[childs[childPtr]] = (byte) bits;
n--;
}
}
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("*** After overflow elimination. ***");
// for (int i=0; i < numLeafs; i++) {
// //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]]
// + " len: "+length[childs[2*i]]);
// }
// }
}
}
#region Instance Fields
/// <summary>
/// Pending buffer to use
/// </summary>
public DeflaterPending pending;
Tree literalTree;
Tree distTree;
Tree blTree;
// Buffer for distances
short[] d_buf;
byte[] l_buf;
int last_lit;
int extra_bits;
#endregion
static DeflaterHuffman()
{
// See RFC 1951 3.2.6
// Literal codes
staticLCodes = new short[LITERAL_NUM];
staticLLength = new byte[LITERAL_NUM];
int i = 0;
while (i < 144) {
staticLCodes[i] = BitReverse((0x030 + i) << 8);
staticLLength[i++] = 8;
}
while (i < 256) {
staticLCodes[i] = BitReverse((0x190 - 144 + i) << 7);
staticLLength[i++] = 9;
}
while (i < 280) {
staticLCodes[i] = BitReverse((0x000 - 256 + i) << 9);
staticLLength[i++] = 7;
}
while (i < LITERAL_NUM) {
staticLCodes[i] = BitReverse((0x0c0 - 280 + i) << 8);
staticLLength[i++] = 8;
}
// Distance codes
staticDCodes = new short[DIST_NUM];
staticDLength = new byte[DIST_NUM];
for (i = 0; i < DIST_NUM; i++) {
staticDCodes[i] = BitReverse(i << 11);
staticDLength[i] = 5;
}
}
/// <summary>
/// Construct instance with pending buffer
/// </summary>
/// <param name="pending">Pending buffer to use</param>
public DeflaterHuffman(DeflaterPending pending)
{
this.pending = pending;
literalTree = new Tree(this, LITERAL_NUM, 257, 15);
distTree = new Tree(this, DIST_NUM, 1, 15);
blTree = new Tree(this, BITLEN_NUM, 4, 7);
d_buf = new short[BUFSIZE];
l_buf = new byte [BUFSIZE];
}
/// <summary>
/// Reset internal state
/// </summary>
public void Reset()
{
last_lit = 0;
extra_bits = 0;
literalTree.Reset();
distTree.Reset();
blTree.Reset();
}
/// <summary>
/// Write all trees to pending buffer
/// </summary>
/// <param name="blTreeCodes">The number/rank of treecodes to send.</param>
public void SendAllTrees(int blTreeCodes)
{
blTree.BuildCodes();
literalTree.BuildCodes();
distTree.BuildCodes();
pending.WriteBits(literalTree.numCodes - 257, 5);
pending.WriteBits(distTree.numCodes - 1, 5);
pending.WriteBits(blTreeCodes - 4, 4);
for (int rank = 0; rank < blTreeCodes; rank++) {
pending.WriteBits(blTree.length[BL_ORDER[rank]], 3);
}
literalTree.WriteTree(blTree);
distTree.WriteTree(blTree);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
blTree.CheckEmpty();
}
#endif
}
/// <summary>
/// Compress current buffer writing data to pending buffer
/// </summary>
public void CompressBlock()
{
for (int i = 0; i < last_lit; i++) {
int litlen = l_buf[i] & 0xff;
int dist = d_buf[i];
if (dist-- != 0) {
// if (DeflaterConstants.DEBUGGING) {
// Console.Write("["+(dist+1)+","+(litlen+3)+"]: ");
// }
int lc = Lcode(litlen);
literalTree.WriteSymbol(lc);
int bits = (lc - 261) / 4;
if (bits > 0 && bits <= 5) {
pending.WriteBits(litlen & ((1 << bits) - 1), bits);
}
int dc = Dcode(dist);
distTree.WriteSymbol(dc);
bits = dc / 2 - 1;
if (bits > 0) {
pending.WriteBits(dist & ((1 << bits) - 1), bits);
}
} else {
// if (DeflaterConstants.DEBUGGING) {
// if (litlen > 32 && litlen < 127) {
// Console.Write("("+(char)litlen+"): ");
// } else {
// Console.Write("{"+litlen+"}: ");
// }
// }
literalTree.WriteSymbol(litlen);
}
}
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
Console.Write("EOF: ");
}
#endif
literalTree.WriteSymbol(EOF_SYMBOL);
#if DebugDeflation
if (DeflaterConstants.DEBUGGING) {
literalTree.CheckEmpty();
distTree.CheckEmpty();
}
#endif
}
/// <summary>
/// Flush block to output with no compression
/// </summary>
/// <param name="stored">Data to write</param>
/// <param name="storedOffset">Index of first byte to write</param>
/// <param name="storedLength">Count of bytes to write</param>
/// <param name="lastBlock">True if this is the last block</param>
public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock)
{
#if DebugDeflation
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Flushing stored block "+ storedLength);
// }
#endif
pending.WriteBits((DeflaterConstants.STORED_BLOCK << 1) + (lastBlock ? 1 : 0), 3);
pending.AlignToByte();
pending.WriteShort(storedLength);
pending.WriteShort(~storedLength);
pending.WriteBlock(stored, storedOffset, storedLength);
Reset();
}
/// <summary>
/// Flush block to output with compression
/// </summary>
/// <param name="stored">Data to flush</param>
/// <param name="storedOffset">Index of first byte to flush</param>
/// <param name="storedLength">Count of bytes to flush</param>
/// <param name="lastBlock">True if this is the last block</param>
public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock)
{
literalTree.freqs[EOF_SYMBOL]++;
// Build trees
literalTree.BuildTree();
distTree.BuildTree();
// Calculate bitlen frequency
literalTree.CalcBLFreq(blTree);
distTree.CalcBLFreq(blTree);
// Build bitlen tree
blTree.BuildTree();
int blTreeCodes = 4;
for (int i = 18; i > blTreeCodes; i--) {
if (blTree.length[BL_ORDER[i]] > 0) {
blTreeCodes = i+1;
}
}
int opt_len = 14 + blTreeCodes * 3 + blTree.GetEncodedLength() +
literalTree.GetEncodedLength() + distTree.GetEncodedLength() +
extra_bits;
int static_len = extra_bits;
for (int i = 0; i < LITERAL_NUM; i++) {
static_len += literalTree.freqs[i] * staticLLength[i];
}
for (int i = 0; i < DIST_NUM; i++) {
static_len += distTree.freqs[i] * staticDLength[i];
}
if (opt_len >= static_len) {
// Force static trees
opt_len = static_len;
}
if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3) {
// Store Block
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("Storing, since " + storedLength + " < " + opt_len
// + " <= " + static_len);
// }
FlushStoredBlock(stored, storedOffset, storedLength, lastBlock);
} else if (opt_len == static_len) {
// Encode with static tree
pending.WriteBits((DeflaterConstants.STATIC_TREES << 1) + (lastBlock ? 1 : 0), 3);
literalTree.SetStaticCodes(staticLCodes, staticLLength);
distTree.SetStaticCodes(staticDCodes, staticDLength);
CompressBlock();
Reset();
} else {
// Encode with dynamic tree
pending.WriteBits((DeflaterConstants.DYN_TREES << 1) + (lastBlock ? 1 : 0), 3);
SendAllTrees(blTreeCodes);
CompressBlock();
Reset();
}
}
/// <summary>
/// Get value indicating if internal buffer is full
/// </summary>
/// <returns>true if buffer is full</returns>
public bool IsFull()
{
return last_lit >= BUFSIZE;
}
/// <summary>
/// Add literal to buffer
/// </summary>
/// <param name="literal">Literal value to add to buffer.</param>
/// <returns>Value indicating internal buffer is full</returns>
public bool TallyLit(int literal)
{
// if (DeflaterConstants.DEBUGGING) {
// if (lit > 32 && lit < 127) {
// //Console.WriteLine("("+(char)lit+")");
// } else {
// //Console.WriteLine("{"+lit+"}");
// }
// }
d_buf[last_lit] = 0;
l_buf[last_lit++] = (byte)literal;
literalTree.freqs[literal]++;
return IsFull();
}
/// <summary>
/// Add distance code and length to literal and distance trees
/// </summary>
/// <param name="distance">Distance code</param>
/// <param name="length">Length</param>
/// <returns>Value indicating if internal buffer is full</returns>
public bool TallyDist(int distance, int length)
{
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("[" + distance + "," + length + "]");
// }
d_buf[last_lit] = (short)distance;
l_buf[last_lit++] = (byte)(length - 3);
int lc = Lcode(length - 3);
literalTree.freqs[lc]++;
if (lc >= 265 && lc < 285) {
extra_bits += (lc - 261) / 4;
}
int dc = Dcode(distance - 1);
distTree.freqs[dc]++;
if (dc >= 4) {
extra_bits += dc / 2 - 1;
}
return IsFull();
}
/// <summary>
/// Reverse the bits of a 16 bit value.
/// </summary>
/// <param name="toReverse">Value to reverse bits</param>
/// <returns>Value with bits reversed</returns>
public static short BitReverse(int toReverse)
{
return (short) (bit4Reverse[toReverse & 0xF] << 12 |
bit4Reverse[(toReverse >> 4) & 0xF] << 8 |
bit4Reverse[(toReverse >> 8) & 0xF] << 4 |
bit4Reverse[toReverse >> 12]);
}
static int Lcode(int length)
{
if (length == 255) {
return 285;
}
int code = 257;
while (length >= 8) {
code += 4;
length >>= 1;
}
return code + length;
}
static int Dcode(int distance)
{
int code = 0;
while (distance >= 4) {
code += 2;
distance >>= 1;
}
return code + distance;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Android.Bluetooth;
using System.Linq;
using Java.Util;
using Android.Media;
using System.Threading.Tasks;
namespace Robotics.Mobile.Core.Bluetooth.LE
{
public class Characteristic : ICharacteristic
{
public event EventHandler<CharacteristicReadEventArgs> ValueUpdated = delegate {};
protected BluetoothGattCharacteristic _nativeCharacteristic;
/// <summary>
/// we have to keep a reference to this because Android's api is weird and requires
/// the GattServer in order to do nearly anything, including enumerating services
/// </summary>
protected BluetoothGatt _gatt;
/// <summary>
/// we also track this because of gogole's weird API. the gatt callback is where
/// we'll get notified when services are enumerated
/// </summary>
protected GattCallback _gattCallback;
public Characteristic (BluetoothGattCharacteristic nativeCharacteristic, BluetoothGatt gatt, GattCallback gattCallback)
{
this._nativeCharacteristic = nativeCharacteristic;
this._gatt = gatt;
this._gattCallback = gattCallback;
if (this._gattCallback != null) {
// wire up the characteristic value updating on the gattcallback
this._gattCallback.CharacteristicValueUpdated += (object sender, CharacteristicReadEventArgs e) => {
// it may be other characteristics, so we need to test
if(e.Characteristic.ID == this.ID) {
// update our underlying characteristic (this one will have a value)
//TODO: is this necessary? probably the underlying reference is the same.
//this._nativeCharacteristic = e.Characteristic;
this.ValueUpdated (this, e);
}
};
}
}
public string Uuid {
get { return this._nativeCharacteristic.Uuid.ToString (); }
}
public Guid ID {
get { return Guid.Parse( this._nativeCharacteristic.Uuid.ToString() ); }
}
public byte[] Value {
get { return this._nativeCharacteristic.GetValue (); }
}
public string StringValue {
get {
if (this.Value == null)
return String.Empty;
else
return System.Text.Encoding.UTF8.GetString (this.Value);
}
}
public string Name {
get { return KnownCharacteristics.Lookup (this.ID).Name; }
}
public CharacteristicPropertyType Properties {
get {
return (CharacteristicPropertyType)(int)this._nativeCharacteristic.Properties;
}
}
public IList<IDescriptor> Descriptors {
get {
// if we haven't converted them to our xplat objects
if (this._descriptors == null) {
this._descriptors = new List<IDescriptor> ();
// convert the internal list of them to the xplat ones
foreach (var item in this._nativeCharacteristic.Descriptors) {
this._descriptors.Add (new Descriptor (item));
}
}
return this._descriptors;
}
} protected IList<IDescriptor> _descriptors;
public object NativeCharacteristic {
get {
return this._nativeCharacteristic;
}
}
public bool CanRead {get{return (this.Properties & CharacteristicPropertyType.Read) != 0; }}
public bool CanUpdate {get{return (this.Properties & CharacteristicPropertyType.Notify) != 0; }}
//NOTE: why this requires Apple, we have no idea. BLE stands for Mystery.
public bool CanWrite {get{return (this.Properties & CharacteristicPropertyType.WriteWithoutResponse | CharacteristicPropertyType.AppleWriteWithoutResponse) != 0; }}
// HACK: UNTESTED - this API has only been tested on iOS
public void Write (byte[] data)
{
if (!CanWrite) {
throw new InvalidOperationException ("Characteristic does not support WRITE");
}
var c = _nativeCharacteristic;
c.SetValue (data);
this._gatt.WriteCharacteristic (c);
Console.WriteLine(".....Write");
}
public async Task<bool> WriteAsync (byte[] data)
{
var tcs = new TaskCompletionSource<bool> ();
EventHandler<CharacteristicReadEventArgs> writeSuccess = (sender, e) => tcs.TrySetResult(true);
this._gattCallback.CharacteristicValueWritten += writeSuccess;
Write (data);
//timeout : 3 secondes
Task.Delay (3000).ContinueWith(t => tcs.TrySetResult(false));
var result = await tcs.Task;
this._gattCallback.CharacteristicValueWritten -= writeSuccess;
return result;
}
// HACK: UNTESTED - this API has only been tested on iOS
public Task<ICharacteristic> ReadAsync()
{
var tcs = new TaskCompletionSource<ICharacteristic>();
if (!CanRead) {
throw new InvalidOperationException ("Characteristic does not support READ");
}
EventHandler<CharacteristicReadEventArgs> updated = null;
updated = (object sender, CharacteristicReadEventArgs e) => {
// it may be other characteristics, so we need to test
var c = e.Characteristic;
tcs.SetResult(c);
if (this._gattCallback != null) {
// wire up the characteristic value updating on the gattcallback
this._gattCallback.CharacteristicValueUpdated -= updated;
}
};
if (this._gattCallback != null) {
// wire up the characteristic value updating on the gattcallback
this._gattCallback.CharacteristicValueUpdated += updated;
}
Console.WriteLine(".....ReadAsync");
this._gatt.ReadCharacteristic (this._nativeCharacteristic);
return tcs.Task;
}
public void StartUpdates ()
{
// TODO: should be bool RequestValue? compare iOS API for commonality
bool successful = false;
if (CanRead) {
Console.WriteLine ("Characteristic.RequestValue, PropertyType = Read, requesting updates");
successful = this._gatt.ReadCharacteristic (this._nativeCharacteristic);
}
if (CanUpdate) {
Console.WriteLine ("Characteristic.RequestValue, PropertyType = Notify, requesting updates");
successful = this._gatt.SetCharacteristicNotification (this._nativeCharacteristic, true);
// [TO20131211@1634] It seems that setting the notification above isn't enough. You have to set the NOTIFY
// descriptor as well, otherwise the receiver will never get the updates. I just grabbed the first (and only)
// descriptor that is associated with the characteristic, which is the NOTIFY descriptor. This seems like a really
// odd way to do things to me, but I'm a Bluetooth newbie. Google has a example here (but ono real explaination as
// to what is going on):
// http://developer.android.com/guide/topics/connectivity/bluetooth-le.html#notification
//
// HACK: further detail, in the Forms client this only seems to work with a breakpoint on it
// (ie. it probably needs to wait until the above 'SetCharacteristicNofication' is done before doing this...?????? [CD]
System.Threading.Thread.Sleep(100); // HACK: did i mention this was a hack?????????? [CD] 50ms was too short, 100ms seems to work
if (_nativeCharacteristic.Descriptors.Count > 0) {
BluetoothGattDescriptor descriptor = _nativeCharacteristic.Descriptors [0];
descriptor.SetValue (BluetoothGattDescriptor.EnableNotificationValue.ToArray ());
_gatt.WriteDescriptor (descriptor);
} else {
Console.WriteLine ("RequestValue, FAILED: _nativeCharacteristic.Descriptors was empty, not sure why");
}
}
Console.WriteLine ("RequestValue, Succesful: " + successful.ToString());
}
public void StopUpdates ()
{
bool successful = false;
if (CanUpdate) {
successful = this._gatt.SetCharacteristicNotification (this._nativeCharacteristic, false);
//TODO: determine whether
Console.WriteLine ("Characteristic.RequestValue, PropertyType = Notify, STOP updates");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime;
using System.Runtime.Serialization;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Xml;
namespace System.ServiceModel.Channels
{
public abstract class AddressHeader
{
private ParameterHeader _header;
protected AddressHeader()
{
}
internal bool IsReferenceProperty
{
get
{
BufferedAddressHeader bah = this as BufferedAddressHeader;
return bah != null && bah.IsReferencePropertyHeader;
}
}
public abstract string Name { get; }
public abstract string Namespace { get; }
public static AddressHeader CreateAddressHeader(object value)
{
Type type = GetObjectType(value);
return CreateAddressHeader(value, DataContractSerializerDefaults.CreateSerializer(type, int.MaxValue/*maxItems*/));
}
public static AddressHeader CreateAddressHeader(object value, XmlObjectSerializer serializer)
{
if (serializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer"));
return new XmlObjectSerializerAddressHeader(value, serializer);
}
public static AddressHeader CreateAddressHeader(string name, string ns, object value)
{
return CreateAddressHeader(name, ns, value, DataContractSerializerDefaults.CreateSerializer(GetObjectType(value), name, ns, int.MaxValue/*maxItems*/));
}
internal static AddressHeader CreateAddressHeader(XmlDictionaryString name, XmlDictionaryString ns, object value)
{
return new DictionaryAddressHeader(name, ns, value);
}
public static AddressHeader CreateAddressHeader(string name, string ns, object value, XmlObjectSerializer serializer)
{
if (serializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer"));
return new XmlObjectSerializerAddressHeader(name, ns, value, serializer);
}
private static Type GetObjectType(object value)
{
return (value == null) ? typeof(object) : value.GetType();
}
public override bool Equals(object obj)
{
AddressHeader hdr = obj as AddressHeader;
if (hdr == null)
return false;
StringBuilder builder = new StringBuilder();
string hdr1 = GetComparableForm(builder);
builder.Remove(0, builder.Length);
string hdr2 = hdr.GetComparableForm(builder);
if (hdr1.Length != hdr2.Length)
return false;
if (string.CompareOrdinal(hdr1, hdr2) != 0)
return false;
return true;
}
internal string GetComparableForm()
{
return GetComparableForm(new StringBuilder());
}
internal string GetComparableForm(StringBuilder builder)
{
return EndpointAddressProcessor.GetComparableForm(builder, GetComparableReader());
}
public override int GetHashCode()
{
return GetComparableForm().GetHashCode();
}
public T GetValue<T>()
{
return GetValue<T>(DataContractSerializerDefaults.CreateSerializer(typeof(T), this.Name, this.Namespace, int.MaxValue/*maxItems*/));
}
public T GetValue<T>(XmlObjectSerializer serializer)
{
if (serializer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer"));
using (XmlDictionaryReader reader = GetAddressHeaderReader())
{
if (serializer.IsStartObject(reader))
return (T)serializer.ReadObject(reader);
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.ExpectedElementMissing, Name, Namespace)));
}
}
public virtual XmlDictionaryReader GetAddressHeaderReader()
{
XmlBuffer buffer = new XmlBuffer(int.MaxValue);
XmlDictionaryWriter writer = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
WriteAddressHeader(writer);
buffer.CloseSection();
buffer.Close();
return buffer.GetReader(0);
}
private XmlDictionaryReader GetComparableReader()
{
throw ExceptionHelper.PlatformNotSupported();
}
protected virtual void OnWriteStartAddressHeader(XmlDictionaryWriter writer)
{
writer.WriteStartElement(Name, Namespace);
}
protected abstract void OnWriteAddressHeaderContents(XmlDictionaryWriter writer);
public MessageHeader ToMessageHeader()
{
if (_header == null)
_header = new ParameterHeader(this);
return _header;
}
public void WriteAddressHeader(XmlWriter writer)
{
WriteAddressHeader(XmlDictionaryWriter.CreateDictionaryWriter(writer));
}
public void WriteAddressHeader(XmlDictionaryWriter writer)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer"));
WriteStartAddressHeader(writer);
WriteAddressHeaderContents(writer);
writer.WriteEndElement();
}
public void WriteStartAddressHeader(XmlDictionaryWriter writer)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer"));
OnWriteStartAddressHeader(writer);
}
public void WriteAddressHeaderContents(XmlDictionaryWriter writer)
{
if (writer == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer"));
OnWriteAddressHeaderContents(writer);
}
internal class ParameterHeader : MessageHeader
{
private AddressHeader _parameter;
public override bool IsReferenceParameter
{
get { return true; }
}
public override string Name
{
get { return _parameter.Name; }
}
public override string Namespace
{
get { return _parameter.Namespace; }
}
public ParameterHeader(AddressHeader parameter)
{
_parameter = parameter;
}
protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
if (messageVersion == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion"));
WriteStartHeader(writer, _parameter, messageVersion.Addressing);
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
WriteHeaderContents(writer, _parameter);
}
internal static void WriteStartHeader(XmlDictionaryWriter writer, AddressHeader parameter, AddressingVersion addressingVersion)
{
parameter.WriteStartAddressHeader(writer);
if (addressingVersion == AddressingVersion.WSAddressing10)
{
writer.WriteAttributeString(XD.AddressingDictionary.IsReferenceParameter, XD.Addressing10Dictionary.Namespace, "true");
}
}
internal static void WriteHeaderContents(XmlDictionaryWriter writer, AddressHeader parameter)
{
parameter.WriteAddressHeaderContents(writer);
}
}
internal class XmlObjectSerializerAddressHeader : AddressHeader
{
private XmlObjectSerializer _serializer;
private object _objectToSerialize;
private string _name;
private string _ns;
public XmlObjectSerializerAddressHeader(object objectToSerialize, XmlObjectSerializer serializer)
{
_serializer = serializer;
_objectToSerialize = objectToSerialize;
throw ExceptionHelper.PlatformNotSupported();
}
public XmlObjectSerializerAddressHeader(string name, string ns, object objectToSerialize, XmlObjectSerializer serializer)
{
if ((null == name) || (name.Length == 0))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name"));
}
_serializer = serializer;
_objectToSerialize = objectToSerialize;
_name = name;
_ns = ns;
}
public override string Name
{
get { return _name; }
}
public override string Namespace
{
get { return _ns; }
}
private object ThisLock
{
get { return this; }
}
protected override void OnWriteAddressHeaderContents(XmlDictionaryWriter writer)
{
lock (ThisLock)
{
_serializer.WriteObjectContent(writer, _objectToSerialize);
}
}
}
internal class DictionaryAddressHeader : XmlObjectSerializerAddressHeader
{
private XmlDictionaryString _name;
private XmlDictionaryString _ns;
public DictionaryAddressHeader(XmlDictionaryString name, XmlDictionaryString ns, object value)
: base(name.Value, ns.Value, value, DataContractSerializerDefaults.CreateSerializer(GetObjectType(value), name, ns, int.MaxValue/*maxItems*/))
{
_name = name;
_ns = ns;
}
protected override void OnWriteStartAddressHeader(XmlDictionaryWriter writer)
{
writer.WriteStartElement(_name, _ns);
}
}
}
internal class BufferedAddressHeader : AddressHeader
{
private string _name;
private string _ns;
private XmlBuffer _buffer;
private bool _isReferenceProperty;
public BufferedAddressHeader(XmlDictionaryReader reader)
{
_buffer = new XmlBuffer(int.MaxValue);
XmlDictionaryWriter writer = _buffer.OpenSection(reader.Quotas);
Fx.Assert(reader.NodeType == XmlNodeType.Element, "");
_name = reader.LocalName;
_ns = reader.NamespaceURI;
Fx.Assert(_name != null, "");
Fx.Assert(_ns != null, "");
writer.WriteNode(reader, false);
_buffer.CloseSection();
_buffer.Close();
_isReferenceProperty = false;
}
public BufferedAddressHeader(XmlDictionaryReader reader, bool isReferenceProperty)
: this(reader)
{
_isReferenceProperty = isReferenceProperty;
}
public bool IsReferencePropertyHeader { get { return _isReferenceProperty; } }
public override string Name
{
get { return _name; }
}
public override string Namespace
{
get { return _ns; }
}
public override XmlDictionaryReader GetAddressHeaderReader()
{
return _buffer.GetReader(0);
}
protected override void OnWriteStartAddressHeader(XmlDictionaryWriter writer)
{
XmlDictionaryReader reader = GetAddressHeaderReader();
writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
writer.WriteAttributes(reader, false);
reader.Dispose();
}
protected override void OnWriteAddressHeaderContents(XmlDictionaryWriter writer)
{
XmlDictionaryReader reader = GetAddressHeaderReader();
reader.ReadStartElement();
while (reader.NodeType != XmlNodeType.EndElement)
writer.WriteNode(reader, false);
reader.ReadEndElement();
reader.Dispose();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using MigAz.Azure.Core.Interface;
using MigAz.Azure.Core.Generator;
using System.Windows.Forms;
using System;
using System.Collections.Generic;
using MigAz.Azure.Core.ArmTemplate;
using System.Collections;
using System.Net;
using System.Linq;
using System.IO;
using System.Threading.Tasks;
using MigAz.Azure.Generator;
namespace MigAz.AWS.Generator
{
public class AwsGenerator : TemplateGenerator
{
//private Dictionary<string, Parameter> this.Parameters;
private Dictionary<string, string> _storageAccountNames;
private ISettingsProvider _settingsProvider;
private AwsGenerator() : base(null, null) { }
public AwsGenerator(ILogProvider logProvider, IStatusProvider statusProvider) : base(logProvider, statusProvider)
{
}
//public async Task UpdateArtifacts2(IExportArtifacts artifacts)
//{
// LogProvider.WriteLog("UpdateArtifacts", "Start - Execution " + this.ExecutionGuid.ToString());
// //Alerts.Clear();
// //TemplateStreams.Clear();
// //Resources.Clear();
// //_AWSExportArtifacts = (AWSExportArtifacts)artifacts;
// ////_storageAccountNames = new Dictionary<string, string>();
// ////var token = _tokenProvider.GetToken(tenantId);
// //LogProvider.WriteLog("UpdateArtifacts", "Start processing selected virtual networks");
// //// process selected virtual networks
// //foreach (var virtualnetworkname in _AWSExportArtifacts.VirtualNetworks)
// //{
// // StatusProvider.UpdateStatus("BUSY: Exporting Virtual Network...");
// // Application.DoEvents();
// // var vpcs = _awsObjectRetriever.Vpcs;
// // Application.DoEvents();
// //}
// //LogProvider.WriteLog("UpdateArtifacts", "End processing selected Vpcs");
// //String storageAccountName = RandomString(22);
// //if (_AWSExportArtifacts.Instances.Count > 0)
// //{
// // LogProvider.WriteLog("UpdateArtifacts", "Start processing storage accounts");
// // BuildStorageAccountObject(storageAccountName);
// // LogProvider.WriteLog("UpdateArtifacts", "End processing selected storage accounts");
// //}
// //LogProvider.WriteLog("UpdateArtifacts", "Start processing selected Instances");
// //// process selected instances
// //foreach (var instance in _AWSExportArtifacts.Instances)
// //{
// // StatusProvider.UpdateStatus("BUSY: Exporting Instances...");
// // Application.DoEvents();
// // var availableInstances = _awsObjectRetriever.Instances;
// // if (availableInstances != null)
// // {
// // // var selectedInstances = availableInstances.Reservations[0].Instances.Find(x => x.InstanceId == instance.InstanceId);
// // var selectedInstances = _awsObjectRetriever.getInstancebyId(instance.InstanceId);
// // List<NetworkProfile_NetworkInterface> networkinterfaces = new List<NetworkProfile_NetworkInterface>();
// // String vpcId = selectedInstances.Instances[0].VpcId.ToString();
// // //Process LBs
// // var LBs = _awsObjectRetriever.getLBs(vpcId);
// // string instanceLBName = "";
// // foreach (var LB in LBs)
// // {
// // foreach (var LBInstance in LB.Instances)
// // {
// // if ((LB.VPCId == vpcId) && (LBInstance.InstanceId == instance.InstanceId))
// // {
// // if (LB.Scheme == "internet-facing")
// // {
// // BuildPublicIPAddressObject(LB);
// // }
// // instanceLBName = LB.LoadBalancerName;
// // BuildLoadBalancerObject(LB, instance.InstanceId.ToString());
// // }
// // }
// // }
// // //Process Network Interface
// // BuildNetworkInterfaceObject(selectedInstances.Instances[0], ref networkinterfaces, LBs);
// // //Process EC2 Instance
// // BuildVirtualMachineObject(selectedInstances.Instances[0], networkinterfaces, storageAccountName, instanceLBName);
// // }
// // Application.DoEvents();
// //}
// //LogProvider.WriteLog("UpdateArtifacts", "End processing selected cloud services and virtual machines");
// //Template template = new Template();
// //template.resources = _resources;
// //template.parameters = this.Parameters;
// //// save JSON template
// //_statusProvider.UpdateStatus("BUSY: saving JSON template");
// //Application.DoEvents();
// //string jsontext = JsonConvert.SerializeObject(template, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore });
// //jsontext = jsontext.Replace("schemalink", "$schema");
// //WriteStream(templateWriter, jsontext);
// //LogProvider.WriteLog("GenerateTemplate", "Write file export.json");
// // OnTemplateChanged();
// ////post Telemetry Record to AWStoARMToolAPI
// //if (app.Default.AllowTelemetry)
// //{
// // _statusProvider.UpdateStatus("BUSY: saving telemetry information");
// // _telemetryProvider.PostTelemetryRecord(teleinfo["AccessKey"].ToString(), _processedItems, teleinfo["Region"].ToString());
// //}
// StatusProvider.UpdateStatus("Ready");
// LogProvider.WriteLog("UpdateArtifacts", "End - Execution " + this.ExecutionGuid.ToString());
//}
//private void BuildPublicIPAddressObject(ref NetworkInterface networkinterface)
//{
// LogProvider.WriteLog("BuildPublicIPAddressObject", "Start");
// string publicipaddress_name = networkinterface.name;
// string publicipallocationmethod = "Dynamic";
// Hashtable dnssettings = new Hashtable();
// dnssettings.Add("domainNameLabel", (publicipaddress_name + _settingsProvider.StorageAccountSuffix).ToLower());
// PublicIPAddress_Properties publicipaddress_properties = new PublicIPAddress_Properties();
// publicipaddress_properties.dnsSettings = dnssettings;
// publicipaddress_properties.publicIPAllocationMethod = publicipallocationmethod;
// PublicIPAddress publicipaddress = new PublicIPAddress(this.ExecutionGuid);
// publicipaddress.name = networkinterface.name + "-PIP";
// // publicipaddress.location = "";
// publicipaddress.properties = publicipaddress_properties;
// this.AddResource(publicipaddress);
// LogProvider.WriteLog("BuildPublicIPAddressObject", "Microsoft.Network/publicIPAddresses/" + publicipaddress.name);
// NetworkInterface_Properties networkinterface_properties = (NetworkInterface_Properties)networkinterface.properties;
// networkinterface_properties.ipConfigurations[0].properties.publicIPAddress = new Reference();
// networkinterface_properties.ipConfigurations[0].properties.publicIPAddress.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/publicIPAddresses/" + publicipaddress.name + "')]";
// networkinterface.properties = networkinterface_properties;
// networkinterface.dependsOn.Add(networkinterface_properties.ipConfigurations[0].properties.publicIPAddress.id);
// LogProvider.WriteLog("BuildPublicIPAddressObject", "End");
//}
//private void BuildPublicIPAddressObject(dynamic resource)
//{
// LogProvider.WriteLog("BuildPublicIPAddressObject", "Start");
// string publicipaddress_name = resource.LoadBalancerName + "-PIP";
// string publicipallocationmethod = "Dynamic";
// char[] delimiterChars = { '.' };
// string LBDNS = resource.DNSName.Split(delimiterChars)[0].ToLower();
// Hashtable dnssettings = new Hashtable();
// dnssettings.Add("domainNameLabel", LBDNS);
// PublicIPAddress_Properties publicipaddress_properties = new PublicIPAddress_Properties();
// publicipaddress_properties.dnsSettings = dnssettings;
// publicipaddress_properties.publicIPAllocationMethod = publicipallocationmethod;
// PublicIPAddress publicipaddress = new PublicIPAddress(this.ExecutionGuid);
// publicipaddress.name = publicipaddress_name;
// // publicipaddress.location = "";
// publicipaddress.properties = publicipaddress_properties;
// this.AddResource(publicipaddress);
// LogProvider.WriteLog("BuildPublicIPAddressObject", "Microsoft.Network/publicIPAddresses/" + publicipaddress.name);
// LogProvider.WriteLog("BuildPublicIPAddressObject", "End");
//}
// convert an hex string into byte array
public static byte[] StrToByteArray(string str)
{
Dictionary<string, byte> hexindex = new Dictionary<string, byte>();
for (int i = 0; i <= 255; i++)
hexindex.Add(i.ToString("X2"), (byte)i);
List<byte> hexres = new List<byte>();
for (int i = 0; i < str.Length; i += 2)
hexres.Add(hexindex[str.Substring(i, 2)]);
return hexres.ToArray();
}
public static string Base64Decode(string base64EncodedData)
{
byte[] base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
public static string Base64Encode(string plainText)
{
byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
private string GetNewStorageAccountName(string oldStorageAccountName)
{
string newStorageAccountName = "";
if (_storageAccountNames.ContainsKey(oldStorageAccountName))
{
_storageAccountNames.TryGetValue(oldStorageAccountName, out newStorageAccountName);
}
else
{
newStorageAccountName = oldStorageAccountName + _settingsProvider.StorageAccountSuffix;
if (newStorageAccountName.Length > 24)
{
string randomString = Guid.NewGuid().ToString("N").Substring(0, 4);
newStorageAccountName = newStorageAccountName.Substring(0, (24 - randomString.Length - _settingsProvider.StorageAccountSuffix.Length)) + randomString + _settingsProvider.StorageAccountSuffix;
}
_storageAccountNames.Add(oldStorageAccountName, newStorageAccountName);
}
return newStorageAccountName;
}
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
private string GetRouteName(dynamic Route)
{
//RouteTableId
string RouteName = Route.RouteTableId.Replace(' ', '-');
foreach (var tag in Route.Tags)
{
if (tag.Key == "Name")
{
RouteName = tag.Value;
}
}
return RouteName;
}
private string GetSGName(dynamic SG)
{
string SGName = SG.NetworkAclId.Replace(' ', '-');
foreach (var tag in SG.Tags)
{
if (tag.Key == "Name")
{
SGName = tag.Value;
}
}
return SGName;
}
private string GetInstanceName(dynamic Instance)
{
string InstanceName = Instance.InstanceId.Replace(' ', '-');
foreach (var tag in Instance.Tags)
{
if (tag.Key == "Name")
{
InstanceName = tag.Value;
}
}
return InstanceName;
}
private string GetNICName(dynamic NIC)
{
string NICName = NIC.NetworkInterfaceId.Replace(' ', '-');
foreach (var tag in NIC.TagSet)
{
if (tag.Key == "Name")
{
NICName = tag.Value;
}
}
return NICName;
}
private string GetVMSize(string instancetype)
{
Dictionary<string, string> VMSizeTable = new Dictionary<string, string>();
VMSizeTable.Add("t2.nano", "Standard_A0");
VMSizeTable.Add("t2.micro", "Standard_A1");
VMSizeTable.Add("t2.small", "Standard_A1_v2");
VMSizeTable.Add("t2.medium", "Standard_A2_v2");
VMSizeTable.Add("t2.large", "Standard_A2m_v2");
VMSizeTable.Add("t2.xlarge", "Standard_A4m_v2");
VMSizeTable.Add("t2.2xlarge", "Standard_A8m_v2");
VMSizeTable.Add("m4.large", "Standard_DS2_v2");
VMSizeTable.Add("m4.xlarge", "Standard_DS3_v2");
VMSizeTable.Add("m4.2xlarge", "Standard_DS4_v2");
VMSizeTable.Add("m4.4xlarge", "Standard_DS5_v2");
VMSizeTable.Add("m4.10xlarge", "Standard_DS15_v2");
VMSizeTable.Add("m4.16xlarge", "Standard_DS15_v2");
VMSizeTable.Add("m3.medium", "Standard_DS1_v2");
VMSizeTable.Add("m3.large", "Standard_DS2_v2");
VMSizeTable.Add("m3.xlarge", "Standard_DS3_v2");
VMSizeTable.Add("m3.2xlarge", "Standard_DS4_v2");
VMSizeTable.Add("c4.large", "Standard_F2s");
VMSizeTable.Add("c4.xlarge", "Standard_F4s");
VMSizeTable.Add("c4.2xlarge", "Standard_F8s");
VMSizeTable.Add("c4.4xlarge", "Standard_F16s");
VMSizeTable.Add("c4.8xlarge", "Standard_F16s");
VMSizeTable.Add("c3.large", "Standard_F2s");
VMSizeTable.Add("c3.xlarge", "Standard_F4s");
VMSizeTable.Add("c3.2xlarge", "Standard_F8s");
VMSizeTable.Add("c3.4xlarge", "Standard_F16s");
VMSizeTable.Add("c3.8xlarge", "Standard_F16s");
VMSizeTable.Add("g2.2xlarge", "Standard_NC6");
VMSizeTable.Add("g2.8xlarge", "Standard_NC24");
VMSizeTable.Add("r4.large", "Standard_DS11_v2");
VMSizeTable.Add("r4.xlarge", "Standard_DS12_v2");
VMSizeTable.Add("r4.2xlarge", "Standard_DS13_v2");
VMSizeTable.Add("r4.4xlarge", "Standard_DS14_v2");
VMSizeTable.Add("r4.8xlarge", "Standard_GS5");
VMSizeTable.Add("r4.16xlarge", "Standard_GS5");
VMSizeTable.Add("r3.large", "Standard_DS11_v2");
VMSizeTable.Add("r3.xlarge", "Standard_DS12_v2");
VMSizeTable.Add("r3.2xlarge", "Standard_DS13_v2");
VMSizeTable.Add("r3.4xlarge", "Standard_DS14_v2");
VMSizeTable.Add("r3.8xlarge", "Standard_GS5");
VMSizeTable.Add("x1.16xlarge", "Standard_GS5");
VMSizeTable.Add("x1.32xlarge", "Standard_GS5");
VMSizeTable.Add("d2.xlarge", "Standard_DS12_v2");
VMSizeTable.Add("d2.2xlarge", "Standard_DS13_v2");
VMSizeTable.Add("d2.4xlarge", "Standard_DS14_v2");
VMSizeTable.Add("d2.8xlarge", "Standard_GS5");
VMSizeTable.Add("i2.xlarge", "Standard_DS12_v2");
VMSizeTable.Add("i2.2xlarge", "Standard_DS13_v2");
VMSizeTable.Add("i2.4xlarge", "Standard_DS14_v2");
VMSizeTable.Add("i2.8xlarge", "Standard_GS5");
if (VMSizeTable.ContainsKey(instancetype))
{
return VMSizeTable[instancetype];
}
else
{
return "Standard_DS2_v2";
}
}
}
}
//private void BuildAvailabilitySetObject(dynamic loadbalancer)
//{
// LogProvider.WriteLog("BuildAvailabilitySetObject", "Start");
// AvailabilitySet availabilityset = new AvailabilitySet(this.ExecutionGuid);
// availabilityset.name = loadbalancer.name + "-AS";
// this.AddResource(availabilityset);
// LogProvider.WriteLog("BuildAvailabilitySetObject", "Microsoft.Compute/availabilitySets/" + availabilityset.name);
// LogProvider.WriteLog("BuildAvailabilitySetObject", "End");
//}
//private void BuildLoadBalancerObject(dynamic LB, string instance)
//{
// LogProvider.WriteLog("BuildLoadBalancerObject", "Start");
// LoadBalancer loadbalancer = new LoadBalancer(this.ExecutionGuid);
// loadbalancer.name = LB.LoadBalancerName;
// FrontendIPConfiguration_Properties frontendipconfiguration_properties = new FrontendIPConfiguration_Properties();
// //// if internal load balancer
// if (LB.Scheme != "internet-facing")
// {
// //string virtualnetworkname = GetVPCName(LB.VPCId);
// var subnet = _awsObjectRetriever.getSubnetbyId(LB.Subnets[0]);
// string subnetname = "SubnetName";
// frontendipconfiguration_properties.privateIPAllocationMethod = "Static";
// try
// {
// IPHostEntry host = Dns.GetHostEntry(LB.DNSName);
// frontendipconfiguration_properties.privateIPAddress = host.AddressList[0].ToString();
// }
// catch
// {
// frontendipconfiguration_properties.privateIPAllocationMethod = "Dynamic";
// }
// List<string> dependson = new List<string>();
// Reference subnet_ref = new Reference();
// subnet_ref.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/virtualNetworks/" + "VNetName" + "/subnets/" + subnetname + "')]";
// frontendipconfiguration_properties.subnet = subnet_ref;
// }
// //// if external load balancer
// else
// {
// List<string> dependson = new List<string>();
// dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Network/publicIPAddresses/" + loadbalancer.name + "-PIP')]");
// loadbalancer.dependsOn = dependson;
// Reference publicipaddress_ref = new Reference();
// publicipaddress_ref.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/publicIPAddresses/" + loadbalancer.name + "-PIP')]";
// frontendipconfiguration_properties.publicIPAddress = publicipaddress_ref;
// }
// LoadBalancer_Properties loadbalancer_properties = new LoadBalancer_Properties();
// FrontendIPConfiguration frontendipconfiguration = new FrontendIPConfiguration();
// frontendipconfiguration.properties = frontendipconfiguration_properties;
// List<FrontendIPConfiguration> frontendipconfigurations = new List<FrontendIPConfiguration>();
// frontendipconfigurations.Add(frontendipconfiguration);
// loadbalancer_properties.frontendIPConfigurations = frontendipconfigurations;
// Hashtable backendaddresspool = new Hashtable();
// backendaddresspool.Add("name", "default");
// List<Hashtable> backendaddresspools = new List<Hashtable>();
// backendaddresspools.Add(backendaddresspool);
// loadbalancer_properties.backendAddressPools = backendaddresspools;
// List<InboundNatRule> inboundnatrules = new List<InboundNatRule>();
// List<LoadBalancingRule> loadbalancingrules = new List<LoadBalancingRule>();
// List<Probe> probes = new List<Probe>();
// foreach (var VM in LB.Instances)
// {
// if (VM.InstanceId == instance)
// {
// Hashtable virtualmachineinfo = new Hashtable();
// virtualmachineinfo.Add("virtualmachinename", VM.InstanceId);
// BuildLoadBalancerRules(VM.InstanceId, LB, ref inboundnatrules, ref loadbalancingrules, ref probes);
// }
// }
// loadbalancer_properties.inboundNatRules = inboundnatrules;
// loadbalancer_properties.loadBalancingRules = loadbalancingrules;
// loadbalancer_properties.probes = probes;
// loadbalancer.properties = loadbalancer_properties;
// // Add the load balancer only if there is any Load Balancing rule or Inbound NAT rule
// if (loadbalancingrules.Count > 0)
// {
// this.AddResource(loadbalancer);
// // Add an Availability Set per load balancer
// BuildAvailabilitySetObject(loadbalancer);
// LogProvider.WriteLog("BuildLoadBalancerObject", "Microsoft.Network/loadBalancers/" + loadbalancer.name);
// }
// else
// {
// LogProvider.WriteLog("BuildLoadBalancerObject", "EMPTY Microsoft.Network/loadBalancers/" + loadbalancer.name);
// }
// LogProvider.WriteLog("BuildLoadBalancerObject", "End");
//}
//private void BuildLoadBalancerRules(String resource, dynamic LB, ref List<InboundNatRule> inboundnatrules, ref List<LoadBalancingRule> loadbalancingrules, ref List<Probe> probes)
//{
// LogProvider.WriteLog("BuildLoadBalancerRules", "Start");
// string virtualmachinename = resource;
// string loadbalancername = LB.LoadBalancerName;
// // process Probe
// Probe_Properties probe_properties = new Probe_Properties();
// char[] delimiterChars = { ':' };
// probe_properties.protocol = LB.HealthCheck.Target.Split(delimiterChars)[0];
// if (probe_properties.protocol == "HTTP")
// {
// probe_properties.protocol = "Http";
// }
// else
// {
// probe_properties.protocol = "Tcp";
// }
// string portPath = LB.HealthCheck.Target.Split(delimiterChars)[1];
// if (portPath.IndexOf("/") == -1)
// {
// probe_properties.port = Convert.ToInt64(portPath);
// }
// else
// {
// delimiterChars[0] = '/';
// probe_properties.port = Convert.ToInt64(portPath.Split(delimiterChars)[0]);
// probe_properties.requestPath = portPath.Split(delimiterChars)[1];
// }
// Probe probe = new Probe();
// probe.name = probe_properties.protocol + "-" + probe_properties.port;
// probe.properties = probe_properties;
// if (!probes.Contains(probe))
// probes.Add(probe);
// // end process Probe
// foreach (var rule in LB.ListenerDescriptions)
// {
// string protocol = "Tcp";
// //if (rule.Listener.InstanceProtocol == "HTTP")
// //{
// // protocol = "Http";
// //}
// string name = protocol + "-" + rule.Listener.LoadBalancerPort;
// // build load balancing rule
// Reference frontendipconfiguration_ref = new Reference();
// frontendipconfiguration_ref.id = "[concat(resourceGroup().id,'/providers/Microsoft.Network/loadBalancers/" + loadbalancername + "/frontendIPConfigurations/default')]";
// Reference backendaddresspool_ref = new Reference();
// backendaddresspool_ref.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/loadBalancers/" + loadbalancername + "/backendAddressPools/default')]";
// Reference probe_ref = new Reference();
// probe_ref.id = "[concat(resourceGroup().id,'/providers/Microsoft.Network/loadBalancers/" + loadbalancername + "/probes/" + probe.name + "')]";
// LoadBalancingRule_Properties loadbalancingrule_properties = new LoadBalancingRule_Properties();
// loadbalancingrule_properties.frontendIPConfiguration = frontendipconfiguration_ref;
// loadbalancingrule_properties.backendAddressPool = backendaddresspool_ref;
// loadbalancingrule_properties.probe = probe_ref;
// loadbalancingrule_properties.frontendPort = rule.Listener.LoadBalancerPort;
// loadbalancingrule_properties.backendPort = rule.Listener.InstancePort;
// loadbalancingrule_properties.protocol = protocol;
// LoadBalancingRule loadbalancingrule = new LoadBalancingRule();
// loadbalancingrule.name = name;
// loadbalancingrule.properties = loadbalancingrule_properties;
// if (!loadbalancingrules.Contains(loadbalancingrule))
// loadbalancingrules.Add(loadbalancingrule);
// LogProvider.WriteLog("BuildLoadBalancerRules", "Microsoft.Network/loadBalancers/" + loadbalancername + "/loadBalancingRules/" + loadbalancingrule.name);
// }
// LogProvider.WriteLog("BuildLoadBalancerRules", "End");
//}
//private NetworkSecurityGroup BuildNetworkSecurityGroup(Amazon.EC2.Model.NetworkAcl securitygroup)
//{
// LogProvider.WriteLog("BuildNetworkSecurityGroup", "Start");
// Hashtable nsginfo = new Hashtable();
// nsginfo.Add("name", GetSGName(securitygroup));
// //XmlDocument resource = _awsRetriever.GetAwsResources(ConfigurationManager.AppSettings["endpoint"], "DescribeNetworkAcls", "");
// NetworkSecurityGroup networksecuritygroup = new NetworkSecurityGroup(this.ExecutionGuid);
// networksecuritygroup.name = GetSGName(securitygroup);
// //networksecuritygroup.location = securitygroup.SelectSingleNode("//Location").InnerText;
// NetworkSecurityGroup_Properties networksecuritygroup_properties = new NetworkSecurityGroup_Properties();
// networksecuritygroup_properties.securityRules = new List<SecurityRule>();
// // for each rule
// foreach (var rule in securitygroup.Entries)
// {
// string ruleDirection = "";
// if (rule.Egress == true)
// ruleDirection = "Outbound";
// else if (rule.Egress == false)
// ruleDirection = "Inbound";
// SecurityRule_Properties securityrule_properties = new SecurityRule_Properties(); //Name -Inbound_32, Outbound_100
// //securityrule_properties.description = rule.SelectSingleNode("Name").InnerText;
// securityrule_properties.direction = ruleDirection;
// if (rule.RuleNumber > 4096)
// securityrule_properties.priority = 4096;
// else
// {
// securityrule_properties.priority = rule.RuleNumber;//RuleNum
// securityrule_properties.access = rule.RuleAction; //ruleAction
// securityrule_properties.sourceAddressPrefix = rule.CidrBlock; //cidrBlock
// securityrule_properties.destinationAddressPrefix = "0.0.0.0/0";
// if (rule.Protocol == "6")
// securityrule_properties.protocol = "tcp";
// else if (rule.Protocol == "17")
// securityrule_properties.protocol = "udp";
// else
// securityrule_properties.protocol = "*";
// if (rule.PortRange != null)
// {
// int from, to;
// from = rule.PortRange.From;
// to = rule.PortRange.To;
// if (from == to)
// securityrule_properties.sourcePortRange = from.ToString();
// else
// securityrule_properties.sourcePortRange = from + "-" + to;
// // number, number-num, * - if portrange not available - from and to tags of port range tag
// }
// else
// {
// securityrule_properties.sourcePortRange = "*";
// }
// securityrule_properties.destinationPortRange = "*";
// SecurityRule securityrule = new SecurityRule();
// securityrule.name = (ruleDirection + "-" + rule.RuleNumber);
// securityrule.properties = securityrule_properties;
// networksecuritygroup_properties.securityRules.Add(securityrule);
// networksecuritygroup.properties = networksecuritygroup_properties;
// }
// }
// this.AddResource(networksecuritygroup);
// LogProvider.WriteLog("BuildNetworkSecurityGroup", "End");
// return networksecuritygroup;
//}
//private NetworkSecurityGroup BuildNetworkSecurityGroup(Amazon.EC2.Model.GroupIdentifier securitygroupidentifier, ref NetworkInterface networkinterface)
//{
// LogProvider.WriteLog("BuildNetworkSecurityGroup", "Start");
// NetworkSecurityGroup networksecuritygroup = new NetworkSecurityGroup(this.ExecutionGuid);
// networksecuritygroup.name = securitygroupidentifier.GroupName;
// NetworkSecurityGroup_Properties networksecuritygroup_properties = new NetworkSecurityGroup_Properties();
// networksecuritygroup_properties.securityRules = new List<SecurityRule>();
// long inboundPriority = 100;
// long outboundPriority = 101;
// Amazon.EC2.Model.SecurityGroup securitygroup = _awsObjectRetriever.getSecurityGroup(securitygroupidentifier.GroupId);
// // process inbound rules
// foreach (Amazon.EC2.Model.IpPermission ippermission in securitygroup.IpPermissions)
// {
// SecurityRule securityrule = new SecurityRule();
// securityrule.name = ("Inbound-" + inboundPriority);
// securityrule.properties = new SecurityRule_Properties();
// SecurityRule_Properties securityrule_properties = new SecurityRule_Properties();
// securityrule_properties.direction = "Inbound";
// securityrule_properties.access = "Allow";
// securityrule_properties.sourcePortRange = "*";
// securityrule_properties.destinationAddressPrefix = "0.0.0.0/0";
// securityrule_properties.priority = inboundPriority;
// inboundPriority = inboundPriority + 100;
// if (ippermission.IpProtocol == "tcp")
// {
// securityrule_properties.protocol = "Tcp";
// }
// else if (ippermission.IpProtocol == "udp")
// {
// securityrule_properties.protocol = "Udp";
// }
// else
// {
// securityrule_properties.protocol = "*";
// }
// securityrule_properties.sourceAddressPrefix = ippermission.IpRanges[0];
// securityrule_properties.destinationPortRange = "*";
// if (ippermission.ToPort > 0)
// {
// securityrule_properties.destinationPortRange = ippermission.ToPort.ToString();
// }
// securityrule.properties = securityrule_properties;
// networksecuritygroup_properties.securityRules.Add(securityrule);
// }
// // process outbound rules
// foreach (Amazon.EC2.Model.IpPermission ippermissionegress in securitygroup.IpPermissionsEgress)
// {
// SecurityRule securityrule = new SecurityRule();
// securityrule.name = ("Outbound-" + outboundPriority);
// securityrule.properties = new SecurityRule_Properties();
// SecurityRule_Properties securityrule_properties = new SecurityRule_Properties();
// securityrule_properties.direction = "Outbound";
// securityrule_properties.access = "Allow";
// securityrule_properties.sourceAddressPrefix = "0.0.0.0/0";
// securityrule_properties.sourcePortRange = "*";
// securityrule_properties.priority = outboundPriority;
// outboundPriority = outboundPriority + 100;
// if (ippermissionegress.IpProtocol == "tcp")
// {
// securityrule_properties.protocol = "Tcp";
// }
// else if (ippermissionegress.IpProtocol == "udp")
// {
// securityrule_properties.protocol = "Udp";
// }
// else
// {
// securityrule_properties.protocol = "*";
// }
// securityrule_properties.destinationAddressPrefix = ippermissionegress.IpRanges[0];
// securityrule_properties.destinationPortRange = "*";
// if (ippermissionegress.ToPort > 0)
// {
// securityrule_properties.destinationPortRange = ippermissionegress.ToPort.ToString();
// }
// securityrule.properties = securityrule_properties;
// networksecuritygroup_properties.securityRules.Add(securityrule);
// }
// networksecuritygroup.properties = networksecuritygroup_properties;
// this.AddResource(networksecuritygroup);
// LogProvider.WriteLog("BuildNetworkSecurityGroup", "Microsoft.Network/networkSecurityGroups/" + networksecuritygroup.name);
// LogProvider.WriteLog("BuildNetworkSecurityGroup", "End");
// return networksecuritygroup;
//}
//private RouteTable BuildRouteTable(Amazon.EC2.Model.RouteTable routeTable)
//{
// LogProvider.WriteLog("BuildRouteTable", "Start");
// Hashtable info = new Hashtable();
// info.Add("name", GetRouteName(routeTable));
// // XmlDocument resource = _awsRetriever.GetAwsResources(ConfigurationManager.AppSettings["endpoint"], "RouteTable", subscriptionId, info, token);
// RouteTable routetable = new RouteTable(this.ExecutionGuid);
// routetable.name = GetRouteName(routeTable);
// // routetable.location = resource.SelectSingleNode("//Location").InnerText;
// RouteTable_Properties routetable_properties = new RouteTable_Properties();
// routetable_properties.routes = new List<Route>();
// foreach (var rule in routeTable.Routes)
// {
// var GWResults = _awsObjectRetriever.getInternetGW(rule.GatewayId);
// if ((((rule.DestinationCidrBlock == "0.0.0.0/0") && (GWResults.Count == 0)) || (rule.DestinationCidrBlock != "0.0.0.0/0")) && (rule.GatewayId != "local"))
// {
// Route_Properties route_properties = new Route_Properties();
// route_properties.addressPrefix = rule.DestinationCidrBlock;
// switch (rule.GatewayId)
// {
// case "local":
// route_properties.nextHopType = "VnetLocal";
// break;
// case "Null":
// route_properties.nextHopType = "None";
// break;
// }
// // route_properties.nextHopIpAddress = routenode.SelectSingleNode("NextHopType/IpAddress").InnerText;
// Route route = new Route();
// route.name = rule.GatewayId;
// route.properties = route_properties;
// routetable_properties.routes.Add(route);
// routetable.properties = routetable_properties;
// }
// }
// if (routetable_properties.routes.Count != 0)
// {
// this.AddResource(routetable);
// LogProvider.WriteLog("BuildRouteTable", "Microsoft.Network/routeTables/" + routetable.name);
// }
// LogProvider.WriteLog("BuildRouteTable", "End");
// return routetable;
//}
//private void BuildNetworkInterfaceObject(dynamic resource, ref List<NetworkProfile_NetworkInterface> networkinterfaces, dynamic LBs)
//{
// LogProvider.WriteLog("BuildNetworkInterfaceObject", "Start");
// string virtualmachinename = GetInstanceName(resource);
// string virtualnetworkname = "VNetName"; //GetVPCName(resource.VpcId);
// foreach (var additionalnetworkinterface in resource.NetworkInterfaces)
// {
// Hashtable NWInfo = new Hashtable();
// NWInfo.Add("networkinterfaceId", additionalnetworkinterface.NetworkInterfaceId);
// //Getting Subnet Details
// string SubnetId = additionalnetworkinterface.SubnetId;
// var Subdetails = _awsObjectRetriever.getSubnetbyId(SubnetId);
// string subnet_name = "SubnetName";
// Reference subnet_ref = new Reference();
// subnet_ref.id = "[concat(resourceGroup().id,'/providers/Microsoft.Network/virtualNetworks/" + virtualnetworkname + "/subnets/" + subnet_name + "')]";
// string privateIPAllocationMethod = "Static";
// string privateIPAddress = additionalnetworkinterface.PrivateIpAddress;
// List<string> dependson = new List<string>();
// if (ResourceExists(typeof(VirtualNetwork), virtualnetworkname))
// {
// dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Network/virtualNetworks/" + virtualnetworkname + "')]");
// }
// // Get the list of endpoints
// List<Reference> loadBalancerBackendAddressPools = new List<Reference>();
// List<Reference> loadBalancerInboundNatRules = new List<Reference>();
// foreach (var LB in LBs)
// {
// foreach (var LBInstance in LB.Instances)
// {
// if ((LB.VPCId == resource.VpcId) && (LBInstance.InstanceId == resource.InstanceId))
// {
// string loadbalancername = LB.LoadBalancerName;
// string BAPoolName = "default";
// Reference loadBalancerBackendAddressPool = new Reference();
// loadBalancerBackendAddressPool.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/loadBalancers/" + loadbalancername + "/backendAddressPools/" + BAPoolName + "')]";
// loadBalancerBackendAddressPools.Add(loadBalancerBackendAddressPool);
// dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Network/loadBalancers/" + loadbalancername + "')]");
// }
// }
// }
// IpConfiguration_Properties ipconfiguration_properties = new IpConfiguration_Properties();
// ipconfiguration_properties.privateIPAllocationMethod = privateIPAllocationMethod;
// ipconfiguration_properties.privateIPAddress = privateIPAddress;
// ipconfiguration_properties.subnet = subnet_ref;
// ipconfiguration_properties.loadBalancerInboundNatRules = loadBalancerInboundNatRules;
// ipconfiguration_properties.loadBalancerBackendAddressPools = loadBalancerBackendAddressPools;
// string ipconfiguration_name = "ipconfig1";
// IpConfiguration ipconfiguration = new IpConfiguration();
// ipconfiguration.name = ipconfiguration_name;
// ipconfiguration.properties = ipconfiguration_properties;
// List<IpConfiguration> ipConfigurations = new List<IpConfiguration>();
// ipConfigurations.Add(ipconfiguration);
// NetworkInterface_Properties networkinterface_properties = new NetworkInterface_Properties();
// networkinterface_properties.ipConfigurations = ipConfigurations;
// networkinterface_properties.enableIPForwarding = (resource.SourceDestCheck == true) ? false : (resource.SourceDestCheck == false) ? true : false;
// // networkinterface_properties.enableIPForwarding = resource.SourceDestCheck;
// var NICDetails = _awsObjectRetriever.getNICbyId(additionalnetworkinterface.NetworkInterfaceId);
// string networkinterfacename = GetNICName(NICDetails[0]);
// string networkinterface_name = networkinterfacename;
// NetworkInterface networkinterface = new NetworkInterface(this.ExecutionGuid);
// networkinterface.name = networkinterface_name;
// // networkinterface.location = "";
// networkinterface.properties = networkinterface_properties;
// networkinterface.dependsOn = dependson;
// NetworkProfile_NetworkInterface_Properties networkinterface_ref_properties = new NetworkProfile_NetworkInterface_Properties();
// networkinterface_ref_properties.primary = additionalnetworkinterface.PrivateIpAddresses[0].Primary;
// NetworkProfile_NetworkInterface networkinterface_ref = new NetworkProfile_NetworkInterface();
// networkinterface_ref.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/networkInterfaces/" + networkinterface.name + "')]";
// networkinterface_ref.properties = networkinterface_ref_properties;
// if (resource.PublicIpAddress != null)
// {
// BuildPublicIPAddressObject(ref networkinterface);
// }
// // Process Network Interface Security Group
// foreach (var group in additionalnetworkinterface.Groups)
// {
// NetworkSecurityGroup networksecuritygroup = new NetworkSecurityGroup(this.ExecutionGuid);
// networksecuritygroup = BuildNetworkSecurityGroup(group, ref networkinterface);
// networkinterface_properties.NetworkSecurityGroup = new Reference();
// networkinterface_properties.NetworkSecurityGroup.id = "[concat(resourceGroup().id, '/providers/Microsoft.Network/networkSecurityGroups/" + networksecuritygroup.name + "')]";
// networkinterface.dependsOn.Add(networkinterface_properties.NetworkSecurityGroup.id);
// networkinterface.properties = networkinterface_properties;
// }
// networkinterfaces.Add(networkinterface_ref);
// this.AddResource(networkinterface);
// LogProvider.WriteLog("BuildNetworkInterfaceObject", "Microsoft.Network/networkInterfaces/" + networkinterface.name);
// }
// LogProvider.WriteLog("BuildNetworkInterfaceObject", "End");
//}
//private void BuildVirtualMachineObject(Amazon.EC2.Model.Instance selectedInstance, List<NetworkProfile_NetworkInterface> networkinterfaces, String newstorageaccountname, string instanceLBName)
//{
// LogProvider.WriteLog("BuildVirtualMachineObject", "Start");
// string virtualmachinename = GetInstanceName(selectedInstance);
// newstorageaccountname = GetNewStorageAccountName(newstorageaccountname);
// var NICDetails = _awsObjectRetriever.getNICbyId(selectedInstance.NetworkInterfaces[0].NetworkInterfaceId);
// string networkinterfacename = GetNICName(NICDetails[0]);
// string ostype;
// if (selectedInstance.Platform == null)
// {
// ostype = "Linux";
// }
// else
// {
// ostype = selectedInstance.Platform;
// }
// Hashtable storageaccountdependencies = new Hashtable();
// storageaccountdependencies.Add(newstorageaccountname, "");
// HardwareProfile hardwareprofile = new HardwareProfile();
// hardwareprofile.vmSize = GetVMSize(selectedInstance.InstanceType.Value);
// NetworkProfile networkprofile = new NetworkProfile();
// networkprofile.networkInterfaces = networkinterfaces;
// Vhd vhd = new Vhd();
// vhd.uri = "http://" + newstorageaccountname + ".blob.core.windows.net/vhds/" + virtualmachinename + "-" + "osdisk0.vhd";
// //CHECK
// OsDisk osdisk = new OsDisk();
// osdisk.name = virtualmachinename + selectedInstance.RootDeviceName.Replace("/", "_");
// osdisk.vhd = vhd;
// osdisk.caching = "ReadOnly";
// ImageReference imagereference = new ImageReference();
// OsProfile osprofile = new OsProfile();
// // if the tool is configured to create new VMs with empty data disks
// if (_settingsProvider.BuildEmpty)
// {
// osdisk.createOption = "FromImage";
// osprofile.computerName = virtualmachinename;
// osprofile.adminUsername = "[parameters('adminUsername')]";
// osprofile.adminPassword = "[parameters('adminPassword')]";
// if (!this.Parameters.ContainsKey("adminUsername"))
// {
// Parameter parameter = new Parameter();
// parameter.type = "string";
// this.Parameters.Add("adminUsername", parameter);
// }
// if (!this.Parameters.ContainsKey("adminPassword"))
// {
// Parameter parameter = new Parameter();
// parameter.type = "securestring";
// this.Parameters.Add("adminPassword", parameter);
// }
// if (ostype == "Windows")
// {
// imagereference.publisher = "MicrosoftWindowsServer";
// imagereference.offer = "WindowsServer";
// imagereference.sku = "2012-R2-Datacenter";
// imagereference.version = "latest";
// }
// else if (ostype == "Linux")
// {
// imagereference.publisher = "Canonical";
// imagereference.offer = "UbuntuServer";
// imagereference.sku = "16.04.0-LTS";
// imagereference.version = "latest";
// }
// else
// {
// imagereference.publisher = "<publisher>";
// imagereference.offer = "<offer>";
// imagereference.sku = "<sku>";
// imagereference.version = "<version>";
// }
// }
// // if the tool is configured to attach copied disks
// else
// {
// osdisk.createOption = "Attach";
// osdisk.osType = ostype;
// // Block of code to help copying the blobs to the new storage accounts
// Hashtable storageaccountinfo = new Hashtable();
// //storageaccountinfo.Add("name", oldstorageaccountname);
// }
// // process data disks
// List<DataDisk> datadisks = new List<DataDisk>();
// int currentLun = 0;
// foreach (var disk in selectedInstance.BlockDeviceMappings)
// {
// if (disk.DeviceName != selectedInstance.RootDeviceName)
// {
// DataDisk datadisk = new DataDisk();
// datadisk.name = virtualmachinename + disk.DeviceName.Substring(0).Replace("/", "_");
// datadisk.caching = "ReadOnly";
// datadisk.diskSizeGB = _awsObjectRetriever.GetVolume(disk.Ebs.VolumeId)[0].Size;
// datadisk.lun = currentLun++;
// if (_settingsProvider.BuildEmpty)
// {
// datadisk.createOption = "Empty";
// }
// else
// {
// datadisk.createOption = "Attach";
// }
// vhd = new Vhd();
// vhd.uri = "http://" + newstorageaccountname + ".blob.core.windows.net/vhds/" + virtualmachinename + "-" + datadisk.name + ".vhd";
// datadisk.vhd = vhd;
// try { storageaccountdependencies.Add(newstorageaccountname, ""); }
// catch { }
// datadisks.Add(datadisk);
// }
// }
// StorageProfile storageprofile = new StorageProfile();
// if (_settingsProvider.BuildEmpty) { storageprofile.imageReference = imagereference; }
// storageprofile.osDisk = osdisk;
// storageprofile.dataDisks = datadisks;
// VirtualMachine_Properties virtualmachine_properties = new VirtualMachine_Properties();
// virtualmachine_properties.hardwareProfile = hardwareprofile;
// if (_settingsProvider.BuildEmpty) { virtualmachine_properties.osProfile = osprofile; }
// virtualmachine_properties.networkProfile = networkprofile;
// virtualmachine_properties.storageProfile = storageprofile;
// List<string> dependson = new List<string>();
// dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Network/networkInterfaces/" + networkinterfacename + "')]");
// // Availability Set
// if (instanceLBName != "")
// {
// string availabilitysetname = instanceLBName + "-AS";
// Reference availabilityset = new Reference();
// availabilityset.id = "[concat(resourceGroup().id, '/providers/Microsoft.Compute/availabilitySets/" + availabilitysetname + "')]";
// virtualmachine_properties.availabilitySet = availabilityset;
// dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Compute/availabilitySets/" + availabilitysetname + "')]");
// }
// foreach (DictionaryEntry storageaccountdependency in storageaccountdependencies)
// {
// if (ResourceExists(typeof(StorageAccount), (string)storageaccountdependency.Key))
// {
// dependson.Add("[concat(resourceGroup().id, '/providers/Microsoft.Storage/storageAccounts/" + storageaccountdependency.Key + "')]");
// }
// }
// VirtualMachine virtualmachine = new VirtualMachine(this.ExecutionGuid);
// virtualmachine.name = virtualmachinename;
// //virtualmachine.location = virtualmachineinfo["location"].ToString();
// virtualmachine.properties = virtualmachine_properties;
// virtualmachine.dependsOn = dependson;
// virtualmachine.resources = new List<ArmResource>();
// //if (extension_iaasdiagnostics != null) { virtualmachine.resources.Add(extension_iaasdiagnostics); }
// this.AddResource(virtualmachine);
// LogProvider.WriteLog("BuildVirtualMachineObject", "Microsoft.Compute/virtualMachines/" + virtualmachine.name);
// LogProvider.WriteLog("BuildVirtualMachineObject", "End");
//}
//private void BuildStorageAccountObject(String StorageAccountName)
//{
// LogProvider.WriteLog("BuildStorageAccountObject", "Start");
// StorageAccount_Properties storageaccount_properties = new StorageAccount_Properties();
// storageaccount_properties.accountType = "Standard_LRS";
// StorageAccount storageaccount = new StorageAccount(this.ExecutionGuid);
// storageaccount.name = GetNewStorageAccountName(StorageAccountName);
// // storageaccount.location = "";
// storageaccount.properties = storageaccount_properties;
// this.AddResource(storageaccount);
// LogProvider.WriteLog("BuildStorageAccountObject", "Microsoft.Storage/storageAccounts/" + storageaccount.name);
// LogProvider.WriteLog("BuildStorageAccountObject", "End");
//}
| |
//
// ReuseBitmapDrawableCache.cs
//
// Author:
// Brett Duncavage <brett.duncavage@rd.io>
//
// Copyright 2013 Rdio, Inc.
//
using System.Linq;
using System;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Graphics;
using Android.App;
using System.Collections.Generic;
using Android.Content;
using Android.Util;
using FFImageLoading.Collections;
using FFImageLoading.Helpers;
using FFImageLoading.Drawables;
namespace FFImageLoading.Cache
{
public class ReuseBitmapDrawableCache : IDictionary<string, SelfDisposingBitmapDrawable>
{
private const string TAG = "ReuseBitmapDrawableCache";
private int total_added;
private int total_removed;
private int total_reuse_hits;
private int total_reuse_misses;
private int total_evictions;
private int total_cache_hits;
private int total_forced_gc_collections;
private long current_cache_byte_count;
private long current_evicted_byte_count;
private readonly object monitor = new object();
private readonly long high_watermark;
private readonly long low_watermark;
private readonly long gc_threshold;
private bool reuse_pool_refill_needed = true;
/// <summary>
/// Contains all entries that are currently being displayed. These entries are not eligible for
/// reuse or eviction. Entries will be added to the reuse pool when they are no longer displayed.
/// </summary>
private IDictionary<string, SelfDisposingBitmapDrawable> displayed_cache;
/// <summary>
/// Contains entries that potentially available for reuse and candidates for eviction.
/// This is the default location for newly added entries. This cache
/// is searched along with the displayed cache for cache hits. If a cache hit is found here, its
/// place in the LRU list will be refreshed. Items only move out of reuse and into displayed
/// when the entry has SetIsDisplayed(true) called on it.
/// </summary>
private readonly ByteBoundStrongLruCache<string, SelfDisposingBitmapDrawable> reuse_pool;
private readonly TimeSpan debug_dump_interval = TimeSpan.FromSeconds(10);
private readonly Handler main_thread_handler;
/// <summary>
/// Initializes a new instance of the <see cref="AndroidBitmapDrawableCache"/> class.
/// </summary>
/// <param name="highWatermark">Maximum number of bytes the reuse pool will hold before starting evictions.
/// <param name="lowWatermark">Number of bytes the reuse pool will be drained down to after the high watermark is exceeded.</param>
/// On Honeycomb and higher this value is used for the reuse pool size.</param>
/// <param name="gcThreshold">Threshold in bytes that triggers a System.GC.Collect (Honeycomb+ only).</param>
/// <param name="debugDump">If set to <c>true</c> dump stats to log every 10 seconds.</param>
public ReuseBitmapDrawableCache(long highWatermark, long lowWatermark, long gcThreshold = 2 * 1024 * 1024, bool debugDump = false)
{
low_watermark = lowWatermark;
high_watermark = highWatermark;
gc_threshold = gcThreshold;
displayed_cache = new Dictionary<string, SelfDisposingBitmapDrawable>();
reuse_pool = new ByteBoundStrongLruCache<string, SelfDisposingBitmapDrawable>(highWatermark, lowWatermark);
reuse_pool.EntryRemoved += OnEntryRemovedFromReusePool;
if (debugDump) {
main_thread_handler = new Handler();
DebugDumpStats();
}
}
/// <summary>
/// Attempts to find a bitmap suitable for reuse based on the given dimensions.
/// Note that any returned instance will have SetIsRetained(true) called on it
/// to ensure that it does not release its resources prematurely as it is leaving
/// cache management. This means you must call SetIsRetained(false) when you no
/// longer need the instance.
/// </summary>
/// <returns>A SelfDisposingBitmapDrawable that has been retained. You must call SetIsRetained(false)
/// when finished using it.</returns>
/// <param name="width">Width of the image to be written to the bitmap allocation.</param>
/// <param name="height">Height of the image to be written to the bitmap allocation.</param>
/// <param name="inSampleSize">DownSample factor.</param>
public SelfDisposingBitmapDrawable GetReusableBitmapDrawable(int width, int height, Bitmap.Config bitmapConfig, int inSampleSize)
{
if (reuse_pool == null) return null;
// Only attempt to get a bitmap for reuse if the reuse cache is full.
// This prevents us from prematurely depleting the pool and allows
// more cache hits, as the most recently added entries will have a high
// likelihood of being accessed again so we don't want to steal those bytes too soon.
lock (monitor) {
if (reuse_pool.CacheSizeInBytes < low_watermark && reuse_pool_refill_needed) {
Log.Debug(TAG, "Reuse pool is not full, refusing reuse request");
total_reuse_misses++;
return null;
}
reuse_pool_refill_needed = false;
SelfDisposingBitmapDrawable reuseDrawable = null;
if (reuse_pool.Count > 0) {
var reuse_keys = reuse_pool.Keys;
foreach (var k in reuse_keys) {
var bd = reuse_pool.Peek(k);
if (bd != null && bd.Handle != IntPtr.Zero && bd.HasValidBitmap && !bd.IsRetained && bd.Bitmap.IsMutable)
{
if (CanUseForInBitmap(bd.Bitmap, width, height, bitmapConfig, inSampleSize))
{
reuseDrawable = bd;
break;
}
}
}
if (reuseDrawable != null) {
reuseDrawable.SetIsRetained(true);
UpdateByteUsage(reuseDrawable.Bitmap, decrement:true, causedByEviction: true);
// Cleanup the entry
reuseDrawable.Displayed -= OnEntryDisplayed;
reuseDrawable.NoLongerDisplayed -= OnEntryNoLongerDisplayed;
reuseDrawable.SetIsCached(false);
reuse_pool.Remove(reuseDrawable.InCacheKey);
total_reuse_hits++;
}
}
if (reuseDrawable == null) {
total_reuse_misses++;
// Indicate that the pool may need to be refilled.
// There is little harm in setting this flag since it will be unset
// on the next reuse request if the threshold is reuse_pool.CacheSizeInBytes >= low_watermark.
reuse_pool_refill_needed = true;
}
return reuseDrawable;
}
}
private bool CanUseForInBitmap(Bitmap item, int width, int height, Bitmap.Config bitmapConfig, int inSampleSize)
{
if (!Utils.HasKitKat())
{
// On earlier versions, the dimensions must match exactly and the inSampleSize must be 1
return item.Width == width && item.Height == height && GetBytesPerPixel(item.GetConfig()) == GetBytesPerPixel(bitmapConfig) && inSampleSize == 1;
}
// From Android 4.4 (KitKat) onward we can re-use if the byte size of the new bitmap
// is smaller than the reusable bitmap candidate allocation byte count.
if (inSampleSize == 0)
{
// avoid division by zero
inSampleSize = 1;
}
int newWidth = (int)Math.Ceiling(width/(float)inSampleSize);
int newHeight = (int)Math.Ceiling(height/(float)inSampleSize);
if (inSampleSize > 1)
{
// Android docs: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.
if (newWidth % 2 != 0)
newWidth += 1;
if (newHeight % 2 != 0)
newHeight += 1;
}
int byteCount = newWidth * newHeight * GetBytesPerPixel(bitmapConfig);
return byteCount <= item.AllocationByteCount;
}
/// <summary>
/// Return the byte usage per pixel of a bitmap based on its configuration.
/// </summary>
/// <param name="config">The bitmap configuration</param>
/// <returns>The byte usage per pixel</returns>
private int GetBytesPerPixel(Bitmap.Config config)
{
if (config == Bitmap.Config.Argb8888)
{
return 4;
}
else if (config == Bitmap.Config.Rgb565)
{
return 2;
}
else if (config == Bitmap.Config.Argb4444)
{
return 2;
}
else if (config == Bitmap.Config.Alpha8)
{
return 1;
}
return 1;
}
private void UpdateByteUsage(Bitmap bitmap, bool decrement = false, bool causedByEviction = false)
{
lock(monitor) {
var byteCount = bitmap.RowBytes * bitmap.Height;
current_cache_byte_count += byteCount * (decrement ? -1 : 1);
if (causedByEviction) {
current_evicted_byte_count += byteCount;
// Kick the gc if we've accrued more than our desired threshold.
// TODO: Implement high/low watermarks to prevent thrashing
if (current_evicted_byte_count > gc_threshold) {
total_forced_gc_collections++;
Log.Debug(TAG, "Memory usage exceeds threshold, invoking GC.Collect");
// Force immediate Garbage collection. Please note that is resource intensive.
System.GC.Collect();
System.GC.WaitForPendingFinalizers ();
System.GC.WaitForPendingFinalizers (); // Double call since GC doesn't always find resources to be collected: https://bugzilla.xamarin.com/show_bug.cgi?id=20503
System.GC.Collect ();
current_evicted_byte_count = 0;
}
}
}
}
private void OnEntryRemovedFromReusePool (object sender, EntryRemovedEventArgs<string, SelfDisposingBitmapDrawable> e)
{
ProcessRemoval(e.OldValue, e.Evicted);
}
private void ProcessRemoval(SelfDisposingBitmapDrawable value, bool evicted)
{
lock(monitor) {
total_removed++;
if (evicted) {
Log.Debug(TAG, "Evicted key: {0}", value.InCacheKey);
total_evictions++;
}
}
// We only really care about evictions because we do direct Remove()als
// all the time when promoting to the displayed_cache. Only when the
// entry has been evicted is it truly not longer being held by us.
if (evicted) {
UpdateByteUsage(value.Bitmap, decrement: true, causedByEviction: true);
value.SetIsCached(false);
value.Displayed -= OnEntryDisplayed;
value.NoLongerDisplayed -= OnEntryNoLongerDisplayed;
}
}
private void OnEntryNoLongerDisplayed(object sender, EventArgs args)
{
if (!(sender is SelfDisposingBitmapDrawable)) return;
var sdbd = (SelfDisposingBitmapDrawable)sender;
lock (monitor) {
if (displayed_cache.ContainsKey(sdbd.InCacheKey)) {
DemoteDisplayedEntryToReusePool(sdbd);
}
}
}
private void OnEntryDisplayed(object sender, EventArgs args)
{
if (!(sender is SelfDisposingBitmapDrawable)) return;
// see if the sender is in the reuse pool and move it
// into the displayed_cache if found.
var sdbd = (SelfDisposingBitmapDrawable)sender;
lock (monitor) {
if (reuse_pool.ContainsKey(sdbd.InCacheKey)) {
PromoteReuseEntryToDisplayedCache(sdbd);
}
}
}
private void OnEntryAdded(string key, BitmapDrawable value)
{
total_added++;
Log.Debug(TAG, "OnEntryAdded(key = {0})", key);
var selfDisposingBitmapDrawable = value as SelfDisposingBitmapDrawable;
if (selfDisposingBitmapDrawable != null) {
selfDisposingBitmapDrawable.SetIsCached(true);
selfDisposingBitmapDrawable.InCacheKey = key;
selfDisposingBitmapDrawable.Displayed += OnEntryDisplayed;
UpdateByteUsage(selfDisposingBitmapDrawable.Bitmap);
}
}
private void PromoteReuseEntryToDisplayedCache(SelfDisposingBitmapDrawable value)
{
value.Displayed -= OnEntryDisplayed;
value.NoLongerDisplayed += OnEntryNoLongerDisplayed;
reuse_pool.Remove(value.InCacheKey);
displayed_cache.Add(value.InCacheKey, value);
}
private void DemoteDisplayedEntryToReusePool(SelfDisposingBitmapDrawable value)
{
value.NoLongerDisplayed -= OnEntryNoLongerDisplayed;
value.Displayed += OnEntryDisplayed;
displayed_cache.Remove(value.InCacheKey);
reuse_pool.Add(value.InCacheKey, value);
}
#region IDictionary implementation
public void Add(string key, SelfDisposingBitmapDrawable value)
{
if (value == null) {
Log.Warn(TAG, "Attempt to add null value, refusing to cache");
return;
}
if (!value.HasValidBitmap) {
Log.Warn(TAG, "Attempt to add Drawable with null or recycled bitmap, refusing to cache");
return;
}
lock (monitor) {
if (!displayed_cache.ContainsKey(key) && !reuse_pool.ContainsKey(key)) {
reuse_pool.Add(key, value);
OnEntryAdded(key, value);
}
}
}
public bool ContainsKey(string key)
{
lock (monitor) {
return displayed_cache.ContainsKey(key) || reuse_pool.ContainsKey(key);
}
}
public bool Remove(string key)
{
SelfDisposingBitmapDrawable tmp = null;
SelfDisposingBitmapDrawable reuseTmp = null;
var result = false;
lock (monitor) {
if (displayed_cache.TryGetValue(key, out tmp)) {
result = displayed_cache.Remove(key);
} else if (reuse_pool.TryGetValue(key, out reuseTmp)) {
result = reuse_pool.Remove(key);
}
if (tmp != null)
{
ProcessRemoval((SelfDisposingBitmapDrawable)tmp, evicted: true);
}
if (reuseTmp != null)
{
ProcessRemoval(reuseTmp, evicted: true);
}
return result;
}
}
public bool TryGetValue(string key, out SelfDisposingBitmapDrawable value)
{
lock (monitor) {
var result = displayed_cache.TryGetValue(key, out value);
if (result) {
total_cache_hits++;
Log.Debug(TAG, "Cache hit");
} else {
SelfDisposingBitmapDrawable tmp = null;
result = reuse_pool.TryGetValue(key, out tmp); // If key is found, its place in the LRU is refreshed
if (result) {
Log.Debug(TAG, "Cache hit from reuse pool");
total_cache_hits++;
}
value = tmp;
}
return result;
}
}
public SelfDisposingBitmapDrawable this[string index] {
get {
lock (monitor) {
SelfDisposingBitmapDrawable tmp = null;
TryGetValue(index, out tmp);
return tmp;
}
}
set {
Add(index, value);
}
}
public ICollection<string> Keys {
get {
lock (monitor) {
var cacheKeys = displayed_cache.Keys;
var allKeys = new List<string>(cacheKeys);
allKeys.AddRange(reuse_pool.Keys);
return allKeys;
}
}
}
public ICollection<SelfDisposingBitmapDrawable> Values {
get {
lock (monitor) {
var cacheValues = displayed_cache.Values;
var allValues = new List<SelfDisposingBitmapDrawable>(cacheValues);
allValues.AddRange(reuse_pool.Values);
return allValues;
}
}
}
#endregion
#region ICollection implementation
public void Add(KeyValuePair<string, SelfDisposingBitmapDrawable> item)
{
Add(item.Key, item.Value);
}
public void Clear()
{
lock (monitor) {
foreach (var k in displayed_cache.Keys.ToList()) { // FMT: we need to make a copy of the list since it's altered during enumeration
var tmp = displayed_cache[k];
if (tmp != null)
{
ProcessRemoval((SelfDisposingBitmapDrawable)tmp, evicted: true);
}
}
displayed_cache.Clear();
foreach (var k in reuse_pool.Keys.ToList()) { // FMT: we need to make a copy of the list since it's altered during enumeration
ProcessRemoval(reuse_pool[k], evicted: true);
}
reuse_pool.Clear();
}
}
public bool Contains(KeyValuePair<string, SelfDisposingBitmapDrawable> item)
{
return ContainsKey(item.Key);
}
public void CopyTo(KeyValuePair<string, SelfDisposingBitmapDrawable>[] array, int arrayIndex)
{
throw new NotImplementedException("CopyTo is not supported");
}
public bool Remove(KeyValuePair<string, SelfDisposingBitmapDrawable> item)
{
return Remove(item.Key);
}
public int Count {
get {
lock (monitor) {
return displayed_cache.Count + reuse_pool.Count;
}
}
}
public bool IsReadOnly {
get {
lock (monitor) {
return displayed_cache.IsReadOnly;
}
}
}
#endregion
#region IEnumerable implementation
public IEnumerator<KeyValuePair<string, SelfDisposingBitmapDrawable>> GetEnumerator()
{
List<KeyValuePair<string, SelfDisposingBitmapDrawable>> values;
lock (monitor) {
values = new List<KeyValuePair<string, SelfDisposingBitmapDrawable>>(Count);
foreach (var k in Keys) {
values.Add(new KeyValuePair<string, SelfDisposingBitmapDrawable>(k, this[k]));
}
}
foreach (var kvp in values) {
yield return kvp;
}
}
#endregion
#region IEnumerable implementation
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
private void DebugDumpStats()
{
main_thread_handler.PostDelayed(DebugDumpStats, (long)debug_dump_interval.TotalMilliseconds);
lock (monitor) {
Log.Debug(TAG, "--------------------");
Log.Debug(TAG, "current total count: " + Count);
Log.Debug(TAG, "cumulative additions: " + total_added);
Log.Debug(TAG, "cumulative removals: " + total_removed);
Log.Debug(TAG, "total evictions: " + total_evictions);
Log.Debug(TAG, "total cache hits: " + total_cache_hits);
Log.Debug(TAG, "reuse hits: " + total_reuse_hits);
Log.Debug(TAG, "reuse misses: " + total_reuse_misses);
Log.Debug(TAG, "reuse pool count: " + reuse_pool.Count);
Log.Debug(TAG, "gc threshlold: " + gc_threshold);
Log.Debug(TAG, "cache size in bytes: " + current_cache_byte_count);
Log.Debug(TAG, "reuse pool in bytes: " + reuse_pool.CacheSizeInBytes);
Log.Debug(TAG, "current evicted bytes: " + current_evicted_byte_count);
Log.Debug(TAG, "high watermark: " + high_watermark);
Log.Debug(TAG, "low watermark: " + low_watermark);
Log.Debug(TAG, "total force gc collections: " + total_forced_gc_collections);
if (total_reuse_hits > 0 || total_reuse_misses > 0) {
Log.Debug(TAG, "reuse hit %: " + (100f * (total_reuse_hits / (float)(total_reuse_hits + total_reuse_misses))));
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.