context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
Copyright (c) 2006 Ladislav Prosek and Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
//#if SILVERLIGHT
#define EMIT_VERIFIABLE_STUBS
//#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Reflection.Emit;
using System.Reflection;
using System.Diagnostics;
using PHP.Core.Reflection;
using PHP.Core.Emit;
namespace PHP.Core.Emit
{
using Overload = ClrMethod.Overload;
using ConversionStrictness = PHP.Core.ConvertToClr.ConversionStrictness;
/// <summary>
/// </summary>
/// <remarks><code>
/// switch (#actuals)
/// {
/// case i:
/// // Conversions for the first overload
/// overload_i_1:
/// strictness_i = ImplExactMatch;
/// formal_i_1_1 = TryConvertTo{typeof(formal_i_1_1)}(actual_1, out strictness_tmp);
/// if (strictness_tmp == Failed) goto overload_i_2;
/// strictness_i += strictness_tmp;
/// formal_i_1_2 = TryConvertTo{typeof(formal_i_1_2)}(actual_2, out strictness_tmp);
/// if (strictness_tmp == Failed) goto overload_i_2;
/// strictness_i += strictness_tmp;
/// ...
/// if (strictness_i_1 == ImplExactMatch) goto call_overload_i_1;
/// best_overload = 1;
///
/// // Conversions for the second overload
/// overload_i_2:
/// formal_i = TryConvertTo{typeof(formal_i)}(actual_i, out strictness_tmp);
/// if (strictness_tmp == Failed) goto overload_i_3;
/// strictness_i_2 += strictness_tmp;
/// ...
/// if (strictness_i_2 == ImplExactMatch) goto call_overload_i_2;
/// if (strictness_i_2 < strictness_i_1)
/// best_overload = 2;
///
/// // ... other overloads
///
/// // select the best overload
/// call_overload_i:
/// switch(best_overload)
/// {
/// case 1:
/// return overload_i_1(formal_i_1_1, ..., formal_i_1_k);
/// case 2:
/// return overload_i_2(formal_i_2_1, ..., formal_i_2_k);
/// // ... other calls
/// }
///
/// case less than #formals:
/// Warning(to few args);
/// --- fill missing with default values of their respective types ---
/// goto case #min_formals;
///
/// case more than #formals:
/// Warning(to many args)
/// goto case #max_formals;
/// }
///
/// error:
/// NoSuitableOverload()
/// </code></remarks>
[DebuggerNonUserCode]
public sealed class ClrOverloadBuilder
{
#region Fields and types
/// <summary>
/// A delegate used to load a parameter to evaluation stack.
/// </summary>
public delegate object ParameterLoader(ILEmitter/*!*/ il, IPlace/*!*/ stack, IPlace/*!*/ parameter);
private ILEmitter/*!*/ il;
private ClrMethod/*!*/ method;
private ConstructedType constructedType;
private IPlace/*!*/ stack;
private IPlace instance;
private ParameterLoader/*!*/ loadValueArg;
private ParameterLoader/*!*/ loadReferenceArg;
private bool emitParentCtorCall;
private List<Overload>/*!!*/ overloads;
//private BitArray argCounts;
private IPlace scriptContext;
/// <summary>
/// Case labels used during by-number resolution
/// </summary>
private Label[] caseLabels;
private Label noSuitableOverloadErrorLabel;
private Label returnLabel;
/// <summary>
/// Marked after the argument load block of the overload with minimal arguments.
/// </summary>
private Label? minArgOverloadTypeResolutionLabel;
private int minArgCount;
private int maxArgCount;
private LocalBuilder strictness;
private LocalBuilder[] valLocals;
private LocalBuilder[] refLocals;
private LocalBuilder returnValue;
#endregion
#region Constructor
/// <summary>
/// Generic type definition of Nullable<_> type.
/// </summary>
static Type NullableType;
static ClrOverloadBuilder()
{
NullableType = typeof(int?).GetGenericTypeDefinition();
}
public ClrOverloadBuilder(ILEmitter/*!*/ il, ClrMethod/*!*/ method, ConstructedType constructedType,
IPlace/*!*/ stack, IPlace/*!*/ instance, bool emitParentCtorCall,
ParameterLoader/*!*/ loadValueArg, ParameterLoader/*!*/ loadReferenceArg)
{
this.il = il;
this.method = method;
this.constructedType = constructedType;
this.stack = stack;
this.instance = instance;
this.loadValueArg = loadValueArg;
this.loadReferenceArg = loadReferenceArg;
this.emitParentCtorCall = emitParentCtorCall;
this.overloads = new List<Overload>(method.Overloads);
SortOverloads(this.overloads);
}
#endregion
#region Utilities
/// <summary>
/// Sorts overloads in the list - so that we guarantee deterministic overload selection.
/// Most important thing is to test subtypes first - because both conversions are evaluated as ImplExactMatch.
/// (sorting also allows some performance tweaks)
/// </summary>
/// <param name="list">List to sort</param>
private void SortOverloads(List<Overload> list)
{
list.Sort(delegate(Overload first, Overload second)
{
// overloads with less parameters are returned first
if (first.ParamCount != second.ParamCount)
return first.ParamCount - second.ParamCount;
// compare parameter types - we want to test subtypes first, so that when we have A :> B
// and foo(A), foo(B) we first test foo(B)
for (int i = 0; i < first.ParamCount; i++)
{
Type t1 = first.Parameters[i].ParameterType, t2 = second.Parameters[i].ParameterType;
if (!t1.Equals(t2)) return CompareTypes(t1, t2); // not equal parameter types - sort by this param
}
return 0;
});
}
/// <summary>
/// Compares two types. Type <paramref name="t1"/> is less if it is subclass
/// of <paramref name="t2"/>, or it is array of subclasses (covariant arrays).
/// Otherwise the types are sorted by name in alphabetical order with an exception
/// of type string which is greather than any other type (because if we allow explicit
/// conversions, the conversion to string is slooow!).
/// </summary>
/// <param name="t1">First type</param>
/// <param name="t2">Second type</param>
/// <returns>-1 if first is less, 1 if second is less</returns>
private int CompareTypes(Type t1, Type t2)
{
if (t1.IsSubclassOf(t2)) return -1;
if (t2.IsSubclassOf(t1)) return +1;
// array covariance (solves vararg overloads too)
// array is after non-array or compare array types
if (t1.IsArray && t2.IsArray) return CompareTypes(t1.GetElementType(), t2.GetElementType());
else if (t1.IsArray) return 1;
else if (t2.IsArray) return -1;
// strings should be at the end ..
if (t1.Equals(Types.String[0])) return +1;
if (t2.Equals(Types.String[0])) return -1;
// not related types.. sort by type name (to make selection deterministic)
if (!t1.Equals(t2)) return String.Compare(t1.Name, t2.Name);
return 0;
}
private static void GetOverloadValRefArgCount(Overload/*!*/ overload, out int byValCount, out int byRefCount)
{
int byref = 0;
ParameterInfo[] parameters = overload.Parameters;
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i].ParameterType.IsByRef) byref++;
}
byValCount = parameters.Length - byref;
byRefCount = byref;
}
private void EmitCreateParamsArray(Type/*!*/ elementType, LocalBuilder/*!*/ local, int count)
{
il.LdcI4(count);
il.Emit(OpCodes.Newarr, elementType);
il.Stloc(local);
}
/// <summary>
/// Emit LOAD <paramref name="instance"/>.
/// </summary>ILEmiter
/// <param name="il"><see cref="ILEmitter"/> object instance.</param>
/// <param name="instance">The place where to load the instance from.</param>
/// <param name="declaringType">The type of resulting instance.</param>
/// <remarks>Instance of value types are wrapped in <see cref="ClrValue<T>"/> object instance.</remarks>
internal static void EmitLoadInstance(ILEmitter/*!*/il, IPlace/*!*/instance, Type/*!*/declaringType)
{
Debug.Assert(il != null && instance != null && declaringType != null, "ClrOverloadBuilder.EmitLoadInstance() null argument!");
// LOAD <instance>
instance.EmitLoad(il);
if (declaringType.IsValueType)
{
var clrValueType = ClrObject.valueTypesCache.Get(declaringType).Item1;
Debug.Assert(clrValueType != null, "Specific ClrValue<T> not found!");
// CAST (ClrValue<T>)
il.Emit(OpCodes.Castclass, clrValueType);
// LOAD .realValue
var realValueField = clrValueType.GetField("realValue");
Debug.Assert(realValueField != null, "ClrValue<T>.realValue field not found!");
il.Emit(OpCodes.Ldflda, clrValueType.GetField("realValue"));
}
else
{
// CAST (T)
il.Emit(OpCodes.Castclass, declaringType);
}
}
/// <summary>
/// Emits overload call
/// </summary>
private void EmitCall(Overload/*!*/ overload, Label failLabel, LocalBuilder[] formals)
{
MethodBase overload_base = overload.Method;
/* CHECK IS DONE IN THE EARLIER PHASE
* (in EmitConversion method)
if (!emitParentCtorCall && (overload_base.IsFamily || overload_base.IsFamilyOrAssembly))
{
// IF (!stack.AllowProtectedCall) THEN GOTO next-overload-or-error;
stack.EmitLoad(il);
il.Emit(OpCodes.Ldfld, Fields.PhpStack_AllowProtectedCall);
il.Emit(OpCodes.Brfalse, failLabel);
}*/
//
// LOAD <instance>
//
if ((emitParentCtorCall) // calling .ctor on parent
||(!overload_base.IsStatic && !overload_base.IsConstructor)// calling method on non-static object
//||(overload_base.IsConstructor && overload_base.DeclaringType.IsValueType)// calling .ctor on structure (which initializes fields on existing value) (but the ClrValue does not exist yet :-))
)
{
EmitLoadInstance(il, instance, overload_base.DeclaringType);
}
//
// LOAD {<args>}
//
for (int i = 0; i < overload.Parameters.Length; i++)
{
if (overload.Parameters[i].ParameterType.IsByRef) il.Ldloca(formals[i]);
else il.Ldloc(formals[i]);
}
//
// CALL <method> or
//
if (!overload_base.IsConstructor)
{
// method
MethodInfo info = DType.MakeConstructed((MethodInfo)overload_base, constructedType);
// CALL <method>(args);
// TODO: il.Emit(info.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, info);
#if SILVERLIGHT
il.Emit(info.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, info);
#else
il.Emit(OpCodes.Call, info);
#endif
// return value conversions:
if (info.ReturnType != Types.Void)
{
il.EmitBoxing(EmitConvertToPhp(il, info.ReturnType/* scriptContext*/));
il.Stloc(returnValue);
}
}
else
{
// .ctor
ConstructorInfo ctor = DType.MakeConstructed((ConstructorInfo)overload_base, constructedType);
if (emitParentCtorCall)
{
// CALL <ctor>(args);
il.Emit(OpCodes.Call, ctor);
}
else
{
// NEW <ctor>(args);
il.Emit(OpCodes.Newobj, ctor);
il.EmitBoxing(EmitConvertToPhp(il, ctor.DeclaringType)); // convert any newly created object to valid PHP object
/*if (ctor.DeclaringType.IsValueType)
{
// box value type:
il.Emit(OpCodes.Box, ctor.DeclaringType);
}
if (!Types.DObject[0].IsAssignableFrom(ctor.DeclaringType))
{
// convert to ClrObject if not DObject:
il.Emit(OpCodes.Call, Methods.ClrObject_Wrap);
}*/
il.Stloc(returnValue);
}
}
// store ref/out parameters back to their PhpReferences shells
int byref_counter = 0;
for (int i = 0; i < overload.Parameters.Length; i++)
{
Type param_type = overload.Parameters[i].ParameterType;
if (param_type.IsByRef)
{
il.Ldloc(refLocals[byref_counter++]);
il.Ldloc(formals[i]);
PhpTypeCode php_type_code = EmitConvertToPhp(
il,
param_type.GetElementType()/*,
scriptContext*/);
il.EmitBoxing(php_type_code);
il.Emit(OpCodes.Stfld, Fields.PhpReference_Value);
}
}
il.Emit(OpCodes.Br, returnLabel);
}
/// <summary>
/// Emits code that is invoked when function is passed not enough parameters
/// </summary>
/// <param name="gotoLabel">Continue execution at this label</param>
private void EmitMissingParameterCountHandling(Label gotoLabel)
{
// CALL PhpException.MissingArguments(<type name>, <routine name>, <actual count>, <required count>);
il.Emit(OpCodes.Ldstr, method.DeclaringType.FullName);
if (method.IsConstructor)
il.Emit(OpCodes.Ldnull);
else
il.Emit(OpCodes.Ldstr, method.FullName);
stack.EmitLoad(il);
il.Emit(OpCodes.Ldfld, Fields.PhpStack_ArgCount);
il.LdcI4(minArgCount);
il.Emit(OpCodes.Call, Methods.PhpException.MissingArguments);
// initialize all PhpReferences
for (int i = 0; i < refLocals.Length; i++)
{
il.Emit(OpCodes.Newobj, Constructors.PhpReference_Void);
il.Stloc(refLocals[i]);
}
// GOTO next-overload
il.Emit(OpCodes.Br, gotoLabel);
}
/// <summary>
/// Emits code that is invoked when function is passed more parameters
/// </summary>
/// <param name="gotoLabel">Continue execution at this label</param>
private void EmitMoreParameterCountHandling(Label gotoLabel)
{
// CALL PhpException.InvalidArgumentCount(<type name>, <routine name>);
il.Emit(OpCodes.Ldstr, method.DeclaringType.FullName);
if (method.IsConstructor)
il.Emit(OpCodes.Ldnull);
else
il.Emit(OpCodes.Ldstr, method.FullName);
il.Emit(OpCodes.Call, Methods.PhpException.InvalidArgumentCount);
// GOTO next-overload
il.Emit(OpCodes.Br, gotoLabel);
}
#endregion
#region Resolution by number
private void Prepare(int maxArgCount, int maxValArgCount, int maxRefArgCount)
{
Debug.Assert(maxValArgCount + maxRefArgCount >= maxArgCount);
this.noSuitableOverloadErrorLabel = il.DefineLabel();
this.scriptContext = new Place(stack, Fields.PhpStack_Context);
this.returnLabel = il.DefineLabel();
// locals:
this.valLocals = new LocalBuilder[maxValArgCount];
for (int i = 0; i < valLocals.Length; i++)
valLocals[i] = il.DeclareLocal(Types.Object[0]);
this.refLocals = new LocalBuilder[maxRefArgCount];
for (int i = 0; i < refLocals.Length; i++)
refLocals[i] = il.DeclareLocal(Types.PhpReference[0]);
this.returnValue = il.DeclareLocal(Types.Object[0]);
this.strictness = il.DeclareLocal(typeof(ConversionStrictness));
}
private void PrepareResolutionByNumber()
{
if (overloads.Count == 0) return;
this.minArgCount = overloads[0].MandatoryParamCount;
this.maxArgCount = overloads[overloads.Count - 1].ParamCount;
// determine maximum number of byval and byref parameters:
int max_val_arg_count = 0;
int max_ref_arg_count = 0;
for (int i = 0; i < overloads.Count; i++)
{
int byval, byref;
GetOverloadValRefArgCount(overloads[i], out byval, out byref);
if (byval > max_val_arg_count) max_val_arg_count = byval;
if (byref > max_ref_arg_count) max_ref_arg_count = byref;
}
int case_count = maxArgCount - minArgCount + 1;
// labels:
caseLabels = new Label[case_count];
for (int i = 0; i < case_count; i++)
caseLabels[i] = il.DefineLabel();
Prepare(maxArgCount, max_val_arg_count, max_ref_arg_count);
}
/// <summary>
/// Has to be chosen which method should be called.This method emits the code that
/// choses which overload to call by number of arguments. After this it calls
/// EmitResolutionByTypes.
/// </summary>
public void EmitResolutionByNumber()
{
PrepareResolutionByNumber();
if (overloads.Count > 0)
{
// SWITCH (stack.ArgCount - <min param count>)
stack.EmitLoad(il);
il.Emit(OpCodes.Ldfld, Fields.PhpStack_ArgCount);
if (minArgCount > 0)
{
il.LdcI4(minArgCount);
il.Emit(OpCodes.Sub);
}
il.Emit(OpCodes.Switch, caseLabels);
// DEFAULT:
EmitDefaultCase();
int last_success_case_index = -1;
int arg_count = minArgCount;
for (int case_index = 0; case_index < caseLabels.Length; case_index++, arg_count++)
{
// CASE <case_index>:
il.MarkLabel(caseLabels[case_index]);
List<Overload> arg_count_overloads = GetOverloadsForArgCount(arg_count);
if (arg_count_overloads.Count == 0)
{
// no overload with arg_count parameters was found
// report error and jump to the last successful arg count:
EmitMoreParameterCountHandling(caseLabels[last_success_case_index]);
}
else
{
EmitResolutionByTypes(arg_count, arg_count_overloads);
last_success_case_index = case_index;
}
}
}
EmitEpilogue();
}
private void EmitEpilogue()
{
// noSuitableOverload:
il.MarkLabel(noSuitableOverloadErrorLabel);
// stack.RemoveFrame
if (!emitParentCtorCall)
{
stack.EmitLoad(il);
il.Emit(OpCodes.Call, Methods.PhpStack.RemoveFrame);
}
il.Emit(OpCodes.Ldstr, method.DeclaringType.FullName);
il.Emit(OpCodes.Ldstr, method.FullName);
il.Emit(OpCodes.Call, Methods.PhpException.NoSuitableOverload);
if (emitParentCtorCall)
{
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Throw);
}
// return:
il.MarkLabel(returnLabel);
if (!emitParentCtorCall)
{
il.Ldloc(returnValue);
il.Emit(OpCodes.Ret);
}
}
/// <summary>
/// Returns a list of overloads that can be called with the given argument count on the stack.
/// </summary>
/// <remarks>
/// Vararg overloads are at the end of the returned list and are sorted, so that more general
/// overloads are at the end of the list (for example: params object[] is more general than int,params object[]).
/// </remarks>
private List<Overload>/*!*/ GetOverloadsForArgCount(int argCount)
{
List<Overload> result = new List<Overload>();
Overload overload;
int vararg_start_index = 0;
int i = 0;
while (i < overloads.Count && (overload = overloads[i]).MandatoryParamCount <= argCount)
{
// keep vararg overload at the end of the list - non-vararg overloads should be preferred
if (overload.MandatoryParamCount == argCount)
result.Insert(vararg_start_index++, overload);
else if ((overload.Flags & ClrMethod.OverloadFlags.IsVararg) == ClrMethod.OverloadFlags.IsVararg)
result.Add(overload);
i++;
}
SortVarArgOverloads(result, vararg_start_index);
return result;
}
/// <summary>
/// Returns overloads including the "params" option
/// </summary>
/// <remarks>
/// Returned overloads are sorted, so that more general overloads are at the end
/// of the list (for example: params object[] is more general than int,params object[]).
/// </remarks>
private List<Overload> GetVarArgOverloads(out int maxMandatoryArgCount)
{
List<Overload> result = null;
maxMandatoryArgCount = 0;
for (int i = 0; i < overloads.Count; i++)
{
if ((overloads[i].Flags & ClrMethod.OverloadFlags.IsVararg) == ClrMethod.OverloadFlags.IsVararg)
{
if (result == null) result = new List<Overload>();
result.Add(overloads[i]);
if (overloads[i].MandatoryParamCount > maxMandatoryArgCount)
{
maxMandatoryArgCount = overloads[i].MandatoryParamCount;
}
}
}
if (result != null) SortVarArgOverloads(result, 0);
return result;
}
/// <summary>
/// This function sorts vararg overloads so that more general overloads are at the end.
/// The only difference to algorithm used for sorting overloads during initialization is
/// that we need overloads with MORE parameters first (because this means we have some more
/// specific type requirements declared by mandatory parameters).
///
/// Assumes that input is sorted only the blocks with same parameter count needs to be reversed.
///
/// We need to sort parameters like this to prevent conversions to supertypes (like object[]),
/// becausethis kind of conversion is treated as ImplExactMatch.
/// </summary>
/// <param name="result">List to be sorted</param>
/// <param name="vararg_start_index">Vararg overloads start at this index</param>
/// <remarks>
/// Sorting should be for example:
/// #parameters = 2 + 1:
/// int, string, [params] int[]
/// int, string, [params] object[]
/// #parameters = 1 + 1:
/// int, [params] object[]
/// #parameters = 0 + 1:
/// [params] int[]
/// [params] object[]
/// </remarks>
private void SortVarArgOverloads(List<Overload>/*!*/ result, int vararg_start_index)
{
// most common situation..
if (result.Count == 1) return;
if (result.Count == vararg_start_index) return;
Overload tmp;
int i, j;
// reverse the list
i = vararg_start_index; j = result.Count - 1;
while (i < j) { tmp = result[i]; result[i] = result[j]; result[j] = tmp; i++; j--; }
// now reverse every single block
int pos = 0;
while (pos < result.Count)
{
int block_end = pos, block_pcount = result[pos].ParamCount;
while (block_end < result.Count && result[block_end].ParamCount == block_pcount) block_end++;
i = pos; j = block_end - 1;
while (i < j) { tmp = result[i]; result[i] = result[j]; result[j] = tmp; i++; j--; }
pos = block_end;
}
}
/// <summary>
/// Load arguments from stack and save them to valLocals (by-value) or refLocals (by-reference)
/// </summary>
/// <returns>Returned bit array specifies whether #i-th parameter is byref or by value</returns>
private BitArray/*!*/ EmitLoadArguments(int argCount, List<Overload>/*!*/ argCountOverloads, bool removeFrame)
{
BitArray aliases = new BitArray(argCount, false);
for (int i = 0; i < argCountOverloads.Count; i++)
{
// "or" the byref mask of all argCountOverloads
for (int j = 0; j < argCountOverloads[i].ParamCount; j++)
{
if (argCountOverloads[i].IsAlias(j)) aliases[j] = true;
}
}
int val_counter = 0;
int ref_counter = 0;
for (int i = 0; i < argCount; i++)
{
// LOAD <actual arg #arg_index>
if (aliases[i])
{
loadReferenceArg(il, stack, new LiteralPlace(i + 1));
il.Stloc(refLocals[ref_counter++]);
}
else
{
loadValueArg(il, stack, new LiteralPlace(i + 1));
il.Stloc(valLocals[val_counter++]);
}
}
if (removeFrame && !emitParentCtorCall)
{
// remove the frame:
stack.EmitLoad(il);
il.Emit(OpCodes.Call, Methods.PhpStack.RemoveFrame);
}
return aliases;
}
/// <summary>
/// Default case in the by-number resolution switch
/// </summary>
private void EmitDefaultCase()
{
Label else_label = il.DefineLabel();
this.minArgOverloadTypeResolutionLabel = il.DefineLabel();
// IF (stack.ArgCount > <max param count>) THEN
stack.EmitLoad(il);
il.Emit(OpCodes.Ldfld, Fields.PhpStack_ArgCount);
il.LdcI4(maxArgCount);
il.Emit(OpCodes.Bge, else_label);
EmitMissingParameterCountHandling(minArgOverloadTypeResolutionLabel.Value);
// ELSE
il.MarkLabel(else_label);
int max_mandatory_arg_count;
List<Overload> vararg_overloads = GetVarArgOverloads(out max_mandatory_arg_count);
// do we have any vararg overloads?
if (vararg_overloads != null)
{
// load fixed arguments from stack to valLocals and refLocals locals
BitArray aliases = EmitLoadArguments(max_mandatory_arg_count, vararg_overloads, false);
Label callSwitch = il.DefineLabel();
List<LocalBuilder[]> formalOverloadParams = new List<LocalBuilder[]>();
// bestOverload = -1
LocalBuilder bestOverload = il.DeclareLocal(Types.Int[0]);
il.LdcI4(-1);
il.Stloc(bestOverload);
// bestStrictness = Int32.MaxValue
LocalBuilder bestStrictness = il.DeclareLocal(typeof(ConversionStrictness));
il.LdcI4(Int32.MaxValue);
il.Stloc(bestStrictness);
for (int i = 0; i < vararg_overloads.Count; i++)
{
Label jump_on_error = il.DefineLabel();
Overload current_overload = vararg_overloads[i];
BitArray overload_aliases;
if (current_overload.MandatoryParamCount < max_mandatory_arg_count)
{
overload_aliases = new BitArray(aliases);
overload_aliases.Length = current_overload.MandatoryParamCount;
}
else
overload_aliases = aliases;
// convert mandatory parameters
// strictness_i = ImplExactMatch;
LocalBuilder overloadStrictness = il.GetTemporaryLocal(typeof(int), false);
il.LdcI4(0); // ConversionStrictness.ImplExactMatch
il.Stloc(overloadStrictness);
// alloc local variables
LocalBuilder[] formals = new LocalBuilder[current_overload.ParamCount];
formalOverloadParams.Add(formals);
// convert parameters and tests after conversion
EmitConversions(overload_aliases, current_overload, jump_on_error, overloadStrictness, formals, false);
// load remaining arguments and construct the params array
EmitLoadRemainingArgs(current_overload.MandatoryParamCount,
current_overload.Parameters[current_overload.MandatoryParamCount].ParameterType,
jump_on_error, formals, overloadStrictness);
EmitConversionEpilogue(callSwitch, bestOverload, bestStrictness, i, i == (vararg_overloads.Count - 1), overloadStrictness);
// reuse locals
il.ReturnTemporaryLocal(overloadStrictness);
il.MarkLabel(jump_on_error);
}
// stack.RemoveFrame
if (!emitParentCtorCall)
{
stack.EmitLoad(il);
il.Emit(OpCodes.Call, Methods.PhpStack.RemoveFrame);
}
// call the best overload
EmitBestOverloadSelection(vararg_overloads, callSwitch, bestOverload, bestStrictness, formalOverloadParams);
}
else
EmitMoreParameterCountHandling(caseLabels[caseLabels.Length - 1]);
// END IF;
}
#endregion
#region Resolution by type
/// <summary>
/// Emits a for loop and constructs the array to be passed as the last 'params' argument.
/// </summary>
private void EmitLoadRemainingArgs(int alreadyLoadedArgs, Type/*!*/ argType, Label failLabel,
LocalBuilder[] formals, LocalBuilder overloadStrictness)
{
Type element_type = argType.GetElementType();
// array = new argType[stack.ArgCount - alreadyLoadedArgs]
LocalBuilder array = il.GetTemporaryLocal(argType);
LocalBuilder item = il.GetTemporaryLocal(element_type);
stack.EmitLoad(il);
il.Emit(OpCodes.Ldfld, Fields.PhpStack_ArgCount);
il.LdcI4(alreadyLoadedArgs);
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Newarr, element_type);
il.Stloc(array);
// FOR (tmp = 0; tmp <= array.Length; tmp++)
LocalBuilder tmp = il.GetTemporaryLocal(Types.Int[0]);
LocalBuilder tmp2 = il.GetTemporaryLocal(Types.Int[0]);
// tmp = 0
il.LdcI4(0);
il.Stloc(tmp);
Label condition_label = il.DefineLabel();
il.Emit(OpCodes.Br_S, condition_label);
Label body_label = il.DefineLabel();
il.MarkLabel(body_label);
// FOR LOOP BODY:
il.Ldloc(tmp);
il.LdcI4(alreadyLoadedArgs + 1);
il.Emit(OpCodes.Add);
il.Stloc(tmp2);
loadValueArg(il, stack, new Place(tmp2));
// item = CONVERT
bool ct_ok = EmitConvertToClr(il, PhpTypeCode.Object, element_type, strictness); //!strictness
il.Stloc(item);
if (!ct_ok)
{
// if (strictness == Failed) goto error;
// strictness_i += strictness
il.Ldloc(strictness);
il.LdcI4((int)ConversionStrictness.Failed);
il.Emit(OpCodes.Beq, failLabel);
il.Ldloc(overloadStrictness);
il.Ldloc(strictness);
il.Emit(OpCodes.Add);
il.Stloc(overloadStrictness);
}
// array[tmp] = item
il.Ldloc(array);
il.Ldloc(tmp);
il.Ldloc(item);
il.Stelem(element_type);
// tmp++
il.Ldloc(tmp);
il.LdcI4(1);
il.Emit(OpCodes.Add);
il.Stloc(tmp);
// tmp <= array.Length
il.MarkLabel(condition_label);
il.Ldloc(tmp);
il.Ldloc(array);
il.Emit(OpCodes.Ldlen);
il.Emit(OpCodes.Conv_I4);
il.Emit(OpCodes.Blt_S, body_label);
formals[alreadyLoadedArgs] = array;
il.ReturnTemporaryLocal(tmp);
il.ReturnTemporaryLocal(tmp2);
il.ReturnTemporaryLocal(item);
}
/// <summary>
/// Emits code that choses overload method based on argument types
/// </summary>
/// <param name="overloadIndex"></param>
public void EmitResolutionByTypes(int overloadIndex)
{
int arg_count = overloads[overloadIndex].MandatoryParamCount;
int max_byref = 0, max_byval = 0;
int i = overloadIndex;
do
{
int byval, byref;
GetOverloadValRefArgCount(overloads[i], out byval, out byref);
if (byval > max_byval) max_byval = byval;
if (byref > max_byref) max_byref = byref;
}
while (++i < overloads.Count && overloads[i].MandatoryParamCount == arg_count);
Prepare(arg_count, max_byval, max_byref);
EmitResolutionByTypes(arg_count, GetOverloadsForArgCount(arg_count));
EmitEpilogue();
}
/// <summary>
/// Emits code that choses overload method based on argument types
/// </summary>
/// <param name="argCount">Count of the arguments</param>
/// <param name="argCountOverloads">Count of overloadesd methods with <paramref name="argCount"/> count of arguments.</param>
private void EmitResolutionByTypes(int argCount, List<Overload> argCountOverloads)
{
// load arguments from stack to valLocals and refLocals locals
BitArray aliases = EmitLoadArguments(argCount, argCountOverloads, true);
// mark the label where missing arguments handler should jump:
if (minArgOverloadTypeResolutionLabel.HasValue && argCount == minArgCount)
{
il.MarkLabel(minArgOverloadTypeResolutionLabel.Value);
}
Label callSwitch = il.DefineLabel();
// bestOverload = -1
LocalBuilder bestOverload = il.DeclareLocal(Types.Int[0]);
il.LdcI4(-1);
il.Stloc(bestOverload);
// bestStrictness = Int32.MaxValue
LocalBuilder bestStrictness = il.DeclareLocal(typeof(ConversionStrictness));
il.LdcI4(Int32.MaxValue);
il.Stloc(bestStrictness);
List<LocalBuilder[]> formalOverloadParams = new List<LocalBuilder[]>();
for (int i = 0; i < argCountOverloads.Count; i++)
{
bool is_last = (i + 1 == argCountOverloads.Count);
Label jump_on_error = il.DefineLabel();
Overload current_overload = argCountOverloads[i];
// strictness_i = ImplExactMatch;
LocalBuilder overloadStrictness = il.GetTemporaryLocal(typeof(int), false);
il.LdcI4(0); // ConversionStrictness.ImplExactMatch
il.Stloc(overloadStrictness);
// alloc local variables
LocalBuilder[] formals = new LocalBuilder[current_overload.ParamCount];
formalOverloadParams.Add(formals);
// convert parameters and tests after conversion
EmitConversions(aliases, current_overload, jump_on_error, overloadStrictness, formals, true);
EmitConversionEpilogue(callSwitch, bestOverload, bestStrictness, i, i == (argCountOverloads.Count - 1), overloadStrictness);
// reuse locals
il.ReturnTemporaryLocal(overloadStrictness);
il.MarkLabel(jump_on_error);
}
// call the best overload
EmitBestOverloadSelection(argCountOverloads, callSwitch, bestOverload, bestStrictness, formalOverloadParams);
}
private void EmitBestOverloadSelection(List<Overload> argCountOverloads, Label callSwitch,
LocalBuilder bestOverload, LocalBuilder bestStrictness, List<LocalBuilder[]> formalOverloadParams)
{
il.MarkLabel(callSwitch);
Label[] cases = new Label[argCountOverloads.Count];
for (int i = 0; i < argCountOverloads.Count; i++) cases[i] = il.DefineLabel();
il.Ldloc(bestOverload);
il.Emit(OpCodes.Switch, cases);
il.Emit(OpCodes.Br, noSuitableOverloadErrorLabel);
for (int i = 0; i < argCountOverloads.Count; i++)
{
il.MarkLabel(cases[i]);
Overload current_overload = argCountOverloads[i];
EmitCall(current_overload, noSuitableOverloadErrorLabel, formalOverloadParams[i]); // TODO: we need to make sure that overload can be called earlier !!! it is too late here
// release variables
foreach (LocalBuilder lb in formalOverloadParams[i])
il.ReturnTemporaryLocal(lb);
}
}
private void EmitConversionEpilogue(Label callSwitch, LocalBuilder bestOverload,
LocalBuilder bestStrictness, int i, bool last, LocalBuilder tmpStrictness)
{
// if (tmpStrictness < best_strictness)
// { best_overload = i; best_strictness = tmpStrictness; }
il.Ldloc(bestStrictness);
il.Ldloc(tmpStrictness);
Label endIf = il.DefineLabel();
il.Emit(OpCodes.Ble, endIf);
il.Ldloc(tmpStrictness);
il.Stloc(bestStrictness);
il.LdcI4(i);
il.Stloc(bestOverload);
il.MarkLabel(endIf);
// test whether we found 'ImplExactMatch' (the best possible)
// if (tmpStrictness == ImplExactMatch) goto call_overload_i;
if (!last)
{
il.Ldloc(tmpStrictness);
il.LdcI4((int)ConversionStrictness.ImplExactMatch);
il.Emit(OpCodes.Beq, callSwitch);
}
}
private void EmitConversions(BitArray/*!*/ aliases, Overload/*!*/ overload, Label failLabel,
LocalBuilder overloadStrictness, LocalBuilder[] formals, bool loadAllFormals)
{
MethodBase overload_base = overload.Method;
if (!emitParentCtorCall && (overload_base.IsFamily || overload_base.IsFamilyOrAssembly))
{
// IF (!stack.AllowProtectedCall) THEN GOTO next-overload-or-error;
stack.EmitLoad(il);
il.Emit(OpCodes.Ldfld, Fields.PhpStack_AllowProtectedCall);
il.Emit(OpCodes.Brfalse, failLabel);
}
if (!emitParentCtorCall && !overload_base.IsStatic && !overload_base.IsConstructor)
{
// IF (<instance> == null) THEN GOTO next-overload-or-error;
instance.EmitLoad(il);
il.Emit(OpCodes.Brfalse, failLabel);
}
ParameterInfo[] parameters = overload.Parameters;
int val_counter = 0, ref_counter = 0;
bool overload_is_vararg = ((overload.Flags & ClrMethod.OverloadFlags.IsVararg) == ClrMethod.OverloadFlags.IsVararg);
bool last_param_is_ambiguous_vararg = (overload_is_vararg && parameters.Length == aliases.Length);
Type params_array_element_type = null;
for (int arg_index = 0; arg_index < aliases.Length; arg_index++)
{
// ambiguous_vararg = true iff this is the trailing nth [ParamsArray] parameter and we've been
// given exactly n arguments - we can accept either the array or one array element
bool vararg = false, ambiguous_vararg = false;
Type formal_param_type;
if (arg_index < parameters.Length)
{
formal_param_type = parameters[arg_index].ParameterType;
if (formal_param_type.IsByRef) formal_param_type = formal_param_type.GetElementType();
// if current parameter is [params] array, set vararg to true
if (arg_index + 1 == parameters.Length)
{
ambiguous_vararg = last_param_is_ambiguous_vararg;
vararg = overload_is_vararg;
}
}
else formal_param_type = null;
// LOAD <actual arg #arg_index>
#region Load value or reference depending on parameter in/out settings
PhpTypeCode php_type_code;
if (aliases[arg_index])
{
if (arg_index >= parameters.Length || !parameters[arg_index].IsOut)
{
il.Ldloc(refLocals[ref_counter++]);
php_type_code = PhpTypeCode.PhpReference;
}
else
{
// TODO: Completely ignoring actual arg type passed to out params - questionable
formals[arg_index] = il.GetTemporaryLocal(formal_param_type);
ref_counter++;
continue;
}
}
else
{
il.Ldloc(valLocals[val_counter++]);
php_type_code = PhpTypeCode.Object;
}
#endregion
// Switch to mode when parameters are stored in [params] array
// (unless we need to try conversion to array first - in case of ambigous vararg)
if (formal_param_type != null && vararg && !ambiguous_vararg)
{
Debug.Assert(formal_param_type.IsArray);
formals[arg_index] = il.GetTemporaryLocal(formal_param_type); // declare local of the vararg array type
params_array_element_type = formal_param_type.GetElementType();
EmitCreateParamsArray(params_array_element_type, formals[arg_index], aliases.Length - arg_index);
formal_param_type = null;
}
// formal = CONVERT(stack, out success);
bool ct_ok = EmitConvertToClr(il, php_type_code, formal_param_type ?? params_array_element_type, strictness);
#region Store converted value in local variable or [params] array
// Store returned value in local variable
if (formal_param_type != null)
{
formals[arg_index] = il.GetTemporaryLocal(formal_param_type); // declare local of the formal param type
il.Stloc(formals[arg_index]);
}
// Store returned value in [params] array
if (formal_param_type == null)
{
Debug.Assert(overload_is_vararg);
// _params[n] = formal
LocalBuilder temp = il.GetTemporaryLocal(params_array_element_type, true);
il.Stloc(temp);
il.Ldloc(formals[parameters.Length - 1]);
il.LdcI4(arg_index - parameters.Length + 1);
il.Ldloc(temp);
il.Stelem(params_array_element_type);
}
#endregion
if (!ct_ok)
{
if (ambiguous_vararg)
{
// if the conversion to array has failed, we should try to convert it to the array element
// this bypasses standard "strictness" handling because type can't be convertible to A and A[] at one time..
Debug.Assert(parameters[arg_index].IsDefined(typeof(ParamArrayAttribute), false));
EmitConversionToAmbiguousVararg(arg_index, formal_param_type, strictness, php_type_code,
(php_type_code == PhpTypeCode.PhpReference ? refLocals[ref_counter - 1] : valLocals[val_counter - 1]), formals);
}
// if (strictness == Failed) goto error;
// strictness_i += strictness
il.Ldloc(strictness);
il.LdcI4((int)ConversionStrictness.Failed);
il.Emit(OpCodes.Beq, failLabel);
il.Ldloc(overloadStrictness);
il.Ldloc(strictness);
il.Emit(OpCodes.Add);
il.Stloc(overloadStrictness);
}
}
if (loadAllFormals && parameters.Length > aliases.Length)
{
// one more params argument left -> add empty array
int arg_index = aliases.Length;
Type formal_param_type = parameters[arg_index].ParameterType;
Debug.Assert(arg_index + 1 == parameters.Length);
Debug.Assert(parameters[arg_index].IsDefined(typeof(ParamArrayAttribute), false));
Debug.Assert(formal_param_type.IsArray);
formals[arg_index] = il.GetTemporaryLocal(formal_param_type);
EmitCreateParamsArray(formal_param_type.GetElementType(), formals[arg_index], 0);
}
}
private void EmitConversionToAmbiguousVararg(int argIndex, Type/*!*/ formalParamType, LocalBuilder/*!*/ tmpStrictness,
PhpTypeCode argLocalTypeCode, LocalBuilder/*!*/ argLocal, LocalBuilder[] formals)
{
Debug.Assert(formalParamType.IsArray);
Type element_type = formalParamType.GetElementType();
Label success_label = il.DefineLabel();
// IF (overloadStrictness == ImplExactMatch) GOTO <success_label>
il.Ldloc(tmpStrictness);
il.LdcI4((int)ConversionStrictness.ImplExactMatch);
il.Emit(OpCodes.Beq, success_label);
// formal = new ELEMENT_TYPE[1] { CONVERT(stack, out strictness) };
EmitCreateParamsArray(element_type, formals[argIndex], 1);
il.Ldloc(formals[argIndex]);
il.LdcI4(0);
// reload the argument
il.Ldloc(argLocal);
bool ct_ok = EmitConvertToClr(il, argLocalTypeCode, element_type, tmpStrictness);
il.Stelem(element_type);
il.MarkLabel(success_label, true);
}
#endregion
#region EmitConvertToClr
/// <summary>
/// Converts a PHP value to the given CLR type that is a generic parameter.
/// </summary>
private static void EmitConvertToClrGeneric(ILEmitter/*!*/ il, Type/*!*/ formalType, LocalBuilder/*!*/ strictnessLocal)
{
Debug.Assert(formalType.IsGenericParameter);
// f...ing GenericTypeParameterBuilder will not allow us to read its attributes and constraints :(
if (!(formalType is GenericTypeParameterBuilder))
{
GenericParameterAttributes attrs = formalType.GenericParameterAttributes;
if (Reflection.Enums.GenericParameterAttrTest(attrs, GenericParameterAttributes.NotNullableValueTypeConstraint))
{
// we know that we are converting to a value type
il.Ldloca(strictnessLocal);
il.Emit(OpCodes.Call, Methods.ConvertToClr.TryObjectToStruct.MakeGenericMethod(formalType));
return;
}
Type[] constraints = formalType.GetGenericParameterConstraints();
for (int i = 0; i < constraints.Length; i++)
{
if (constraints[i].IsClass)
{
if (!constraints[i].IsArray && !typeof(Delegate).IsAssignableFrom(constraints[i]))
{
// we know that we are converting to a class that is not an array nor a delegate
il.Ldloca(strictnessLocal);
il.Emit(OpCodes.Call, Methods.ConvertToClr.TryObjectToClass.MakeGenericMethod(formalType));
return;
}
else break;
}
}
}
// postpone the conversion to runtime
il.Ldloca(strictnessLocal);
il.Emit(OpCodes.Call, Methods.Convert.TryObjectToType.MakeGenericMethod(formalType));
}
/// <summary>
/// Converts a PHP value to the given CLR type (the caller is not interested in the success of the conversion).
/// </summary>
public static void EmitConvertToClr(ILEmitter/*!*/ il, PhpTypeCode typeCode, Type/*!*/ formalType)
{
EmitConvertToClr(il, typeCode, formalType, il.GetTemporaryLocal(typeof(ConversionStrictness), true));
}
/// <summary>
/// Converts a PHP value to the given CLR type (the caller passes a <paramref name="strictnessLocal"/> that will
/// receive one of the <see cref="PHP.Core.ConvertToClr.ConversionStrictness"/> enumeration values that
/// describe the conversion result (the Failed value indicates that conversion was not successful).
/// </summary>
/// <returns><B>True</B> if it the conversion will surely succeed.</returns>
internal static bool EmitConvertToClr(ILEmitter/*!*/ il, PhpTypeCode typeCode,
Type/*!*/ formalType, LocalBuilder/*!*/ strictnessLocal)
{
Debug.Assert(strictnessLocal.LocalType == typeof(ConversionStrictness));
// preprocess the value according to the PHP type code
switch (typeCode)
{
case PhpTypeCode.PhpReference:
{
// dereference
il.Emit(OpCodes.Ldfld, Fields.PhpReference_Value);
typeCode = PhpTypeCode.Object;
break;
}
case PhpTypeCode.ObjectAddress:
{
// dereference
il.Emit(OpCodes.Ldind_Ref);
typeCode = PhpTypeCode.Object;
break;
}
case PhpTypeCode.PhpRuntimeChain:
{
Debug.Fail(null);
return true;
}
}
// special treatment for generic parameters
if (formalType.IsGenericParameter)
{
EmitConvertToClrGeneric(il, formalType, strictnessLocal);
return false;
}
// convert CLR type
return EmitConvertObjectToClr(il, typeCode, formalType, strictnessLocal);
}
/// <summary>
/// Converts object to CLR type
/// </summary>
private static bool EmitConvertObjectToClr(ILEmitter il, PhpTypeCode typeCode, Type formalType, LocalBuilder strictnessLocal)
{
MethodInfo convert_method = null;
switch (Type.GetTypeCode(formalType))
{
case TypeCode.Boolean: if (typeCode != PhpTypeCode.Boolean)
convert_method = Methods.ConvertToClr.TryObjectToBoolean; break;
case TypeCode.Int32: if (typeCode != PhpTypeCode.Integer)
convert_method = Methods.ConvertToClr.TryObjectToInt32; break;
case TypeCode.Int64: if (typeCode != PhpTypeCode.LongInteger)
convert_method = Methods.ConvertToClr.TryObjectToInt64; break;
case TypeCode.Double: if (typeCode != PhpTypeCode.Double)
convert_method = Methods.ConvertToClr.TryObjectToDouble; break;
case TypeCode.String: if (typeCode != PhpTypeCode.String)
convert_method = Methods.ConvertToClr.TryObjectToString; break;
case TypeCode.SByte: convert_method = Methods.ConvertToClr.TryObjectToInt8; break;
case TypeCode.Int16: convert_method = Methods.ConvertToClr.TryObjectToInt16; break;
case TypeCode.Byte: convert_method = Methods.ConvertToClr.TryObjectToUInt8; break;
case TypeCode.UInt16: convert_method = Methods.ConvertToClr.TryObjectToUInt16; break;
case TypeCode.UInt32: convert_method = Methods.ConvertToClr.TryObjectToUInt32; break;
case TypeCode.UInt64: convert_method = Methods.ConvertToClr.TryObjectToUInt64; break;
case TypeCode.Single: convert_method = Methods.ConvertToClr.TryObjectToSingle; break;
case TypeCode.Decimal: convert_method = Methods.ConvertToClr.TryObjectToDecimal; break;
case TypeCode.Char: convert_method = Methods.ConvertToClr.TryObjectToChar; break;
case TypeCode.DateTime: convert_method = Methods.ConvertToClr.TryObjectToDateTime; break;
case TypeCode.DBNull: convert_method = Methods.ConvertToClr.TryObjectToDBNull; break;
case TypeCode.Object:
{
if (formalType.IsValueType)
{
if (formalType.IsGenericType && NullableType == formalType.GetGenericTypeDefinition())
{
// This is an ugly corner case (using generic TryObjectToStruct wouldn't work, because
// for nullables .IsValueType returns true, but it doesn't match "T : struct" constraint)!
// We have to try converting object to Nullable<T> first and then to T
// (which requires a new call to 'EmitConvertObjectToClr')
Type nullableArg = formalType.GetGenericArguments()[0];
Type nullableType = NullableType.MakeGenericType(nullableArg);
LocalBuilder tmpVar = il.DeclareLocal(typeof(object));
// This succeeds only for exact match
il.Emit(OpCodes.Call, Methods.ConvertToClr.UnwrapNullable);
il.Emit(OpCodes.Dup);
il.Stloc(tmpVar);
// <stack_0> = tmpVar = UnwrapNullable(...)
// if (<stack_0> != null)
Label lblNull = il.DefineLabel(), lblDone = il.DefineLabel();
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Beq, lblNull);
// {
// Convert tmpVar to T and wrap it into Nullable<T>
il.Ldloc(tmpVar);
bool ret = EmitConvertObjectToClr(il, typeCode, nullableArg, strictnessLocal);
// TODO: use reflection cache?
il.Emit(OpCodes.Newobj, nullableType.GetConstructors()[0]);
il.Emit(OpCodes.Br, lblDone);
// } else /* == null */ {
il.MarkLabel(lblNull);
// return (T?)null;
LocalBuilder tmpNull = il.DeclareLocal(nullableType);
il.Ldloca(tmpNull);
il.Emit(OpCodes.Initobj, nullableType);
il.Ldloc(tmpNull);
// }
il.MarkLabel(lblDone);
return ret;
}
else
convert_method = Methods.ConvertToClr.TryObjectToStruct.MakeGenericMethod(formalType);
}
else
{
if (formalType.IsArray)
convert_method = Methods.ConvertToClr.TryObjectToArray.MakeGenericMethod(formalType.GetElementType());
else if (typeof(Delegate).IsAssignableFrom(formalType))
convert_method = Methods.ConvertToClr.TryObjectToDelegate.MakeGenericMethod(formalType);
else
convert_method = Methods.ConvertToClr.TryObjectToClass.MakeGenericMethod(formalType);
}
break;
}
default:
Debug.Fail(null);
return true;
}
if (convert_method != null)
{
il.Ldloca(strictnessLocal);
il.Emit(OpCodes.Call, convert_method);
return false;
}
else return true;
}
#endregion
#region EmitConvertToPhp
/// <summary>
/// Converts a value of the given CLR type to PHP value.
/// </summary>
internal static PhpTypeCode EmitConvertToPhp(ILEmitter/*!*/ il, Type/*!*/ type)
{
// box generic parameter
if (type.IsGenericParameter)
{
il.Emit(OpCodes.Box, type);
type = Types.Object[0];
}
switch (Type.GetTypeCode(type))
{
// primitives:
case TypeCode.Boolean: return PhpTypeCode.Boolean;
case TypeCode.Int32: return PhpTypeCode.Integer;
case TypeCode.Int64: return PhpTypeCode.LongInteger;
case TypeCode.Double: return PhpTypeCode.Double;
case TypeCode.String: return PhpTypeCode.String;
// coercion:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Byte:
case TypeCode.UInt16:
{
il.Emit(OpCodes.Conv_I4);
return PhpTypeCode.Integer;
}
case TypeCode.UInt32: EmitConstrainedCoercion(il, typeof(int), typeof(long), Int32.MaxValue); return PhpTypeCode.Object;
case TypeCode.UInt64: EmitConstrainedCoercion(il, typeof(int), typeof(long), Int32.MaxValue); return PhpTypeCode.Object;
case TypeCode.Single: il.Emit(OpCodes.Conv_R8); return PhpTypeCode.Double;
case TypeCode.Char:
il.Emit(OpCodes.Box, type);
il.Emit(OpCodes.Callvirt, Methods.Object_ToString);
return PhpTypeCode.String;
case TypeCode.DBNull:
{
il.Emit(OpCodes.Pop);
il.Emit(OpCodes.Ldnull);
return PhpTypeCode.Object;
}
case TypeCode.Decimal: // TODO: what to do with this guy?
case TypeCode.DateTime:
{
il.Emit(OpCodes.Box, type);
il.Emit(OpCodes.Call, Methods.ClrObject_Wrap);
return PhpTypeCode.DObject;
}
case TypeCode.Object:
{
if (!typeof(IPhpVariable).IsAssignableFrom(type))
{
if (type.IsValueType)
il.Emit(OpCodes.Box, type);
il.Emit(OpCodes.Call, Methods.ClrObject_WrapDynamic);
return PhpTypeCode.Object;
}
else return PhpTypeCodeEnum.FromType(type);
}
default:
{
Debug.Fail(null);
return PhpTypeCode.Invalid;
}
}
}
internal static void EmitConstrainedCoercion(ILEmitter/*!*/ il, Type/*!*/ narrow, Type/*!*/ wide, object threshold)
{
Label else_label = il.DefineLabel();
Label endif_label = il.DefineLabel();
il.Emit(OpCodes.Dup);
// IF (STACK <= threshold) THEN
il.LoadLiteral(threshold);
il.Emit(OpCodes.Bgt_S, else_label);
// LOAD (narrow)STACK
il.Conv(narrow, false);
il.Emit(OpCodes.Box, narrow);
il.Emit(OpCodes.Br_S, endif_label);
// ELSE
il.MarkLabel(else_label);
// LOAD (wide)STACK
il.Conv(wide, false);
il.Emit(OpCodes.Box, wide);
// ENDIF
il.MarkLabel(endif_label);
}
#endregion
}
}
| |
using System;
using System.Globalization;
namespace Abp.Extensions
{
/// <summary>
/// Extension methods for String class.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Adds a char to end of given string if it does not ends with the char.
/// </summary>
public static string EnsureEndsWith(this string str, char c)
{
return EnsureEndsWith(str, c, StringComparison.InvariantCulture);
}
/// <summary>
/// Adds a char to end of given string if it does not ends with the char.
/// </summary>
public static string EnsureEndsWith(this string str, char c, StringComparison comparisonType)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.EndsWith(c.ToString(CultureInfo.InvariantCulture), comparisonType))
{
return str;
}
return str + c;
}
/// <summary>
/// Adds a char to end of given string if it does not ends with the char.
/// </summary>
public static string EnsureEndsWith(this string str, char c, bool ignoreCase, CultureInfo culture)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.EndsWith(c.ToString(culture), ignoreCase, culture))
{
return str;
}
return str + c;
}
/// <summary>
/// Adds a char to beginning of given string if it does not starts with the char.
/// </summary>
public static string EnsureStartsWith(this string str, char c)
{
return EnsureStartsWith(str, c, StringComparison.InvariantCulture);
}
/// <summary>
/// Adds a char to beginning of given string if it does not starts with the char.
/// </summary>
public static string EnsureStartsWith(this string str, char c, StringComparison comparisonType)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.StartsWith(c.ToString(CultureInfo.InvariantCulture), comparisonType))
{
return str;
}
return c + str;
}
/// <summary>
/// Adds a char to beginning of given string if it does not starts with the char.
/// </summary>
public static string EnsureStartsWith(this string str, char c, bool ignoreCase, CultureInfo culture)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.StartsWith(c.ToString(culture), ignoreCase, culture))
{
return str;
}
return c + str;
}
/// <summary>
/// Indicates whether this string is null or an System.String.Empty string.
/// </summary>
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
/// <summary>
/// indicates whether this string is null, empty, or consists only of white-space characters.
/// </summary>
public static bool IsNullOrWhiteSpace(this string str)
{
return string.IsNullOrWhiteSpace(str);
}
/// <summary>
/// Gets a substring of a string from beginning of the string.
/// </summary>
/// <param name="str"></param>
/// <param name="len"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception>
public static string Left(this string str, int len)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.Length < len)
{
throw new ArgumentException("len argument can not be bigger than given string's length!");
}
return str.Substring(0, len);
}
/// <summary>
/// Gets index of nth occurence of a char in a string.
/// </summary>
/// <param name="str">source string to be searched</param>
/// <param name="c">Char to search in <see cref="str"/></param>
/// <param name="n">Count of the occurence</param>
public static int NthIndexOf(this string str, char c, int n)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
var count = 0;
for (var i = 0; i < str.Length; i++)
{
if (str[i] != c)
{
continue;
}
if ((++count) == n)
{
return i;
}
}
return -1;
}
/// <summary>
/// Gets a substring of a string from end of the string.
/// </summary>
/// <param name="str"></param>
/// <param name="len"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="len"/> is bigger that string's length</exception>
public static string Right(this string str, int len)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
if (str.Length < len)
{
throw new ArgumentException("len argument can not be bigger than given string's length!");
}
return str.Substring(str.Length - len, len);
}
/// <summary>
/// Converts PascalCase string to camelCase string.
/// </summary>
/// <param name="str">String to convert</param>
/// <returns>camelCase of the string</returns>
public static string ToCamelCase(this string str)
{
return str.ToCamelCase(CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts PascalCase string to camelCase string in specified culture.
/// </summary>
/// <param name="str">String to convert</param>
/// <param name="culture">An object that supplies culture-specific casing rules</param>
/// <returns>camelCase of the string</returns>
public static string ToCamelCase(this string str, CultureInfo culture)
{
if (string.IsNullOrWhiteSpace(str))
{
return str;
}
if (str.Length == 1)
{
return str.ToLower(culture);
}
return char.ToLower(str[0], culture) + str.Substring(1);
}
/// <summary>
/// Converts string to enum value.
/// </summary>
/// <typeparam name="T">Type of enum</typeparam>
/// <param name="value">String value to convert</param>
/// <returns>Returns enum object</returns>
public static T ToEnum<T>(this string value)
where T : struct
{
if (value == null)
{
throw new ArgumentNullException("value");
}
return (T)Enum.Parse(typeof(T), value);
}
/// <summary>
/// Converts string to enum value.
/// </summary>
/// <typeparam name="T">Type of enum</typeparam>
/// <param name="value">String value to convert</param>
/// <param name="ignoreCase">Ignore case</param>
/// <returns>Returns enum object</returns>
public static T ToEnum<T>(this string value, bool ignoreCase)
where T : struct
{
if (value == null)
{
throw new ArgumentNullException("value");
}
return (T)Enum.Parse(typeof(T), value, ignoreCase);
}
/// <summary>
/// Converts camelCase string to PascalCase string.
/// </summary>
/// <param name="str">String to convert</param>
/// <returns>PascalCase of the string</returns>
public static string ToPascalCase(this string str)
{
return str.ToPascalCase(CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts camelCase string to PascalCase string in specified culture.
/// </summary>
/// <param name="str">String to convert</param>
/// <param name="culture">An object that supplies culture-specific casing rules</param>
/// <returns>PascalCase of the string</returns>
public static string ToPascalCase(this string str, CultureInfo culture)
{
if (string.IsNullOrWhiteSpace(str))
{
return str;
}
if (str.Length == 1)
{
return str.ToUpper(culture);
}
return char.ToUpper(str[0], culture) + str.Substring(1);
}
/// <summary>
/// Gets a substring of a string from beginning of the string if it exceeds maximum length.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
public static string Truncate(this string str, int maxLength)
{
if (str == null)
{
return null;
}
if (str.Length <= maxLength)
{
return str;
}
return str.Left(maxLength);
}
/// <summary>
/// Gets a substring of a string from beginning of the string if it exceeds maximum length.
/// It adds a "..." postfix to end of the string if it's truncated.
/// Returning string can not be longer than maxLength.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
public static string TruncateWithPostfix(this string str, int maxLength)
{
return TruncateWithPostfix(str, maxLength, "...");
}
/// <summary>
/// Gets a substring of a string from beginning of the string if it exceeds maximum length.
/// It adds given <paramref name="postfix"/> to end of the string if it's truncated.
/// Returning string can not be longer than maxLength.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="str"/> is null</exception>
public static string TruncateWithPostfix(this string str, int maxLength, string postfix)
{
if (str == null)
{
return null;
}
if (str == string.Empty || maxLength == 0)
{
return string.Empty;
}
if (str.Length <= maxLength)
{
return str;
}
if (maxLength <= postfix.Length)
{
return postfix.Left(maxLength);
}
return str.Left(maxLength - postfix.Length) + postfix;
}
}
}
| |
namespace Lewis.SST.Gui
{
partial class XmlNodeExplorer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(XmlNodeExplorer));
System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("XML Node Top Level", 2, 1);
this.contextEditMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.findToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.findAToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.resyncWithXMLDocToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.treeView1 = new Lewis.SST.Controls.XmlTreeView();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.XmlProperties = new System.Windows.Forms.PropertyGrid();
this.contextEditMenuStrip.SuspendLayout();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.SuspendLayout();
//
// contextEditMenuStrip
//
this.contextEditMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.findToolStripMenuItem,
this.findAToolStripMenuItem,
this.toolStripMenuItem1,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.cutToolStripMenuItem,
this.toolStripMenuItem2,
this.resyncWithXMLDocToolStripMenuItem});
this.contextEditMenuStrip.Name = "contextEditMenuStrip";
this.contextEditMenuStrip.Size = new System.Drawing.Size(187, 148);
//
// findToolStripMenuItem
//
this.findToolStripMenuItem.Name = "findToolStripMenuItem";
this.findToolStripMenuItem.Size = new System.Drawing.Size(186, 22);
this.findToolStripMenuItem.Text = "Find";
this.findToolStripMenuItem.Click += new System.EventHandler(this.findToolStripMenuItem_Click);
//
// findAToolStripMenuItem
//
this.findAToolStripMenuItem.Name = "findAToolStripMenuItem";
this.findAToolStripMenuItem.Size = new System.Drawing.Size(186, 22);
this.findAToolStripMenuItem.Text = "Find and Replace";
this.findAToolStripMenuItem.Visible = false;
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(183, 6);
this.toolStripMenuItem1.Visible = false;
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.Size = new System.Drawing.Size(186, 22);
this.copyToolStripMenuItem.Text = "Copy";
this.copyToolStripMenuItem.Visible = false;
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(186, 22);
this.pasteToolStripMenuItem.Text = "Paste";
this.pasteToolStripMenuItem.Visible = false;
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.Size = new System.Drawing.Size(186, 22);
this.cutToolStripMenuItem.Text = "Cut";
this.cutToolStripMenuItem.Visible = false;
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(183, 6);
this.toolStripMenuItem2.Visible = false;
//
// resyncWithXMLDocToolStripMenuItem
//
this.resyncWithXMLDocToolStripMenuItem.Name = "resyncWithXMLDocToolStripMenuItem";
this.resyncWithXMLDocToolStripMenuItem.Size = new System.Drawing.Size(186, 22);
this.resyncWithXMLDocToolStripMenuItem.Text = "Resync with XML Doc";
this.resyncWithXMLDocToolStripMenuItem.Visible = false;
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
this.imageList1.Images.SetKeyName(0, "");
this.imageList1.Images.SetKeyName(1, "");
this.imageList1.Images.SetKeyName(2, "");
this.imageList1.Images.SetKeyName(3, "");
this.imageList1.Images.SetKeyName(4, "");
this.imageList1.Images.SetKeyName(5, "");
this.imageList1.Images.SetKeyName(6, "");
this.imageList1.Images.SetKeyName(7, "");
this.imageList1.Images.SetKeyName(8, "");
this.imageList1.Images.SetKeyName(9, "");
this.imageList1.Images.SetKeyName(10, "");
this.imageList1.Images.SetKeyName(11, "");
this.imageList1.Images.SetKeyName(12, "");
this.imageList1.Images.SetKeyName(13, "BlueBall.gif");
//
// toolTip1
//
this.toolTip1.IsBalloon = true;
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl1.Location = new System.Drawing.Point(0, 24);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(267, 330);
this.tabControl1.TabIndex = 1;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.treeView1);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(259, 304);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Xml Node View";
this.tabPage1.UseVisualStyleBackColor = true;
//
// treeView1
//
this.treeView1.ContextMenuStrip = this.contextEditMenuStrip;
this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView1.DrawMode = System.Windows.Forms.TreeViewDrawMode.OwnerDrawText;
this.treeView1.HideSelection = false;
this.treeView1.HotTracking = true;
this.treeView1.ImageIndex = 13;
this.treeView1.ImageList = this.imageList1;
this.treeView1.Indent = 19;
this.treeView1.LineColor = System.Drawing.Color.CornflowerBlue;
this.treeView1.Location = new System.Drawing.Point(3, 3);
this.treeView1.Name = "treeView1";
this.treeView1.Navigator = null;
treeNode1.ImageIndex = 2;
treeNode1.Name = "";
treeNode1.SelectedImageIndex = 1;
treeNode1.Text = "XML Node Top Level";
this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
treeNode1});
this.treeView1.SelectedImageIndex = 13;
this.treeView1.ShowNodeToolTips = true;
this.treeView1.Size = new System.Drawing.Size(253, 298);
this.treeView1.TabIndex = 1;
this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
this.treeView1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseUp);
this.treeView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseDown);
//
// tabPage2
//
this.tabPage2.Controls.Add(this.XmlProperties);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(259, 304);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Xml Node Properties";
this.tabPage2.UseVisualStyleBackColor = true;
//
// XmlProperties
//
this.XmlProperties.Dock = System.Windows.Forms.DockStyle.Fill;
this.XmlProperties.HelpVisible = false;
this.XmlProperties.LineColor = System.Drawing.SystemColors.ScrollBar;
this.XmlProperties.Location = new System.Drawing.Point(3, 3);
this.XmlProperties.Name = "XmlProperties";
this.XmlProperties.Size = new System.Drawing.Size(253, 298);
this.XmlProperties.TabIndex = 10;
this.XmlProperties.ToolbarVisible = false;
//
// XmlNodeExplorer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.ClientSize = new System.Drawing.Size(267, 355);
this.Controls.Add(this.tabControl1);
this.DockAreas = ((WeifenLuo.WinFormsUI.Docking.DockAreas)((((WeifenLuo.WinFormsUI.Docking.DockAreas.DockLeft | WeifenLuo.WinFormsUI.Docking.DockAreas.DockRight)
| WeifenLuo.WinFormsUI.Docking.DockAreas.DockTop)
| WeifenLuo.WinFormsUI.Docking.DockAreas.DockBottom)));
this.DoubleBuffered = true;
this.HideOnClose = true;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "XmlNodeExplorer";
this.Padding = new System.Windows.Forms.Padding(0, 24, 0, 1);
this.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.DockLeft;
this.ShowInTaskbar = false;
this.TabText = "Xml Node Explorer";
this.Text = "XML Node Explorer";
this.contextEditMenuStrip.ResumeLayout(false);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.ContextMenuStrip contextEditMenuStrip;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem findToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem resyncWithXMLDocToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem findAToolStripMenuItem;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private Lewis.SST.Controls.XmlTreeView treeView1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.PropertyGrid XmlProperties;
}
}
| |
/*
* InformationMachineAPI.PCL
*
*
*/
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InformationMachineAPI.PCL;
using InformationMachineAPI.PCL.Http.Request;
using InformationMachineAPI.PCL.Http.Response;
using InformationMachineAPI.PCL.Http.Client;
using InformationMachineAPI.PCL.Exceptions;
using InformationMachineAPI.PCL.Models;
namespace InformationMachineAPI.PCL.Controllers
{
public partial class UserPurchasesController: BaseController
{
#region Singleton Pattern
//private static variables for the singleton pattern
private static object syncObject = new object();
private static UserPurchasesController instance = null;
/// <summary>
/// Singleton pattern implementation
/// </summary>
internal static UserPurchasesController Instance
{
get
{
lock (syncObject)
{
if (null == instance)
{
instance = new UserPurchasesController();
}
}
return instance;
}
}
#endregion Singleton Pattern
/// <summary>
/// Get specified purchase details
/// </summary>
/// <param name="userId">Required parameter: Example: </param>
/// <param name="purchaseId">Required parameter: Example: </param>
/// <param name="fullResp">Optional parameter: default:false (set true for response with purchase item details)</param>
/// <return>Returns the GetSingleUserPurchaseWrapper response from the API call</return>
public GetSingleUserPurchaseWrapper UserPurchasesGetSingleUserPurchase(string userId, string purchaseId, bool? fullResp = null)
{
Task<GetSingleUserPurchaseWrapper> t = UserPurchasesGetSingleUserPurchaseAsync(userId, purchaseId, fullResp);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// Get specified purchase details
/// </summary>
/// <param name="userId">Required parameter: Example: </param>
/// <param name="purchaseId">Required parameter: Example: </param>
/// <param name="fullResp">Optional parameter: default:false (set true for response with purchase item details)</param>
/// <return>Returns the GetSingleUserPurchaseWrapper response from the API call</return>
public async Task<GetSingleUserPurchaseWrapper> UserPurchasesGetSingleUserPurchaseAsync(string userId, string purchaseId, bool? fullResp = null)
{
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/v1/users/{user_id}/purchases/{purchase_id}");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "user_id", userId },
{ "purchase_id", purchaseId }
});
//process optional query parameters
APIHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "full_resp", fullResp },
{ "client_id", Configuration.ClientId },
{ "client_secret", Configuration.ClientSecret }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "" },
{ "accept", "application/json" }
};
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Get(_queryUrl,_headers);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//Error handling using HTTP status codes
if (_response.StatusCode == 404)
throw new APIException(@"Not Found", _context);
else if (_response.StatusCode == 401)
throw new APIException(@"Unauthorized", _context);
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<GetSingleUserPurchaseWrapper>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// Get purchases made by a specified user [purchased product mode]
/// </summary>
/// <param name="userId">Required parameter: Example: </param>
/// <param name="storeId">Optional parameter: Check Lookup/Stores section for ID of all stores. E.g., Amazon = 4, Walmart = 3.</param>
/// <param name="foodOnly">Optional parameter: default:false [Filter out food purchase items.]</param>
/// <param name="upcOnly">Optional parameter: default:false [Filter out purchase items with UPC.]</param>
/// <param name="showProductDetails">Optional parameter: default:false [Show details of a purchased products (image, nutrients, ingredients, manufacturer, etc..)]</param>
/// <param name="receiptsOnly">Optional parameter: default:false [Filter out purchases transcribed from receipts.]</param>
/// <param name="upcResolvedAfter">Optional parameter: List only purchases having UPC resolved by IM after specified date. Expected format: "yyyy-MM-dd"</param>
/// <param name="purchaseDateBefore">Optional parameter: Retrieve purchases made during and before specified date. Combined with "purchase_date_after" date range can be defined. Expected format: yyyy-MM-dd<br />[e.g., 2015-04-18]</param>
/// <param name="purchaseDateAfter">Optional parameter: Retrieve purchases made during and after specified date. Combined with "purchase_date_before" date range can be defined. Expected format: yyyy-MM-dd<br />[e.g., 2015-04-18]</param>
/// <param name="recordedAtBefore">Optional parameter: Retrieve purchases after it is created in our database. Combined with "recorded_at_after" date range can be defined. Expected format: yyyy-MM-dd<br />[e.g., 2015-04-18]</param>
/// <param name="recordedAtAfter">Optional parameter: Retrieve purchases after it is created in our database. Combined with "recorded_at_before" date range can be defined. Expected format: yyyy-MM-dd<br />[e.g., 2015-04-18]</param>
/// <return>Returns the GetUserPurchaseHistoryWrapper response from the API call</return>
public GetUserPurchaseHistoryWrapper UserPurchasesGetPurchaseHistoryUnified(
string userId,
int? storeId = null,
bool? foodOnly = null,
bool? upcOnly = null,
bool? showProductDetails = true,
bool? receiptsOnly = null,
DateTime? upcResolvedAfter = null,
DateTime? purchaseDateBefore = null,
DateTime? purchaseDateAfter = null,
DateTime? recordedAtBefore = null,
DateTime? recordedAtAfter = null)
{
Task<GetUserPurchaseHistoryWrapper> t = UserPurchasesGetPurchaseHistoryUnifiedAsync(userId, storeId, foodOnly, upcOnly, showProductDetails, receiptsOnly, upcResolvedAfter, purchaseDateBefore, purchaseDateAfter, recordedAtBefore, recordedAtAfter);
Task.WaitAll(t);
return t.Result;
}
/// <summary>
/// Get purchases made by a specified user [purchased product mode]
/// </summary>
/// <param name="userId">Required parameter: Example: </param>
/// <param name="storeId">Optional parameter: Check Lookup/Stores section for ID of all stores. E.g., Amazon = 4, Walmart = 3.</param>
/// <param name="foodOnly">Optional parameter: default:false [Filter out food purchase items.]</param>
/// <param name="upcOnly">Optional parameter: default:false [Filter out purchase items with UPC.]</param>
/// <param name="showProductDetails">Optional parameter: default:false [Show details of a purchased products (image, nutrients, ingredients, manufacturer, etc..)]</param>
/// <param name="receiptsOnly">Optional parameter: default:false [Filter out purchases transcribed from receipts.]</param>
/// <param name="upcResolvedAfter">Optional parameter: List only purchases having UPC resolved by IM after specified date. Expected format: "yyyy-MM-dd"</param>
/// <param name="purchaseDateBefore">Optional parameter: Retrieve purchases made during and before specified date. Combined with "purchase_date_after" date range can be defined. Expected format: yyyy-MM-dd<br />[e.g., 2015-04-18]</param>
/// <param name="purchaseDateAfter">Optional parameter: Retrieve purchases made during and after specified date. Combined with "purchase_date_before" date range can be defined. Expected format: yyyy-MM-dd<br />[e.g., 2015-04-18]</param>
/// <param name="recordedAtBefore">Optional parameter: Retrieve purchases after it is created in our database. Combined with "recorded_at_after" date range can be defined. Expected format: yyyy-MM-dd<br />[e.g., 2015-04-18]</param>
/// <param name="recordedAtAfter">Optional parameter: Retrieve purchases after it is created in our database. Combined with "recorded_at_before" date range can be defined. Expected format: yyyy-MM-dd<br />[e.g., 2015-04-18]</param>
/// <return>Returns the GetUserPurchaseHistoryWrapper response from the API call</return>
public async Task<GetUserPurchaseHistoryWrapper> UserPurchasesGetPurchaseHistoryUnifiedAsync(
string userId,
int? storeId = null,
bool? foodOnly = null,
bool? upcOnly = null,
bool? showProductDetails = true,
bool? receiptsOnly = null,
DateTime? upcResolvedAfter = null,
DateTime? purchaseDateBefore = null,
DateTime? purchaseDateAfter = null,
DateTime? recordedAtBefore = null,
DateTime? recordedAtAfter = null)
{
//the base uri for api requestss
string _baseUri = Configuration.BaseUri;
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/v1/users/{user_id}/purchases_product_based");
//process optional template parameters
APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "user_id", userId }
});
//process optional query parameters
APIHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "store_id", storeId },
{ "food_only", foodOnly },
{ "upc_only", upcOnly },
{ "show_product_details", (null != showProductDetails) ? showProductDetails : true },
{ "receipts_only", receiptsOnly },
{ "upc_resolved_after", upcResolvedAfter },
{ "purchase_date_before", purchaseDateBefore },
{ "purchase_date_after", purchaseDateAfter },
{ "recorded_at_before", recordedAtBefore },
{ "recorded_at_after", recordedAtAfter },
{ "client_id", Configuration.ClientId },
{ "client_secret", Configuration.ClientSecret }
});
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "" },
{ "accept", "application/json" }
};
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Get(_queryUrl,_headers);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request);
HttpContext _context = new HttpContext(_request,_response);
//Error handling using HTTP status codes
if (_response.StatusCode == 404)
throw new APIException(@"Not Found", _context);
else if (_response.StatusCode == 401)
throw new APIException(@"Unauthorized", _context);
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<GetUserPurchaseHistoryWrapper>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal abstract partial class AbstractCodeModelService : ICodeModelService
{
private readonly ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>> _treeToNodeKeyMaps =
new ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>>();
protected readonly ISyntaxFactsService SyntaxFactsService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly AbstractNodeNameGenerator _nodeNameGenerator;
private readonly AbstractNodeLocator _nodeLocator;
private readonly AbstractCodeModelEventCollector _eventCollector;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
private readonly IFormattingRule _lineAdjustmentFormattingRule;
private readonly IFormattingRule _endRegionFormattingRule;
protected AbstractCodeModelService(
HostLanguageServices languageServiceProvider,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
IFormattingRule lineAdjustmentFormattingRule,
IFormattingRule endRegionFormattingRule)
{
Debug.Assert(languageServiceProvider != null);
Debug.Assert(editorOptionsFactoryService != null);
this.SyntaxFactsService = languageServiceProvider.GetService<ISyntaxFactsService>();
_editorOptionsFactoryService = editorOptionsFactoryService;
_lineAdjustmentFormattingRule = lineAdjustmentFormattingRule;
_endRegionFormattingRule = endRegionFormattingRule;
_refactorNotifyServices = refactorNotifyServices;
_nodeNameGenerator = CreateNodeNameGenerator();
_nodeLocator = CreateNodeLocator();
_eventCollector = CreateCodeModelEventCollector();
}
protected string GetNewLineCharacter(SourceText text)
{
return _editorOptionsFactoryService.GetEditorOptions(text).GetNewLineCharacter();
}
protected SyntaxToken GetTokenWithoutAnnotation(SyntaxToken current, Func<SyntaxToken, SyntaxToken> nextTokenGetter)
{
while (current.ContainsAnnotations)
{
current = nextTokenGetter(current);
}
return current;
}
protected TextSpan GetEncompassingSpan(SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken)
{
var startPosition = startToken.SpanStart;
var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End;
return TextSpan.FromBounds(startPosition, endPosition);
}
private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> BuildNodeKeyMap(SyntaxTree syntaxTree)
{
var nameOrdinalMap = new Dictionary<string, int>();
var nodeKeyMap = BidirectionalMap<SyntaxNodeKey, SyntaxNode>.Empty;
foreach (var node in GetFlattenedMemberNodes(syntaxTree))
{
var name = _nodeNameGenerator.GenerateName(node);
if (!nameOrdinalMap.TryGetValue(name, out var ordinal))
{
ordinal = 0;
}
nameOrdinalMap[name] = ++ordinal;
var key = new SyntaxNodeKey(name, ordinal);
nodeKeyMap = nodeKeyMap.Add(key, node);
}
return nodeKeyMap;
}
private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> GetNodeKeyMap(SyntaxTree syntaxTree)
{
return _treeToNodeKeyMaps.GetValue(syntaxTree, BuildNodeKeyMap);
}
public SyntaxNodeKey GetNodeKey(SyntaxNode node)
{
var nodeKey = TryGetNodeKey(node);
if (nodeKey.IsEmpty)
{
throw new ArgumentException();
}
return nodeKey;
}
public SyntaxNodeKey TryGetNodeKey(SyntaxNode node)
{
var nodeKeyMap = GetNodeKeyMap(node.SyntaxTree);
if (!nodeKeyMap.TryGetKey(node, out var nodeKey))
{
return SyntaxNodeKey.Empty;
}
return nodeKey;
}
public SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree)
{
var nodeKeyMap = GetNodeKeyMap(syntaxTree);
if (!nodeKeyMap.TryGetValue(nodeKey, out var node))
{
throw new ArgumentException();
}
return node;
}
public bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node)
{
var nodeKeyMap = GetNodeKeyMap(syntaxTree);
return nodeKeyMap.TryGetValue(nodeKey, out node);
}
public abstract bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope);
public abstract IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent);
protected IEnumerable<SyntaxNode> GetFlattenedMemberNodes(SyntaxTree syntaxTree)
{
return GetMemberNodes(syntaxTree.GetRoot(), includeSelf: true, recursive: true, logicalFields: true, onlySupportedNodes: true);
}
protected IEnumerable<SyntaxNode> GetLogicalMemberNodes(SyntaxNode container)
{
return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: false);
}
public IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container)
{
return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: true);
}
/// <summary>
/// Retrieves the members of a specified <paramref name="container"/> node. The members that are
/// returned can be controlled by passing various parameters.
/// </summary>
/// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param>
/// <param name="includeSelf">If true, the container is returned as well.</param>
/// <param name="recursive">If true, members are recursed to return descendant members as well
/// as immediate children. For example, a namespace would return the namespaces and types within.
/// However, if <paramref name="recursive"/> is true, members with the namespaces and types would
/// also be returned.</param>
/// <param name="logicalFields">If true, field declarations are broken into their respective declarators.
/// For example, the field "int x, y" would return two declarators, one for x and one for y in place
/// of the field.</param>
/// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param>
public abstract IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes);
public abstract string Language { get; }
public abstract string AssemblyAttributeString { get; }
public EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Event:
return (EnvDTE.CodeElement)ExternalCodeEvent.Create(state, projectId, (IEventSymbol)symbol);
case SymbolKind.Field:
return (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, (IFieldSymbol)symbol);
case SymbolKind.Method:
return (EnvDTE.CodeElement)ExternalCodeFunction.Create(state, projectId, (IMethodSymbol)symbol);
case SymbolKind.Namespace:
return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, (INamespaceSymbol)symbol);
case SymbolKind.NamedType:
var namedType = (INamedTypeSymbol)symbol;
switch (namedType.TypeKind)
{
case TypeKind.Class:
case TypeKind.Module:
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, namedType);
case TypeKind.Delegate:
return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, namedType);
case TypeKind.Enum:
return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, namedType);
case TypeKind.Interface:
return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, namedType);
case TypeKind.Struct:
return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, namedType);
default:
throw Exceptions.ThrowEFail();
}
case SymbolKind.Property:
var propertySymbol = (IPropertySymbol)symbol;
return propertySymbol.IsWithEvents
? (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, propertySymbol)
: (EnvDTE.CodeElement)ExternalCodeProperty.Create(state, projectId, (IPropertySymbol)symbol);
default:
throw Exceptions.ThrowEFail();
}
}
/// <summary>
/// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/>
/// </summary>
public abstract EnvDTE.CodeElement CreateInternalCodeElement(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNode node);
public EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol)
{
if (typeSymbol.TypeKind == TypeKind.Pointer ||
typeSymbol.TypeKind == TypeKind.TypeParameter ||
typeSymbol.TypeKind == TypeKind.Submission)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Error ||
typeSymbol.TypeKind == TypeKind.Unknown)
{
return ExternalCodeUnknown.Create(state, projectId, typeSymbol);
}
var project = state.Workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Dynamic)
{
var obj = project.GetCompilationAsync().Result.GetSpecialType(SpecialType.System_Object);
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, obj);
}
if (TryGetElementFromSource(state, project, typeSymbol, out var element))
{
return element;
}
EnvDTE.vsCMElement elementKind = GetElementKind(typeSymbol);
switch (elementKind)
{
case EnvDTE.vsCMElement.vsCMElementClass:
case EnvDTE.vsCMElement.vsCMElementModule:
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementInterface:
return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementDelegate:
return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementEnum:
return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementStruct:
return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, typeSymbol);
default:
Debug.Fail("Unsupported element kind: " + elementKind);
throw Exceptions.ThrowEInvalidArg();
}
}
public abstract EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type);
public abstract EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract bool IsParameterNode(SyntaxNode node);
public abstract bool IsAttributeNode(SyntaxNode node);
public abstract bool IsAttributeArgumentNode(SyntaxNode node);
public abstract bool IsOptionNode(SyntaxNode node);
public abstract bool IsImportNode(SyntaxNode node);
public ISymbol ResolveSymbol(Workspace workspace, ProjectId projectId, SymbolKey symbolId)
{
var project = workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
return symbolId.Resolve(project.GetCompilationAsync().Result).Symbol;
}
protected EnvDTE.CodeFunction CreateInternalCodeAccessorFunction(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
var accessorKind = GetAccessorKind(node);
return CodeAccessorFunction.Create(state, parentObj, accessorKind);
}
protected EnvDTE.CodeAttribute CreateInternalCodeAttribute(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = GetEffectiveParentForAttribute(node);
AbstractCodeElement parentObject;
if (IsParameterNode(parentNode))
{
var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement);
}
else
{
var nodeKey = parentNode.AncestorsAndSelf()
.Select(n => TryGetNodeKey(n))
.FirstOrDefault(nk => nk != SyntaxNodeKey.Empty);
if (nodeKey == SyntaxNodeKey.Empty)
{
// This is an assembly-level attribute.
parentNode = fileCodeModel.GetSyntaxRoot();
parentObject = null;
}
else
{
parentNode = fileCodeModel.LookupNode(nodeKey);
var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement);
}
}
GetAttributeNameAndOrdinal(parentNode, node, out var name, out var ordinal);
return CodeAttribute.Create(state, fileCodeModel, parentObject, name, ordinal);
}
protected EnvDTE80.CodeImport CreateInternalCodeImport(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
GetImportParentAndName(node, out var parentNode, out var name);
AbstractCodeElement parentObj = null;
if (parentNode != null)
{
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObj = ComAggregate.GetManagedObject<AbstractCodeElement>(parent);
}
return CodeImport.Create(state, fileCodeModel, parentObj, name);
}
protected EnvDTE.CodeParameter CreateInternalCodeParameter(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
string name = GetParameterName(node);
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeParameter.Create(state, parentObj, name);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeOptionStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
GetOptionNameAndOrdinal(node.Parent, node, out var name, out var ordinal);
return CodeOptionsStatement.Create(state, fileCodeModel, name, ordinal);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeInheritsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
GetInheritsNamespaceAndOrdinal(parentNode, node, out var namespaceName, out var ordinal);
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeInheritsStatement.Create(state, parentObj, namespaceName, ordinal);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeImplementsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
GetImplementsNamespaceAndOrdinal(parentNode, node, out var namespaceName, out var ordinal);
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeImplementsStatement.Create(state, parentObj, namespaceName, ordinal);
}
protected EnvDTE80.CodeAttributeArgument CreateInternalCodeAttributeArgument(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
GetAttributeArgumentParentAndIndex(node, out var attributeNode, out var index);
var codeAttribute = CreateInternalCodeAttribute(state, fileCodeModel, attributeNode);
var codeAttributeObj = ComAggregate.GetManagedObject<CodeAttribute>(codeAttribute);
return CodeAttributeArgument.Create(state, codeAttributeObj, index);
}
public abstract EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node);
public abstract EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel);
public abstract string GetUnescapedName(string name);
public abstract string GetName(SyntaxNode node);
public abstract SyntaxNode GetNodeWithName(SyntaxNode node);
public abstract SyntaxNode SetName(SyntaxNode node, string name);
public abstract string GetFullName(SyntaxNode node, SemanticModel semanticModel);
public abstract string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel);
public void Rename(ISymbol symbol, string newName, Solution solution)
{
// TODO: (tomescht) make this testable through unit tests.
// Right now we have to go through the project system to find all
// the outstanding CodeElements which might be affected by the
// rename. This is silly. This functionality should be moved down
// into the service layer.
var workspace = solution.Workspace as VisualStudioWorkspaceImpl;
if (workspace == null)
{
throw Exceptions.ThrowEFail();
}
// Save the node keys.
var nodeKeyValidation = new NodeKeyValidation();
foreach (var project in workspace.DeferredState.ProjectTracker.ImmutableProjects)
{
nodeKeyValidation.AddProject(project);
}
// Rename symbol.
var newSolution = Renamer.RenameSymbolAsync(solution, symbol, newName, solution.Options).WaitAndGetResult_CodeModel(CancellationToken.None);
var changedDocuments = newSolution.GetChangedDocuments(solution);
// Notify third parties of the coming rename operation and let exceptions propagate out
_refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
// Update the workspace.
if (!workspace.TryApplyChanges(newSolution))
{
throw Exceptions.ThrowEFail();
}
// Notify third parties of the completed rename operation and let exceptions propagate out
_refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments);
// Update the node keys.
nodeKeyValidation.RestoreKeys();
}
public abstract bool IsValidExternalSymbol(ISymbol symbol);
public abstract string GetExternalSymbolName(ISymbol symbol);
public abstract string GetExternalSymbolFullName(ISymbol symbol);
public VirtualTreePoint? GetStartPoint(SyntaxNode node, OptionSet options, EnvDTE.vsCMPart? part)
{
return _nodeLocator.GetStartPoint(node, options, part);
}
public VirtualTreePoint? GetEndPoint(SyntaxNode node, OptionSet options, EnvDTE.vsCMPart? part)
{
return _nodeLocator.GetEndPoint(node, options, part);
}
public abstract EnvDTE.vsCMAccess GetAccess(ISymbol symbol);
public abstract EnvDTE.vsCMAccess GetAccess(SyntaxNode node);
public abstract SyntaxNode GetNodeWithModifiers(SyntaxNode node);
public abstract SyntaxNode GetNodeWithType(SyntaxNode node);
public abstract SyntaxNode GetNodeWithInitializer(SyntaxNode node);
public abstract SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access);
public abstract EnvDTE.vsCMElement GetElementKind(SyntaxNode node);
protected EnvDTE.vsCMElement GetElementKind(ITypeSymbol typeSymbol)
{
switch (typeSymbol.TypeKind)
{
case TypeKind.Array:
case TypeKind.Class:
return EnvDTE.vsCMElement.vsCMElementClass;
case TypeKind.Interface:
return EnvDTE.vsCMElement.vsCMElementInterface;
case TypeKind.Struct:
return EnvDTE.vsCMElement.vsCMElementStruct;
case TypeKind.Enum:
return EnvDTE.vsCMElement.vsCMElementEnum;
case TypeKind.Delegate:
return EnvDTE.vsCMElement.vsCMElementDelegate;
case TypeKind.Module:
return EnvDTE.vsCMElement.vsCMElementModule;
default:
Debug.Fail("Unexpected TypeKind: " + typeSymbol.TypeKind);
throw Exceptions.ThrowEInvalidArg();
}
}
protected bool TryGetElementFromSource(
CodeModelState state, Project project, ITypeSymbol typeSymbol, out EnvDTE.CodeElement element)
{
element = null;
if (!typeSymbol.IsDefinition)
{
return false;
}
// Here's the strategy for determine what source file we'd try to return an element from.
// 1. Prefer source files that we don't heuristically flag as generated code.
// 2. If all of the source files are generated code, pick the first one.
Compilation compilation = null;
Tuple<DocumentId, Location> generatedCode = null;
DocumentId chosenDocumentId = null;
Location chosenLocation = null;
foreach (var location in typeSymbol.Locations)
{
if (location.IsInSource)
{
compilation = compilation ?? project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult_CodeModel(CancellationToken.None);
if (compilation.ContainsSyntaxTree(location.SourceTree))
{
var document = project.GetDocument(location.SourceTree);
if (!document.IsGeneratedCode(CancellationToken.None))
{
chosenLocation = location;
chosenDocumentId = document.Id;
break;
}
else
{
generatedCode = generatedCode ?? Tuple.Create(document.Id, location);
}
}
}
}
if (chosenDocumentId == null && generatedCode != null)
{
chosenDocumentId = generatedCode.Item1;
chosenLocation = generatedCode.Item2;
}
if (chosenDocumentId != null)
{
var fileCodeModel = state.Workspace.GetFileCodeModel(chosenDocumentId);
if (fileCodeModel != null)
{
var underlyingFileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(fileCodeModel);
element = underlyingFileCodeModel.CodeElementFromPosition(chosenLocation.SourceSpan.Start, GetElementKind(typeSymbol));
return element != null;
}
}
return false;
}
public abstract bool IsExpressionBodiedProperty(SyntaxNode node);
public abstract bool IsAccessorNode(SyntaxNode node);
public abstract MethodKind GetAccessorKind(SyntaxNode node);
public abstract bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode);
public abstract bool TryGetAutoPropertyExpressionBody(SyntaxNode parentNode, out SyntaxNode accessorNode);
public abstract bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode);
public abstract bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode);
public abstract bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode);
public abstract bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode);
public abstract bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode);
public abstract bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode);
public abstract bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode);
public abstract void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal);
public abstract void GetInheritsNamespaceAndOrdinal(SyntaxNode inheritsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal);
public abstract void GetImplementsNamespaceAndOrdinal(SyntaxNode implementsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal);
public abstract void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal);
public abstract SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode);
public abstract string GetAttributeTarget(SyntaxNode attributeNode);
public abstract string GetAttributeValue(SyntaxNode attributeNode);
public abstract SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value);
public abstract SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value);
public abstract SyntaxNode GetNodeWithAttributes(SyntaxNode node);
public abstract SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node);
public abstract SyntaxNode CreateAttributeNode(string name, string value, string target = null);
public abstract void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index);
public abstract SyntaxNode CreateAttributeArgumentNode(string name, string value);
public abstract string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode);
public abstract string GetImportAlias(SyntaxNode node);
public abstract string GetImportNamespaceOrType(SyntaxNode node);
public abstract void GetImportParentAndName(SyntaxNode importNode, out SyntaxNode namespaceNode, out string name);
public abstract SyntaxNode CreateImportNode(string name, string alias = null);
public abstract string GetParameterName(SyntaxNode node);
public virtual string GetParameterFullName(SyntaxNode node)
{
return GetParameterName(node);
}
public abstract EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node);
public abstract SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind);
public abstract EnvDTE80.vsCMParameterKind UpdateParameterKind(EnvDTE80.vsCMParameterKind parameterKind, PARAMETER_PASSING_MODE passingMode);
public abstract SyntaxNode CreateParameterNode(string name, string type);
public abstract EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name);
public abstract bool SupportsEventThrower { get; }
public abstract bool GetCanOverride(SyntaxNode memberNode);
public abstract SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value);
public abstract EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
public abstract SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind);
public abstract string GetComment(SyntaxNode node);
public abstract SyntaxNode SetComment(SyntaxNode node, string value);
public abstract EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode);
public abstract SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind);
public abstract EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol);
public abstract SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind);
public abstract string GetDocComment(SyntaxNode node);
public abstract SyntaxNode SetDocComment(SyntaxNode node, string value);
public abstract EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol);
public abstract EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
public abstract SyntaxNode SetInheritanceKind(SyntaxNode typeNode, EnvDTE80.vsCMInheritanceKind kind);
public abstract bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol);
public abstract SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value);
public abstract bool GetIsConstant(SyntaxNode variableNode);
public abstract SyntaxNode SetIsConstant(SyntaxNode variableNode, bool value);
public abstract bool GetIsDefault(SyntaxNode propertyNode);
public abstract SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value);
public abstract bool GetIsGeneric(SyntaxNode memberNode);
public abstract bool GetIsPropertyStyleEvent(SyntaxNode eventNode);
public abstract bool GetIsShared(SyntaxNode memberNode, ISymbol symbol);
public abstract SyntaxNode SetIsShared(SyntaxNode memberNode, bool value);
public abstract bool GetMustImplement(SyntaxNode memberNode);
public abstract SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value);
public abstract EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode);
public abstract SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind);
public abstract EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode);
public abstract SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract Document Delete(Document document, SyntaxNode node);
public abstract string GetMethodXml(SyntaxNode node, SemanticModel semanticModel);
public abstract string GetInitExpression(SyntaxNode node);
public abstract SyntaxNode AddInitExpression(SyntaxNode node, string value);
public abstract CodeGenerationDestination GetDestination(SyntaxNode containerNode);
protected abstract Accessibility GetDefaultAccessibility(SymbolKind targetSymbolKind, CodeGenerationDestination destination);
public Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified)
{
// Note: Some EnvDTE.vsCMAccess members aren't "bitwise-mutually-exclusive"
// Specifically, vsCMAccessProjectOrProtected (12) is a combination of vsCMAccessProject (4) and vsCMAccessProtected (8)
// We therefore check for this first.
if ((access & EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) == EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
{
return Accessibility.ProtectedOrInternal;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessPrivate) != 0)
{
return Accessibility.Private;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessProject) != 0)
{
return Accessibility.Internal;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessProtected) != 0)
{
return Accessibility.Protected;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessPublic) != 0)
{
return Accessibility.Public;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessDefault) != 0)
{
return GetDefaultAccessibility(targetSymbolKind, destination);
}
else
{
throw new ArgumentException(ServicesVSResources.Invalid_access, nameof(access));
}
}
public bool GetWithEvents(EnvDTE.vsCMAccess access)
{
return (access & EnvDTE.vsCMAccess.vsCMAccessWithEvents) != 0;
}
protected SpecialType GetSpecialType(EnvDTE.vsCMTypeRef type)
{
// TODO(DustinCa): Verify this list against VB
switch (type)
{
case EnvDTE.vsCMTypeRef.vsCMTypeRefBool:
return SpecialType.System_Boolean;
case EnvDTE.vsCMTypeRef.vsCMTypeRefByte:
return SpecialType.System_Byte;
case EnvDTE.vsCMTypeRef.vsCMTypeRefChar:
return SpecialType.System_Char;
case EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal:
return SpecialType.System_Decimal;
case EnvDTE.vsCMTypeRef.vsCMTypeRefDouble:
return SpecialType.System_Double;
case EnvDTE.vsCMTypeRef.vsCMTypeRefFloat:
return SpecialType.System_Single;
case EnvDTE.vsCMTypeRef.vsCMTypeRefInt:
return SpecialType.System_Int32;
case EnvDTE.vsCMTypeRef.vsCMTypeRefLong:
return SpecialType.System_Int64;
case EnvDTE.vsCMTypeRef.vsCMTypeRefObject:
return SpecialType.System_Object;
case EnvDTE.vsCMTypeRef.vsCMTypeRefShort:
return SpecialType.System_Int16;
case EnvDTE.vsCMTypeRef.vsCMTypeRefString:
return SpecialType.System_String;
case EnvDTE.vsCMTypeRef.vsCMTypeRefVoid:
return SpecialType.System_Void;
default:
// TODO: Support vsCMTypeRef2? It doesn't appear that Dev10 C# does...
throw new ArgumentException();
}
}
private ITypeSymbol GetSpecialType(EnvDTE.vsCMTypeRef type, Compilation compilation)
{
return compilation.GetSpecialType(GetSpecialType(type));
}
protected abstract ITypeSymbol GetTypeSymbolFromPartialName(string partialName, SemanticModel semanticModel, int position);
public abstract ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation);
public ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position)
{
if (type is EnvDTE.CodeTypeRef)
{
return GetTypeSymbolFromPartialName(((EnvDTE.CodeTypeRef)type).AsString, semanticModel, position);
}
else if (type is EnvDTE.CodeType)
{
return GetTypeSymbolFromFullName(((EnvDTE.CodeType)type).FullName, semanticModel.Compilation);
}
ITypeSymbol typeSymbol;
if (type is EnvDTE.vsCMTypeRef || type is int)
{
typeSymbol = GetSpecialType((EnvDTE.vsCMTypeRef)type, semanticModel.Compilation);
}
else if (type is string s)
{
typeSymbol = GetTypeSymbolFromPartialName(s, semanticModel, position);
}
else
{
throw new InvalidOperationException();
}
if (typeSymbol == null)
{
throw new ArgumentException();
}
return typeSymbol;
}
public abstract SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type);
protected abstract int GetAttributeIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
/// <summary>
/// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string
/// representing the name of a member. This function translates the argument and returns the
/// 1-based position of the specified attribute.
/// </summary>
public int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetAttributeIndexInContainer,
GetAttributeNodes);
}
protected abstract int GetAttributeArgumentIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetAttributeArgumentIndexInContainer,
GetAttributeArgumentNodes);
}
protected abstract int GetImportIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetImportIndexInContainer,
GetImportNodes);
}
protected abstract int GetParameterIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetParameterIndexInContainer,
GetParameterNodes);
}
/// <summary>
/// Finds the index of the first child within the container for which <paramref name="predicate"/> returns true.
/// Note that the result is a 1-based as that is what code model expects. Returns -1 if no match is found.
/// </summary>
protected abstract int GetMemberIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
/// <summary>
/// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string
/// representing the name of a member. This function translates the argument and returns the
/// 1-based position of the specified member.
/// </summary>
public int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetMemberIndexInContainer,
n => GetMemberNodes(n, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false));
}
private int PositionVariantToInsertionIndex(
object position,
SyntaxNode containerNode,
FileCodeModel fileCodeModel,
Func<SyntaxNode, Func<SyntaxNode, bool>, int> getIndexInContainer,
Func<SyntaxNode, IEnumerable<SyntaxNode>> getChildNodes)
{
int result;
if (position is int i)
{
result = i;
}
else if (position is EnvDTE.CodeElement)
{
var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(position);
if (codeElement == null || codeElement.FileCodeModel != fileCodeModel)
{
throw Exceptions.ThrowEInvalidArg();
}
var positionNode = codeElement.LookupNode();
if (positionNode == null)
{
throw Exceptions.ThrowEFail();
}
result = getIndexInContainer(containerNode, child => child == positionNode);
}
else if (position is string name)
{
result = getIndexInContainer(containerNode, child => GetName(child) == name);
}
else if (position == null || position == Type.Missing)
{
result = 0;
}
else
{
// Nothing we can handle...
throw Exceptions.ThrowEInvalidArg();
}
// -1 means to insert at the end, so we'll return the last child.
return result == -1
? getChildNodes(containerNode).ToArray().Length
: result;
}
protected abstract SyntaxNode GetFieldFromVariableNode(SyntaxNode variableNode);
protected abstract SyntaxNode GetVariableFromFieldNode(SyntaxNode fieldNode);
protected abstract SyntaxNode GetAttributeFromAttributeDeclarationNode(SyntaxNode attributeDeclarationNode);
protected void GetNodesAroundInsertionIndex<TSyntaxNode>(
TSyntaxNode containerNode,
int childIndexToInsertAfter,
out TSyntaxNode insertBeforeNode,
out TSyntaxNode insertAfterNode)
where TSyntaxNode : SyntaxNode
{
var childNodes = GetLogicalMemberNodes(containerNode).ToArray();
// Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members.
// If it isn't 0, it means to insert the member node *after* the node at the 1-based index.
Debug.Assert(childIndexToInsertAfter >= 0 && childIndexToInsertAfter <= childNodes.Length);
// Initialize the nodes that we'll insert the new member before and after.
insertBeforeNode = null;
insertAfterNode = null;
if (childIndexToInsertAfter == 0)
{
if (childNodes.Length > 0)
{
insertBeforeNode = (TSyntaxNode)childNodes[0];
}
}
else
{
insertAfterNode = (TSyntaxNode)childNodes[childIndexToInsertAfter - 1];
if (childIndexToInsertAfter < childNodes.Length)
{
insertBeforeNode = (TSyntaxNode)childNodes[childIndexToInsertAfter];
}
}
if (insertBeforeNode != null)
{
insertBeforeNode = (TSyntaxNode)GetFieldFromVariableNode(insertBeforeNode);
}
if (insertAfterNode != null)
{
insertAfterNode = (TSyntaxNode)GetFieldFromVariableNode(insertAfterNode);
}
}
private int GetMemberInsertionIndex(SyntaxNode container, int insertionIndex)
{
var childNodes = GetLogicalMemberNodes(container).ToArray();
// Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members.
// If it isn't 0, it means to insert the member node *after* the node at the 1-based index.
Debug.Assert(insertionIndex >= 0 && insertionIndex <= childNodes.Length);
if (insertionIndex == 0)
{
return 0;
}
else
{
var nodeAtIndex = GetFieldFromVariableNode(childNodes[insertionIndex - 1]);
return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false).ToList().IndexOf(nodeAtIndex) + 1;
}
}
private int GetAttributeArgumentInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
private int GetAttributeInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
private int GetImportInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
private int GetParameterInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
protected abstract bool IsCodeModelNode(SyntaxNode node);
protected abstract TextSpan GetSpanToFormat(SyntaxNode root, TextSpan span);
protected abstract SyntaxNode InsertMemberNodeIntoContainer(int index, SyntaxNode member, SyntaxNode container);
protected abstract SyntaxNode InsertAttributeArgumentIntoContainer(int index, SyntaxNode attributeArgument, SyntaxNode container);
protected abstract SyntaxNode InsertAttributeListIntoContainer(int index, SyntaxNode attribute, SyntaxNode container);
protected abstract SyntaxNode InsertImportIntoContainer(int index, SyntaxNode import, SyntaxNode container);
protected abstract SyntaxNode InsertParameterIntoContainer(int index, SyntaxNode parameter, SyntaxNode container);
private Document FormatAnnotatedNode(Document document, SyntaxAnnotation annotation, IEnumerable<IFormattingRule> additionalRules, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var annotatedNode = root.GetAnnotatedNodesAndTokens(annotation).Single().AsNode();
var formattingSpan = GetSpanToFormat(root, annotatedNode.FullSpan);
var formattingRules = Formatter.GetDefaultFormattingRules(document);
if (additionalRules != null)
{
formattingRules = additionalRules.Concat(formattingRules);
}
return Formatter.FormatAsync(
document,
new TextSpan[] { formattingSpan },
options: null,
rules: formattingRules,
cancellationToken: cancellationToken).WaitAndGetResult_CodeModel(cancellationToken);
}
private SyntaxNode InsertNode(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode node,
Func<int, SyntaxNode, SyntaxNode, SyntaxNode> insertNodeIntoContainer,
CancellationToken cancellationToken,
out Document newDocument)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
// Annotate the member we're inserting so we can get back to it.
var annotation = new SyntaxAnnotation();
var gen = SyntaxGenerator.GetGenerator(document);
node = node.WithAdditionalAnnotations(annotation);
if (gen.GetDeclarationKind(node) != DeclarationKind.NamespaceImport)
{
// REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before?
node = node.WithAdditionalAnnotations(Simplifier.Annotation);
}
var newContainerNode = insertNodeIntoContainer(insertionIndex, node, containerNode);
var newRoot = root.ReplaceNode(containerNode, newContainerNode);
document = document.WithSyntaxRoot(newRoot);
if (!batchMode)
{
document = Simplifier.ReduceAsync(document, annotation, optionSet: null, cancellationToken: cancellationToken).WaitAndGetResult_CodeModel(cancellationToken);
}
document = FormatAnnotatedNode(document, annotation, new[] { _lineAdjustmentFormattingRule, _endRegionFormattingRule }, cancellationToken);
// out param
newDocument = document;
// new node
return document
.GetSyntaxRootSynchronously(cancellationToken)
.GetAnnotatedNodesAndTokens(annotation)
.Single()
.AsNode();
}
/// <summary>
/// Override to determine whether <param name="newNode"/> adds a method body to <param name="node"/>.
/// This is used to determine whether a blank line should be added inside the body when formatting.
/// </summary>
protected abstract bool AddBlankLineToMethodBody(SyntaxNode node, SyntaxNode newNode);
public Document UpdateNode(
Document document,
SyntaxNode node,
SyntaxNode newNode,
CancellationToken cancellationToken)
{
// Annotate the member we're inserting so we can get back to it.
var annotation = new SyntaxAnnotation();
// REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before?
var annotatedNode = newNode.WithAdditionalAnnotations(annotation, Simplifier.Annotation);
var oldRoot = document.GetSyntaxRootSynchronously(cancellationToken);
var newRoot = oldRoot.ReplaceNode(node, annotatedNode);
document = document.WithSyntaxRoot(newRoot);
var additionalRules = AddBlankLineToMethodBody(node, newNode)
? SpecializedCollections.SingletonEnumerable(_lineAdjustmentFormattingRule)
: null;
document = FormatAnnotatedNode(document, annotation, additionalRules, cancellationToken);
return document;
}
public SyntaxNode InsertAttribute(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetAttributeInsertionIndex(containerNode, insertionIndex),
containerNode,
attributeNode,
InsertAttributeListIntoContainer,
cancellationToken,
out newDocument);
return GetAttributeFromAttributeDeclarationNode(finalNode);
}
public SyntaxNode InsertAttributeArgument(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeArgumentNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetAttributeArgumentInsertionIndex(containerNode, insertionIndex),
containerNode,
attributeArgumentNode,
InsertAttributeArgumentIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertImport(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode importNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetImportInsertionIndex(containerNode, insertionIndex),
containerNode,
importNode,
InsertImportIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertParameter(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode parameterNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetParameterInsertionIndex(containerNode, insertionIndex),
containerNode,
parameterNode,
InsertParameterIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertMember(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode memberNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetMemberInsertionIndex(containerNode, insertionIndex),
containerNode,
memberNode,
InsertMemberNodeIntoContainer,
cancellationToken,
out newDocument);
return GetVariableFromFieldNode(finalNode);
}
public Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree)
{
return _eventCollector.Collect(oldTree, newTree);
}
public abstract bool IsNamespace(SyntaxNode node);
public abstract bool IsType(SyntaxNode node);
public virtual IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel)
{
// descendants may override (particularly VB).
return SpecializedCollections.EmptyList<string>();
}
public virtual bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel)
{
// descendants may override (particularly VB).
return false;
}
public virtual Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken)
{
// descendants may override (particularly VB).
return document;
}
public virtual Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken)
{
// descendants may override (particularly VB).
return document;
}
public abstract string[] GetFunctionExtenderNames();
public abstract object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol);
public abstract string[] GetPropertyExtenderNames();
public abstract object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol);
public abstract string[] GetExternalTypeExtenderNames();
public abstract object GetExternalTypeExtender(string name, string externalLocation);
public abstract string[] GetTypeExtenderNames();
public abstract object GetTypeExtender(string name, AbstractCodeType codeType);
public abstract bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
public abstract SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
public abstract bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
public abstract SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
public abstract string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags);
public virtual void AttachFormatTrackingToBuffer(ITextBuffer buffer)
{
// can be override by languages if needed
}
public virtual void DetachFormatTrackingToBuffer(ITextBuffer buffer)
{
// can be override by languages if needed
}
public virtual void EnsureBufferFormatted(ITextBuffer buffer)
{
// can be override by languages if needed
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This class implements a set of methods for retrieving
// character type information. Character type information is
// independent of culture and region.
//
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Security;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
public static partial class CharUnicodeInfo
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//
// Native methods to access the Unicode category data tables in charinfo.nlp.
//
internal const char HIGH_SURROGATE_START = '\ud800';
internal const char HIGH_SURROGATE_END = '\udbff';
internal const char LOW_SURROGATE_START = '\udc00';
internal const char LOW_SURROGATE_END = '\udfff';
internal const int UNICODE_CATEGORY_OFFSET = 0;
internal const int BIDI_CATEGORY_OFFSET = 1;
// The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff.
internal const int UNICODE_PLANE01_START = 0x10000;
////////////////////////////////////////////////////////////////////////
//
// Actions:
// Convert the BMP character or surrogate pointed by index to a UTF32 value.
// This is similar to Char.ConvertToUTF32, but the difference is that
// it does not throw exceptions when invalid surrogate characters are passed in.
//
// WARNING: since it doesn't throw an exception it CAN return a value
// in the surrogate range D800-DFFF, which are not legal unicode values.
//
////////////////////////////////////////////////////////////////////////
internal static int InternalConvertToUtf32(String s, int index)
{
Contract.Assert(s != null, "s != null");
Contract.Assert(index >= 0 && index < s.Length, "index < s.Length");
if (index < s.Length - 1)
{
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
if (temp1 >= 0 && temp1 <= 0x3ff)
{
int temp2 = (int)s[index + 1] - LOW_SURROGATE_START;
if (temp2 >= 0 && temp2 <= 0x3ff)
{
// Convert the surrogate to UTF32 and get the result.
return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
}
}
}
return ((int)s[index]);
}
////////////////////////////////////////////////////////////////////////
//
// Convert a character or a surrogate pair starting at index of string s
// to UTF32 value.
//
// Parameters:
// s The string
// index The starting index. It can point to a BMP character or
// a surrogate pair.
// len The length of the string.
// charLength [out] If the index points to a BMP char, charLength
// will be 1. If the index points to a surrogate pair,
// charLength will be 2.
//
// WARNING: since it doesn't throw an exception it CAN return a value
// in the surrogate range D800-DFFF, which are not legal unicode values.
//
// Returns:
// The UTF32 value
//
////////////////////////////////////////////////////////////////////////
internal static int InternalConvertToUtf32(String s, int index, out int charLength)
{
Contract.Assert(s != null, "s != null");
Contract.Assert(s.Length > 0, "s.Length > 0");
Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
charLength = 1;
if (index < s.Length - 1)
{
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
if (temp1 >= 0 && temp1 <= 0x3ff)
{
int temp2 = (int)s[index + 1] - LOW_SURROGATE_START;
if (temp2 >= 0 && temp2 <= 0x3ff)
{
// Convert the surrogate to UTF32 and get the result.
charLength++;
return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
}
}
}
return ((int)s[index]);
}
////////////////////////////////////////////////////////////////////////
//
// IsWhiteSpace
//
// Determines if the given character is a white space character.
//
////////////////////////////////////////////////////////////////////////
internal static bool IsWhiteSpace(String s, int index)
{
Contract.Assert(s != null, "s!=null");
Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
UnicodeCategory uc = GetUnicodeCategory(s, index);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
// And U+2029 is th eonly character which is under the category "ParagraphSeparator".
switch (uc)
{
case (UnicodeCategory.SpaceSeparator):
case (UnicodeCategory.LineSeparator):
case (UnicodeCategory.ParagraphSeparator):
return (true);
}
return (false);
}
internal static bool IsWhiteSpace(char c)
{
UnicodeCategory uc = GetUnicodeCategory(c);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
// And U+2029 is th eonly character which is under the category "ParagraphSeparator".
switch (uc)
{
case (UnicodeCategory.SpaceSeparator):
case (UnicodeCategory.LineSeparator):
case (UnicodeCategory.ParagraphSeparator):
return (true);
}
return (false);
}
//
// This is called by the public char and string, index versions
//
// Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
//
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static double InternalGetNumericValue(int ch)
{
Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// The offset is referred to an float item in m_pNumericFloatData.
// Note that & has the lower precedence than addition, so don't forget the parathesis.
index = s_pNumericLevel1Index[index + ((ch >> 4) & 0x000f)];
fixed (ushort* pUshortPtr = &(s_pNumericLevel1Index[index]))
{
byte* pBytePtr = (byte*)pUshortPtr;
fixed (byte* pByteNum = s_pNumericValues)
{
double* pDouble = (double*)pByteNum;
return pDouble[pBytePtr[(ch & 0x000f)]];
}
}
}
////////////////////////////////////////////////////////////////////////
//
//Returns the numeric value associated with the character c. If the character is a fraction,
// the return value will not be an integer. If the character does not have a numeric value, the return value is -1.
//
//Returns:
// the numeric value for the specified Unicode character. If the character does not have a numeric value, the return value is -1.
//Arguments:
// ch a Unicode character
//Exceptions:
// ArgumentNullException
// ArgumentOutOfRangeException
//
////////////////////////////////////////////////////////////////////////
public static double GetNumericValue(char ch)
{
return (InternalGetNumericValue(ch));
}
public static double GetNumericValue(String s, int index)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
if (index < 0 || index >= s.Length)
{
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
return (InternalGetNumericValue(InternalConvertToUtf32(s, index)));
}
public static UnicodeCategory GetUnicodeCategory(char ch)
{
return (InternalGetUnicodeCategory(ch));
}
public static UnicodeCategory GetUnicodeCategory(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
return InternalGetUnicodeCategory(s, index);
}
internal unsafe static UnicodeCategory InternalGetUnicodeCategory(int ch)
{
return ((UnicodeCategory)InternalGetCategoryValue(ch, UNICODE_CATEGORY_OFFSET));
}
////////////////////////////////////////////////////////////////////////
//
//Action: Returns the Unicode Category property for the character c.
//Returns:
// an value in UnicodeCategory enum
//Arguments:
// ch a Unicode character
//Exceptions:
// None
//
//Note that this API will return values for D800-DF00 surrogate halves.
//
////////////////////////////////////////////////////////////////////////
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static byte InternalGetCategoryValue(int ch, int offset)
{
Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pCategoryLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// Note that & has the lower precedence than addition, so don't forget the parathesis.
index = s_pCategoryLevel1Index[index + ((ch >> 4) & 0x000f)];
fixed (ushort* pUshortPtr = &(s_pCategoryLevel1Index[index]))
{
byte* pBytePtr = (byte*)pUshortPtr;
// Get the result from the 0 -3 bit of ch.
byte valueIndex = pBytePtr[(ch & 0x000f)];
byte uc = s_pCategoriesValue[valueIndex * 2 + offset];
//
// Make sure that OtherNotAssigned is the last category in UnicodeCategory.
// If that changes, change the following assertion as well.
//
//Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
return (uc);
}
}
////////////////////////////////////////////////////////////////////////
//
//Action: Returns the Unicode Category property for the character c.
//Returns:
// an value in UnicodeCategory enum
//Arguments:
// value a Unicode String
// index Index for the specified string.
//Exceptions:
// None
//
////////////////////////////////////////////////////////////////////////
internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index)
{
Contract.Assert(value != null, "value can not be null");
Contract.Assert(index < value.Length, "index < value.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index)));
}
////////////////////////////////////////////////////////////////////////
//
// Get the Unicode category of the character starting at index. If the character is in BMP, charLength will return 1.
// If the character is a valid surrogate pair, charLength will return 2.
//
////////////////////////////////////////////////////////////////////////
internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength)
{
Contract.Assert(str != null, "str can not be null");
Contract.Assert(str.Length > 0, "str.Length > 0"); ;
Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength)));
}
internal static bool IsCombiningCategory(UnicodeCategory uc)
{
Contract.Assert(uc >= 0, "uc >= 0");
return (
uc == UnicodeCategory.NonSpacingMark ||
uc == UnicodeCategory.SpacingCombiningMark ||
uc == UnicodeCategory.EnclosingMark
);
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Provisioning.Framework.Cloud.AsyncWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
internal interface IContentFocusManager
{
void Activate(IDockContent content);
void GiveUpFocus(IDockContent content);
void AddToList(IDockContent content);
void RemoveFromList(IDockContent content);
}
partial class DockPanel
{
private interface IFocusManager
{
void SuspendFocusTracking();
void ResumeFocusTracking();
bool IsFocusTrackingSuspended { get; }
IDockContent ActiveContent { get; }
DockPane ActivePane { get; }
IDockContent ActiveDocument { get; }
DockPane ActiveDocumentPane { get; }
}
private class FocusManagerImpl : Component, IContentFocusManager, IFocusManager
{
private class HookEventArgs : EventArgs
{
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
public int HookCode;
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
public IntPtr wParam;
public IntPtr lParam;
}
private class LocalWindowsHook : IDisposable
{
// Internal properties
private IntPtr m_hHook = IntPtr.Zero;
private NativeMethods.HookProc m_filterFunc = null;
private Win32.HookType m_hookType;
// Event delegate
public delegate void HookEventHandler(object sender, HookEventArgs e);
// Event: HookInvoked
public event HookEventHandler HookInvoked;
protected void OnHookInvoked(HookEventArgs e)
{
if (HookInvoked != null)
HookInvoked(this, e);
}
public LocalWindowsHook(Win32.HookType hook)
{
m_hookType = hook;
m_filterFunc = new NativeMethods.HookProc(this.CoreHookProc);
}
// Default filter function
public IntPtr CoreHookProc(int code, IntPtr wParam, IntPtr lParam)
{
if (code < 0)
return NativeMethods.CallNextHookEx(m_hHook, code, wParam, lParam);
// Let clients determine what to do
HookEventArgs e = new HookEventArgs();
e.HookCode = code;
e.wParam = wParam;
e.lParam = lParam;
OnHookInvoked(e);
// Yield to the next hook in the chain
return NativeMethods.CallNextHookEx(m_hHook, code, wParam, lParam);
}
// Install the hook
public void Install()
{
if (m_hHook != IntPtr.Zero)
Uninstall();
int threadId = NativeMethods.GetCurrentThreadId();
m_hHook = NativeMethods.SetWindowsHookEx(m_hookType, m_filterFunc, IntPtr.Zero, threadId);
}
// Uninstall the hook
public void Uninstall()
{
if (m_hHook != IntPtr.Zero)
{
NativeMethods.UnhookWindowsHookEx(m_hHook);
m_hHook = IntPtr.Zero;
}
}
~LocalWindowsHook()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
Uninstall();
}
}
// Use a static instance of the windows hook to prevent stack overflows in the windows kernel.
[ThreadStatic]
private static LocalWindowsHook sm_localWindowsHook;
private LocalWindowsHook.HookEventHandler m_hookEventHandler;
public FocusManagerImpl(DockPanel dockPanel)
{
m_dockPanel = dockPanel;
if (Win32Helper.IsRunningOnMono)
return;
m_hookEventHandler = new LocalWindowsHook.HookEventHandler(HookEventHandler);
// Ensure the windows hook has been created for this thread
if (sm_localWindowsHook == null)
{
sm_localWindowsHook = new LocalWindowsHook(Win32.HookType.WH_CALLWNDPROCRET);
sm_localWindowsHook.Install();
}
sm_localWindowsHook.HookInvoked += m_hookEventHandler;
}
private DockPanel m_dockPanel;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
private bool m_disposed = false;
protected override void Dispose(bool disposing)
{
if (!m_disposed && disposing)
{
if (!Win32Helper.IsRunningOnMono)
{
sm_localWindowsHook.HookInvoked -= m_hookEventHandler;
}
m_disposed = true;
}
base.Dispose(disposing);
}
private IDockContent m_contentActivating = null;
private IDockContent ContentActivating
{
get { return m_contentActivating; }
set { m_contentActivating = value; }
}
public void Activate(IDockContent content)
{
if (IsFocusTrackingSuspended)
{
ContentActivating = content;
return;
}
if (content == null)
return;
DockContentHandler handler = content.DockHandler;
if (handler.Form.IsDisposed)
return; // Should not reach here, but better than throwing an exception
if (ContentContains(content, handler.ActiveWindowHandle))
{
if (!Win32Helper.IsRunningOnMono)
{
NativeMethods.SetFocus(handler.ActiveWindowHandle);
}
}
if (handler.Form.ContainsFocus)
return;
if (handler.Form.SelectNextControl(handler.Form.ActiveControl, true, true, true, true))
return;
if (Win32Helper.IsRunningOnMono)
return;
// Since DockContent Form is not selectalbe, use Win32 SetFocus instead
NativeMethods.SetFocus(handler.Form.Handle);
}
private List<IDockContent> m_listContent = new List<IDockContent>();
private List<IDockContent> ListContent
{
get { return m_listContent; }
}
public void AddToList(IDockContent content)
{
if (ListContent.Contains(content) || IsInActiveList(content))
return;
ListContent.Add(content);
}
public void RemoveFromList(IDockContent content)
{
if (IsInActiveList(content))
RemoveFromActiveList(content);
if (ListContent.Contains(content))
ListContent.Remove(content);
}
private IDockContent m_lastActiveContent = null;
private IDockContent LastActiveContent
{
get { return m_lastActiveContent; }
set { m_lastActiveContent = value; }
}
private bool IsInActiveList(IDockContent content)
{
return !(content.DockHandler.NextActive == null && LastActiveContent != content);
}
private void AddLastToActiveList(IDockContent content)
{
IDockContent last = LastActiveContent;
if (last == content)
return;
DockContentHandler handler = content.DockHandler;
if (IsInActiveList(content))
RemoveFromActiveList(content);
handler.PreviousActive = last;
handler.NextActive = null;
LastActiveContent = content;
if (last != null)
last.DockHandler.NextActive = LastActiveContent;
}
private void RemoveFromActiveList(IDockContent content)
{
if (LastActiveContent == content)
LastActiveContent = content.DockHandler.PreviousActive;
IDockContent prev = content.DockHandler.PreviousActive;
IDockContent next = content.DockHandler.NextActive;
if (prev != null)
prev.DockHandler.NextActive = next;
if (next != null)
next.DockHandler.PreviousActive = prev;
content.DockHandler.PreviousActive = null;
content.DockHandler.NextActive = null;
}
public void GiveUpFocus(IDockContent content)
{
DockContentHandler handler = content.DockHandler;
if (!handler.Form.ContainsFocus)
return;
if (IsFocusTrackingSuspended)
DockPanel.DummyControl.Focus();
if (LastActiveContent == content)
{
IDockContent prev = handler.PreviousActive;
if (prev != null)
Activate(prev);
else if (ListContent.Count > 0)
Activate(ListContent[ListContent.Count - 1]);
}
else if (LastActiveContent != null)
Activate(LastActiveContent);
else if (ListContent.Count > 0)
Activate(ListContent[ListContent.Count - 1]);
}
private static bool ContentContains(IDockContent content, IntPtr hWnd)
{
Control control = Control.FromChildHandle(hWnd);
for (Control parent = control; parent != null; parent = parent.Parent)
if (parent == content.DockHandler.Form)
return true;
return false;
}
private int m_countSuspendFocusTracking = 0;
public void SuspendFocusTracking()
{
m_countSuspendFocusTracking++;
if (!Win32Helper.IsRunningOnMono)
sm_localWindowsHook.HookInvoked -= m_hookEventHandler;
}
public void ResumeFocusTracking()
{
if (m_countSuspendFocusTracking > 0)
m_countSuspendFocusTracking--;
if (m_countSuspendFocusTracking == 0)
{
if (ContentActivating != null)
{
Activate(ContentActivating);
ContentActivating = null;
}
if (!Win32Helper.IsRunningOnMono)
sm_localWindowsHook.HookInvoked += m_hookEventHandler;
if (!InRefreshActiveWindow)
RefreshActiveWindow();
}
}
public bool IsFocusTrackingSuspended
{
get { return m_countSuspendFocusTracking != 0; }
}
// Windows hook event handler
private void HookEventHandler(object sender, HookEventArgs e)
{
Win32.Msgs msg = (Win32.Msgs)Marshal.ReadInt32(e.lParam, IntPtr.Size * 3);
if (msg == Win32.Msgs.WM_KILLFOCUS)
{
IntPtr wParam = Marshal.ReadIntPtr(e.lParam, IntPtr.Size * 2);
DockPane pane = GetPaneFromHandle(wParam);
if (pane == null)
RefreshActiveWindow();
}
else if (msg == Win32.Msgs.WM_SETFOCUS)
RefreshActiveWindow();
}
private DockPane GetPaneFromHandle(IntPtr hWnd)
{
Control control = Control.FromChildHandle(hWnd);
IDockContent content = null;
DockPane pane = null;
for (; control != null; control = control.Parent)
{
content = control as IDockContent;
if (content != null)
content.DockHandler.ActiveWindowHandle = hWnd;
if (content != null && content.DockHandler.DockPanel == DockPanel)
return content.DockHandler.Pane;
pane = control as DockPane;
if (pane != null && pane.DockPanel == DockPanel)
break;
}
return pane;
}
private bool m_inRefreshActiveWindow = false;
private bool InRefreshActiveWindow
{
get { return m_inRefreshActiveWindow; }
}
private void RefreshActiveWindow()
{
SuspendFocusTracking();
m_inRefreshActiveWindow = true;
DockPane oldActivePane = ActivePane;
IDockContent oldActiveContent = ActiveContent;
IDockContent oldActiveDocument = ActiveDocument;
SetActivePane();
SetActiveContent();
SetActiveDocumentPane();
SetActiveDocument();
DockPanel.AutoHideWindow.RefreshActivePane();
ResumeFocusTracking();
m_inRefreshActiveWindow = false;
if (oldActiveContent != ActiveContent)
DockPanel.OnActiveContentChanged(EventArgs.Empty);
if (oldActiveDocument != ActiveDocument)
DockPanel.OnActiveDocumentChanged(EventArgs.Empty);
if (oldActivePane != ActivePane)
DockPanel.OnActivePaneChanged(EventArgs.Empty);
}
private DockPane m_activePane = null;
public DockPane ActivePane
{
get { return m_activePane; }
}
private void SetActivePane()
{
DockPane value = Win32Helper.IsRunningOnMono ? null : GetPaneFromHandle(NativeMethods.GetFocus());
if (m_activePane == value)
return;
if (m_activePane != null)
m_activePane.SetIsActivated(false);
m_activePane = value;
if (m_activePane != null)
m_activePane.SetIsActivated(true);
}
private IDockContent m_activeContent = null;
public IDockContent ActiveContent
{
get { return m_activeContent; }
}
internal void SetActiveContent()
{
IDockContent value = ActivePane == null ? null : ActivePane.ActiveContent;
if (m_activeContent == value)
return;
if (m_activeContent != null)
m_activeContent.DockHandler.IsActivated = false;
m_activeContent = value;
if (m_activeContent != null)
{
m_activeContent.DockHandler.IsActivated = true;
if (!DockHelper.IsDockStateAutoHide((m_activeContent.DockHandler.DockState)))
AddLastToActiveList(m_activeContent);
}
}
private DockPane m_activeDocumentPane = null;
public DockPane ActiveDocumentPane
{
get { return m_activeDocumentPane; }
}
private void SetActiveDocumentPane()
{
DockPane value = null;
if (ActivePane != null && ActivePane.DockState == DockState.Document)
value = ActivePane;
if (value == null && DockPanel.DockWindows != null)
{
if (ActiveDocumentPane == null)
value = DockPanel.DockWindows[DockState.Document].DefaultPane;
else if (ActiveDocumentPane.DockPanel != DockPanel || ActiveDocumentPane.DockState != DockState.Document)
value = DockPanel.DockWindows[DockState.Document].DefaultPane;
else
value = ActiveDocumentPane;
}
if (m_activeDocumentPane == value)
return;
if (m_activeDocumentPane != null)
m_activeDocumentPane.SetIsActiveDocumentPane(false);
m_activeDocumentPane = value;
if (m_activeDocumentPane != null)
m_activeDocumentPane.SetIsActiveDocumentPane(true);
}
private IDockContent m_activeDocument = null;
public IDockContent ActiveDocument
{
get { return m_activeDocument; }
}
private void SetActiveDocument()
{
IDockContent value = ActiveDocumentPane == null ? null : ActiveDocumentPane.ActiveContent;
if (m_activeDocument == value)
return;
m_activeDocument = value;
}
}
private IFocusManager FocusManager
{
get { return m_focusManager; }
}
internal IContentFocusManager ContentFocusManager
{
get { return m_focusManager; }
}
internal void SaveFocus()
{
DummyControl.Focus();
}
[Browsable(false)]
public IDockContent ActiveContent
{
get { return FocusManager.ActiveContent; }
}
[Browsable(false)]
public DockPane ActivePane
{
get { return FocusManager.ActivePane; }
}
[Browsable(false)]
public IDockContent ActiveDocument
{
get { return FocusManager.ActiveDocument; }
}
[Browsable(false)]
public DockPane ActiveDocumentPane
{
get { return FocusManager.ActiveDocumentPane; }
}
private static readonly object ActiveDocumentChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActiveDocumentChanged_Description")]
public event EventHandler ActiveDocumentChanged
{
add { Events.AddHandler(ActiveDocumentChangedEvent, value); }
remove { Events.RemoveHandler(ActiveDocumentChangedEvent, value); }
}
protected virtual void OnActiveDocumentChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActiveDocumentChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object ActiveContentChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActiveContentChanged_Description")]
public event EventHandler ActiveContentChanged
{
add { Events.AddHandler(ActiveContentChangedEvent, value); }
remove { Events.RemoveHandler(ActiveContentChangedEvent, value); }
}
protected void OnActiveContentChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActiveContentChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object ActivePaneChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActivePaneChanged_Description")]
public event EventHandler ActivePaneChanged
{
add { Events.AddHandler(ActivePaneChangedEvent, value); }
remove { Events.RemoveHandler(ActivePaneChangedEvent, value); }
}
protected virtual void OnActivePaneChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActivePaneChangedEvent];
if (handler != null)
handler(this, e);
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* 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.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
/// <summary>
/// Represents a file attachment.
/// </summary>
public sealed class FileAttachment : Attachment
{
private string fileName;
private Stream contentStream;
private byte[] content;
private Stream loadToStream;
private bool isContactPhoto;
/// <summary>
/// Initializes a new instance of the <see cref="FileAttachment"/> class.
/// </summary>
/// <param name="owner">The owner.</param>
internal FileAttachment(Item owner)
: base(owner)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FileAttachment"/> class.
/// </summary>
/// <param name="service">The service.</param>
internal FileAttachment(ExchangeService service)
: base(service)
{
}
/// <summary>
/// Gets the name of the XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetXmlElementName()
{
return XmlElementNames.FileAttachment;
}
/// <summary>
/// Validates this instance.
/// </summary>
/// <param name="attachmentIndex">Index of this attachment.</param>
internal override void Validate(int attachmentIndex)
{
if (string.IsNullOrEmpty(this.fileName) && (this.content == null) && (this.contentStream == null))
{
throw new ServiceValidationException(string.Format(Strings.FileAttachmentContentIsNotSet, attachmentIndex));
}
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>True if element was read.</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
bool result = base.TryReadElementFromXml(reader);
if (!result)
{
if (reader.LocalName == XmlElementNames.IsContactPhoto)
{
this.isContactPhoto = reader.ReadElementValue<bool>();
}
else if (reader.LocalName == XmlElementNames.Content)
{
if (this.loadToStream != null)
{
reader.ReadBase64ElementValue(this.loadToStream);
}
else
{
// If there's a file attachment content handler, use it. Otherwise
// load the content into a byte array.
// TODO: Should we mark the attachment to indicate that content is stored elsewhere?
if (reader.Service.FileAttachmentContentHandler != null)
{
Stream outputStream = reader.Service.FileAttachmentContentHandler.GetOutputStream(this.Id);
if (outputStream != null)
{
reader.ReadBase64ElementValue(outputStream);
}
else
{
this.content = reader.ReadBase64ElementValue();
}
}
else
{
this.content = reader.ReadBase64ElementValue();
}
}
result = true;
}
}
return result;
}
/// <summary>
/// For FileAttachment, the only thing need to patch is the AttachmentId.
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
internal override bool TryReadElementFromXmlToPatch(EwsServiceXmlReader reader)
{
return base.TryReadElementFromXml(reader);
}
/// <summary>
/// Writes elements and content to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
base.WriteElementsToXml(writer);
if (writer.Service.RequestedServerVersion > ExchangeVersion.Exchange2007_SP1)
{
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.IsContactPhoto, this.isContactPhoto);
}
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Content);
if (!string.IsNullOrEmpty(this.FileName))
{
using (FileStream fileStream = new FileStream(this.FileName, FileMode.Open, FileAccess.Read))
{
writer.WriteBase64ElementValue(fileStream);
}
}
else if (this.ContentStream != null)
{
writer.WriteBase64ElementValue(this.ContentStream);
}
else if (this.Content != null)
{
writer.WriteBase64ElementValue(this.Content);
}
else
{
EwsUtilities.Assert(
false,
"FileAttachment.WriteElementsToXml",
"The attachment's content is not set.");
}
writer.WriteEndElement();
}
/// <summary>
/// Loads the content of the file attachment into the specified stream. Calling this method results in a call to EWS.
/// </summary>
/// <param name="stream">The stream to load the content of the attachment into.</param>
public void Load(Stream stream)
{
this.loadToStream = stream;
try
{
this.Load();
}
finally
{
this.loadToStream = null;
}
}
/// <summary>
/// Loads the content of the file attachment into the specified file. Calling this method results in a call to EWS.
/// </summary>
/// <param name="fileName">The name of the file to load the content of the attachment into. If the file already exists, it is overwritten.</param>
public void Load(string fileName)
{
this.loadToStream = new FileStream(fileName, FileMode.Create);
try
{
this.Load();
}
finally
{
this.loadToStream.Dispose();
this.loadToStream = null;
}
this.fileName = fileName;
this.content = null;
this.contentStream = null;
}
/// <summary>
/// Gets the name of the file the attachment is linked to.
/// </summary>
public string FileName
{
get
{
return this.fileName;
}
internal set
{
this.ThrowIfThisIsNotNew();
this.fileName = value;
this.content = null;
this.contentStream = null;
}
}
/// <summary>
/// Gets or sets the content stream.
/// </summary>
/// <value>The content stream.</value>
internal Stream ContentStream
{
get
{
return this.contentStream;
}
set
{
this.ThrowIfThisIsNotNew();
this.contentStream = value;
this.content = null;
this.fileName = null;
}
}
/// <summary>
/// Gets the content of the attachment into memory. Content is set only when Load() is called.
/// </summary>
public byte[] Content
{
get
{
return this.content;
}
internal set
{
this.ThrowIfThisIsNotNew();
this.content = value;
this.fileName = null;
this.contentStream = null;
}
}
/// <summary>
/// Gets or sets a value indicating whether this attachment is a contact photo.
/// </summary>
public bool IsContactPhoto
{
get
{
EwsUtilities.ValidatePropertyVersion(this.Service, ExchangeVersion.Exchange2010, "IsContactPhoto");
return this.isContactPhoto;
}
set
{
EwsUtilities.ValidatePropertyVersion(this.Service, ExchangeVersion.Exchange2010, "IsContactPhoto");
this.ThrowIfThisIsNotNew();
this.isContactPhoto = value;
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Sql;
using Microsoft.WindowsAzure.Management.Sql.Models;
namespace Microsoft.WindowsAzure.Management.Sql
{
/// <summary>
/// The SQL Database Management API includes operations for managing SQL
/// Database servers for a subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715271.aspx for
/// more information)
/// </summary>
internal partial class ServerOperations : IServiceOperations<SqlManagementClient>, IServerOperations
{
/// <summary>
/// Initializes a new instance of the ServerOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ServerOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Sets the administrative password of a SQL Database server for a
/// subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715272.aspx
/// for more information)
/// </summary>
/// <param name='serverName'>
/// The server that will have the change made to the administrative
/// user.
/// </param>
/// <param name='parameters'>
/// Parameters for the Manage Administrator Password operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> ChangeAdministratorPasswordAsync(string serverName, ServerChangeAdministratorPasswordParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.NewPassword == null)
{
throw new ArgumentNullException("parameters.NewPassword");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "ChangeAdministratorPasswordAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/sqlservers/servers/" + serverName + "?op=ResetPassword";
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement administratorLoginPasswordElement = new XElement(XName.Get("AdministratorLoginPassword", "http://schemas.microsoft.com/sqlazure/2010/12/"));
requestDoc.Add(administratorLoginPasswordElement);
administratorLoginPasswordElement.Value = parameters.NewPassword;
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Adds a new SQL Database server to a subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715274.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Create Server operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response returned from the Create Server operation.
/// </returns>
public async Task<ServerCreateResponse> CreateAsync(ServerCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.AdministratorPassword == null)
{
throw new ArgumentNullException("parameters.AdministratorPassword");
}
if (parameters.AdministratorUserName == null)
{
throw new ArgumentNullException("parameters.AdministratorUserName");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/sqlservers/servers";
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement serverElement = new XElement(XName.Get("Server", "http://schemas.microsoft.com/sqlazure/2010/12/"));
requestDoc.Add(serverElement);
XElement administratorLoginElement = new XElement(XName.Get("AdministratorLogin", "http://schemas.microsoft.com/sqlazure/2010/12/"));
administratorLoginElement.Value = parameters.AdministratorUserName;
serverElement.Add(administratorLoginElement);
XElement administratorLoginPasswordElement = new XElement(XName.Get("AdministratorLoginPassword", "http://schemas.microsoft.com/sqlazure/2010/12/"));
administratorLoginPasswordElement.Value = parameters.AdministratorPassword;
serverElement.Add(administratorLoginPasswordElement);
XElement locationElement = new XElement(XName.Get("Location", "http://schemas.microsoft.com/sqlazure/2010/12/"));
locationElement.Value = parameters.Location;
serverElement.Add(locationElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerCreateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerCreateResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serverNameElement = responseDoc.Element(XName.Get("ServerName", "http://schemas.microsoft.com/sqlazure/2010/12/"));
if (serverNameElement != null)
{
result.ServerName = serverNameElement.Value;
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Drops a SQL Database server from a subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715285.aspx
/// for more information)
/// </summary>
/// <param name='serverName'>
/// The name of the server to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> DeleteAsync(string serverName, CancellationToken cancellationToken)
{
// Validate
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serverName", serverName);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/sqlservers/servers/" + serverName;
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns all SQL Database servers that are provisioned for a
/// subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg715269.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response structure for the Server List operation.
/// </returns>
public async Task<ServerListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/sqlservers/servers";
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2012-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerListResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement serversSequenceElement = responseDoc.Element(XName.Get("Servers", "http://schemas.microsoft.com/sqlazure/2010/12/"));
if (serversSequenceElement != null)
{
foreach (XElement serversElement in serversSequenceElement.Elements(XName.Get("Server", "http://schemas.microsoft.com/sqlazure/2010/12/")))
{
ServerListResponse.Server serverInstance = new ServerListResponse.Server();
result.Servers.Add(serverInstance);
XElement nameElement = serversElement.Element(XName.Get("Name", "http://schemas.microsoft.com/sqlazure/2010/12/"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
serverInstance.Name = nameInstance;
}
XElement administratorLoginElement = serversElement.Element(XName.Get("AdministratorLogin", "http://schemas.microsoft.com/sqlazure/2010/12/"));
if (administratorLoginElement != null)
{
string administratorLoginInstance = administratorLoginElement.Value;
serverInstance.AdministratorUserName = administratorLoginInstance;
}
XElement locationElement = serversElement.Element(XName.Get("Location", "http://schemas.microsoft.com/sqlazure/2010/12/"));
if (locationElement != null)
{
string locationInstance = locationElement.Value;
serverInstance.Location = locationInstance;
}
XElement featuresSequenceElement = serversElement.Element(XName.Get("Features", "http://schemas.microsoft.com/sqlazure/2010/12/"));
if (featuresSequenceElement != null)
{
foreach (XElement featuresElement in featuresSequenceElement.Elements(XName.Get("Feature", "http://schemas.microsoft.com/sqlazure/2010/12/")))
{
string featuresKey = featuresElement.Element(XName.Get("Name", "http://schemas.microsoft.com/sqlazure/2010/12/")).Value;
string featuresValue = featuresElement.Element(XName.Get("Value", "http://schemas.microsoft.com/sqlazure/2010/12/")).Value;
serverInstance.Features.Add(featuresKey, featuresValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.LegacyMap
{
public enum DrawRoutine
{
Rectangle,
Polygon,
Ellipse
}
public struct face
{
public Point[] pts;
}
public struct DrawStruct
{
public DrawRoutine dr;
// public Rectangle rect;
public SolidBrush brush;
public face[] trns;
}
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapImageModule")]
public class MapImageModule : IMapImageGenerator, INonSharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
private IConfigSource m_config;
private IMapTileTerrainRenderer terrainRenderer;
private bool m_Enabled = false;
#region IMapImageGenerator Members
public Bitmap CreateMapTile()
{
bool drawPrimVolume = true;
bool textureTerrain = false;
bool generateMaptiles = true;
Bitmap mapbmp;
string[] configSections = new string[] { "Map", "Startup" };
drawPrimVolume
= Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, drawPrimVolume);
textureTerrain
= Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, textureTerrain);
generateMaptiles
= Util.GetConfigVarFromSections<bool>(m_config, "GenerateMaptiles", configSections, generateMaptiles);
if (generateMaptiles)
{
if (textureTerrain)
{
terrainRenderer = new TexturedMapTileRenderer();
}
else
{
terrainRenderer = new ShadedMapTileRenderer();
}
terrainRenderer.Initialise(m_scene, m_config);
mapbmp = new Bitmap((int)Constants.RegionSize, (int)Constants.RegionSize, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
//long t = System.Environment.TickCount;
//for (int i = 0; i < 10; ++i) {
terrainRenderer.TerrainToBitmap(mapbmp);
//}
//t = System.Environment.TickCount - t;
//m_log.InfoFormat("[MAPTILE] generation of 10 maptiles needed {0} ms", t);
if (drawPrimVolume)
{
DrawObjectVolume(m_scene, mapbmp);
}
}
else
{
mapbmp = FetchTexture(m_scene.RegionInfo.RegionSettings.TerrainImageID);
}
return mapbmp;
}
public byte[] WriteJpeg2000Image()
{
try
{
using (Bitmap mapbmp = CreateMapTile())
{
if (mapbmp != null)
return OpenJPEG.EncodeFromImage(mapbmp, true);
}
}
catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke
{
m_log.Error("Failed generating terrain map: " + e);
}
return null;
}
#endregion
#region Region Module interface
public void Initialise(IConfigSource source)
{
m_config = source;
if (Util.GetConfigVarFromSections<string>(
m_config, "MapImageModule", new string[] { "Startup", "Map" }, "MapImageModule") != "MapImageModule")
return;
m_Enabled = true;
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_scene = scene;
m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
public string Name
{
get { return "MapImageModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
// TODO: unused:
// private void ShadeBuildings(Bitmap map)
// {
// lock (map)
// {
// lock (m_scene.Entities)
// {
// foreach (EntityBase entity in m_scene.Entities.Values)
// {
// if (entity is SceneObjectGroup)
// {
// SceneObjectGroup sog = (SceneObjectGroup) entity;
//
// foreach (SceneObjectPart primitive in sog.Children.Values)
// {
// int x = (int) (primitive.AbsolutePosition.X - (primitive.Scale.X / 2));
// int y = (int) (primitive.AbsolutePosition.Y - (primitive.Scale.Y / 2));
// int w = (int) primitive.Scale.X;
// int h = (int) primitive.Scale.Y;
//
// int dx;
// for (dx = x; dx < x + w; dx++)
// {
// int dy;
// for (dy = y; dy < y + h; dy++)
// {
// if (x < 0 || y < 0)
// continue;
// if (x >= map.Width || y >= map.Height)
// continue;
//
// map.SetPixel(dx, dy, Color.DarkGray);
// }
// }
// }
// }
// }
// }
// }
// }
private Bitmap FetchTexture(UUID id)
{
AssetBase asset = m_scene.AssetService.Get(id.ToString());
if (asset != null)
{
m_log.DebugFormat("[MAPTILE]: Static map image texture {0} found for {1}", id, m_scene.Name);
}
else
{
m_log.WarnFormat("[MAPTILE]: Static map image texture {0} not found for {1}", id, m_scene.Name);
return null;
}
ManagedImage managedImage;
Image image;
try
{
if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
return new Bitmap(image);
else
return null;
}
catch (DllNotFoundException)
{
m_log.ErrorFormat("[MAPTILE]: OpenJpeg is not installed correctly on this system. Asset Data is empty for {0}", id);
}
catch (IndexOutOfRangeException)
{
m_log.ErrorFormat("[MAPTILE]: OpenJpeg was unable to decode this. Asset Data is empty for {0}", id);
}
catch (Exception)
{
m_log.ErrorFormat("[MAPTILE]: OpenJpeg was unable to decode this. Asset Data is empty for {0}", id);
}
return null;
}
private Bitmap DrawObjectVolume(Scene whichScene, Bitmap mapbmp)
{
int tc = 0;
double[,] hm = whichScene.Heightmap.GetDoubles();
tc = Environment.TickCount;
m_log.Debug("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile");
EntityBase[] objs = whichScene.GetEntities();
List<float> z_sortheights = new List<float>();
List<uint> z_localIDs = new List<uint>();
Dictionary<uint, DrawStruct> z_sort = new Dictionary<uint, DrawStruct>();
try
{
//SortedList<float, RectangleDrawStruct> z_sort = new SortedList<float, RectangleDrawStruct>();
lock (objs)
{
foreach (EntityBase obj in objs)
{
// Only draw the contents of SceneObjectGroup
if (obj is SceneObjectGroup)
{
SceneObjectGroup mapdot = (SceneObjectGroup)obj;
Color mapdotspot = Color.Gray; // Default color when prim color is white
// Loop over prim in group
foreach (SceneObjectPart part in mapdot.Parts)
{
if (part == null)
continue;
// Draw if the object is at least 1 meter wide in any direction
if (part.Scale.X > 1f || part.Scale.Y > 1f || part.Scale.Z > 1f)
{
// Try to get the RGBA of the default texture entry..
//
try
{
// get the null checks out of the way
// skip the ones that break
if (part == null)
continue;
if (part.Shape == null)
continue;
if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree || part.Shape.PCode == (byte)PCode.Grass)
continue; // eliminates trees from this since we don't really have a good tree representation
// if you want tree blocks on the map comment the above line and uncomment the below line
//mapdotspot = Color.PaleGreen;
Primitive.TextureEntry textureEntry = part.Shape.Textures;
if (textureEntry == null || textureEntry.DefaultTexture == null)
continue;
Color4 texcolor = textureEntry.DefaultTexture.RGBA;
// Not sure why some of these are null, oh well.
int colorr = 255 - (int)(texcolor.R * 255f);
int colorg = 255 - (int)(texcolor.G * 255f);
int colorb = 255 - (int)(texcolor.B * 255f);
if (!(colorr == 255 && colorg == 255 && colorb == 255))
{
//Try to set the map spot color
try
{
// If the color gets goofy somehow, skip it *shakes fist at Color4
mapdotspot = Color.FromArgb(colorr, colorg, colorb);
}
catch (ArgumentException)
{
}
}
}
catch (IndexOutOfRangeException)
{
// Windows Array
}
catch (ArgumentOutOfRangeException)
{
// Mono Array
}
Vector3 pos = part.GetWorldPosition();
// skip prim outside of retion
if (pos.X < 0f || pos.X > 256f || pos.Y < 0f || pos.Y > 256f)
continue;
// skip prim in non-finite position
if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) ||
Single.IsInfinity(pos.X) || Single.IsInfinity(pos.Y))
continue;
// Figure out if object is under 256m above the height of the terrain
bool isBelow256AboveTerrain = false;
try
{
isBelow256AboveTerrain = (pos.Z < ((float)hm[(int)pos.X, (int)pos.Y] + 256f));
}
catch (Exception)
{
}
if (isBelow256AboveTerrain)
{
// Translate scale by rotation so scale is represented properly when object is rotated
Vector3 lscale = new Vector3(part.Shape.Scale.X, part.Shape.Scale.Y, part.Shape.Scale.Z);
Vector3 scale = new Vector3();
Vector3 tScale = new Vector3();
Vector3 axPos = new Vector3(pos.X,pos.Y,pos.Z);
Quaternion llrot = part.GetWorldRotation();
Quaternion rot = new Quaternion(llrot.W, llrot.X, llrot.Y, llrot.Z);
scale = lscale * rot;
// negative scales don't work in this situation
scale.X = Math.Abs(scale.X);
scale.Y = Math.Abs(scale.Y);
scale.Z = Math.Abs(scale.Z);
// This scaling isn't very accurate and doesn't take into account the face rotation :P
int mapdrawstartX = (int)(pos.X - scale.X);
int mapdrawstartY = (int)(pos.Y - scale.Y);
int mapdrawendX = (int)(pos.X + scale.X);
int mapdrawendY = (int)(pos.Y + scale.Y);
// If object is beyond the edge of the map, don't draw it to avoid errors
if (mapdrawstartX < 0 || mapdrawstartX > ((int)Constants.RegionSize - 1) || mapdrawendX < 0 || mapdrawendX > ((int)Constants.RegionSize - 1)
|| mapdrawstartY < 0 || mapdrawstartY > ((int)Constants.RegionSize - 1) || mapdrawendY < 0
|| mapdrawendY > ((int)Constants.RegionSize - 1))
continue;
#region obb face reconstruction part duex
Vector3[] vertexes = new Vector3[8];
// float[] distance = new float[6];
Vector3[] FaceA = new Vector3[6]; // vertex A for Facei
Vector3[] FaceB = new Vector3[6]; // vertex B for Facei
Vector3[] FaceC = new Vector3[6]; // vertex C for Facei
Vector3[] FaceD = new Vector3[6]; // vertex D for Facei
tScale = new Vector3(lscale.X, -lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[0] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[0].x = pos.X + vertexes[0].x;
//vertexes[0].y = pos.Y + vertexes[0].y;
//vertexes[0].z = pos.Z + vertexes[0].z;
FaceA[0] = vertexes[0];
FaceB[3] = vertexes[0];
FaceA[4] = vertexes[0];
tScale = lscale;
scale = ((tScale * rot));
vertexes[1] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[1].x = pos.X + vertexes[1].x;
// vertexes[1].y = pos.Y + vertexes[1].y;
//vertexes[1].z = pos.Z + vertexes[1].z;
FaceB[0] = vertexes[1];
FaceA[1] = vertexes[1];
FaceC[4] = vertexes[1];
tScale = new Vector3(lscale.X, -lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[2] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
//vertexes[2].x = pos.X + vertexes[2].x;
//vertexes[2].y = pos.Y + vertexes[2].y;
//vertexes[2].z = pos.Z + vertexes[2].z;
FaceC[0] = vertexes[2];
FaceD[3] = vertexes[2];
FaceC[5] = vertexes[2];
tScale = new Vector3(lscale.X, lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[3] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
//vertexes[3].x = pos.X + vertexes[3].x;
// vertexes[3].y = pos.Y + vertexes[3].y;
// vertexes[3].z = pos.Z + vertexes[3].z;
FaceD[0] = vertexes[3];
FaceC[1] = vertexes[3];
FaceA[5] = vertexes[3];
tScale = new Vector3(-lscale.X, lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[4] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[4].x = pos.X + vertexes[4].x;
// vertexes[4].y = pos.Y + vertexes[4].y;
// vertexes[4].z = pos.Z + vertexes[4].z;
FaceB[1] = vertexes[4];
FaceA[2] = vertexes[4];
FaceD[4] = vertexes[4];
tScale = new Vector3(-lscale.X, lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[5] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[5].x = pos.X + vertexes[5].x;
// vertexes[5].y = pos.Y + vertexes[5].y;
// vertexes[5].z = pos.Z + vertexes[5].z;
FaceD[1] = vertexes[5];
FaceC[2] = vertexes[5];
FaceB[5] = vertexes[5];
tScale = new Vector3(-lscale.X, -lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[6] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[6].x = pos.X + vertexes[6].x;
// vertexes[6].y = pos.Y + vertexes[6].y;
// vertexes[6].z = pos.Z + vertexes[6].z;
FaceB[2] = vertexes[6];
FaceA[3] = vertexes[6];
FaceB[4] = vertexes[6];
tScale = new Vector3(-lscale.X, -lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[7] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[7].x = pos.X + vertexes[7].x;
// vertexes[7].y = pos.Y + vertexes[7].y;
// vertexes[7].z = pos.Z + vertexes[7].z;
FaceD[2] = vertexes[7];
FaceC[3] = vertexes[7];
FaceD[5] = vertexes[7];
#endregion
//int wy = 0;
//bool breakYN = false; // If we run into an error drawing, break out of the
// loop so we don't lag to death on error handling
DrawStruct ds = new DrawStruct();
ds.brush = new SolidBrush(mapdotspot);
//ds.rect = new Rectangle(mapdrawstartX, (255 - mapdrawstartY), mapdrawendX - mapdrawstartX, mapdrawendY - mapdrawstartY);
ds.trns = new face[FaceA.Length];
for (int i = 0; i < FaceA.Length; i++)
{
Point[] working = new Point[5];
working[0] = project(FaceA[i], axPos);
working[1] = project(FaceB[i], axPos);
working[2] = project(FaceD[i], axPos);
working[3] = project(FaceC[i], axPos);
working[4] = project(FaceA[i], axPos);
face workingface = new face();
workingface.pts = working;
ds.trns[i] = workingface;
}
z_sort.Add(part.LocalId, ds);
z_localIDs.Add(part.LocalId);
z_sortheights.Add(pos.Z);
//for (int wx = mapdrawstartX; wx < mapdrawendX; wx++)
//{
//for (wy = mapdrawstartY; wy < mapdrawendY; wy++)
//{
//m_log.InfoFormat("[MAPDEBUG]: {0},{1}({2})", wx, (255 - wy),wy);
//try
//{
// Remember, flip the y!
// mapbmp.SetPixel(wx, (255 - wy), mapdotspot);
//}
//catch (ArgumentException)
//{
// breakYN = true;
//}
//if (breakYN)
// break;
//}
//if (breakYN)
// break;
//}
} // Object is within 256m Z of terrain
} // object is at least a meter wide
} // loop over group children
} // entitybase is sceneobject group
} // foreach loop over entities
float[] sortedZHeights = z_sortheights.ToArray();
uint[] sortedlocalIds = z_localIDs.ToArray();
// Sort prim by Z position
Array.Sort(sortedZHeights, sortedlocalIds);
using (Graphics g = Graphics.FromImage(mapbmp))
{
for (int s = 0; s < sortedZHeights.Length; s++)
{
if (z_sort.ContainsKey(sortedlocalIds[s]))
{
DrawStruct rectDrawStruct = z_sort[sortedlocalIds[s]];
for (int r = 0; r < rectDrawStruct.trns.Length; r++)
{
g.FillPolygon(rectDrawStruct.brush,rectDrawStruct.trns[r].pts);
}
//g.FillRectangle(rectDrawStruct.brush , rectDrawStruct.rect);
}
}
}
} // lock entities objs
}
finally
{
foreach (DrawStruct ds in z_sort.Values)
ds.brush.Dispose();
}
m_log.Debug("[MAPTILE]: Generating Maptile Step 2: Done in " + (Environment.TickCount - tc) + " ms");
return mapbmp;
}
private Point project(Vector3 point3d, Vector3 originpos)
{
Point returnpt = new Point();
//originpos = point3d;
//int d = (int)(256f / 1.5f);
//Vector3 topos = new Vector3(0, 0, 0);
// float z = -point3d.z - topos.z;
returnpt.X = (int)point3d.X;//(int)((topos.x - point3d.x) / z * d);
returnpt.Y = (int)(((int)Constants.RegionSize - 1) - point3d.Y);//(int)(255 - (((topos.y - point3d.y) / z * d)));
return returnpt;
}
public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
{
return null;
}
}
}
| |
//
// Dispatch.cs: Support for Grand Central Dispatch framework
//
// Authors:
// Miguel de Icaza ([email protected])
// Marek Safar ([email protected])
//
// Copyright 2010 Novell, Inc.
// Copyright 2011-2013 Xamarin Inc
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Runtime.InteropServices;
using System.Threading;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
namespace MonoMac.CoreFoundation {
public enum DispatchQueuePriority {
High = 2,
Default = 0,
Low = -2,
}
public abstract class DispatchObject : INativeObject, IDisposable {
internal IntPtr handle;
//
// Constructors and lifecycle
//
[Preserve (Conditional = true)]
internal DispatchObject (IntPtr handle, bool owns)
{
if (handle == IntPtr.Zero)
throw new ArgumentNullException ("handle");
this.handle = handle;
if (!owns)
dispatch_retain (handle);
}
internal DispatchObject ()
{
}
[DllImport ("libc")]
extern static IntPtr dispatch_release (IntPtr o);
[DllImport ("libc")]
extern static IntPtr dispatch_retain (IntPtr o);
~DispatchObject ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
dispatch_release (handle);
handle = IntPtr.Zero;
}
}
public static bool operator == (DispatchObject a, DispatchObject b)
{
var oa = a as object;
var ob = b as object;
if (oa == null){
if (ob == null)
return true;
return false;
} else {
if (ob == null)
return false;
return a.handle == b.handle;
}
}
public static bool operator != (DispatchObject a, DispatchObject b)
{
var oa = a as object;
var ob = b as object;
if (oa == null){
if (ob == null)
return false;
return true;
} else {
if (ob == null)
return true;
return a.handle != b.handle;
}
}
public override bool Equals (object other)
{
if (other == null)
return false;
var od = other as DispatchQueue;
return od.handle == handle;
}
public override int GetHashCode ()
{
return (int) handle;
}
protected void Check ()
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException (GetType ().ToString ());
}
[DllImport ("libc")]
extern static void dispatch_set_target_queue (/* dispatch_object_t */ IntPtr queue, /* dispatch_queue_t */ IntPtr target);
public void SetTargetQueue (DispatchQueue queue)
{
// note: null is allowed because DISPATCH_TARGET_QUEUE_DEFAULT is defined as NULL (dispatch/queue.h)
IntPtr q = queue == null ? IntPtr.Zero : queue.Handle;
dispatch_set_target_queue (handle, q);
}
}
public class DispatchQueue : DispatchObject {
[Preserve (Conditional = true)]
internal DispatchQueue (IntPtr handle, bool owns) : base (handle, owns)
{
}
public DispatchQueue (IntPtr handle) : base (handle, false)
{
}
public DispatchQueue (string label) : base ()
{
// Initialized in owned state for the queue.
handle = dispatch_queue_create (label, IntPtr.Zero);
if (handle == IntPtr.Zero)
throw new Exception ("Error creating dispatch queue");
}
//
// Properties and methods
//
public string Label {
get {
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("DispatchQueue");
return Marshal.PtrToStringAnsi (dispatch_queue_get_label (handle));
}
}
[DllImport ("libc")]
extern static void dispatch_suspend (IntPtr o);
public void Suspend ()
{
Check ();
dispatch_suspend (handle);
}
[DllImport ("libc")]
extern static void dispatch_resume (IntPtr o);
public void Resume ()
{
Check ();
dispatch_resume (handle);
}
[DllImport ("libc")]
extern static IntPtr dispatch_get_context (IntPtr o);
[DllImport ("libc")]
extern static void dispatch_set_context (IntPtr o, IntPtr ctx);
public IntPtr Context {
get {
Check ();
return dispatch_get_context (handle);
}
set {
Check ();
dispatch_set_context (handle, value);
}
}
[Obsolete ("Deprecated in iOS 6.0")]
public static DispatchQueue CurrentQueue {
get {
return new DispatchQueue (dispatch_get_current_queue (), false);
}
}
public static DispatchQueue GetGlobalQueue (DispatchQueuePriority priority)
{
return new DispatchQueue (dispatch_get_global_queue ((IntPtr) priority, IntPtr.Zero), false);
}
public static DispatchQueue DefaultGlobalQueue {
get {
return new DispatchQueue (dispatch_get_global_queue ((IntPtr) DispatchQueuePriority.Default, IntPtr.Zero), false);
}
}
#if MONOMAC
static DispatchQueue PInvokeDispatchGetMainQueue ()
{
return new DispatchQueue (dispatch_get_main_queue (), false);
}
#endif
static IntPtr main_q;
static object lockobj = new object ();
public static DispatchQueue MainQueue {
get {
lock (lockobj) {
if (main_q == IntPtr.Zero) {
// Try loading the symbol from our address space first, should work everywhere
main_q = Dlfcn.dlsym ((IntPtr) (-2), "_dispatch_main_q");
// Last case: this is technically not right for the simulator, as this path
// actually points to the MacOS library, not the one in the SDK.
if (main_q == IntPtr.Zero){
var h = Dlfcn.dlopen ("/usr/lib/libSystem.dylib", 0x0);
main_q = Dlfcn.GetIndirect (h, "_dispatch_main_q");
Dlfcn.dlclose (h);
}
}
}
#if MONOMAC
// For Snow Leopard
if (main_q == IntPtr.Zero)
return PInvokeDispatchGetMainQueue ();
#endif
return new DispatchQueue (main_q, false);
}
}
//
// Dispatching
//
internal delegate void dispatch_callback_t (IntPtr context);
internal static readonly dispatch_callback_t static_dispatch = static_dispatcher_to_managed;
[MonoPInvokeCallback (typeof (dispatch_callback_t))]
static void static_dispatcher_to_managed (IntPtr context)
{
GCHandle gch = GCHandle.FromIntPtr (context);
var obj = gch.Target as Tuple<NSAction, DispatchQueue>;
if (obj != null) {
var sc = SynchronizationContext.Current;
// Set GCD synchronization context. Mainly used when await executes inside GCD to continue
// execution on same dispatch queue. Set the context only when there is no user context
// set, including UIKitSynchronizationContext
//
// This assumes that only 1 queue can run on thread at the same time
//
if (sc == null)
SynchronizationContext.SetSynchronizationContext (new DispatchQueueSynchronizationContext (obj.Item2));
try {
obj.Item1 ();
} catch {
gch.Free ();
throw;
} finally {
if (sc == null)
SynchronizationContext.SetSynchronizationContext (null);
}
}
gch.Free ();
}
public void DispatchAsync (NSAction action)
{
if (action == null)
throw new ArgumentNullException ("action");
dispatch_async_f (handle, (IntPtr) GCHandle.Alloc (Tuple.Create (action, this)), static_dispatch);
}
public void DispatchSync (NSAction action)
{
if (action == null)
throw new ArgumentNullException ("action");
dispatch_sync_f (handle, (IntPtr) GCHandle.Alloc (Tuple.Create (action, this)), static_dispatch);
}
//
// Native methods
//
[DllImport ("libc")]
extern static IntPtr dispatch_queue_create (string label, IntPtr attr);
[DllImport ("libc")]
extern static void dispatch_async_f (IntPtr queue, IntPtr context, dispatch_callback_t dispatch);
[DllImport ("libc")]
extern static void dispatch_sync_f (IntPtr queue, IntPtr context, dispatch_callback_t dispatch);
[DllImport ("libc")]
extern static IntPtr dispatch_get_current_queue ();
[DllImport ("libc")]
// dispatch_queue_t dispatch_get_global_queue (long priority, unsigned long flags);
// IntPtr used for 32/64 bits
extern static IntPtr dispatch_get_global_queue (IntPtr priority, IntPtr flags);
[DllImport ("libc")]
extern static IntPtr dispatch_get_main_queue ();
[DllImport ("libc")]
// this returns a "const char*" so we cannot make a string out of it since it will be freed (and crash)
extern static IntPtr dispatch_queue_get_label (IntPtr queue);
#if MONOMAC
//
// Not to be used by apps that use UIApplicationMain, NSApplicationMain or CFRunLoopRun,
// so not available on Monotouch
//
[DllImport ("libc")]
static extern IntPtr dispatch_main ();
public static void MainIteration ()
{
dispatch_main ();
}
#endif
}
// FIXME: Remove when MONOMAC is more up-to-date
#if MONOMAC
static class Tuple {
public static Tuple<T1, T2> Create<T1, T2>
(
T1 item1,
T2 item2) {
return new Tuple<T1, T2> (item1, item2);
}
}
class Tuple<T1, T2>
{
T1 item1;
T2 item2;
public Tuple (T1 item1, T2 item2)
{
this.item1 = item1;
this.item2 = item2;
}
public T1 Item1 {
get { return item1; }
}
public T2 Item2 {
get { return item2; }
}
}
#endif
public struct DispatchTime
{
public static readonly DispatchTime Now = new DispatchTime ();
public static readonly DispatchTime Forever = new DispatchTime (ulong.MaxValue);
public DispatchTime (ulong nanoseconds)
: this ()
{
this.Nanoseconds = nanoseconds;
}
public ulong Nanoseconds { get; private set; }
// TODO: Bind more
}
public class DispatchGroup : DispatchObject
{
private DispatchGroup (IntPtr handle, bool owns)
: base (handle, owns)
{
}
public static DispatchGroup Create ()
{
var ptr = dispatch_group_create ();
if (ptr == IntPtr.Zero)
return null;
return new DispatchGroup (ptr, true);
}
public void DispatchAsync (DispatchQueue queue, NSAction action)
{
if (queue == null)
throw new ArgumentNullException ("queue");
if (action == null)
throw new ArgumentNullException ("action");
Check ();
dispatch_group_async_f (handle, queue.handle, (IntPtr) GCHandle.Alloc (Tuple.Create (action, queue)), DispatchQueue.static_dispatch);
}
public void Enter ()
{
Check ();
dispatch_group_enter (handle);
}
public void Leave ()
{
Check ();
dispatch_group_leave (handle);
}
public bool Wait (DispatchTime timeout)
{
Check ();
return dispatch_group_wait (handle, timeout.Nanoseconds) == IntPtr.Zero;
}
// TODO: dispatch_group_notify_f
[DllImport ("libc")]
extern static IntPtr dispatch_group_create ();
[DllImport ("libc")]
extern static void dispatch_group_async_f (IntPtr group, IntPtr queue, IntPtr context, DispatchQueue.dispatch_callback_t block);
[DllImport ("libc")]
extern static void dispatch_group_enter (IntPtr group);
[DllImport ("libc")]
extern static void dispatch_group_leave (IntPtr group);
[DllImport ("libc")]
// return IntPtr used for 32/64 bits
extern static IntPtr dispatch_group_wait (IntPtr group, ulong timeout);
}
}
| |
using YAF.Lucene.Net.Store;
using YAF.Lucene.Net.Support.IO;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace YAF.Lucene.Net.Util
{
/*
* 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.
*/
/// <summary>
/// On-disk sorting of byte arrays. Each byte array (entry) is a composed of the following
/// fields:
/// <list type="bullet">
/// <item><description>(two bytes) length of the following byte array,</description></item>
/// <item><description>exactly the above count of bytes for the sequence to be sorted.</description></item>
/// </list>
/// </summary>
public sealed class OfflineSorter
{
private void InitializeInstanceFields()
{
buffer = new BytesRefArray(bufferBytesUsed);
}
/// <summary>
/// Convenience constant for megabytes </summary>
public static readonly long MB = 1024 * 1024;
/// <summary>
/// Convenience constant for gigabytes </summary>
public static readonly long GB = MB * 1024;
/// <summary>
/// Minimum recommended buffer size for sorting.
/// </summary>
public static readonly long MIN_BUFFER_SIZE_MB = 32;
/// <summary>
/// Absolute minimum required buffer size for sorting.
/// </summary>
public static readonly long ABSOLUTE_MIN_SORT_BUFFER_SIZE = MB / 2;
private static readonly string MIN_BUFFER_SIZE_MSG = "At least 0.5MB RAM buffer is needed";
/// <summary>
/// Maximum number of temporary files before doing an intermediate merge.
/// </summary>
public static readonly int MAX_TEMPFILES = 128;
/// <summary>
/// A bit more descriptive unit for constructors.
/// </summary>
/// <seealso cref="Automatic()"/>
/// <seealso cref="Megabytes(long)"/>
public sealed class BufferSize
{
internal readonly int bytes;
private BufferSize(long bytes)
{
if (bytes > int.MaxValue)
{
throw new System.ArgumentException("Buffer too large for Java (" + (int.MaxValue / MB) + "mb max): " + bytes);
}
if (bytes < ABSOLUTE_MIN_SORT_BUFFER_SIZE)
{
throw new System.ArgumentException(MIN_BUFFER_SIZE_MSG + ": " + bytes);
}
this.bytes = (int)bytes;
}
/// <summary>
/// Creates a <see cref="BufferSize"/> in MB. The given
/// values must be > 0 and < 2048.
/// </summary>
public static BufferSize Megabytes(long mb)
{
return new BufferSize(mb * MB);
}
/// <summary>
/// Approximately half of the currently available free heap, but no less
/// than <see cref="ABSOLUTE_MIN_SORT_BUFFER_SIZE"/>. However if current heap allocation
/// is insufficient or if there is a large portion of unallocated heap-space available
/// for sorting consult with max allowed heap size.
/// </summary>
public static BufferSize Automatic()
{
long max, total, free;
using (var proc = Process.GetCurrentProcess())
{
// take sizes in "conservative" order
max = proc.PeakVirtualMemorySize64; // max allocated; java has it as Runtime.maxMemory();
total = proc.VirtualMemorySize64; // currently allocated; java has it as Runtime.totalMemory();
free = proc.PrivateMemorySize64; // unused portion of currently allocated; java has it as Runtime.freeMemory();
}
long totalAvailableBytes = max - total + free;
// by free mem (attempting to not grow the heap for this)
long sortBufferByteSize = free / 2;
long minBufferSizeBytes = MIN_BUFFER_SIZE_MB * MB;
if (sortBufferByteSize < minBufferSizeBytes || totalAvailableBytes > 10 * minBufferSizeBytes) // lets see if we need/should to grow the heap
{
if (totalAvailableBytes / 2 > minBufferSizeBytes) // there is enough mem for a reasonable buffer
{
sortBufferByteSize = totalAvailableBytes / 2; // grow the heap
}
else
{
//heap seems smallish lets be conservative fall back to the free/2
sortBufferByteSize = Math.Max(ABSOLUTE_MIN_SORT_BUFFER_SIZE, sortBufferByteSize);
}
}
return new BufferSize(Math.Min((long)int.MaxValue, sortBufferByteSize));
}
}
/// <summary>
/// Sort info (debugging mostly).
/// </summary>
public class SortInfo
{
private readonly OfflineSorter outerInstance;
/// <summary>
/// Number of temporary files created when merging partitions </summary>
public int TempMergeFiles { get; set; }
/// <summary>
/// Number of partition merges </summary>
public int MergeRounds { get; set; }
/// <summary>
/// Number of lines of data read </summary>
public int Lines { get; set; }
/// <summary>
/// Time spent merging sorted partitions (in milliseconds) </summary>
public long MergeTime { get; set; }
/// <summary>
/// Time spent sorting data (in milliseconds) </summary>
public long SortTime { get; set; }
/// <summary>
/// Total time spent (in milliseconds) </summary>
public long TotalTime { get; set; }
/// <summary>
/// Time spent in i/o read (in milliseconds) </summary>
public long ReadTime { get; set; }
/// <summary>
/// Read buffer size (in bytes) </summary>
public long BufferSize { get; private set; }
/// <summary>
/// Create a new <see cref="SortInfo"/> (with empty statistics) for debugging. </summary>
public SortInfo(OfflineSorter outerInstance)
{
this.outerInstance = outerInstance;
BufferSize = outerInstance.ramBufferSize.bytes;
}
/// <summary>
/// Returns a string representation of this object.
/// </summary>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture,
"time={0:0.00} sec. total ({1:0.00} reading, {2:0.00} sorting, {3:0.00} merging), lines={4}, temp files={5}, merges={6}, soft ram limit={7:0.00} MB",
TotalTime / 1000.0d, ReadTime / 1000.0d, SortTime / 1000.0d, MergeTime / 1000.0d,
Lines, TempMergeFiles, MergeRounds,
(double)BufferSize / MB);
}
}
private readonly BufferSize ramBufferSize;
private readonly Counter bufferBytesUsed = Counter.NewCounter();
private BytesRefArray buffer;
private SortInfo sortInfo;
private readonly int maxTempFiles;
private readonly IComparer<BytesRef> comparer;
/// <summary>
/// Default comparer: sorts in binary (codepoint) order </summary>
public static readonly IComparer<BytesRef> DEFAULT_COMPARER = Utf8SortedAsUnicodeComparer.Instance;
/// <summary>
/// Defaults constructor.
/// </summary>
/// <seealso cref="DefaultTempDir()"/>
/// <seealso cref="BufferSize.Automatic()"/>
public OfflineSorter()
: this(DEFAULT_COMPARER, BufferSize.Automatic(), DefaultTempDir(), MAX_TEMPFILES)
{
}
/// <summary>
/// Defaults constructor with a custom comparer.
/// </summary>
/// <seealso cref="DefaultTempDir()"/>
/// <seealso cref="BufferSize.Automatic()"/>
public OfflineSorter(IComparer<BytesRef> comparer)
: this(comparer, BufferSize.Automatic(), DefaultTempDir(), MAX_TEMPFILES)
{
}
/// <summary>
/// All-details constructor.
/// </summary>
public OfflineSorter(IComparer<BytesRef> comparer, BufferSize ramBufferSize, DirectoryInfo tempDirectory, int maxTempfiles)
{
InitializeInstanceFields();
if (ramBufferSize.bytes < ABSOLUTE_MIN_SORT_BUFFER_SIZE)
{
throw new System.ArgumentException(MIN_BUFFER_SIZE_MSG + ": " + ramBufferSize.bytes);
}
if (maxTempfiles < 2)
{
throw new System.ArgumentException("maxTempFiles must be >= 2");
}
this.ramBufferSize = ramBufferSize;
this.maxTempFiles = maxTempfiles;
this.comparer = comparer;
}
/// <summary>
/// Sort input to output, explicit hint for the buffer size. The amount of allocated
/// memory may deviate from the hint (may be smaller or larger).
/// </summary>
public SortInfo Sort(FileInfo input, FileInfo output)
{
sortInfo = new SortInfo(this) { TotalTime = Environment.TickCount };
output.Delete();
var merges = new List<FileInfo>();
bool success2 = false;
try
{
var inputStream = new ByteSequencesReader(input);
bool success = false;
try
{
int lines = 0;
while ((lines = ReadPartition(inputStream)) > 0)
{
merges.Add(SortPartition(lines));
sortInfo.TempMergeFiles++;
sortInfo.Lines += lines;
// Handle intermediate merges.
if (merges.Count == maxTempFiles)
{
var intermediate = new FileInfo(Path.GetTempFileName());
try
{
MergePartitions(merges, intermediate);
}
finally
{
foreach (var file in merges)
{
file.Delete();
}
merges.Clear();
merges.Add(intermediate);
}
sortInfo.TempMergeFiles++;
}
}
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(inputStream);
}
else
{
IOUtils.DisposeWhileHandlingException(inputStream);
}
}
// One partition, try to rename or copy if unsuccessful.
if (merges.Count == 1)
{
FileInfo single = merges[0];
Copy(single, output);
try
{
File.Delete(single.FullName);
}
catch (Exception)
{
// ignored
}
}
else
{
// otherwise merge the partitions with a priority queue.
MergePartitions(merges, output);
}
success2 = true;
}
finally
{
foreach (FileInfo file in merges)
{
file.Delete();
}
if (!success2)
{
output.Delete();
}
}
sortInfo.TotalTime = (Environment.TickCount - sortInfo.TotalTime);
return sortInfo;
}
/// <summary>
/// Returns the default temporary directory. By default, the System's temp folder. If not accessible
/// or not available, an <see cref="IOException"/> is thrown.
/// </summary>
public static DirectoryInfo DefaultTempDir()
{
return new DirectoryInfo(Path.GetTempPath());
}
/// <summary>
/// Copies one file to another.
/// </summary>
private static void Copy(FileInfo file, FileInfo output)
{
using (Stream inputStream = file.OpenRead())
{
using (Stream outputStream = output.OpenWrite())
{
inputStream.CopyTo(outputStream);
}
}
}
/// <summary>
/// Sort a single partition in-memory. </summary>
private FileInfo SortPartition(int len) // LUCENENET NOTE: made private, since protected is not valid in a sealed class
{
var data = this.buffer;
FileInfo tempFile = FileSupport.CreateTempFile("sort", "partition", DefaultTempDir());
long start = Environment.TickCount;
sortInfo.SortTime += (Environment.TickCount - start);
using (var @out = new ByteSequencesWriter(tempFile))
{
BytesRef spare;
IBytesRefIterator iter = buffer.GetIterator(comparer);
while ((spare = iter.Next()) != null)
{
Debug.Assert(spare.Length <= ushort.MaxValue);
@out.Write(spare);
}
}
// Clean up the buffer for the next partition.
data.Clear();
return tempFile;
}
/// <summary>
/// Merge a list of sorted temporary files (partitions) into an output file. </summary>
internal void MergePartitions(IEnumerable<FileInfo> merges, FileInfo outputFile)
{
long start = Environment.TickCount;
var @out = new ByteSequencesWriter(outputFile);
PriorityQueue<FileAndTop> queue = new PriorityQueueAnonymousInnerClassHelper(this, merges.Count());
var streams = new ByteSequencesReader[merges.Count()];
try
{
// Open streams and read the top for each file
for (int i = 0; i < merges.Count(); i++)
{
streams[i] = new ByteSequencesReader(merges.ElementAt(i));
byte[] line = streams[i].Read();
if (line != null)
{
queue.InsertWithOverflow(new FileAndTop(i, line));
}
}
// Unix utility sort() uses ordered array of files to pick the next line from, updating
// it as it reads new lines. The PQ used here is a more elegant solution and has
// a nicer theoretical complexity bound :) The entire sorting process is I/O bound anyway
// so it shouldn't make much of a difference (didn't check).
FileAndTop top;
while ((top = queue.Top) != null)
{
@out.Write(top.Current);
if (!streams[top.Fd].Read(top.Current))
{
queue.Pop();
}
else
{
queue.UpdateTop();
}
}
sortInfo.MergeTime += Environment.TickCount - start;
sortInfo.MergeRounds++;
}
finally
{
// The logic below is: if an exception occurs in closing out, it has a priority over exceptions
// happening in closing streams.
try
{
IOUtils.Dispose(streams);
}
finally
{
IOUtils.Dispose(@out);
}
}
}
private class PriorityQueueAnonymousInnerClassHelper : PriorityQueue<FileAndTop>
{
private readonly OfflineSorter outerInstance;
public PriorityQueueAnonymousInnerClassHelper(OfflineSorter outerInstance, int size)
: base(size)
{
this.outerInstance = outerInstance;
}
protected internal override bool LessThan(FileAndTop a, FileAndTop b)
{
return outerInstance.comparer.Compare(a.Current, b.Current) < 0;
}
}
/// <summary>
/// Read in a single partition of data. </summary>
internal int ReadPartition(ByteSequencesReader reader)
{
long start = Environment.TickCount;
var scratch = new BytesRef();
while ((scratch.Bytes = reader.Read()) != null)
{
scratch.Length = scratch.Bytes.Length;
buffer.Append(scratch);
// Account for the created objects.
// (buffer slots do not account to buffer size.)
if (ramBufferSize.bytes < bufferBytesUsed.Get())
{
break;
}
}
sortInfo.ReadTime += (Environment.TickCount - start);
return buffer.Length;
}
internal class FileAndTop
{
internal int Fd { get; private set; }
internal BytesRef Current { get; private set; }
internal FileAndTop(int fd, byte[] firstLine)
{
this.Fd = fd;
this.Current = new BytesRef(firstLine);
}
}
/// <summary>
/// Utility class to emit length-prefixed <see cref="T:byte[]"/> entries to an output stream for sorting.
/// Complementary to <see cref="ByteSequencesReader"/>.
/// </summary>
public class ByteSequencesWriter : IDisposable
{
private readonly DataOutput os;
/// <summary>
/// Constructs a <see cref="ByteSequencesWriter"/> to the provided <see cref="FileInfo"/>. </summary>
public ByteSequencesWriter(FileInfo file)
: this(NewBinaryWriterDataOutput(file))
{
}
/// <summary>
/// Constructs a <see cref="ByteSequencesWriter"/> to the provided <see cref="DataOutput"/>. </summary>
public ByteSequencesWriter(DataOutput os)
{
this.os = os;
}
/// <summary>
/// LUCENENET specific - ensures the file has been created with no BOM
/// if it doesn't already exist and opens the file for writing.
/// Java doesn't use a BOM by default.
/// </summary>
private static BinaryWriterDataOutput NewBinaryWriterDataOutput(FileInfo file)
{
string fileName = file.FullName;
// Create the file (without BOM) if it doesn't already exist
if (!File.Exists(fileName))
{
// Create the file
File.WriteAllText(fileName, string.Empty, new UTF8Encoding(false) /* No BOM */);
}
return new BinaryWriterDataOutput(new BinaryWriter(new FileStream(fileName, FileMode.Open, FileAccess.Write)));
}
/// <summary>
/// Writes a <see cref="BytesRef"/>. </summary>
/// <seealso cref="Write(byte[], int, int)"/>
public virtual void Write(BytesRef @ref)
{
Debug.Assert(@ref != null);
Write(@ref.Bytes, @ref.Offset, @ref.Length);
}
/// <summary>
/// Writes a byte array. </summary>
/// <seealso cref="Write(byte[], int, int)"/>
public virtual void Write(byte[] bytes)
{
Write(bytes, 0, bytes.Length);
}
/// <summary>
/// Writes a byte array.
/// <para/>
/// The length is written as a <see cref="short"/>, followed
/// by the bytes.
/// </summary>
public virtual void Write(byte[] bytes, int off, int len)
{
Debug.Assert(bytes != null);
Debug.Assert(off >= 0 && off + len <= bytes.Length);
Debug.Assert(len >= 0);
os.WriteInt16((short)len);
os.WriteBytes(bytes, off, len); // LUCENENET NOTE: We call WriteBytes, since there is no Write() on Lucene's version of DataOutput
}
/// <summary>
/// Disposes the provided <see cref="DataOutput"/> if it is <see cref="IDisposable"/>.
/// </summary>
public void Dispose()
{
var os = this.os as IDisposable;
if (os != null)
{
os.Dispose();
}
}
}
/// <summary>
/// Utility class to read length-prefixed <see cref="T:byte[]"/> entries from an input.
/// Complementary to <see cref="ByteSequencesWriter"/>.
/// </summary>
public class ByteSequencesReader : IDisposable
{
private readonly DataInput inputStream;
/// <summary>
/// Constructs a <see cref="ByteSequencesReader"/> from the provided <see cref="FileInfo"/>. </summary>
public ByteSequencesReader(FileInfo file)
: this(new BinaryReaderDataInput(new BinaryReader(new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))))
{
}
/// <summary>
/// Constructs a <see cref="ByteSequencesReader"/> from the provided <see cref="DataInput"/>. </summary>
public ByteSequencesReader(DataInput inputStream)
{
this.inputStream = inputStream;
}
/// <summary>
/// Reads the next entry into the provided <see cref="BytesRef"/>. The internal
/// storage is resized if needed.
/// </summary>
/// <returns> Returns <c>false</c> if EOF occurred when trying to read
/// the header of the next sequence. Returns <c>true</c> otherwise. </returns>
/// <exception cref="EndOfStreamException"> If the file ends before the full sequence is read. </exception>
public virtual bool Read(BytesRef @ref)
{
ushort length;
try
{
length = (ushort)inputStream.ReadInt16();
}
catch (EndOfStreamException)
{
return false;
}
@ref.Grow(length);
@ref.Offset = 0;
@ref.Length = length;
inputStream.ReadBytes(@ref.Bytes, 0, length);
return true;
}
/// <summary>
/// Reads the next entry and returns it if successful.
/// </summary>
/// <seealso cref="Read(BytesRef)"/>
/// <returns> Returns <c>null</c> if EOF occurred before the next entry
/// could be read. </returns>
/// <exception cref="EndOfStreamException"> If the file ends before the full sequence is read. </exception>
public virtual byte[] Read()
{
ushort length;
try
{
length = (ushort)inputStream.ReadInt16();
}
catch (EndOfStreamException)
{
return null;
}
Debug.Assert(length >= 0, "Sanity: sequence length < 0: " + length);
byte[] result = new byte[length];
inputStream.ReadBytes(result, 0, length);
return result;
}
/// <summary>
/// Disposes the provided <see cref="DataInput"/> if it is <see cref="IDisposable"/>.
/// </summary>
public void Dispose()
{
var @is = inputStream as IDisposable;
if (@is != null)
{
@is.Dispose();
}
}
}
/// <summary>
/// Returns the comparer in use to sort entries </summary>
public IComparer<BytesRef> Comparer
{
get
{
return comparer;
}
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace Moscrif.IDE.Components
{
public partial class StartEventControl
{
private global::Gtk.Table table1;
private global::Gtk.Table tblAction;
private global::Gtk.HBox hbox1;
private global::Gtk.Image imgActions;
private global::Gtk.Label lblActions;
private global::Gtk.Label lblAccount;
private global::Gtk.Label lblProject;
private global::Gtk.Label lblWorkspace;
private global::Gtk.Label lbRecent;
private global::Gtk.Table tblContent;
private global::Gtk.HBox hbox3;
private global::Gtk.Image imgContent;
private global::Gtk.Label lblContent;
private global::Gtk.Table tblSamples;
private global::Gtk.HBox hbox2;
private global::Gtk.Image imgSamples;
private global::Gtk.Label lblSamples;
private global::Gtk.Table tblTwitt;
private global::Gtk.Button btnTwitLoad;
private global::Gtk.Image imgTwiter;
private global::Gtk.Label lblTwiter;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget Moscrif.IDE.Components.StartEventControl
global::Stetic.BinContainer.Attach (this);
this.Name = "Moscrif.IDE.Components.StartEventControl";
// Container child Moscrif.IDE.Components.StartEventControl.Gtk.Container+ContainerChild
this.table1 = new global::Gtk.Table (((uint)(5)), ((uint)(3)), false);
this.table1.Name = "table1";
this.table1.RowSpacing = ((uint)(6));
this.table1.ColumnSpacing = ((uint)(6));
// Container child table1.Gtk.Table+TableChild
this.tblAction = new global::Gtk.Table (((uint)(6)), ((uint)(5)), false);
this.tblAction.Name = "tblAction";
this.tblAction.RowSpacing = ((uint)(6));
this.tblAction.ColumnSpacing = ((uint)(6));
// Container child tblAction.Gtk.Table+TableChild
this.hbox1 = new global::Gtk.HBox ();
this.hbox1.Name = "hbox1";
this.hbox1.Spacing = 6;
// Container child hbox1.Gtk.Box+BoxChild
this.imgActions = new global::Gtk.Image ();
this.imgActions.WidthRequest = 24;
this.imgActions.HeightRequest = 24;
this.imgActions.Name = "imgActions";
this.hbox1.Add (this.imgActions);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.imgActions]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child hbox1.Gtk.Box+BoxChild
this.lblActions = new global::Gtk.Label ();
this.lblActions.Name = "lblActions";
this.lblActions.Xalign = 0F;
this.lblActions.LabelProp = global::Mono.Unix.Catalog.GetString ("Actions");
this.hbox1.Add (this.lblActions);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.lblActions]));
w2.Position = 1;
w2.Expand = false;
w2.Fill = false;
this.tblAction.Add (this.hbox1);
global::Gtk.Table.TableChild w3 = ((global::Gtk.Table.TableChild)(this.tblAction [this.hbox1]));
w3.RightAttach = ((uint)(5));
w3.XOptions = ((global::Gtk.AttachOptions)(4));
w3.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child tblAction.Gtk.Table+TableChild
this.lblAccount = new global::Gtk.Label ();
this.lblAccount.Name = "lblAccount";
this.lblAccount.LabelProp = global::Mono.Unix.Catalog.GetString ("Account");
this.tblAction.Add (this.lblAccount);
global::Gtk.Table.TableChild w4 = ((global::Gtk.Table.TableChild)(this.tblAction [this.lblAccount]));
w4.TopAttach = ((uint)(1));
w4.BottomAttach = ((uint)(2));
w4.LeftAttach = ((uint)(3));
w4.RightAttach = ((uint)(4));
w4.XOptions = ((global::Gtk.AttachOptions)(4));
w4.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child tblAction.Gtk.Table+TableChild
this.lblProject = new global::Gtk.Label ();
this.lblProject.Name = "lblProject";
this.lblProject.LabelProp = global::Mono.Unix.Catalog.GetString ("Project");
this.tblAction.Add (this.lblProject);
global::Gtk.Table.TableChild w5 = ((global::Gtk.Table.TableChild)(this.tblAction [this.lblProject]));
w5.TopAttach = ((uint)(1));
w5.BottomAttach = ((uint)(2));
w5.LeftAttach = ((uint)(1));
w5.RightAttach = ((uint)(2));
w5.XOptions = ((global::Gtk.AttachOptions)(4));
w5.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child tblAction.Gtk.Table+TableChild
this.lblWorkspace = new global::Gtk.Label ();
this.lblWorkspace.Name = "lblWorkspace";
this.lblWorkspace.LabelProp = global::Mono.Unix.Catalog.GetString ("Workspace");
this.tblAction.Add (this.lblWorkspace);
global::Gtk.Table.TableChild w6 = ((global::Gtk.Table.TableChild)(this.tblAction [this.lblWorkspace]));
w6.TopAttach = ((uint)(1));
w6.BottomAttach = ((uint)(2));
w6.XOptions = ((global::Gtk.AttachOptions)(4));
w6.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child tblAction.Gtk.Table+TableChild
this.lbRecent = new global::Gtk.Label ();
this.lbRecent.Name = "lbRecent";
this.lbRecent.LabelProp = global::Mono.Unix.Catalog.GetString ("Recent");
this.tblAction.Add (this.lbRecent);
global::Gtk.Table.TableChild w7 = ((global::Gtk.Table.TableChild)(this.tblAction [this.lbRecent]));
w7.TopAttach = ((uint)(1));
w7.BottomAttach = ((uint)(2));
w7.LeftAttach = ((uint)(2));
w7.RightAttach = ((uint)(3));
w7.XOptions = ((global::Gtk.AttachOptions)(4));
w7.YOptions = ((global::Gtk.AttachOptions)(4));
this.table1.Add (this.tblAction);
global::Gtk.Table.TableChild w8 = ((global::Gtk.Table.TableChild)(this.table1 [this.tblAction]));
w8.TopAttach = ((uint)(1));
w8.BottomAttach = ((uint)(2));
w8.RightAttach = ((uint)(2));
w8.XPadding = ((uint)(10));
w8.XOptions = ((global::Gtk.AttachOptions)(4));
w8.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.tblContent = new global::Gtk.Table (((uint)(2)), ((uint)(6)), false);
this.tblContent.HeightRequest = 60;
this.tblContent.Name = "tblContent";
this.tblContent.RowSpacing = ((uint)(6));
this.tblContent.ColumnSpacing = ((uint)(6));
// Container child tblContent.Gtk.Table+TableChild
this.hbox3 = new global::Gtk.HBox ();
this.hbox3.Name = "hbox3";
this.hbox3.Spacing = 6;
// Container child hbox3.Gtk.Box+BoxChild
this.imgContent = new global::Gtk.Image ();
this.imgContent.WidthRequest = 24;
this.imgContent.HeightRequest = 24;
this.imgContent.Name = "imgContent";
this.hbox3.Add (this.imgContent);
global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.imgContent]));
w9.Position = 0;
w9.Expand = false;
w9.Fill = false;
// Container child hbox3.Gtk.Box+BoxChild
this.lblContent = new global::Gtk.Label ();
this.lblContent.Name = "lblContent";
this.lblContent.Xalign = 0F;
this.lblContent.LabelProp = global::Mono.Unix.Catalog.GetString ("Content");
this.hbox3.Add (this.lblContent);
global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.hbox3 [this.lblContent]));
w10.Position = 1;
w10.Expand = false;
w10.Fill = false;
this.tblContent.Add (this.hbox3);
global::Gtk.Table.TableChild w11 = ((global::Gtk.Table.TableChild)(this.tblContent [this.hbox3]));
w11.RightAttach = ((uint)(6));
w11.YOptions = ((global::Gtk.AttachOptions)(4));
this.table1.Add (this.tblContent);
global::Gtk.Table.TableChild w12 = ((global::Gtk.Table.TableChild)(this.table1 [this.tblContent]));
w12.TopAttach = ((uint)(3));
w12.BottomAttach = ((uint)(4));
w12.XPadding = ((uint)(10));
w12.XOptions = ((global::Gtk.AttachOptions)(4));
w12.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.tblSamples = new global::Gtk.Table (((uint)(2)), ((uint)(6)), false);
this.tblSamples.Name = "tblSamples";
this.tblSamples.RowSpacing = ((uint)(6));
this.tblSamples.ColumnSpacing = ((uint)(6));
// Container child tblSamples.Gtk.Table+TableChild
this.hbox2 = new global::Gtk.HBox ();
this.hbox2.Name = "hbox2";
this.hbox2.Spacing = 6;
// Container child hbox2.Gtk.Box+BoxChild
this.imgSamples = new global::Gtk.Image ();
this.imgSamples.WidthRequest = 24;
this.imgSamples.HeightRequest = 24;
this.imgSamples.Name = "imgSamples";
this.hbox2.Add (this.imgSamples);
global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.imgSamples]));
w13.Position = 0;
w13.Expand = false;
w13.Fill = false;
// Container child hbox2.Gtk.Box+BoxChild
this.lblSamples = new global::Gtk.Label ();
this.lblSamples.Name = "lblSamples";
this.lblSamples.Xalign = 0F;
this.lblSamples.LabelProp = global::Mono.Unix.Catalog.GetString ("Samples");
this.hbox2.Add (this.lblSamples);
global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.lblSamples]));
w14.Position = 1;
w14.Expand = false;
w14.Fill = false;
this.tblSamples.Add (this.hbox2);
global::Gtk.Table.TableChild w15 = ((global::Gtk.Table.TableChild)(this.tblSamples [this.hbox2]));
w15.RightAttach = ((uint)(6));
w15.YOptions = ((global::Gtk.AttachOptions)(4));
this.table1.Add (this.tblSamples);
global::Gtk.Table.TableChild w16 = ((global::Gtk.Table.TableChild)(this.table1 [this.tblSamples]));
w16.TopAttach = ((uint)(2));
w16.BottomAttach = ((uint)(3));
w16.RightAttach = ((uint)(2));
w16.XPadding = ((uint)(10));
w16.XOptions = ((global::Gtk.AttachOptions)(4));
w16.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child table1.Gtk.Table+TableChild
this.tblTwitt = new global::Gtk.Table (((uint)(6)), ((uint)(2)), false);
this.tblTwitt.WidthRequest = 0;
this.tblTwitt.Name = "tblTwitt";
this.tblTwitt.RowSpacing = ((uint)(6));
this.tblTwitt.ColumnSpacing = ((uint)(6));
// Container child tblTwitt.Gtk.Table+TableChild
this.btnTwitLoad = new global::Gtk.Button ();
this.btnTwitLoad.WidthRequest = 250;
this.btnTwitLoad.Sensitive = false;
this.btnTwitLoad.CanFocus = true;
this.btnTwitLoad.Name = "btnTwitLoad";
this.btnTwitLoad.UseUnderline = true;
this.btnTwitLoad.Relief = ((global::Gtk.ReliefStyle)(2));
this.btnTwitLoad.Label = "";
this.tblTwitt.Add (this.btnTwitLoad);
global::Gtk.Table.TableChild w17 = ((global::Gtk.Table.TableChild)(this.tblTwitt [this.btnTwitLoad]));
w17.TopAttach = ((uint)(1));
w17.BottomAttach = ((uint)(2));
w17.RightAttach = ((uint)(2));
w17.XOptions = ((global::Gtk.AttachOptions)(4));
w17.YOptions = ((global::Gtk.AttachOptions)(4));
// Container child tblTwitt.Gtk.Table+TableChild
this.imgTwiter = new global::Gtk.Image ();
this.imgTwiter.WidthRequest = 24;
this.imgTwiter.HeightRequest = 24;
this.imgTwiter.Name = "imgTwiter";
this.tblTwitt.Add (this.imgTwiter);
global::Gtk.Table.TableChild w18 = ((global::Gtk.Table.TableChild)(this.tblTwitt [this.imgTwiter]));
w18.XOptions = ((global::Gtk.AttachOptions)(0));
w18.YOptions = ((global::Gtk.AttachOptions)(0));
// Container child tblTwitt.Gtk.Table+TableChild
this.lblTwiter = new global::Gtk.Label ();
this.lblTwiter.Name = "lblTwiter";
this.lblTwiter.Xalign = 0F;
this.lblTwiter.LabelProp = global::Mono.Unix.Catalog.GetString ("Twitter");
this.tblTwitt.Add (this.lblTwiter);
global::Gtk.Table.TableChild w19 = ((global::Gtk.Table.TableChild)(this.tblTwitt [this.lblTwiter]));
w19.LeftAttach = ((uint)(1));
w19.RightAttach = ((uint)(2));
w19.YOptions = ((global::Gtk.AttachOptions)(4));
this.table1.Add (this.tblTwitt);
global::Gtk.Table.TableChild w20 = ((global::Gtk.Table.TableChild)(this.table1 [this.tblTwitt]));
w20.XPadding = ((uint)(10));
w20.YPadding = ((uint)(10));
w20.XOptions = ((global::Gtk.AttachOptions)(0));
w20.YOptions = ((global::Gtk.AttachOptions)(4));
this.Add (this.table1);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.Hide ();
}
}
}
| |
/* DO NOT EDIT: automatically built by dist/s_csharp_const. */
namespace BerkeleyDB.Internal {
internal class DbConstants {
internal const uint DB_AFTER = 1;
internal const uint DB_AGGRESSIVE = 0x00000001;
internal const uint DB_APPEND = 2;
internal const uint DB_ARCH_ABS = 0x00000001;
internal const uint DB_ARCH_DATA = 0x00000002;
internal const uint DB_ARCH_LOG = 0x00000004;
internal const uint DB_ARCH_REMOVE = 0x00000008;
internal const uint DB_AUTO_COMMIT = 0x00000100;
internal const uint DB_BEFORE = 3;
internal const uint DB_BTREE = 1;
internal const int DB_BUFFER_SMALL = -30999;
internal const uint DB_CDB_ALLDB = 0x00000040;
internal const uint DB_CHKSUM = 0x00000008;
internal const uint DB_CONSUME = 4;
internal const uint DB_CONSUME_WAIT = 5;
internal const uint DB_CREATE = 0x00000001;
internal const uint DB_CURRENT = 6;
internal const uint DB_CURSOR_BULK = 0x00000001;
internal const uint DB_DBT_APPMALLOC = 0x001;
internal const uint DB_DBT_BULK = 0x002;
internal const uint DB_DBT_MALLOC = 0x010;
internal const uint DB_DBT_MULTIPLE = 0x020;
internal const uint DB_DBT_PARTIAL = 0x040;
internal const uint DB_DBT_REALLOC = 0x080;
internal const uint DB_DBT_USERCOPY = 0x200;
internal const uint DB_DBT_USERMEM = 0x400;
internal const uint DB_DIRECT_DB = 0x00000080;
internal const int DB_DONOTINDEX = -30998;
internal const uint DB_DSYNC_DB = 0x00000200;
internal const uint DB_DUP = 0x00000010;
internal const uint DB_DUPSORT = 0x00000004;
internal const int DB_EID_BROADCAST = -1;
internal const int DB_EID_INVALID = -2;
internal const uint DB_ENCRYPT = 0x00000001;
internal const uint DB_ENCRYPT_AES = 0x00000001;
internal const uint DB_EVENT_PANIC = 0;
internal const uint DB_EVENT_REP_CLIENT = 3;
internal const uint DB_EVENT_REP_DUPMASTER = 4;
internal const uint DB_EVENT_REP_ELECTED = 5;
internal const uint DB_EVENT_REP_ELECTION_FAILED = 6;
internal const uint DB_EVENT_REP_JOIN_FAILURE = 7;
internal const uint DB_EVENT_REP_MASTER = 8;
internal const uint DB_EVENT_REP_MASTER_FAILURE = 9;
internal const uint DB_EVENT_REP_NEWMASTER = 10;
internal const uint DB_EVENT_REP_PERM_FAILED = 11;
internal const uint DB_EVENT_REP_STARTUPDONE = 12;
internal const uint DB_EVENT_WRITE_FAILED = 13;
internal const uint DB_EXCL = 0x00000040;
internal const uint DB_FAST_STAT = 0x00000001;
internal const uint DB_FIRST = 7;
internal const uint DB_FLUSH = 0x00000001;
internal const uint DB_FORCE = 0x00000001;
internal const uint DB_FORCESYNC = 0x00000001;
internal const uint DB_FOREIGN_ABORT = 0x00000001;
internal const uint DB_FOREIGN_CASCADE = 0x00000002;
internal const int DB_FOREIGN_CONFLICT = -30997;
internal const uint DB_FOREIGN_NULLIFY = 0x00000004;
internal const uint DB_FREELIST_ONLY = 0x00000001;
internal const uint DB_FREE_SPACE = 0x00000002;
internal const uint DB_GET_BOTH = 8;
internal const uint DB_GET_BOTH_RANGE = 10;
internal const uint DB_GET_RECNO = 11;
internal const uint DB_GID_SIZE = 128;
internal const uint DB_HASH = 2;
internal const uint DB_IGNORE_LEASE = 0x00001000;
internal const uint DB_IMMUTABLE_KEY = 0x00000002;
internal const uint DB_INIT_CDB = 0x00000040;
internal const uint DB_INIT_LOCK = 0x00000080;
internal const uint DB_INIT_LOG = 0x00000100;
internal const uint DB_INIT_MPOOL = 0x00000200;
internal const uint DB_INIT_REP = 0x00000400;
internal const uint DB_INIT_TXN = 0x00000800;
internal const uint DB_INORDER = 0x00000020;
internal const uint DB_JOINENV = 0x0;
internal const uint DB_JOIN_ITEM = 12;
internal const uint DB_JOIN_NOSORT = 0x00000001;
internal const int DB_KEYEMPTY = -30996;
internal const int DB_KEYEXIST = -30995;
internal const uint DB_KEYFIRST = 13;
internal const uint DB_KEYLAST = 14;
internal const uint DB_LAST = 15;
internal const uint DB_LOCKDOWN = 0x00001000;
internal const int DB_LOCK_DEADLOCK = -30994;
internal const uint DB_LOCK_DEFAULT = 1;
internal const uint DB_LOCK_EXPIRE = 2;
internal const uint DB_LOCK_GET = 1;
internal const uint DB_LOCK_GET_TIMEOUT = 2;
internal const uint DB_LOCK_IREAD = 5;
internal const uint DB_LOCK_IWR = 6;
internal const uint DB_LOCK_IWRITE = 4;
internal const uint DB_LOCK_MAXLOCKS = 3;
internal const uint DB_LOCK_MAXWRITE = 4;
internal const uint DB_LOCK_MINLOCKS = 5;
internal const uint DB_LOCK_MINWRITE = 6;
internal const int DB_LOCK_NOTGRANTED = -30993;
internal const uint DB_LOCK_NOWAIT = 0x00000001;
internal const uint DB_LOCK_OLDEST = 7;
internal const uint DB_LOCK_PUT = 4;
internal const uint DB_LOCK_PUT_ALL = 5;
internal const uint DB_LOCK_PUT_OBJ = 6;
internal const uint DB_LOCK_RANDOM = 8;
internal const uint DB_LOCK_READ = 1;
internal const uint DB_LOCK_TIMEOUT = 8;
internal const uint DB_LOCK_WRITE = 2;
internal const uint DB_LOCK_YOUNGEST = 9;
internal const uint DB_LOG_AUTO_REMOVE = 0x00000001;
internal const int DB_LOG_BUFFER_FULL = -30992;
internal const uint DB_LOG_DIRECT = 0x00000002;
internal const uint DB_LOG_DSYNC = 0x00000004;
internal const uint DB_LOG_IN_MEMORY = 0x00000008;
internal const uint DB_LOG_ZERO = 0x00000010;
internal const uint DB_MPOOL_NOFILE = 0x00000001;
internal const uint DB_MPOOL_UNLINK = 0x00000002;
internal const uint DB_MULTIPLE = 0x00000800;
internal const uint DB_MULTIPLE_KEY = 0x00004000;
internal const uint DB_MULTIVERSION = 0x00000004;
internal const uint DB_MUTEX_PROCESS_ONLY = 0x00000008;
internal const uint DB_MUTEX_SELF_BLOCK = 0x00000010;
internal const uint DB_NEXT = 16;
internal const uint DB_NEXT_DUP = 17;
internal const uint DB_NEXT_NODUP = 18;
internal const uint DB_NODUPDATA = 19;
internal const uint DB_NOLOCKING = 0x00000400;
internal const uint DB_NOMMAP = 0x00000008;
internal const uint DB_NOORDERCHK = 0x00000002;
internal const uint DB_NOOVERWRITE = 20;
internal const uint DB_NOPANIC = 0x00000800;
internal const int DB_NOSERVER = -30990;
internal const int DB_NOSERVER_HOME = -30989;
internal const int DB_NOSERVER_ID = -30988;
internal const uint DB_NOSYNC = 21;
internal const int DB_NOTFOUND = -30987;
internal const int DB_OLD_VERSION = -30986;
internal const uint DB_ORDERCHKONLY = 0x00000004;
internal const uint DB_OVERWRITE = 0x00001000;
internal const int DB_PAGE_NOTFOUND = -30985;
internal const uint DB_PANIC_ENVIRONMENT = 0x00002000;
internal const uint DB_POSITION = 23;
internal const uint DB_PREV = 24;
internal const uint DB_PREV_DUP = 25;
internal const uint DB_PREV_NODUP = 26;
internal const uint DB_PRINTABLE = 0x00000008;
internal const uint DB_PRIORITY_DEFAULT = 3;
internal const uint DB_PRIORITY_HIGH = 4;
internal const uint DB_PRIORITY_LOW = 2;
internal const uint DB_PRIORITY_VERY_HIGH = 5;
internal const uint DB_PRIORITY_VERY_LOW = 1;
internal const uint DB_PRIVATE = 0x00002000;
internal const uint DB_QUEUE = 4;
internal const uint DB_RDONLY = 0x00000400;
internal const uint DB_READ_COMMITTED = 0x00000400;
internal const uint DB_READ_UNCOMMITTED = 0x00000200;
internal const uint DB_RECNO = 3;
internal const uint DB_RECNUM = 0x00000040;
internal const uint DB_RECOVER = 0x00000002;
internal const uint DB_RECOVER_FATAL = 0x00004000;
internal const uint DB_REGION_INIT = 0x00004000;
internal const uint DB_REGISTER = 0x00008000;
internal const uint DB_RENUMBER = 0x00000080;
internal const int DB_REPMGR_ACKS_ALL = 1;
internal const int DB_REPMGR_ACKS_ALL_PEERS = 2;
internal const int DB_REPMGR_ACKS_NONE = 3;
internal const int DB_REPMGR_ACKS_ONE = 4;
internal const int DB_REPMGR_ACKS_ONE_PEER = 5;
internal const int DB_REPMGR_ACKS_QUORUM = 6;
internal const uint DB_REPMGR_CONF_2SITE_STRICT = 0x00000001;
internal const uint DB_REPMGR_CONF_ELECTIONS = 0x00000002;
internal const uint DB_REPMGR_CONNECTED = 1;
internal const uint DB_REPMGR_PEER = 0x00000001;
internal const int DB_REP_ACK_TIMEOUT = 1;
internal const uint DB_REP_ANYWHERE = 0x00000001;
internal const int DB_REP_CHECKPOINT_DELAY = 2;
internal const uint DB_REP_CLIENT = 0x00000001;
internal const uint DB_REP_CONF_AUTOINIT = 0x00000004;
internal const uint DB_REP_CONF_BULK = 0x00000008;
internal const uint DB_REP_CONF_DELAYCLIENT = 0x00000010;
internal const uint DB_REP_CONF_INMEM = 0x00000020;
internal const uint DB_REP_CONF_LEASE = 0x00000040;
internal const uint DB_REP_CONF_NOWAIT = 0x00000080;
internal const int DB_REP_CONNECTION_RETRY = 3;
internal const uint DB_REP_DEFAULT_PRIORITY = 100;
internal const int DB_REP_DUPMASTER = -30984;
internal const uint DB_REP_ELECTION = 0x00000004;
internal const int DB_REP_ELECTION_RETRY = 4;
internal const int DB_REP_ELECTION_TIMEOUT = 5;
internal const int DB_REP_FULL_ELECTION_TIMEOUT = 6;
internal const int DB_REP_HANDLE_DEAD = -30983;
internal const int DB_REP_HEARTBEAT_MONITOR = 7;
internal const int DB_REP_HEARTBEAT_SEND = 8;
internal const int DB_REP_HOLDELECTION = -30982;
internal const int DB_REP_IGNORE = -30981;
internal const int DB_REP_ISPERM = -30980;
internal const int DB_REP_JOIN_FAILURE = -30979;
internal const int DB_REP_LEASE_EXPIRED = -30978;
internal const int DB_REP_LEASE_TIMEOUT = 9;
internal const int DB_REP_LOCKOUT = -30977;
internal const uint DB_REP_MASTER = 0x00000002;
internal const int DB_REP_NEWSITE = -30976;
internal const uint DB_REP_NOBUFFER = 0x00000002;
internal const int DB_REP_NOTPERM = -30975;
internal const uint DB_REP_PERMANENT = 0x00000004;
internal const uint DB_REP_REREQUEST = 0x00000008;
internal const int DB_REP_UNAVAIL = -30974;
internal const uint DB_REVSPLITOFF = 0x00000100;
internal const uint DB_RMW = 0x00002000;
internal const uint DB_RPCCLIENT = 0x00000001;
internal const int DB_RUNRECOVERY = -30973;
internal const uint DB_SALVAGE = 0x00000040;
internal const int DB_SECONDARY_BAD = -30972;
internal const uint DB_SEQ_DEC = 0x00000001;
internal const uint DB_SEQ_INC = 0x00000002;
internal const uint DB_SEQ_WRAP = 0x00000008;
internal const uint DB_SET = 27;
internal const uint DB_SET_LOCK_TIMEOUT = 0x00000001;
internal const uint DB_SET_RANGE = 28;
internal const uint DB_SET_RECNO = 29;
internal const uint DB_SET_TXN_TIMEOUT = 0x00000002;
internal const uint DB_SNAPSHOT = 0x00000200;
internal const uint DB_STAT_ALL = 0x00000004;
internal const uint DB_STAT_CLEAR = 0x00000001;
internal const uint DB_STAT_LOCK_CONF = 0x00000008;
internal const uint DB_STAT_LOCK_LOCKERS = 0x00000010;
internal const uint DB_STAT_LOCK_OBJECTS = 0x00000020;
internal const uint DB_STAT_LOCK_PARAMS = 0x00000040;
internal const uint DB_STAT_MEMP_HASH = 0x00000008;
internal const uint DB_STAT_SUBSYSTEM = 0x00000002;
internal const uint DB_SYSTEM_MEM = 0x00010000;
internal const uint DB_THREAD = 0x00000010;
internal const int DB_TIMEOUT = -30971;
internal const uint DB_TIME_NOTGRANTED = 0x00008000;
internal const uint DB_TRUNCATE = 0x00008000;
internal const uint DB_TXN_ABORT = 0;
internal const uint DB_TXN_APPLY = 1;
internal const uint DB_TXN_BACKWARD_ROLL = 3;
internal const uint DB_TXN_FORWARD_ROLL = 4;
internal const uint DB_TXN_NOSYNC = 0x00000001;
internal const uint DB_TXN_NOT_DURABLE = 0x00000002;
internal const uint DB_TXN_NOWAIT = 0x00000010;
internal const uint DB_TXN_PRINT = 7;
internal const uint DB_TXN_SNAPSHOT = 0x00000002;
internal const uint DB_TXN_SYNC = 0x00000004;
internal const uint DB_TXN_WAIT = 0x00000040;
internal const uint DB_TXN_WRITE_NOSYNC = 0x00000020;
internal const uint DB_TXN_TOKEN_SIZE = 20;
internal const uint DB_UNKNOWN = 5;
internal const uint DB_UPGRADE = 0x00000001;
internal const uint DB_USE_ENVIRON = 0x00000004;
internal const uint DB_USE_ENVIRON_ROOT = 0x00000008;
internal const uint DB_VERB_DEADLOCK = 0x00000001;
internal const uint DB_VERB_FILEOPS = 0x00000002;
internal const uint DB_VERB_FILEOPS_ALL = 0x00000004;
internal const uint DB_VERB_RECOVERY = 0x00000008;
internal const uint DB_VERB_REGISTER = 0x00000010;
internal const uint DB_VERB_REPLICATION = 0x00000020;
internal const uint DB_VERB_REPMGR_CONNFAIL = 0x00000040;
internal const uint DB_VERB_REPMGR_MISC = 0x00000080;
internal const uint DB_VERB_REP_ELECT = 0x00000100;
internal const uint DB_VERB_REP_LEASE = 0x00000200;
internal const uint DB_VERB_REP_MISC = 0x00000400;
internal const uint DB_VERB_REP_MSGS = 0x00000800;
internal const uint DB_VERB_REP_SYNC = 0x00001000;
internal const uint DB_VERB_REP_SYSTEM = 0x00002000;
internal const uint DB_VERB_REP_TEST = 0x00004000;
internal const uint DB_VERB_WAITSFOR = 0x00008000;
internal const uint DB_VERIFY = 0x00000002;
internal const int DB_VERIFY_BAD = -30970;
internal const uint DB_VERSION_FAMILY = 11;
internal const string DB_VERSION_FAMILY_STR = "11";
internal const uint DB_VERSION_RELEASE = 2;
internal const string DB_VERSION_RELEASE_STR = "2";
internal const uint DB_VERSION_MAJOR = 5;
internal const string DB_VERSION_MAJOR_STR = "5";
internal const uint DB_VERSION_MINOR = 0;
internal const string DB_VERSION_MINOR_STR = "0";
internal const int DB_VERSION_MISMATCH = -30969;
internal const uint DB_VERSION_PATCH = 11;
internal const string DB_VERSION_PATCH_STR = "11";
internal const string DB_VERSION_STRING = "Berkeley DB 5.0.11: March 15 2010 ";
internal const string DB_VERSION_FULL_STRING = "Berkeley DB 11g Release 2 library version 11.2.5.0.11: March 15 2010 ";
internal const uint DB_WRITECURSOR = 0x00000008;
internal const uint DB_YIELDCPU = 0x00010000;
internal const uint DB_USERCOPY_GETDATA = 0x00000001;
internal const uint DB_USERCOPY_SETDATA = 0x00000002;
}
}
// end of DbConstants.cs
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Orleans.Runtime
{
// This is the public interface to be used by the consistent ring
public interface IRingRange
{
/// <summary>
/// Check if <paramref name="n"/> is our responsibility to serve
/// </summary>
/// <param name="id"></param>
/// <returns>true if the reminder is in our responsibility range, false otherwise</returns>
bool InRange(uint n);
bool InRange(GrainReference grainReference);
}
// This is the internal interface to be used only by the different range implementations.
internal interface IRingRangeInternal : IRingRange
{
long RangeSize();
double RangePercentage();
string ToFullString();
}
[Serializable]
internal class SingleRange : IRingRangeInternal, IEquatable<SingleRange>
{
private readonly uint begin;
private readonly uint end;
/// <summary>
/// Exclusive
/// </summary>
public uint Begin { get { return begin; } }
/// <summary>
/// Inclusive
/// </summary>
public uint End { get { return end; } }
public SingleRange(uint begin, uint end)
{
this.begin = begin;
this.end = end;
}
public bool InRange(GrainReference grainReference)
{
return InRange(grainReference.GetUniformHashCode());
}
/// <summary>
/// checks if n is element of (Begin, End], while remembering that the ranges are on a ring
/// </summary>
/// <param name="n"></param>
/// <returns>true if n is in (Begin, End], false otherwise</returns>
public bool InRange(uint n)
{
uint num = n;
if (begin < end)
{
return num > begin && num <= end;
}
// Begin > End
return num > begin || num <= end;
}
public long RangeSize()
{
if (begin < end)
{
return end - begin;
}
return RangeFactory.RING_SIZE - (begin - end);
}
public double RangePercentage()
{
return ((double)RangeSize() / (double)RangeFactory.RING_SIZE) * ((double)100.0);
}
#region IEquatable<SingleRange> Members
public bool Equals(SingleRange other)
{
return other != null && begin == other.begin && end == other.end;
}
#endregion
public override bool Equals(object obj)
{
return Equals(obj as SingleRange);
}
public override int GetHashCode()
{
return (int)(begin ^ end);
}
public override string ToString()
{
if (begin == 0 && end == 0)
{
return String.Format("<(0 0], Size=x{0,8:X8}, %Ring={1:0.000}%>", RangeSize(), RangePercentage());
}
return String.Format("<(x{0,8:X8} x{1,8:X8}], Size=x{2,8:X8}, %Ring={3:0.000}%>", begin, end, RangeSize(), RangePercentage());
}
public string ToCompactString()
{
return ToString();
}
public string ToFullString()
{
return ToString();
}
}
internal static class RangeFactory
{
public const long RING_SIZE = ((long)uint.MaxValue) + 1;
public static IRingRange CreateFullRange()
{
return new SingleRange(0, 0);
}
public static IRingRange CreateRange(uint begin, uint end)
{
return new SingleRange(begin, end);
}
public static IRingRange CreateRange(List<IRingRange> inRanges)
{
return new GeneralMultiRange(inRanges);
}
public static EquallyDividedMultiRange CreateEquallyDividedMultiRange(IRingRange range, int numSubRanges)
{
return new EquallyDividedMultiRange(range, numSubRanges);
}
public static IEnumerable<SingleRange> GetSubRanges(IRingRange range)
{
if (range is SingleRange)
{
return new SingleRange[] { (SingleRange)range };
}
else if (range is GeneralMultiRange)
{
return ((GeneralMultiRange)range).Ranges;
}
return null;
}
}
[Serializable]
internal class GeneralMultiRange : IRingRangeInternal
{
private readonly List<SingleRange> ranges;
private readonly long rangeSize;
private readonly double rangePercentage;
internal IEnumerable<SingleRange> Ranges { get { return ranges; } }
internal GeneralMultiRange(IEnumerable<IRingRange> inRanges)
{
ranges = inRanges.Cast<SingleRange>().ToList();
if (ranges.Count == 0)
{
rangeSize = 0;
rangePercentage = 0;
}
else
{
rangeSize = ranges.Sum(r => r.RangeSize());
rangePercentage = ranges.Sum(r => r.RangePercentage());
}
}
public bool InRange(uint n)
{
foreach (IRingRange s in Ranges)
{
if (s.InRange(n)) return true;
}
return false;
}
public bool InRange(GrainReference grainReference)
{
return InRange(grainReference.GetUniformHashCode());
}
public long RangeSize()
{
return rangeSize;
}
public double RangePercentage()
{
return rangePercentage;
}
public override string ToString()
{
return ToCompactString();
}
public string ToCompactString()
{
if (ranges.Count == 0) return "Empty MultiRange";
if (ranges.Count == 1) return ranges[0].ToString();
return String.Format("<MultiRange: Size=x{0,8:X8}, %Ring={1:0.000}%>", RangeSize(), RangePercentage());
}
public string ToFullString()
{
if (ranges.Count == 0) return "Empty MultiRange";
if (ranges.Count == 1) return ranges[0].ToString();
return String.Format("<MultiRange: Size=x{0,8:X8}, %Ring={1:0.000}%, {2} Ranges: {3}>", RangeSize(), RangePercentage(), ranges.Count, Utils.EnumerableToString(ranges, r => r.ToFullString()));
}
}
[Serializable]
internal class EquallyDividedMultiRange
{
[Serializable]
private class EquallyDividedSingleRange
{
private readonly List<SingleRange> ranges;
internal EquallyDividedSingleRange(SingleRange singleRange, int numSubRanges)
{
ranges = new List<SingleRange>();
if (numSubRanges == 0) throw new ArgumentException("numSubRanges is 0.", "numSubRanges");
if (numSubRanges == 1)
{
ranges.Add(singleRange);
}
else
{
uint uNumSubRanges = checked((uint)numSubRanges);
uint portion = (uint)(singleRange.RangeSize() / uNumSubRanges);
uint remainder = (uint)(singleRange.RangeSize() - portion * uNumSubRanges);
uint start = singleRange.Begin;
for (uint i = 0; i < uNumSubRanges; i++)
{
// (Begin, End]
uint end = (unchecked(start + portion));
// I want it to overflow on purpose. It will do the right thing.
if (remainder > 0)
{
end++;
remainder--;
}
ranges.Add(new SingleRange(start, end));
start = end; // nextStart
}
}
}
internal SingleRange GetSubRange(int mySubRangeIndex)
{
return ranges[mySubRangeIndex];
}
}
private readonly Dictionary<int, IRingRangeInternal> multiRanges;
private readonly long rangeSize;
private readonly double rangePercentage;
// This class takes a range and devides it into X (x being numSubRanges) equal ranges.
public EquallyDividedMultiRange(IRingRange range, int numSubRanges)
{
multiRanges = new Dictionary<int, IRingRangeInternal>();
if (range is SingleRange)
{
var fullSingleRange = range as SingleRange;
var singleDevided = new EquallyDividedSingleRange(fullSingleRange, numSubRanges);
for (int i = 0; i < numSubRanges; i++)
{
var singleRange = singleDevided.GetSubRange(i);
multiRanges[i] = singleRange;
}
}
else if (range is GeneralMultiRange)
{
var fullMultiRange = range as GeneralMultiRange;
// Take each of the single ranges in the multi range and divide each into equal sub ranges.
// Then go over all those and group them by sub range index.
var allSinglesDevided = new List<EquallyDividedSingleRange>();
foreach (var singleRange in fullMultiRange.Ranges)
{
var singleDevided = new EquallyDividedSingleRange(singleRange, numSubRanges);
allSinglesDevided.Add(singleDevided);
}
for (int i = 0; i < numSubRanges; i++)
{
var singlesForThisIndex = new List<IRingRange>();
foreach (var singleDevided in allSinglesDevided)
{
IRingRange singleRange = singleDevided.GetSubRange(i);
singlesForThisIndex.Add(singleRange);
}
IRingRangeInternal multi = (IRingRangeInternal)RangeFactory.CreateRange(singlesForThisIndex);
multiRanges[i] = multi;
}
}
if (multiRanges.Count == 0)
{
rangeSize = 0;
rangePercentage = 0;
}
else
{
rangeSize = multiRanges.Values.Sum(r => r.RangeSize());
rangePercentage = multiRanges.Values.Sum(r => r.RangePercentage());
}
}
internal IRingRange GetSubRange(int mySubRangeIndex)
{
return multiRanges[mySubRangeIndex];
}
public override string ToString()
{
return ToCompactString();
}
public string ToCompactString()
{
if (multiRanges.Count == 0) return "Empty EquallyDevidedMultiRange";
if (multiRanges.Count == 1) return multiRanges.First().Value.ToString();
return String.Format("<EquallyDevidedMultiRange: Size=x{0,8:X8}, %Ring={1:0.000}%>", rangeSize, rangePercentage);
}
public string ToFullString()
{
if (multiRanges.Count == 0) return "Empty EquallyDevidedMultiRange";
if (multiRanges.Count == 1) return multiRanges.First().Value.ToFullString();
return String.Format("<EquallyDevidedMultiRange: Size=x{0,8:X8}, %Ring={1:0.000}%, {2} Ranges: {3}>", rangeSize, rangePercentage, multiRanges.Count,
Utils.DictionaryToString(multiRanges, r => r.ToFullString()));
}
}
}
| |
// 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.IO;
using System.Threading;
namespace System.Net.Security
{
//
// This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context.
// This file contains the private implementation.
//
public partial class NegotiateStream : AuthenticatedStream
{
private static AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback);
private static AsyncProtocolCallback s_readCallback = new AsyncProtocolCallback(ReadCallback);
private int _NestedWrite;
private int _NestedRead;
private byte[] _ReadHeader;
// Never updated directly, special properties are used.
private byte[] _InternalBuffer;
private int _InternalOffset;
private int _InternalBufferCount;
private FixedSizeReader _FrameReader;
private void InitializeStreamPart()
{
_ReadHeader = new byte[4];
_FrameReader = new FixedSizeReader(InnerStream);
}
private byte[] InternalBuffer
{
get
{
return _InternalBuffer;
}
}
private int InternalOffset
{
get
{
return _InternalOffset;
}
}
private int InternalBufferCount
{
get
{
return _InternalBufferCount;
}
}
private void DecrementInternalBufferCount(int decrCount)
{
_InternalOffset += decrCount;
_InternalBufferCount -= decrCount;
}
private void EnsureInternalBufferSize(int bytes)
{
_InternalBufferCount = bytes;
_InternalOffset = 0;
if (InternalBuffer == null || InternalBuffer.Length < bytes)
{
_InternalBuffer = new byte[bytes];
}
}
private void AdjustInternalBufferOffsetSize(int bytes, int offset)
{
_InternalBufferCount = bytes;
_InternalOffset = offset;
}
//
// Validates user parameters for all Read/Write methods.
//
private void ValidateParameters(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (count > buffer.Length - offset)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.net_offset_plus_count);
}
}
//
// Combined sync/async write method. For sync request asyncRequest==null.
//
private void ProcessWrite(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
ValidateParameters(buffer, offset, count);
if (Interlocked.Exchange(ref _NestedWrite, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncRequest != null ? "BeginWrite" : "Write"), "write"));
}
bool failed = false;
try
{
StartWriting(buffer, offset, count, asyncRequest);
}
catch (Exception e)
{
failed = true;
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_write, e);
}
finally
{
if (asyncRequest == null || failed)
{
_NestedWrite = 0;
}
}
}
private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
// We loop to this method from the callback.
// If the last chunk was just completed from async callback (count < 0), we complete user request.
if (count >= 0)
{
byte[] outBuffer = null;
do
{
int chunkBytes = Math.Min(count, NegoState.MaxWriteDataSize);
int encryptedBytes;
try
{
encryptedBytes = _negoState.EncryptData(buffer, offset, chunkBytes, ref outBuffer);
}
catch (Exception e)
{
throw new IOException(SR.net_io_encrypt, e);
}
if (asyncRequest != null)
{
// prepare for the next request
asyncRequest.SetNextRequest(buffer, offset + chunkBytes, count - chunkBytes, null);
IAsyncResult ar = InnerStream.BeginWrite(outBuffer, 0, encryptedBytes, s_writeCallback, asyncRequest);
if (!ar.CompletedSynchronously)
{
return;
}
InnerStream.EndWrite(ar);
}
else
{
InnerStream.Write(outBuffer, 0, encryptedBytes);
}
offset += chunkBytes;
count -= chunkBytes;
} while (count != 0);
}
if (asyncRequest != null)
{
asyncRequest.CompleteUser();
}
}
//
// Combined sync/async read method. For sync request asyncRequest==null.
// There is a little overhead because we need to pass buffer/offset/count used only in sync.
// Still the benefit is that we have a common sync/async code path.
//
private int ProcessRead(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
ValidateParameters(buffer, offset, count);
if (Interlocked.Exchange(ref _NestedRead, 1) == 1)
{
throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncRequest != null ? "BeginRead" : "Read"), "read"));
}
bool failed = false;
try
{
if (InternalBufferCount != 0)
{
int copyBytes = InternalBufferCount > count ? count : InternalBufferCount;
if (copyBytes != 0)
{
Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, copyBytes);
DecrementInternalBufferCount(copyBytes);
}
if (asyncRequest != null)
{
asyncRequest.CompleteUser((object)copyBytes);
}
return copyBytes;
}
// Performing actual I/O.
return StartReading(buffer, offset, count, asyncRequest);
}
catch (Exception e)
{
failed = true;
if (e is IOException)
{
throw;
}
throw new IOException(SR.net_io_read, e);
}
finally
{
if (asyncRequest == null || failed)
{
_NestedRead = 0;
}
}
}
//
// To avoid recursion when 0 bytes have been decrypted, loop until decryption results in at least 1 byte.
//
private int StartReading(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
int result;
// When we read -1 bytes means we have decrypted 0 bytes, need looping.
while ((result = StartFrameHeader(buffer, offset, count, asyncRequest)) == -1);
return result;
}
private int StartFrameHeader(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
int readBytes = 0;
if (asyncRequest != null)
{
asyncRequest.SetNextRequest(_ReadHeader, 0, _ReadHeader.Length, s_readCallback);
_FrameReader.AsyncReadPacket(asyncRequest);
if (!asyncRequest.MustCompleteSynchronously)
{
return 0;
}
readBytes = asyncRequest.Result;
}
else
{
readBytes = _FrameReader.ReadPacket(_ReadHeader, 0, _ReadHeader.Length);
}
return StartFrameBody(readBytes, buffer, offset, count, asyncRequest);
}
private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
if (readBytes == 0)
{
//EOF
if (asyncRequest != null)
{
asyncRequest.CompleteUser((object)0);
}
return 0;
}
if (!(readBytes == _ReadHeader.Length))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("NegoStream::ProcessHeader()|Frame size must be 4 but received {0} bytes.", readBytes);
}
Debug.Fail("NegoStream::ProcessHeader()|Frame size must be 4 but received " + readBytes + " bytes.");
}
// Replace readBytes with the body size recovered from the header content.
readBytes = _ReadHeader[3];
readBytes = (readBytes << 8) | _ReadHeader[2];
readBytes = (readBytes << 8) | _ReadHeader[1];
readBytes = (readBytes << 8) | _ReadHeader[0];
//
// The body carries 4 bytes for trailer size slot plus trailer, hence <=4 frame size is always an error.
// Additionally we'd like to restrict the read frame size to 64k.
//
if (readBytes <= 4 || readBytes > NegoState.MaxReadFrameSize)
{
throw new IOException(SR.net_frame_read_size);
}
//
// Always pass InternalBuffer for SSPI "in place" decryption.
// A user buffer can be shared by many threads in that case decryption/integrity check may fail cause of data corruption.
//
EnsureInternalBufferSize(readBytes);
if (asyncRequest != null)
{
asyncRequest.SetNextRequest(InternalBuffer, 0, readBytes, s_readCallback);
_FrameReader.AsyncReadPacket(asyncRequest);
if (!asyncRequest.MustCompleteSynchronously)
{
return 0;
}
readBytes = asyncRequest.Result;
}
else //Sync
{
readBytes = _FrameReader.ReadPacket(InternalBuffer, 0, readBytes);
}
return ProcessFrameBody(readBytes, buffer, offset, count, asyncRequest);
}
private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
if (readBytes == 0)
{
// We already checked that the frame body is bigger than 0 bytes
// Hence, this is an EOF ... fire.
throw new IOException(SR.net_io_eof);
}
// Decrypt into internal buffer, change "readBytes" to count now _Decrypted Bytes_
int internalOffset;
readBytes = _negoState.DecryptData(InternalBuffer, 0, readBytes, out internalOffset);
// Decrypted data start from zero offset, the size can be shrunk after decryption.
AdjustInternalBufferOffsetSize(readBytes, internalOffset);
if (readBytes == 0 && count != 0)
{
// Read again.
return -1;
}
if (readBytes > count)
{
readBytes = count;
}
Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, readBytes);
// This will adjust both the remaining internal buffer count and the offset.
DecrementInternalBufferCount(readBytes);
if (asyncRequest != null)
{
asyncRequest.CompleteUser((object)readBytes);
}
return readBytes;
}
private static void WriteCallback(IAsyncResult transportResult)
{
if (transportResult.CompletedSynchronously)
{
return;
}
if (!(transportResult.AsyncState is AsyncProtocolRequest))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("NegotiateSteam::WriteCallback|State type is wrong, expected AsyncProtocolRequest.");
}
Debug.Fail("NegotiateSteam::WriteCallback|State type is wrong, expected AsyncProtocolRequest.");
}
AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState;
try
{
NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject;
negoStream.InnerStream.EndWrite(transportResult);
if (asyncRequest.Count == 0)
{
// This was the last chunk.
asyncRequest.Count = -1;
}
negoStream.StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest);
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
asyncRequest.CompleteWithError(e);
}
}
private static void ReadCallback(AsyncProtocolRequest asyncRequest)
{
// Async ONLY completion.
try
{
NegotiateStream negoStream = (NegotiateStream)asyncRequest.AsyncObject;
BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult;
// This is an optimization to avoid an additional callback.
if ((object)asyncRequest.Buffer == (object)negoStream._ReadHeader)
{
negoStream.StartFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest);
}
else
{
if (-1 == negoStream.ProcessFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest))
{
// In case we decrypted 0 bytes, start another reading.
negoStream.StartReading(bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest);
}
}
}
catch (Exception e)
{
if (asyncRequest.IsUserCompleted)
{
// This will throw on a worker thread.
throw;
}
asyncRequest.CompleteWithError(e);
}
}
}
}
| |
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Web;
using EnvDTE;
using Microsoft.NodejsTools.Debugger.Communication;
using Microsoft.NodejsTools.Debugger.Remote;
using Microsoft.NodejsTools.Logging;
using Microsoft.NodejsTools.Project;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools.Project;
using SR = Microsoft.NodejsTools.Project.SR;
namespace Microsoft.NodejsTools.Debugger.DebugEngine {
// AD7Engine is the primary entrypoint object for the debugging engine.
//
// It implements:
//
// IDebugEngine2: This interface represents a debug engine (DE). It is used to manage various aspects of a debugging session,
// from creating breakpoints to setting and clearing exceptions.
//
// IDebugEngineLaunch2: Used by a debug engine (DE) to launch and terminate programs.
//
// IDebugProgram3: This interface represents a program that is running in a process. Since this engine only debugs one process at a time and each
// process only contains one program, it is implemented on the engine.
[ComVisible(true)]
[Guid(Guids.DebugEngine)]
public sealed class AD7Engine : IDebugEngine2, IDebugEngineLaunch2, IDebugProgram3, IDebugSymbolSettings100 {
// used to send events to the debugger. Some examples of these events are thread create, exception thrown, module load.
private IDebugEventCallback2 _events;
// The core of the engine is implemented by NodeDebugger - we wrap and expose that to VS.
private NodeDebugger _process;
// mapping between NodeThread threads and AD7Threads
private readonly Dictionary<NodeThread, AD7Thread> _threads = new Dictionary<NodeThread, AD7Thread>();
private readonly Dictionary<NodeModule, AD7Module> _modules = new Dictionary<NodeModule, AD7Module>();
private AD7Thread _mainThread;
private bool _sdmAttached;
private bool _processLoaded;
private bool _processLoadedRunning;
private bool _loadComplete;
private readonly object _syncLock = new object();
private bool _attached;
private readonly AutoResetEvent _threadExitedEvent = new AutoResetEvent(false), _processExitedEvent = new AutoResetEvent(false);
private readonly BreakpointManager _breakpointManager;
private Guid _ad7ProgramId; // A unique identifier for the program being debugged.
private static readonly HashSet<WeakReference> Engines = new HashSet<WeakReference>();
private string _webBrowserUrl;
public const string DebugEngineId = "{0A638DAC-429B-4973-ADA0-E8DCDFB29B61}";
public static Guid DebugEngineGuid = new Guid(DebugEngineId);
private bool _trackFileChanges;
private DocumentEvents _documentEvents;
/// <summary>
/// Specifies whether the process should prompt for input before exiting on an abnormal exit.
/// </summary>
public const string WaitOnAbnormalExitSetting = "WAIT_ON_ABNORMAL_EXIT";
/// <summary>
/// Specifies whether the process should prompt for input before exiting on a normal exit.
/// </summary>
public const string WaitOnNormalExitSetting = "WAIT_ON_NORMAL_EXIT";
/// <summary>
/// Specifies if the output should be redirected to the visual studio output window.
/// </summary>
public const string RedirectOutputSetting = "REDIRECT_OUTPUT";
/// <summary>
/// Specifies options which should be passed to the Node runtime before the script. If
/// the interpreter options should include a semicolon then it should be escaped as a double
/// semi-colon.
/// </summary>
public const string InterpreterOptions = "INTERPRETER_OPTIONS";
/// <summary>
/// Specifies URL to which to open web browser on node debug connect.
/// </summary>
public const string WebBrowserUrl = "WEB_BROWSER_URL";
/// <summary>
/// Specifies the port to be used for the debugger.
/// </summary>
public const string DebuggerPort = "DEBUGGER_PORT";
/// <summary>
/// Specifies a directory mapping in the form of:
///
/// OldDir|NewDir
///
/// for mapping between the files on the local machine and the files deployed on the
/// running machine.
/// </summary>
public const string DirMappingSetting = "DIR_MAPPING";
public AD7Engine() {
LiveLogger.WriteLine("--------------------------------------------------------------------------------");
LiveLogger.WriteLine("AD7Engine Created ({0})", GetHashCode());
_breakpointManager = new BreakpointManager(this);
Engines.Add(new WeakReference(this));
}
~AD7Engine() {
LiveLogger.WriteLine("AD7Engine Finalized ({0})", GetHashCode());
if (!_attached && _process != null) {
// detach the process exited event, we don't need to send the exited event
// which could happen when we terminate the process and check if it's still
// running.
_process.ProcessExited -= OnProcessExited;
// we launched the process, go ahead and kill it now that
// VS has released us
_process.Terminate();
}
foreach (var engine in Engines) {
if (engine.Target == this) {
Engines.Remove(engine);
break;
}
}
}
internal static IList<AD7Engine> GetEngines() {
var engines = new List<AD7Engine>();
foreach (var engine in Engines) {
var target = (AD7Engine)engine.Target;
if (target != null) {
engines.Add(target);
}
}
return engines;
}
internal NodeDebugger Process {
get {
return _process;
}
}
internal AD7Thread MainThread {
get {
return _mainThread;
}
}
internal BreakpointManager BreakpointManager {
get {
return _breakpointManager;
}
}
#region IDebugEngine2 Members
// Attach the debug engine to a program.
int IDebugEngine2.Attach(IDebugProgram2[] rgpPrograms, IDebugProgramNode2[] rgpProgramNodes, uint celtPrograms, IDebugEventCallback2 ad7Callback, enum_ATTACH_REASON dwReason) {
DebugWriteCommand("Attach");
AssertMainThread();
Debug.Assert(_ad7ProgramId == Guid.Empty);
if (celtPrograms != 1) {
Debug.Fail("Node debugging only supports one program in a process");
throw new ArgumentException();
}
int processId = EngineUtils.GetProcessId(rgpPrograms[0]);
if (processId == 0) {
// engine only supports system processes
LiveLogger.WriteLine("AD7Engine failed to get process id during attach");
return VSConstants.E_NOTIMPL;
}
EngineUtils.RequireOk(rgpPrograms[0].GetProgramId(out _ad7ProgramId));
// Attach can either be called to attach to a new process, or to complete an attach
// to a launched process
if (_process == null) {
_events = ad7Callback;
var program = (NodeRemoteDebugProgram)rgpPrograms[0];
var process = program.DebugProcess;
var uri = process.DebugPort.Uri;
_process = new NodeDebugger(uri, process.Id);
// We only need to do fuzzy comparisons when debugging remotely
if (!uri.IsLoopback) {
_process.IsRemote = true;
_process.FileNameMapper = new FuzzyLogicFileNameMapper(EnumerateSolutionFiles());
}
AttachEvents(_process);
_attached = true;
} else {
if (processId != _process.Id) {
Debug.Fail("Asked to attach to a process while we are debugging");
return VSConstants.E_FAIL;
}
}
lock (_syncLock) {
_sdmAttached = true;
HandleLoadComplete();
}
LiveLogger.WriteLine("AD7Engine Attach returning S_OK");
return VSConstants.S_OK;
}
private void HandleLoadComplete() {
// Handle load complete once both sdm attached and process loaded
if (!_sdmAttached || !_processLoaded) {
return;
}
LiveLogger.WriteLine("Sending load complete ({0})", GetHashCode());
AD7EngineCreateEvent.Send(this);
AD7ProgramCreateEvent.Send(this);
foreach (var module in _modules.Values) {
SendModuleLoad(module);
}
foreach (var thread in _threads.Values) {
SendThreadCreate(thread);
}
lock (_syncLock) {
if (_processLoadedRunning) {
Send(new AD7LoadCompleteRunningEvent(), AD7LoadCompleteRunningEvent.IID, _mainThread);
} else {
Send(new AD7LoadCompleteEvent(), AD7LoadCompleteEvent.IID, _mainThread);
}
}
_loadComplete = true;
if (!String.IsNullOrWhiteSpace(_webBrowserUrl)) {
var uri = new Uri(_webBrowserUrl);
lock (_syncLock) {
OnPortOpenedHandler.CreateHandler(
uri.Port,
shortCircuitPredicate: () => !_processLoaded,
action: LaunchBrowserDebugger
);
}
}
}
private void SendThreadCreate(AD7Thread ad7Thread) {
Send(new AD7ThreadCreateEvent(), AD7ThreadCreateEvent.IID, ad7Thread);
}
private void SendModuleLoad(AD7Module ad7Module) {
var eventObject = new AD7ModuleLoadEvent(ad7Module, true /* this is a module load */);
// TODO: Bind breakpoints when the module loads
Send(eventObject, AD7ModuleLoadEvent.IID, null);
}
// Requests that all programs being debugged by this DE stop execution the next time one of their threads attempts to run.
// This is normally called in response to the user clicking on the pause button in the debugger.
// When the break is complete, an AsyncBreakComplete event will be sent back to the debugger.
int IDebugEngine2.CauseBreak() {
DebugWriteCommand("CauseBreak");
AssertMainThread();
return CauseBreak();
}
[Conditional("DEBUG")]
private static void AssertMainThread() {
//Debug.Assert(Worker.MainThreadId == Worker.CurrentThreadId);
}
// Called by the SDM to indicate that a synchronous debug event, previously sent by the DE to the SDM,
// was received and processed. The only event we send in this fashion is Program Destroy.
// It responds to that event by shutting down the engine.
int IDebugEngine2.ContinueFromSynchronousEvent(IDebugEvent2 eventObject) {
DebugWriteCommand("ContinueFromSynchronousEvent");
AssertMainThread();
if (eventObject is AD7ProgramDestroyEvent) {
var debuggedProcess = _process;
_events = null;
_process = null;
_ad7ProgramId = Guid.Empty;
_threads.Clear();
_modules.Clear();
if (_trackFileChanges) {
_documentEvents.DocumentSaved -= OnDocumentSaved;
_documentEvents = null;
}
debuggedProcess.Close();
} else {
Debug.Fail("Unknown synchronous event");
}
return VSConstants.S_OK;
}
// Creates a pending breakpoint in the engine. A pending breakpoint is contains all the information needed to bind a breakpoint to
// a location in the debuggee.
int IDebugEngine2.CreatePendingBreakpoint(IDebugBreakpointRequest2 pBpRequest, out IDebugPendingBreakpoint2 ppPendingBp) {
DebugWriteCommand("CreatePendingBreakpoint");
Debug.Assert(_breakpointManager != null);
ppPendingBp = null;
// Check whether breakpoint request for our language
var requestInfo = new BP_REQUEST_INFO[1];
EngineUtils.CheckOk(pBpRequest.GetRequestInfo(enum_BPREQI_FIELDS.BPREQI_LANGUAGE | enum_BPREQI_FIELDS.BPREQI_BPLOCATION, requestInfo));
if (requestInfo[0].guidLanguage != Guids.NodejsDebugLanguage &&
requestInfo[0].guidLanguage != Guids.ScriptDebugLanguage &&
requestInfo[0].guidLanguage != Guids.TypeScriptDebugLanguage) {
// Check whether breakpoint request for our "downloaded" script
// "Downloaded" script will have our IDebugDocument2
IDebugDocument2 debugDocument;
var debugDocumentPosition = Marshal.GetObjectForIUnknown(requestInfo[0].bpLocation.unionmember2) as IDebugDocumentPosition2;
if (debugDocumentPosition == null || VSConstants.S_OK != debugDocumentPosition.GetDocument(out debugDocument) || null == debugDocument as AD7Document) {
// Not ours
return VSConstants.E_FAIL;
}
}
_breakpointManager.CreatePendingBreakpoint(pBpRequest, out ppPendingBp);
return VSConstants.S_OK;
}
// Informs a DE that the program specified has been atypically terminated and that the DE should
// clean up all references to the program and send a program destroy event.
int IDebugEngine2.DestroyProgram(IDebugProgram2 pProgram) {
DebugWriteCommand("DestroyProgram");
// Tell the SDM that the engine knows that the program is exiting, and that the
// engine will send a program destroy. We do this because the Win32 debug api will always
// tell us that the process exited, and otherwise we have a race condition.
return (DebuggerConstants.E_PROGRAM_DESTROY_PENDING);
}
// Gets the GUID of the DE.
int IDebugEngine2.GetEngineId(out Guid guidEngine) {
DebugWriteCommand("GetEngineId");
guidEngine = DebugEngineGuid;
return VSConstants.S_OK;
}
private static ExceptionHitTreatment GetExceptionTreatment(enum_EXCEPTION_STATE exceptionState) {
if ((exceptionState & enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE) != 0) {
return ExceptionHitTreatment.BreakAlways;
}
// UNDONE Handle break on unhandled, once just my code is supported
// Node has a catch all, so there are no uncaught exceptions
// For now just break always or never
//if ((exceptionState & enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT) != 0)
//{
// return ExceptionHitTreatment.BreakOnUnhandled;
//}
return ExceptionHitTreatment.BreakNever;
}
private static void UpdateExceptionTreatment(
IEnumerable<EXCEPTION_INFO> exceptionInfos,
Action<ExceptionHitTreatment?, ICollection<KeyValuePair<string, ExceptionHitTreatment>>> updateExceptionTreatment
) {
ExceptionHitTreatment? defaultExceptionTreatment = null;
var exceptionTreatments = new List<KeyValuePair<string, ExceptionHitTreatment>>();
bool sendUpdate = false;
foreach (var exceptionInfo in exceptionInfos) {
if (exceptionInfo.guidType == DebugEngineGuid) {
sendUpdate = true;
if (exceptionInfo.bstrExceptionName == "Node.js Exceptions") {
defaultExceptionTreatment = GetExceptionTreatment(exceptionInfo.dwState);
} else {
exceptionTreatments.Add(new KeyValuePair<string, ExceptionHitTreatment>(exceptionInfo.bstrExceptionName, GetExceptionTreatment(exceptionInfo.dwState)));
}
}
}
if (sendUpdate) {
updateExceptionTreatment(defaultExceptionTreatment, exceptionTreatments);
}
}
int IDebugEngine2.RemoveAllSetExceptions(ref Guid guidType) {
DebugWriteCommand("RemoveAllSetExceptions");
if (guidType == DebugEngineGuid || guidType == Guid.Empty) {
_process.ClearExceptionTreatment();
}
return VSConstants.S_OK;
}
int IDebugEngine2.RemoveSetException(EXCEPTION_INFO[] pException) {
DebugWriteCommand("RemoveSetException");
UpdateExceptionTreatment(pException, _process.ClearExceptionTreatment);
return VSConstants.S_OK;
}
int IDebugEngine2.SetException(EXCEPTION_INFO[] pException) {
DebugWriteCommand("SetException");
UpdateExceptionTreatment(pException, _process.SetExceptionTreatment);
return VSConstants.S_OK;
}
// Sets the locale of the DE.
// This method is called by the session debug manager (SDM) to propagate the locale settings of the IDE so that
// strings returned by the DE are properly localized. The engine is not localized so this is not implemented.
int IDebugEngine2.SetLocale(ushort wLangId) {
DebugWriteCommand("SetLocale");
return VSConstants.S_OK;
}
// A metric is a registry value used to change a debug engine's behavior or to advertise supported functionality.
// This method can forward the call to the appropriate form of the Debugging SDK Helpers function, SetMetric.
int IDebugEngine2.SetMetric(string pszMetric, object varValue) {
DebugWriteCommand("SetMetric");
return VSConstants.S_OK;
}
// Sets the registry root currently in use by the DE. Different installations of Visual Studio can change where their registry information is stored
// This allows the debugger to tell the engine where that location is.
int IDebugEngine2.SetRegistryRoot(string pszRegistryRoot) {
DebugWriteCommand("SetRegistryRoot");
return VSConstants.S_OK;
}
#endregion
#region IDebugEngineLaunch2 Members
// Determines if a process can be terminated.
int IDebugEngineLaunch2.CanTerminateProcess(IDebugProcess2 process) {
DebugWriteCommand("CanTerminateProcess");
AssertMainThread();
Debug.Assert(_events != null);
Debug.Assert(_process != null);
int processId = EngineUtils.GetProcessId(process);
if (processId == _process.Id) {
return VSConstants.S_OK;
}
return VSConstants.S_FALSE;
}
// Launches a process by means of the debug engine.
// Normally, Visual Studio launches a program using the IDebugPortEx2::LaunchSuspended method and then attaches the debugger
// to the suspended program. However, there are circumstances in which the debug engine may need to launch a program
// (for example, if the debug engine is part of an interpreter and the program being debugged is an interpreted language),
// in which case Visual Studio uses the IDebugEngineLaunch2::LaunchSuspended method
// The IDebugEngineLaunch2::ResumeProcess method is called to start the process after the process has been successfully launched in a suspended state.
int IDebugEngineLaunch2.LaunchSuspended(string pszServer, IDebugPort2 port, string exe, string args, string dir, string env, string options, enum_LAUNCH_FLAGS launchFlags, uint hStdInput, uint hStdOutput, uint hStdError, IDebugEventCallback2 ad7Callback, out IDebugProcess2 process) {
LiveLogger.WriteLine("AD7Engine LaunchSuspended Called with flags '{0}' ({1})", launchFlags, GetHashCode());
AssertMainThread();
Debug.Assert(_events == null);
Debug.Assert(_process == null);
Debug.Assert(_ad7ProgramId == Guid.Empty);
_events = ad7Callback;
var debugOptions = NodeDebugOptions.None;
List<string[]> dirMapping = null;
string interpreterOptions = null;
ushort? debugPort = null;
if (options != null) {
var splitOptions = SplitOptions(options);
foreach (var optionSetting in splitOptions) {
var setting = optionSetting.Split(new[] { '=' }, 2);
if (setting.Length == 2) {
setting[1] = HttpUtility.UrlDecode(setting[1]);
switch (setting[0]) {
case WaitOnAbnormalExitSetting:
bool value;
if (Boolean.TryParse(setting[1], out value) && value) {
debugOptions |= NodeDebugOptions.WaitOnAbnormalExit;
}
break;
case WaitOnNormalExitSetting:
if (Boolean.TryParse(setting[1], out value) && value) {
debugOptions |= NodeDebugOptions.WaitOnNormalExit;
}
break;
case RedirectOutputSetting:
if (Boolean.TryParse(setting[1], out value) && value) {
debugOptions |= NodeDebugOptions.RedirectOutput;
}
break;
case DirMappingSetting:
string[] dirs = setting[1].Split('|');
if (dirs.Length == 2) {
if (dirMapping == null) {
dirMapping = new List<string[]>();
}
LiveLogger.WriteLine(String.Format("Mapping dir {0} to {1}", dirs[0], dirs[1]));
dirMapping.Add(dirs);
}
break;
case InterpreterOptions:
interpreterOptions = setting[1];
break;
case WebBrowserUrl:
_webBrowserUrl = setting[1];
break;
case DebuggerPort:
ushort dbgPortTmp;
if (ushort.TryParse(setting[1], out dbgPortTmp)) {
debugPort = dbgPortTmp;
}
break;
}
}
}
}
_process =
new NodeDebugger(
exe,
args,
dir,
env,
interpreterOptions,
debugOptions,
debugPort
);
_process.Start(false);
AttachEvents(_process);
var adProcessId = new AD_PROCESS_ID();
adProcessId.ProcessIdType = (uint)enum_AD_PROCESS_ID.AD_PROCESS_ID_SYSTEM;
adProcessId.dwProcessId = (uint)_process.Id;
EngineUtils.RequireOk(port.GetProcess(adProcessId, out process));
LiveLogger.WriteLine("AD7Engine LaunchSuspended returning S_OK");
Debug.Assert(process != null);
Debug.Assert(!_process.HasExited);
return VSConstants.S_OK;
}
private static IEnumerable<string> SplitOptions(string options) {
var res = new List<string>();
int lastStart = 0;
for (int i = 0; i < options.Length; i++) {
if (options[i] == ';') {
if (i < options.Length - 1 && options[i + 1] != ';') {
// valid option boundary
res.Add(options.Substring(lastStart, i - lastStart));
lastStart = i + 1;
} else {
i++;
}
}
}
if (options.Length - lastStart > 0) {
res.Add(options.Substring(lastStart, options.Length - lastStart));
}
return res;
}
// Resume a process launched by IDebugEngineLaunch2.LaunchSuspended
int IDebugEngineLaunch2.ResumeProcess(IDebugProcess2 process) {
DebugWriteCommand("ResumeProcess");
AssertMainThread();
if (_events == null) {
// process failed to start
LiveLogger.WriteLine("ResumeProcess fails, no events");
return VSConstants.E_FAIL;
}
Debug.Assert(_events != null);
Debug.Assert(_process != null);
Debug.Assert(_process != null);
Debug.Assert(_ad7ProgramId == Guid.Empty);
int processId = EngineUtils.GetProcessId(process);
if (processId != _process.Id) {
LiveLogger.WriteLine("ResumeProcess fails, wrong process");
return VSConstants.S_FALSE;
}
// Send a program node to the SDM. This will cause the SDM to turn around and call IDebugEngine2.Attach
// which will complete the hookup with AD7
IDebugPort2 port;
EngineUtils.RequireOk(process.GetPort(out port));
var defaultPort = (IDebugDefaultPort2)port;
IDebugPortNotify2 portNotify;
EngineUtils.RequireOk(defaultPort.GetPortNotify(out portNotify));
EngineUtils.RequireOk(portNotify.AddProgramNode(new AD7ProgramNode(_process.Id)));
if (_ad7ProgramId == Guid.Empty) {
LiveLogger.WriteLine("ResumeProcess fails, empty program guid");
Debug.Fail("Unexpected problem -- IDebugEngine2.Attach wasn't called");
return VSConstants.E_FAIL;
}
LiveLogger.WriteLine("ResumeProcess return S_OK");
return VSConstants.S_OK;
}
// This function is used to terminate a process that the engine launched
// The debugger will call IDebugEngineLaunch2::CanTerminateProcess before calling this method.
int IDebugEngineLaunch2.TerminateProcess(IDebugProcess2 process) {
DebugWriteCommand("TerminateProcess");
AssertMainThread();
Debug.Assert(_events != null);
Debug.Assert(_process != null);
int processId = EngineUtils.GetProcessId(process);
if (processId != _process.Id) {
return VSConstants.S_FALSE;
}
_process.Terminate();
return VSConstants.S_OK;
}
#endregion
#region IDebugProgram2 Members
// Determines if a debug engine (DE) can detach from the program.
public int CanDetach() {
DebugWriteCommand("CanDetach");
return VSConstants.S_OK;
}
// The debugger calls CauseBreak when the user clicks on the pause button in VS. The debugger should respond by entering
// breakmode.
public int CauseBreak() {
DebugWriteCommand("CauseBreak");
AssertMainThread();
_process.BreakAllAsync().Wait();
return VSConstants.S_OK;
}
// Continue is called from the SDM when it wants execution to continue in the debugee
// but have stepping state remain. An example is when a tracepoint is executed,
// and the debugger does not want to actually enter break mode.
public int Continue(IDebugThread2 pThread) {
AssertMainThread();
var thread = (AD7Thread)pThread;
DebugWriteCommand("Continue");
// TODO: How does this differ from ExecuteOnThread?
thread.GetDebuggedThread().Resume();
return VSConstants.S_OK;
}
// Detach is called when debugging is stopped and the process was attached to (as opposed to launched)
// or when one of the Detach commands are executed in the UI.
public int Detach() {
DebugWriteCommand("Detach");
AssertMainThread();
_breakpointManager.ClearBreakpointBindingResults();
_process.Detach();
// Before unregistering event handlers, make sure that we have received thread exit and process exit events,
// since we need to report these as AD7 events to VS to gracefully terminate the debugging session.
_threadExitedEvent.WaitOne(3000);
_processExitedEvent.WaitOne(3000);
DetachEvents(_process);
_ad7ProgramId = Guid.Empty;
return VSConstants.S_OK;
}
// Enumerates the code contexts for a given position in a source file.
public int EnumCodeContexts(IDebugDocumentPosition2 pDocPos, out IEnumDebugCodeContexts2 ppEnum) {
DebugWriteCommand("EnumCodeContexts");
string filename;
pDocPos.GetFileName(out filename);
TEXT_POSITION[] beginning = new TEXT_POSITION[1], end = new TEXT_POSITION[1];
pDocPos.GetRange(beginning, end);
ppEnum = new AD7CodeContextEnum(new[] { new AD7MemoryAddress(this, filename, (int)beginning[0].dwLine, (int)beginning[0].dwColumn) });
return VSConstants.S_OK;
}
// EnumCodePaths is used for the step-into specific feature -- right click on the current statment and decide which
// function to step into. This is not something that we support.
public int EnumCodePaths(string hint, IDebugCodeContext2 start, IDebugStackFrame2 frame, int fSource, out IEnumCodePaths2 pathEnum, out IDebugCodeContext2 safetyContext) {
DebugWriteCommand("EnumCodePaths");
pathEnum = null;
safetyContext = null;
return VSConstants.E_NOTIMPL;
}
// EnumModules is called by the debugger when it needs to enumerate the modules in the program.
public int EnumModules(out IEnumDebugModules2 ppEnum) {
DebugWriteCommand("EnumModules");
AssertMainThread();
var moduleObjects = new AD7Module[_modules.Count];
int i = 0;
foreach (var keyValue in _modules) {
var adModule = keyValue.Value;
moduleObjects[i++] = adModule;
}
ppEnum = new AD7ModuleEnum(moduleObjects);
return VSConstants.S_OK;
}
// EnumThreads is called by the debugger when it needs to enumerate the threads in the program.
public int EnumThreads(out IEnumDebugThreads2 ppEnum) {
DebugWriteCommand("EnumThreads");
AssertMainThread();
var threadObjects = new AD7Thread[_threads.Count];
int i = 0;
foreach (var keyValue in _threads) {
var adThread = keyValue.Value;
Debug.Assert(adThread != null);
threadObjects[i++] = adThread;
}
ppEnum = new AD7ThreadEnum(threadObjects);
return VSConstants.S_OK;
}
// The properties returned by this method are specific to the program. If the program needs to return more than one property,
// then the IDebugProperty2 object returned by this method is a container of additional properties and calling the
// IDebugProperty2::EnumChildren method returns a list of all properties.
// A program may expose any number and type of additional properties that can be described through the IDebugProperty2 interface.
// An IDE might display the additional program properties through a generic property browser user interface.
public int GetDebugProperty(out IDebugProperty2 ppProperty) {
DebugWriteCommand("GetDebugProperty");
throw new Exception("The method or operation is not implemented.");
}
// The debugger calls this when it needs to obtain the IDebugDisassemblyStream2 for a particular code-context.
public int GetDisassemblyStream(enum_DISASSEMBLY_STREAM_SCOPE dwScope, IDebugCodeContext2 codeContext, out IDebugDisassemblyStream2 disassemblyStream) {
DebugWriteCommand("GetDisassemblyStream");
disassemblyStream = null;
return VSConstants.E_NOTIMPL;
}
// This method gets the Edit and Continue (ENC) update for this program. A custom debug engine always returns E_NOTIMPL
public int GetENCUpdate(out object update) {
DebugWriteCommand("GetENCUpdate");
update = null;
return VSConstants.S_OK;
}
// Gets the name and identifier of the debug engine (DE) running this program.
public int GetEngineInfo(out string engineName, out Guid engineGuid) {
DebugWriteCommand("GetEngineInfo");
engineName = "Node Engine";
engineGuid = DebugEngineGuid;
return VSConstants.S_OK;
}
// The memory bytes as represented by the IDebugMemoryBytes2 object is for the program's image in memory and not any memory
// that was allocated when the program was executed.
public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes) {
DebugWriteCommand("GetMemoryBytes");
throw new Exception("The method or operation is not implemented.");
}
// Gets the name of the program.
// The name returned by this method is always a friendly, user-displayable name that describes the program.
public int GetName(out string programName) {
// The engine uses default transport and doesn't need to customize the name of the program,
// so return NULL.
programName = null;
return VSConstants.S_OK;
}
// Gets a GUID for this program. A debug engine (DE) must return the program identifier originally passed to the IDebugProgramNodeAttach2::OnAttach
// or IDebugEngine2::Attach methods. This allows identification of the program across debugger components.
public int GetProgramId(out Guid guidProgramId) {
DebugWriteCommand("GetProgramId");
guidProgramId = _ad7ProgramId;
return guidProgramId == Guid.Empty ? VSConstants.E_FAIL : VSConstants.S_OK;
}
// This method is deprecated. Use the IDebugProcess3::Step method instead.
/// <summary>
/// Performs a step.
///
/// In case there is any thread synchronization or communication between threads, other threads in the program should run when a particular thread is stepping.
/// </summary>
public int Step(IDebugThread2 pThread, enum_STEPKIND sk, enum_STEPUNIT step) {
DebugWriteCommand("Step");
var thread = ((AD7Thread)pThread).GetDebuggedThread();
switch (sk) {
case enum_STEPKIND.STEP_INTO: thread.StepInto(); break;
case enum_STEPKIND.STEP_OUT: thread.StepOut(); break;
case enum_STEPKIND.STEP_OVER: thread.StepOver(); break;
}
return VSConstants.S_OK;
}
// Terminates the program.
public int Terminate() {
DebugWriteCommand("Terminate");
// Because we implement IDebugEngineLaunch2 we will terminate
// the process in IDebugEngineLaunch2.TerminateProcess
return VSConstants.S_OK;
}
// Writes a dump to a file.
public int WriteDump(enum_DUMPTYPE dumptype, string pszDumpUrl) {
DebugWriteCommand("WriteDump");
return VSConstants.E_NOTIMPL;
}
#endregion
#region IDebugProgram3 Members
// ExecuteOnThread is called when the SDM wants execution to continue and have
// stepping state cleared. See http://msdn.microsoft.com/en-us/library/bb145596.aspx for a
// description of different ways we can resume.
public int ExecuteOnThread(IDebugThread2 pThread) {
DebugWriteCommand("ExecuteOnThread");
AssertMainThread();
// clear stepping state on the thread the user was currently on
var thread = (AD7Thread)pThread;
thread.GetDebuggedThread().ClearSteppingState();
_process.Resume();
return VSConstants.S_OK;
}
#endregion
#region IDebugSymbolSettings100 members
public int SetSymbolLoadState(int bIsManual, int bLoadAdjacent, string strIncludeList, string strExcludeList) {
DebugWriteCommand("SetSymbolLoadState");
// The SDM will call this method on the debug engine when it is created, to notify it of the user's
// symbol settings in Tools->Options->Debugging->Symbols.
//
// Params:
// bIsManual: true if 'Automatically load symbols: Only for specified modules' is checked
// bLoadAdjacent: true if 'Specify modules'->'Always load symbols next to the modules' is checked
// strIncludeList: semicolon-delimited list of modules when automatically loading 'Only specified modules'
// strExcludeList: semicolon-delimited list of modules when automatically loading 'All modules, unless excluded'
return VSConstants.S_OK;
}
#endregion
#region Deprecated interface methods
// These methods are not called by the Visual Studio debugger, so they don't need to be implemented
int IDebugEngine2.EnumPrograms(out IEnumDebugPrograms2 programs) {
Debug.Fail("This function is not called by the debugger");
programs = null;
return VSConstants.E_NOTIMPL;
}
public int Attach(IDebugEventCallback2 pCallback) {
Debug.Fail("This function is not called by the debugger");
return VSConstants.E_NOTIMPL;
}
public int GetProcess(out IDebugProcess2 process) {
Debug.Fail("This function is not called by the debugger");
process = null;
return VSConstants.E_NOTIMPL;
}
public int Execute() {
Debug.Fail("This function is not called by the debugger.");
return VSConstants.E_NOTIMPL;
}
#endregion
#region Events
internal void Send(IDebugEvent2 eventObject, string iidEvent, IDebugProgram2 program, IDebugThread2 thread) {
LiveLogger.WriteLine("AD7Engine Event: {0} ({1})", eventObject.GetType(), iidEvent);
// Check that events was not disposed
var events = _events;
if (events == null) {
return;
}
uint attributes;
var riidEvent = new Guid(iidEvent);
EngineUtils.RequireOk(eventObject.GetAttributes(out attributes));
if ((attributes & (uint)enum_EVENTATTRIBUTES.EVENT_STOPPING) != 0 && thread == null) {
Debug.Fail("A thread must be provided for a stopping event");
return;
}
try {
EngineUtils.RequireOk(events.Event(this, null, program, thread, eventObject, ref riidEvent, attributes));
} catch (InvalidCastException) {
// COM object has gone away
}
}
internal void Send(IDebugEvent2 eventObject, string iidEvent, IDebugThread2 thread) {
Send(eventObject, iidEvent, this, thread);
}
private void AttachEvents(NodeDebugger process) {
process.ProcessLoaded += OnProcessLoaded;
process.ModuleLoaded += OnModuleLoaded;
process.ThreadCreated += OnThreadCreated;
process.BreakpointBound += OnBreakpointBound;
process.BreakpointUnbound += OnBreakpointUnbound;
process.BreakpointBindFailure += OnBreakpointBindFailure;
process.BreakpointHit += OnBreakpointHit;
process.AsyncBreakComplete += OnAsyncBreakComplete;
process.ExceptionRaised += OnExceptionRaised;
process.ProcessExited += OnProcessExited;
process.EntryPointHit += OnEntryPointHit;
process.StepComplete += OnStepComplete;
process.ThreadExited += OnThreadExited;
process.DebuggerOutput += OnDebuggerOutput;
// Subscribe to document changes if Edit and Continue is enabled.
var shell = (IVsShell)Package.GetGlobalService(typeof(SVsShell));
if (shell != null) {
// The debug engine is loaded by VS separately from the main NTVS package, so we
// need to make sure that the package is also loaded before querying its options.
var packageGuid = new Guid(Guids.NodejsPackageString);
IVsPackage package;
shell.LoadPackage(ref packageGuid, out package);
var nodejsPackage = package as NodejsPackage;
if (nodejsPackage != null) {
_trackFileChanges = nodejsPackage.GeneralOptionsPage.EditAndContinue;
if (_trackFileChanges) {
_documentEvents = nodejsPackage.DTE.Events.DocumentEvents;
_documentEvents.DocumentSaved += OnDocumentSaved;
}
}
}
process.StartListening();
}
private void DetachEvents(NodeDebugger process) {
process.ProcessLoaded -= OnProcessLoaded;
process.ModuleLoaded -= OnModuleLoaded;
process.ThreadCreated -= OnThreadCreated;
process.BreakpointBound -= OnBreakpointBound;
process.BreakpointUnbound -= OnBreakpointUnbound;
process.BreakpointBindFailure -= OnBreakpointBindFailure;
process.BreakpointHit -= OnBreakpointHit;
process.AsyncBreakComplete -= OnAsyncBreakComplete;
process.ExceptionRaised -= OnExceptionRaised;
process.ProcessExited -= OnProcessExited;
process.EntryPointHit -= OnEntryPointHit;
process.StepComplete -= OnStepComplete;
process.ThreadExited -= OnThreadExited;
process.DebuggerOutput -= OnDebuggerOutput;
if (_documentEvents != null) {
_documentEvents.DocumentSaved -= OnDocumentSaved;
}
}
private void OnThreadExited(object sender, ThreadEventArgs e) {
// TODO: Thread exit code
AD7Thread oldThread;
_threads.TryGetValue(e.Thread, out oldThread);
_threads.Remove(e.Thread);
_threadExitedEvent.Set();
if (oldThread != null) {
Send(new AD7ThreadDestroyEvent(0), AD7ThreadDestroyEvent.IID, oldThread);
}
}
private void OnThreadCreated(object sender, ThreadEventArgs e) {
LiveLogger.WriteLine("Thread created: " + e.Thread.Id);
lock (_syncLock) {
var newThread = new AD7Thread(this, e.Thread);
// Treat first thread created as main thread
// Should only be one for Node
Debug.Assert(_mainThread == null);
if (_mainThread == null) {
_mainThread = newThread;
}
_threads.Add(e.Thread, newThread);
if (_loadComplete) {
SendThreadCreate(newThread);
}
}
}
public static List<IVsDocumentPreviewer> GetDefaultBrowsers() {
var browserList = new List<IVsDocumentPreviewer>();
var doc3 = (IVsUIShellOpenDocument3)NodejsPackage.Instance.GetService(typeof(SVsUIShellOpenDocument));
IVsEnumDocumentPreviewers previewersEnum = doc3.DocumentPreviewersEnum;
var rgPreviewers = new IVsDocumentPreviewer[1];
uint celtFetched;
while (ErrorHandler.Succeeded(previewersEnum.Next(1, rgPreviewers, out celtFetched)) && celtFetched == 1) {
if (rgPreviewers[0].IsDefault && !string.IsNullOrEmpty(rgPreviewers[0].Path)) {
browserList.Add(rgPreviewers[0]);
}
}
return browserList;
}
private void OnEntryPointHit(object sender, ThreadEventArgs e) {
Send(new AD7EntryPointEvent(), AD7EntryPointEvent.IID, _threads[e.Thread]);
}
private void LaunchBrowserDebugger() {
LiveLogger.WriteLine("LaunchBrowserDebugger Started");
var vsDebugger = (IVsDebugger2)ServiceProvider.GlobalProvider.GetService(typeof(SVsShellDebugger));
var info = new VsDebugTargetInfo2();
var infoSize = Marshal.SizeOf(info);
info.cbSize = (uint)infoSize;
info.bstrExe = _webBrowserUrl;
info.dlo = (uint)_DEBUG_LAUNCH_OPERATION3.DLO_LaunchBrowser;
var defaultBrowsers = GetDefaultBrowsers();
if (defaultBrowsers.Count != 1 || defaultBrowsers[0].DisplayName != "Internet Explorer") {
// if we use UseDefaultBrowser we lose the nice control & debugging of IE, so
// instead launch w/ no debugging when the user has selected a browser other than IE.
info.LaunchFlags |= (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd |
(uint)__VSDBGLAUNCHFLAGS4.DBGLAUNCH_UseDefaultBrowser |
(uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_NoDebug;
}
info.guidLaunchDebugEngine = DebugEngineGuid;
IntPtr infoPtr = Marshal.AllocCoTaskMem(infoSize);
Marshal.StructureToPtr(info, infoPtr, false);
try {
vsDebugger.LaunchDebugTargets2(1, infoPtr);
} finally {
if (infoPtr != IntPtr.Zero) {
Marshal.FreeCoTaskMem(infoPtr);
}
}
LiveLogger.WriteLine("LaunchBrowserDebugger Completed");
}
private void OnStepComplete(object sender, ThreadEventArgs e) {
Send(new AD7SteppingCompleteEvent(), AD7SteppingCompleteEvent.IID, _threads[e.Thread]);
}
private void OnProcessLoaded(object sender, ProcessLoadedEventArgs e) {
lock (_syncLock) {
_processLoaded = true;
_processLoadedRunning = e.Running;
HandleLoadComplete();
}
}
private void OnProcessExited(object sender, ProcessExitedEventArgs e) {
try {
_processExitedEvent.Set();
lock (_syncLock) {
_processLoaded = false;
_processLoadedRunning = false;
Send(new AD7ProgramDestroyEvent((uint)e.ExitCode), AD7ProgramDestroyEvent.IID, null);
}
} catch (InvalidOperationException) {
// we can race at shutdown and deliver the event after the debugger is shutting down.
}
}
private void OnModuleLoaded(object sender, ModuleLoadedEventArgs e) {
lock (_syncLock) {
var adModule = _modules[e.Module] = new AD7Module(e.Module);
if (_loadComplete) {
SendModuleLoad(adModule);
}
}
}
private void OnExceptionRaised(object sender, ExceptionRaisedEventArgs e) {
// Exception events are sent when an exception occurs in the debuggee that the debugger was not expecting.
AD7Thread thread;
if (_threads.TryGetValue(e.Thread, out thread)) {
Send(
new AD7DebugExceptionEvent(e.Exception.TypeName, e.Exception.Description, e.IsUnhandled, this),
AD7DebugExceptionEvent.IID,
thread
);
}
}
private void OnBreakpointHit(object sender, BreakpointHitEventArgs e) {
var boundBreakpoint = _breakpointManager.GetBoundBreakpoint(e.BreakpointBinding);
Send(new AD7BreakpointEvent(new AD7BoundBreakpointsEnum(new[] { boundBreakpoint })), AD7BreakpointEvent.IID, _threads[e.Thread]);
}
private void OnBreakpointBound(object sender, BreakpointBindingEventArgs e) {
var pendingBreakpoint = _breakpointManager.GetPendingBreakpoint(e.Breakpoint);
var breakpointBinding = e.BreakpointBinding;
var codeContext = new AD7MemoryAddress(this, pendingBreakpoint.DocumentName, breakpointBinding.Target.Line, breakpointBinding.Target.Column);
var documentContext = new AD7DocumentContext(codeContext);
var breakpointResolution = new AD7BreakpointResolution(this, breakpointBinding, documentContext);
var boundBreakpoint = new AD7BoundBreakpoint(breakpointBinding, pendingBreakpoint, breakpointResolution, breakpointBinding.Enabled);
_breakpointManager.AddBoundBreakpoint(breakpointBinding, boundBreakpoint);
Send(
new AD7BreakpointBoundEvent(pendingBreakpoint, boundBreakpoint),
AD7BreakpointBoundEvent.IID,
null
);
}
private void OnBreakpointUnbound(object sender, BreakpointBindingEventArgs e) {
var breakpointBinding = e.BreakpointBinding;
var boundBreakpoint = _breakpointManager.GetBoundBreakpoint(breakpointBinding);
if (boundBreakpoint != null) {
_breakpointManager.RemoveBoundBreakpoint(breakpointBinding);
Send(
new AD7BreakpointUnboundEvent(boundBreakpoint),
AD7BreakpointUnboundEvent.IID,
null
);
}
}
private void OnBreakpointBindFailure(object sender, BreakpointBindingEventArgs e) {
var pendingBreakpoint = _breakpointManager.GetPendingBreakpoint(e.Breakpoint);
var breakpointErrorEvent = new AD7BreakpointErrorEvent(pendingBreakpoint, this);
pendingBreakpoint.AddBreakpointError(breakpointErrorEvent);
Send(breakpointErrorEvent, AD7BreakpointErrorEvent.IID, null);
}
private void OnAsyncBreakComplete(object sender, ThreadEventArgs e) {
AD7Thread thread;
if (!_threads.TryGetValue(e.Thread, out thread)) {
_threads[e.Thread] = thread = new AD7Thread(this, e.Thread);
}
Send(new AD7AsyncBreakCompleteEvent(), AD7AsyncBreakCompleteEvent.IID, thread);
}
private void OnDebuggerOutput(object sender, OutputEventArgs e) {
AD7Thread thread = null;
if (e.Thread != null && !_threads.TryGetValue(e.Thread, out thread)) {
_threads[e.Thread] = thread = new AD7Thread(this, e.Thread);
}
// thread can be null for an output string event because it is not
// a stopping event.
Send(new AD7DebugOutputStringEvent2(e.Output), AD7DebugOutputStringEvent2.IID, thread);
}
private void OnDocumentSaved(Document document) {
var module = Process.GetModuleForFilePath(document.FullName);
if (module == null) {
return;
}
// For .ts files, we need to build the project to regenerate .js code.
if (String.Equals(Path.GetExtension(module.FileName), NodejsConstants.TypeScriptExtension, StringComparison.OrdinalIgnoreCase)) {
if (document.ProjectItem.ContainingProject.GetNodeProject().Build(null, null) != MSBuildResult.Successful) {
var statusBar = (IVsStatusbar)ServiceProvider.GlobalProvider.GetService(typeof(SVsStatusbar));
statusBar.SetText(SR.GetString(SR.DebuggerModuleUpdateFailed));
return;
}
}
DebuggerClient.RunWithRequestExceptionsHandled(async () => {
if (!await Process.UpdateModuleSourceAsync(module).ConfigureAwait(false)) {
var statusBar = (IVsStatusbar)ServiceProvider.GlobalProvider.GetService(typeof(SVsStatusbar));
statusBar.SetText(SR.GetString(SR.DebuggerModuleUpdateFailed));
}
});
}
#endregion
internal static void MapLanguageInfo(string filename, out string pbstrLanguage, out Guid pguidLanguage) {
if (String.Equals(Path.GetExtension(filename), NodejsConstants.TypeScriptExtension, StringComparison.OrdinalIgnoreCase)) {
pbstrLanguage = NodejsConstants.TypeScript;
pguidLanguage = Guids.TypeScriptDebugLanguage;
} else {
pbstrLanguage = NodejsConstants.JavaScript;
pguidLanguage = Guids.NodejsDebugLanguage;
}
}
/// <summary>
/// Enumerates files in the solution projects.
/// </summary>
/// <returns>File names collection.</returns>
private IEnumerable<string> EnumerateSolutionFiles() {
var solution = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution;
if (solution != null) {
foreach (IVsProject project in solution.EnumerateLoadedProjects(false)) {
foreach (uint itemid in project.EnumerateProjectItems()) {
string moniker;
if (ErrorHandler.Succeeded(project.GetMkDocument(itemid, out moniker)) && moniker != null) {
yield return moniker;
}
}
}
}
}
private void DebugWriteCommand(string commandName) {
LiveLogger.WriteLine("AD7Engine Called " + commandName);
}
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Glass.Mapper.Sc.DataMappers;
using Glass.Mapper.Sc.IoC;
using NSubstitute;
using NUnit.Framework;
using Image = Glass.Mapper.Sc.Fields.Image;
namespace Glass.Mapper.Sc.Integration.DataMappers
{
[TestFixture]
public class SitecoreFieldImageMapperFixture : AbstractMapperFixture
{
#region Method - GetField
[Test]
public void GetField_ImageInField_ReturnsImageObject()
{
//Assign
var fieldValue =
"<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" mediapath=\"/Files/20121222_001405\" src=\"~/media/D897833C1F534FAEB54BBB5B11B8F851.ashx\" hspace=\"15\" vspace=\"20\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, null) as Image;
//Assert
Assert.AreEqual("test alt", result.Alt);
// Assert.Equals(null, result.Border);
Assert.AreEqual(string.Empty, result.Class);
Assert.AreEqual(15, result.HSpace);
Assert.AreEqual(480, result.Height);
Assert.AreEqual(new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"), result.MediaId);
Assert.IsTrue(result.Src.EndsWith("/~/media/D897833C1F534FAEB54BBB5B11B8F851.ashx"));
Assert.AreEqual(20, result.VSpace);
Assert.AreEqual(640, result.Width);
}
[Test]
public void GetField_ImageFieldEmpty_ReturnsNull()
{
//Assign
var fieldValue = string.Empty;
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
var field = item.Fields[FieldName];
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
var context = Context.Create(new DependencyResolver(new Config()));
var service = new SitecoreService(Database, context);
//Act
var result =
service.GetItem<StubImage>("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
//Assert
Assert.IsNull(result.Field);
}
[Test]
public void GetField_FieldIsEmpty_ReturnsNullImageObject()
{
//Assign
var fieldValue = string.Empty;
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
var service = Substitute.For<ISitecoreService>();
service.Config = new Config();
var context = new SitecoreDataMappingContext(null, null, service);
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, context) as Image;
//Assert
Assert.IsNull(result);
}
[Test]
public void GetField_FieldIsNull_ReturnsNullImageObject()
{
//Assign
string fieldValue = null;
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
var service = Substitute.For<ISitecoreService>();
service.Config = new Config();
var context = new SitecoreDataMappingContext(null, null, service);
using (new ItemEditing(item, true))
{
field.Value = fieldValue;
}
//Act
var result = mapper.GetField(field, null, context) as Image;
//Assert
Assert.IsNull(result);
}
#endregion
#region Method - SetField
[Test]
public void SetField_ImagePassed_ReturnsPopulatedField()
{
//Assign
var expected =
"<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" width=\"640\" vspace=\"50\" height=\"480\" hspace=\"30\" alt=\"test alt\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
var image = new Image()
{
Alt = "test alt",
HSpace = 30,
Height = 480,
MediaId = new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"),
VSpace = 50,
Width = 640,
Border = String.Empty,
Class = String.Empty
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, image, null, null);
}
//Assert
Assert.AreEqual(expected, field.Value);
}
[Test]
public void SetField_JustImageId_ReturnsPopulatedField()
{
//Assign
var expected =
"<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" alt=\"\" />";
var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldImageMapper/GetField");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
var image = new Image()
{
MediaId = new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"),
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, image, null, null);
}
//Assert
Assert.AreEqual(expected, field.Value);
}
#endregion
#region Stubs
public class StubImage
{
public virtual Image Field { get; set; }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using ServiceStack.Text;
namespace ServiceStack.OrmLite.SqlServer
{
public class SqlServerOrmLiteDialectProvider : OrmLiteDialectProviderBase<SqlServerOrmLiteDialectProvider>
{
public static SqlServerOrmLiteDialectProvider Instance = new SqlServerOrmLiteDialectProvider();
private static DateTime timeSpanOffset = new DateTime(1900,01,01);
public SqlServerOrmLiteDialectProvider()
{
base.AutoIncrementDefinition = "IDENTITY(1,1)";
StringColumnDefinition = UseUnicode ? "NVARCHAR(4000)" : "VARCHAR(8000)";
base.GuidColumnDefinition = "UniqueIdentifier";
base.RealColumnDefinition = "FLOAT";
base.BoolColumnDefinition = "BIT";
base.DecimalColumnDefinition = "DECIMAL(38,6)";
base.TimeColumnDefinition = "TIME"; //SQLSERVER 2008+
base.BlobColumnDefinition = "VARBINARY(MAX)";
base.InitColumnTypeMap();
}
public override string GetQuotedParam(string paramValue)
{
return (UseUnicode ? "N'" : "'") + paramValue.Replace("'", "''") + "'";
}
public override IDbConnection CreateConnection(string connectionString, Dictionary<string, string> options)
{
var isFullConnectionString = connectionString.Contains(";");
if (!isFullConnectionString)
{
var filePath = connectionString;
var filePathWithExt = filePath.ToLower().EndsWith(".mdf")
? filePath
: filePath + ".mdf";
var fileName = Path.GetFileName(filePathWithExt);
var dbName = fileName.Substring(0, fileName.Length - ".mdf".Length);
connectionString = string.Format(
@"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Initial Catalog={1};Integrated Security=True;User Instance=True;",
filePathWithExt, dbName);
}
if (options != null)
{
foreach (var option in options)
{
if (option.Key.ToLower() == "read only")
{
if (option.Value.ToLower() == "true")
{
connectionString += "Mode = Read Only;";
}
continue;
}
connectionString += option.Key + "=" + option.Value + ";";
}
}
return new SqlConnection(connectionString);
}
public override string GetQuotedTableName(ModelDefinition modelDef)
{
if (!modelDef.IsInSchema)
return base.GetQuotedTableName(modelDef);
var escapedSchema = modelDef.Schema.Replace(".", "\".\"");
return string.Format("\"{0}\".\"{1}\"", escapedSchema, NamingStrategy.GetTableName(modelDef.ModelName));
}
public override object ConvertDbValue(object value, Type type)
{
try
{
if (value == null || value is DBNull) return null;
if (type == typeof(bool) && !(value is bool))
{
var intVal = Convert.ToInt32(value.ToString());
return intVal != 0;
}
if (type == typeof(TimeSpan) && value is DateTime)
{
var dateTimeValue = (DateTime)value;
return dateTimeValue - timeSpanOffset;
}
if (type == typeof(byte[]))
return value;
return base.ConvertDbValue(value, type);
}
catch (Exception ex)
{
throw;
}
}
public override string GetQuotedValue(object value, Type fieldType)
{
if (value == null) return "NULL";
if (fieldType == typeof(Guid))
{
var guidValue = (Guid)value;
return string.Format("CAST('{0}' AS UNIQUEIDENTIFIER)", guidValue);
}
if (fieldType == typeof(DateTime))
{
var dateValue = (DateTime)value;
const string iso8601Format = "yyyyMMdd HH:mm:ss.fff";
return base.GetQuotedValue(dateValue.ToString(iso8601Format), typeof(string));
}
if (fieldType == typeof(bool))
{
var boolValue = (bool)value;
return base.GetQuotedValue(boolValue ? 1 : 0, typeof(int));
}
if(fieldType == typeof(string)) {
return GetQuotedParam(value.ToString());
}
if (fieldType == typeof(byte[]))
{
return "0x" + BitConverter.ToString((byte[])value).Replace("-", "");
}
return base.GetQuotedValue(value, fieldType);
}
public override long GetLastInsertId(IDbCommand dbCmd)
{
dbCmd.CommandText = "SELECT SCOPE_IDENTITY()";
return dbCmd.GetLongScalar();
}
public override SqlExpressionVisitor<T> ExpressionVisitor<T>()
{
return new SqlServerExpressionVisitor<T>();
}
public override bool DoesTableExist(IDbCommand dbCmd, string tableName)
{
var sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = {0}"
.SqlFormat(tableName);
//if (!string.IsNullOrEmpty(schemaName))
// sql += " AND TABLE_SCHEMA = {0}".SqlFormat(schemaName);
dbCmd.CommandText = sql;
var result = dbCmd.GetLongScalar();
return result > 0;
}
public override bool UseUnicode
{
get
{
return useUnicode;
}
set
{
useUnicode = value;
if (useUnicode && this.DefaultStringLength > 4000)
{
this.DefaultStringLength = 4000;
}
// UpdateStringColumnDefinitions(); is called by changing DefaultStringLength
}
}
public override string GetForeignKeyOnDeleteClause(ForeignKeyConstraint foreignKey)
{
return "RESTRICT" == (foreignKey.OnDelete ?? "").ToUpper()
? ""
: base.GetForeignKeyOnDeleteClause(foreignKey);
}
public override string GetForeignKeyOnUpdateClause(ForeignKeyConstraint foreignKey)
{
return "RESTRICT" == (foreignKey.OnDelete ?? "").ToUpper()
? ""
: base.GetForeignKeyOnUpdateClause(foreignKey);
}
public override string GetDropForeignKeyConstraints(ModelDefinition modelDef)
{
//TODO: find out if this should go in base class?
var sb = new StringBuilder();
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (fieldDef.ForeignKey != null)
{
var foreignKeyName = fieldDef.ForeignKey.GetForeignKeyName(
modelDef,
GetModelDefinition(fieldDef.ForeignKey.ReferenceType),
NamingStrategy,
fieldDef);
var tableName = GetQuotedTableName(modelDef);
sb.AppendLine("IF EXISTS (SELECT name FROM sys.foreign_keys WHERE name = '{0}')".Fmt(foreignKeyName));
sb.AppendLine("BEGIN");
sb.AppendLine(" ALTER TABLE {0} DROP {1};".Fmt(tableName, foreignKeyName));
sb.AppendLine("END");
}
}
return sb.ToString();
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Analysis.Values;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Interpreter.Default;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools;
using TestUtilities;
using TestUtilities.Python;
using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
namespace AnalysisTests {
[TestClass]
public class AnalysisSaveTest : BaseAnalysisTest {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy(includeTestData: false);
}
[TestMethod, Priority(0)]
public void General() {
string code = @"def f(a, *b, **c): pass
def f1(x = 42): pass
def f2(x = []): pass
class C(object):
@property
def f(self):
return 42
def g(self):
return 100
class D(C):
x = C().g
abc = 42
fob = int
class X(object): pass
class Y(object): pass
union = X()
union = Y()
list_of_int = [1, 2, 3]
tuple_of_str = 'a', 'b', 'c'
m = max
class Aliased(object):
def f(self):
pass
def Aliased(fob):
pass
";
using (var newPs = SaveLoad(PythonLanguageVersion.V27, new AnalysisModule("test", "test.py", code))) {
AssertUtil.Contains(newPs.Analyzer.Analyzer.GetModules().Select(x => x.Name), "test");
string codeText = @"
import test
abc = test.abc
fob = test.fob
a = test.C()
cf = a.f
cg = a.g()
dx = test.D().x
scg = test.C.g
f1 = test.f1
union = test.union
list_of_int = test.list_of_int
tuple_of_str = test.tuple_of_str
f1 = test.f1
f2 = test.f2
m = test.m
Aliased = test.Aliased
";
var newMod = newPs.NewModule("baz", codeText);
int pos = codeText.LastIndexOf('\n');
AssertUtil.ContainsExactly(newMod.Analysis.GetTypeIdsByIndex("abc", pos), BuiltinTypeId.Int);
AssertUtil.ContainsExactly(newMod.Analysis.GetTypeIdsByIndex("cf", pos), BuiltinTypeId.Int);
AssertUtil.ContainsExactly(newMod.Analysis.GetTypeIdsByIndex("cg", pos), BuiltinTypeId.Int);
Assert.AreEqual("function f1(x = 42)", newMod.Analysis.GetValuesByIndex("f1", pos).First().Description);
Assert.AreEqual("bound method x", newMod.Analysis.GetValuesByIndex("dx", pos).First().Description);
Assert.AreEqual("function test.C.g(self)", newMod.Analysis.GetValuesByIndex("scg", pos).First().Description);
var unionMembers = new List<AnalysisValue>(newMod.Analysis.GetValuesByIndex("union", pos));
Assert.AreEqual(unionMembers.Count, 2);
AssertUtil.ContainsExactly(unionMembers.Select(x => x.PythonType.Name), "X", "Y");
var list = newMod.Analysis.GetValuesByIndex("list_of_int", pos).First();
AssertUtil.ContainsExactly(newMod.Analysis.GetShortDescriptionsByIndex("list_of_int", pos), "list of int");
AssertUtil.ContainsExactly(newMod.Analysis.GetShortDescriptionsByIndex("tuple_of_str", pos), "tuple of str");
AssertUtil.ContainsExactly(newMod.Analysis.GetShortDescriptionsByIndex("fob", pos), "type int");
var result = newMod.Analysis.GetSignaturesByIndex("f1", pos).ToArray();
Assert.AreEqual(1, result.Length);
Assert.AreEqual(1, result[0].Parameters.Length);
Assert.AreEqual("int", result[0].Parameters[0].Type);
result = newMod.Analysis.GetSignaturesByIndex("m", pos).ToArray();
Assert.AreEqual(6, result.Length);
var members = newMod.Analysis.GetMembersByIndex("Aliased", pos, GetMemberOptions.None);
AssertUtil.Contains(members.Select(x => x.Name), "f");
AssertUtil.Contains(members.Select(x => x.Name), "__self__");
}
}
[TestMethod, Priority(0)]
public void OverloadDocString() {
string code = @"
class FunctionNoRetType(object):
def __init__(self, value):
pass
class Aliased(object):
'''class doc'''
pass
def Aliased(fob):
'''function doc'''
pass
def Overloaded(a):
'''help 1'''
pass
def Overloaded(a, b):
'''help 2'''
pass
def Overloaded(a, b):
'''help 2'''
pass
";
using (var newPs = SaveLoad(PythonLanguageVersion.V27, new AnalysisModule("test", "test.py", code))) {
AssertUtil.Contains(newPs.Analyzer.Analyzer.GetModules().Select(x => x.Name), "test");
string codeText = @"
import test
Aliased = test.Aliased
FunctionNoRetType = test.FunctionNoRetType
Overloaded = test.Overloaded
";
var newMod = newPs.NewModule("baz", codeText);
int pos = codeText.LastIndexOf('\n');
var allMembers = newMod.Analysis.GetAllAvailableMembersByIndex(pos, GetMemberOptions.None);
Assert.AreEqual("class test.Aliased\r\nclass doc\r\n\r\nfunction Aliased(fob)\r\nfunction doc", allMembers.First(x => x.Name == "Aliased").Documentation);
newPs.Analyzer.AssertHasParameters("FunctionNoRetType", "value");
//var doc = newMod.Analysis.GetMembersByIndex("test", pos).Where(x => x.Name == "Overloaded").First();
// help 2 should be first because it has more parameters
//Assert.AreEqual("function Overloaded(a, b)\r\nhelp 2\r\n\r\nfunction Overloaded(a)\r\nhelp 1", doc.Documentation);
AssertUtil.ContainsExactly(newPs.Analyzer.GetDescriptions("test.Overloaded"), "function Overloaded(a, b)\r\nhelp 2", "function Overloaded(a)\r\nhelp 1");
}
}
[TestMethod, Priority(1)]
public void Inheritance() {
string code = @"
class WithInstanceMembers(object):
def __init__(self):
self.fob = 42
class WithMemberFunctions(object):
def oar(self):
pass
class SingleInheritance(WithMemberFunctions):
def baz(self):
pass
class DoubleInheritance(SingleInheritance):
pass
class MultipleInheritance(WithInstanceMembers, WithMemberFunctions):
pass
";
using (var newPs = SaveLoad(PythonLanguageVersion.V27, new AnalysisModule("test", "test.py", code))) {
AssertUtil.Contains(newPs.Analyzer.Analyzer.GetModules().Select(x => x.Name), "test");
string codeText = @"
import test
WithInstanceMembers = test.WithInstanceMembers
WithMemberFunctions = test.WithMemberFunctions
SingleInheritance = test.SingleInheritance
DoubleInheritance = test.DoubleInheritance
MultipleInheritance = test.MultipleInheritance
";
var newMod = newPs.NewModule("baz", codeText);
int pos = codeText.LastIndexOf('\n');
// instance attributes are present
var instMembers = newMod.Analysis.GetMembersByIndex("WithInstanceMembers", pos);
var fobMembers = instMembers.Where(x => x.Name == "fob");
Assert.AreNotEqual(null, fobMembers.FirstOrDefault().Name);
newPs.Analyzer.AssertHasAttr("WithMemberFunctions", "oar");
newPs.Analyzer.AssertHasAttr("SingleInheritance", "oar", "baz");
newPs.Analyzer.AssertHasAttr("DoubleInheritance", "oar", "baz");
newPs.Analyzer.AssertHasAttr("MultipleInheritance", "fob", "oar");
}
}
[TestMethod, Priority(1)]
public void MultiplyDefinedClasses() {
string code = @"
class MultiplyDefinedClass(object): pass
class MultiplyDefinedClass(object): pass
def ReturningMultiplyDefinedClass():
return MultiplyDefinedClass()
";
using (var newPs = SaveLoad(PythonLanguageVersion.V27, new AnalysisModule("test", "test.py", code))) {
AssertUtil.Contains(newPs.Analyzer.Analyzer.GetModules().Select(x => x.Name), "test");
string codeText = @"
import test
MultiplyDefinedClass = test.MultiplyDefinedClass
ReturningMultiplyDefinedClass = test.ReturningMultiplyDefinedClass
";
var newMod = newPs.NewModule("baz", codeText);
var mdc = newPs.Analyzer.GetValues("MultiplyDefinedClass");
Assert.AreEqual(2, mdc.Length);
var rmdc = newPs.Analyzer.GetValue<BuiltinFunctionInfo>("ReturningMultiplyDefinedClass");
AssertUtil.ContainsExactly(rmdc.Function.Overloads.Single().ReturnType, mdc.Select(p => p.PythonType));
}
}
[TestMethod, Priority(0)]
public void RecursionClasses() {
string code = @"
class C(object): pass
C.abc = C
";
using (var newPs = SaveLoad(PythonLanguageVersion.V27, new AnalysisModule("test", "test.py", code))) {
}
}
[TestMethod, Priority(0)]
public void RecursionSequenceClasses() {
string code = @"
C = []
C.append(C)
";
using (var newPs = SaveLoad(PythonLanguageVersion.V27, new AnalysisModule("test", "test.py", code))) {
string code2 = @"import test
C = test.C";
newPs.NewModule("test2", code2);
newPs.Analyzer.AssertDescription("C", "list of list");
}
}
[TestMethod, Priority(0)]
public void ModuleRef() {
string fob = @"
import oar
x = oar.f()
";
string oar = @"
def f(): return 42";
using (var newPs = SaveLoad(PythonLanguageVersion.V27, new AnalysisModule("fob", "fob.py", fob), new AnalysisModule("oar", "oar.py", oar))) {
string code = @"
import fob
abc = fob.x
";
newPs.NewModule("baz", code);
newPs.Analyzer.AssertIsInstance("abc", BuiltinTypeId.Int);
}
}
[TestMethod, Priority(0)]
public void CrossModuleTypeRef() {
string fob = @"
class Fob(object):
pass
";
string oar = @"
from fob import *
";
string baz = @"
from oar import *
";
using (var newPs = SaveLoad(
PythonLanguageVersion.V27,
new AnalysisModule("fob", "fob.py", fob),
new AnalysisModule("oar", "oar.py", oar),
new AnalysisModule("baz", "baz.py", baz)
)) {
string code = @"
import oar, baz
oar_Fob = oar.Fob
baz_Fob = baz.Fob
";
newPs.NewModule("fez", code);
newPs.Analyzer.AssertDescription("oar_Fob", "class fob.Fob");
newPs.Analyzer.AssertDescription("baz_Fob", "class fob.Fob");
}
}
[TestMethod, Priority(0)]
public void FunctionOverloads() {
string code = @"
def f(a, b):
return a * b
f(1, 2)
f(3, 'abc')
f([1, 2], 3)
";
using (var newPs = SaveLoad(PythonLanguageVersion.V27, new AnalysisModule("test", "test.py", code))) {
newPs.NewModule("test2", "from test import f; x = f()");
newPs.Analyzer.AssertIsInstance("x", BuiltinTypeId.Int, BuiltinTypeId.Str, BuiltinTypeId.List);
var lst = newPs.Analyzer.GetValues("x")
.OfType<SequenceBuiltinInstanceInfo>()
.Where(s => s.TypeId == BuiltinTypeId.List)
.Single();
Assert.AreEqual("list of int", lst.ShortDescription);
}
}
[TestMethod, Priority(0)]
public void StandaloneMethods() {
string code = @"
class A(object):
def f(self, a, b):
pass
cls_f = A.f
inst_f = A().f
";
using (var newPs = SaveLoad(PythonLanguageVersion.V27, new AnalysisModule("test", "test.py", code))) {
var newMod = newPs.NewModule("test2", "from test import cls_f, inst_f");
newPs.Analyzer.AssertHasParameters("cls_f", "self", "a", "b");
newPs.Analyzer.AssertHasParameters("inst_f", "a", "b");
}
}
[TestMethod, Priority(0)]
public void DefaultParameters() {
var code = @"
def f(x = None): pass
def g(x = {}): pass
def h(x = {2:3}): pass
def i(x = []): pass
def j(x = [None]): pass
def k(x = ()): pass
def l(x = (2, )): pass
def m(x = math.atan2(1, 0)): pass
";
var tests = new[] {
new { FuncName = "f", ParamName="x", DefaultValue = "None" },
new { FuncName = "g", ParamName="x", DefaultValue = "{}" },
new { FuncName = "h", ParamName="x", DefaultValue = "{...}" },
new { FuncName = "i", ParamName="x", DefaultValue = "[]" },
new { FuncName = "j", ParamName="x", DefaultValue="[...]" },
new { FuncName = "k", ParamName="x", DefaultValue = "()" },
new { FuncName = "l", ParamName="x", DefaultValue = "(...)" },
new { FuncName = "m", ParamName="x", DefaultValue = "math.atan2(1,0)" },
};
using (var newPs = SaveLoad(PythonLanguageVersion.V27, new AnalysisModule("test", "test.py", code))) {
var entry = newPs.NewModule("test2", "from test import *");
foreach (var test in tests) {
var result = entry.Analysis.GetSignaturesByIndex(test.FuncName, 1).ToArray();
Assert.AreEqual(result.Length, 1);
Assert.AreEqual(result[0].Parameters.Length, 1);
Assert.AreEqual(result[0].Parameters[0].Name, test.ParamName);
Assert.AreEqual(result[0].Parameters[0].DefaultValue, test.DefaultValue);
}
}
}
[TestMethod, Priority(0)]
public void ChildModuleThroughSysModules() {
var code = @"# This is what the os module does
import test_import_1
import test_import_2
import sys
sys.modules['test.imported'] = test_import_1
sys.modules['test.imported'] = test_import_2
";
using (var newPs = SaveLoad(PythonLanguageVersion.V27,
new AnalysisModule("test", "test.py", code),
new AnalysisModule("test_import_1", "test_import_1.py", "n = 1"),
new AnalysisModule("test_import_2", "test_import_2.py", "f = 3.1415")
)) {
var entry = newPs.NewModule("test2", "import test as t; import test.imported as p");
AssertUtil.ContainsExactly(
entry.Analysis.GetMemberNamesByIndex("t", 0),
"test_import_1",
"test_import_2",
"imported"
);
var p = entry.Analysis.GetValuesByIndex("p", 0).ToList();
Assert.AreEqual(2, p.Count);
Assert.IsInstanceOfType(p[0], typeof(BuiltinModule));
Assert.IsInstanceOfType(p[1], typeof(BuiltinModule));
AssertUtil.ContainsExactly(p.Select(m => m.Name), "test_import_1", "test_import_2");
AssertUtil.ContainsExactly(entry.Analysis.GetTypeIdsByIndex("p.n", 0), BuiltinTypeId.Int);
AssertUtil.ContainsExactly(entry.Analysis.GetTypeIdsByIndex("p.f", 0), BuiltinTypeId.Float);
}
}
[TestMethod, Priority(0)]
public void SpecializedCallableWithNoOriginal() {
string code = @"
import unittest
# skipIf is specialized and calling it returns a callable
# with no original value to save.
x = unittest.skipIf(False)
";
using (var newPs = SaveLoad(PythonLanguageVersion.V27, new AnalysisModule("test", "test.py", code))) {
var entry = newPs.NewModule("test2", "import test; x = test.x");
AssertUtil.ContainsExactly(entry.Analysis.GetTypeIdsByIndex("x", 0));
}
}
private SaveLoadResult SaveLoad(PythonLanguageVersion version, params AnalysisModule[] modules) {
IPythonProjectEntry[] entries = new IPythonProjectEntry[modules.Length];
var fact = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version.ToVersion());
var interp = fact.CreateInterpreter();
var dbFolder = TestData.GetTempPath(randomSubPath: true);
Directory.CreateDirectory(dbFolder);
var state = new PythonAnalysis(fact, interp, SharedDatabaseState.BuiltinName2x);
state.CreateProjectOnDisk = true;
for (int i = 0; i < modules.Length; i++) {
state.AddModule(modules[i].ModuleName, modules[i].Code, modules[i].Filename);
}
state.WaitForAnalysis();
new SaveAnalysis().Save(state.Analyzer, dbFolder);
File.Copy(
Path.Combine(PythonTypeDatabase.BaselineDatabasePath, "__builtin__.idb"),
Path.Combine(dbFolder, "__builtin__.idb"),
true
);
var loadFactory = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(
version.ToVersion(),
null,
dbFolder
);
return new SaveLoadResult(CreateAnalyzer(loadFactory), state.CodeFolder);
}
class AnalysisModule {
public readonly string ModuleName;
public readonly string Code;
public readonly string Filename;
public AnalysisModule(string moduleName, string filename, string code) {
ModuleName = moduleName;
Code = code;
Filename = filename;
}
}
class SaveLoadResult : IDisposable {
private readonly string _dir;
public readonly PythonAnalysis Analyzer;
public SaveLoadResult(PythonAnalysis analyzer, string dir) {
Analyzer = analyzer;
_dir = dir;
}
public IPythonProjectEntry NewModule(string name, string code) {
var entry = Analyzer.AddModule(name, code);
Analyzer.WaitForAnalysis();
return entry;
}
#region IDisposable Members
public void Dispose() {
//Directory.Delete(_dir, true);
}
#endregion
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace CloudStack.Net
{
public class DeployVirtualMachineRequest : APIRequest
{
public DeployVirtualMachineRequest() : base("deployVirtualMachine") {}
/// <summary>
/// the ID of the service offering for the virtual machine
/// </summary>
public Guid ServiceOfferingId {
get { return GetParameterValue<Guid>(nameof(ServiceOfferingId).ToLower()); }
set { SetParameterValue(nameof(ServiceOfferingId).ToLower(), value); }
}
/// <summary>
/// the ID of the template for the virtual machine
/// </summary>
public Guid TemplateId {
get { return GetParameterValue<Guid>(nameof(TemplateId).ToLower()); }
set { SetParameterValue(nameof(TemplateId).ToLower(), value); }
}
/// <summary>
/// availability zone for the virtual machine
/// </summary>
public Guid ZoneId {
get { return GetParameterValue<Guid>(nameof(ZoneId).ToLower()); }
set { SetParameterValue(nameof(ZoneId).ToLower(), value); }
}
/// <summary>
/// an optional account for the virtual machine. Must be used with domainId.
/// </summary>
public string Account {
get { return GetParameterValue<string>(nameof(Account).ToLower()); }
set { SetParameterValue(nameof(Account).ToLower(), value); }
}
/// <summary>
/// comma separated list of affinity groups id that are going to be applied to the virtual machine. Mutually exclusive with affinitygroupnames parameter
/// </summary>
public IList<Guid> Affinitygroupids {
get { return GetList<Guid>(nameof(Affinitygroupids).ToLower()); }
set { SetParameterValue(nameof(Affinitygroupids).ToLower(), value); }
}
/// <summary>
/// comma separated list of affinity groups names that are going to be applied to the virtual machine.Mutually exclusive with affinitygroupids parameter
/// </summary>
public IList<string> Affinitygroupnames {
get { return GetList<string>(nameof(Affinitygroupnames).ToLower()); }
set { SetParameterValue(nameof(Affinitygroupnames).ToLower(), value); }
}
/// <summary>
/// an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only
/// </summary>
public string CustomId {
get { return GetParameterValue<string>(nameof(CustomId).ToLower()); }
set { SetParameterValue(nameof(CustomId).ToLower(), value); }
}
/// <summary>
/// Deployment planner to use for vm allocation. Available to ROOT admin only
/// </summary>
public string DeploymentPlanner {
get { return GetParameterValue<string>(nameof(DeploymentPlanner).ToLower()); }
set { SetParameterValue(nameof(DeploymentPlanner).ToLower(), value); }
}
/// <summary>
/// used to specify the custom parameters.
/// </summary>
public IList<IDictionary<string, object>> Details {
get { return GetList<IDictionary<string, object>>(nameof(Details).ToLower()); }
set { SetParameterValue(nameof(Details).ToLower(), value); }
}
/// <summary>
/// the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume. If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created.
/// </summary>
public Guid? DiskOfferingId {
get { return GetParameterValue<Guid?>(nameof(DiskOfferingId).ToLower()); }
set { SetParameterValue(nameof(DiskOfferingId).ToLower(), value); }
}
/// <summary>
/// an optional user generated name for the virtual machine
/// </summary>
public string DisplayName {
get { return GetParameterValue<string>(nameof(DisplayName).ToLower()); }
set { SetParameterValue(nameof(DisplayName).ToLower(), value); }
}
/// <summary>
/// an optional field, whether to the display the vm to the end user or not.
/// </summary>
public bool? DisplayVm {
get { return GetParameterValue<bool?>(nameof(DisplayVm).ToLower()); }
set { SetParameterValue(nameof(DisplayVm).ToLower(), value); }
}
/// <summary>
/// an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.
/// </summary>
public Guid? DomainId {
get { return GetParameterValue<Guid?>(nameof(DomainId).ToLower()); }
set { SetParameterValue(nameof(DomainId).ToLower(), value); }
}
/// <summary>
/// an optional group for the virtual machine
/// </summary>
public string Group {
get { return GetParameterValue<string>(nameof(Group).ToLower()); }
set { SetParameterValue(nameof(Group).ToLower(), value); }
}
/// <summary>
/// destination Host ID to deploy the VM to - parameter available for root admin only
/// </summary>
public Guid? HostId {
get { return GetParameterValue<Guid?>(nameof(HostId).ToLower()); }
set { SetParameterValue(nameof(HostId).ToLower(), value); }
}
/// <summary>
/// the hypervisor on which to deploy the virtual machine. The parameter is required and respected only when hypervisor info is not set on the ISO/Template passed to the call
/// </summary>
public string Hypervisor {
get { return GetParameterValue<string>(nameof(Hypervisor).ToLower()); }
set { SetParameterValue(nameof(Hypervisor).ToLower(), value); }
}
/// <summary>
/// the ipv6 address for default vm's network
/// </summary>
public string Ip6Address {
get { return GetParameterValue<string>(nameof(Ip6Address).ToLower()); }
set { SetParameterValue(nameof(Ip6Address).ToLower(), value); }
}
/// <summary>
/// the ip address for default vm's network
/// </summary>
public string IpAddress {
get { return GetParameterValue<string>(nameof(IpAddress).ToLower()); }
set { SetParameterValue(nameof(IpAddress).ToLower(), value); }
}
/// <summary>
/// ip to network mapping. Can't be specified with networkIds parameter. Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].ipv6=fc00:1234:5678::abcd&iptonetworklist[0].networkid=uuid - requests to use ip 10.10.10.11 in network id=uuid
/// </summary>
public IList<IDictionary<string, object>> IpToNetworkList {
get { return GetList<IDictionary<string, object>>(nameof(IpToNetworkList).ToLower()); }
set { SetParameterValue(nameof(IpToNetworkList).ToLower(), value); }
}
/// <summary>
/// an optional keyboard device type for the virtual machine. valid value can be one of de,de-ch,es,fi,fr,fr-be,fr-ch,is,it,jp,nl-be,no,pt,uk,us
/// </summary>
public string Keyboard {
get { return GetParameterValue<string>(nameof(Keyboard).ToLower()); }
set { SetParameterValue(nameof(Keyboard).ToLower(), value); }
}
/// <summary>
/// name of the ssh key pair used to login to the virtual machine
/// </summary>
public string Keypair {
get { return GetParameterValue<string>(nameof(Keypair).ToLower()); }
set { SetParameterValue(nameof(Keypair).ToLower(), value); }
}
/// <summary>
/// host name for the virtual machine
/// </summary>
public string Name {
get { return GetParameterValue<string>(nameof(Name).ToLower()); }
set { SetParameterValue(nameof(Name).ToLower(), value); }
}
/// <summary>
/// list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter
/// </summary>
public IList<Guid> NetworkIds {
get { return GetList<Guid>(nameof(NetworkIds).ToLower()); }
set { SetParameterValue(nameof(NetworkIds).ToLower(), value); }
}
/// <summary>
/// Deploy vm for the project
/// </summary>
public Guid? ProjectId {
get { return GetParameterValue<Guid?>(nameof(ProjectId).ToLower()); }
set { SetParameterValue(nameof(ProjectId).ToLower(), value); }
}
/// <summary>
/// Optional field to resize root disk on deploy. Value is in GB. Only applies to template-based deployments. Analogous to details[0].rootdisksize, which takes precedence over this parameter if both are provided
/// </summary>
public long? Rootdisksize {
get { return GetParameterValue<long?>(nameof(Rootdisksize).ToLower()); }
set { SetParameterValue(nameof(Rootdisksize).ToLower(), value); }
}
/// <summary>
/// comma separated list of security groups id that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupnames parameter
/// </summary>
public IList<Guid> Securitygroupids {
get { return GetList<Guid>(nameof(Securitygroupids).ToLower()); }
set { SetParameterValue(nameof(Securitygroupids).ToLower(), value); }
}
/// <summary>
/// comma separated list of security groups names that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupids parameter
/// </summary>
public IList<string> Securitygroupnames {
get { return GetList<string>(nameof(Securitygroupnames).ToLower()); }
set { SetParameterValue(nameof(Securitygroupnames).ToLower(), value); }
}
/// <summary>
/// the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId
/// </summary>
public long? Size {
get { return GetParameterValue<long?>(nameof(Size).ToLower()); }
set { SetParameterValue(nameof(Size).ToLower(), value); }
}
/// <summary>
/// true if start vm after creating; defaulted to true if not specified
/// </summary>
public bool? StartVm {
get { return GetParameterValue<bool?>(nameof(StartVm).ToLower()); }
set { SetParameterValue(nameof(StartVm).ToLower(), value); }
}
/// <summary>
/// an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding. Using HTTP POST(via POST body), you can send up to 32K of data after base64 encoding.
/// </summary>
public string UserData {
get { return GetParameterValue<string>(nameof(UserData).ToLower()); }
set { SetParameterValue(nameof(UserData).ToLower(), value); }
}
}
/// <summary>
/// Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.
/// </summary>
public partial interface ICloudStackAPIClient
{
AsyncJobResponse DeployVirtualMachine(DeployVirtualMachineRequest request);
Task<AsyncJobResponse> DeployVirtualMachineAsync(DeployVirtualMachineRequest request);
}
public partial class CloudStackAPIClient : ICloudStackAPIClient
{
public AsyncJobResponse DeployVirtualMachine(DeployVirtualMachineRequest request) => Proxy.Request<AsyncJobResponse>(request);
public Task<AsyncJobResponse> DeployVirtualMachineAsync(DeployVirtualMachineRequest request) => Proxy.RequestAsync<AsyncJobResponse>(request);
}
}
| |
/*
* 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 ZXing.Common;
using ZXing.Common.Detector;
using ZXing.Common.ReedSolomon;
namespace ZXing.Aztec.Internal
{
/// <summary>
/// Encapsulates logic that can detect an Aztec Code in an image, even if the Aztec Code
/// is rotated or skewed, or partially obscured.
/// </summary>
/// <author>David Olivier</author>
public sealed class Detector
{
private static readonly int[] EXPECTED_CORNER_BITS =
{
0xee0, // 07340 XXX .XX X.. ...
0x1dc, // 00734 ... XXX .XX X..
0x83b, // 04073 X.. ... XXX .XX
0x707, // 03407 .XX X.. ... XXX
};
private readonly BitMatrix image;
private bool compact;
private int nbLayers;
private int nbDataBlocks;
private int nbCenterLayers;
private int shift;
/// <summary>
/// Initializes a new instance of the <see cref="Detector"/> class.
/// </summary>
/// <param name="image">The image.</param>
public Detector(BitMatrix image)
{
this.image = image;
}
/// <summary>
/// Detects an Aztec Code in an image.
/// </summary>
public AztecDetectorResult detect()
{
return detect(false);
}
/// <summary>
/// Detects an Aztec Code in an image.
/// </summary>
/// <param name="isMirror">if true, image is a mirror-image of original.</param>
/// <returns>
/// encapsulating results of detecting an Aztec Code
/// </returns>
public AztecDetectorResult detect(bool isMirror)
{
// 1. Get the center of the aztec matrix
var pCenter = getMatrixCenter();
if (pCenter == null)
return null;
// 2. Get the center points of the four diagonal points just outside the bull's eye
// [topRight, bottomRight, bottomLeft, topLeft]
var bullsEyeCorners = getBullsEyeCorners(pCenter);
if (bullsEyeCorners == null)
{
return null;
}
if (isMirror)
{
ResultPoint temp = bullsEyeCorners[0];
bullsEyeCorners[0] = bullsEyeCorners[2];
bullsEyeCorners[2] = temp;
}
// 3. Get the size of the matrix and other parameters from the bull's eye
if (!extractParameters(bullsEyeCorners))
{
return null;
}
// 4. Sample the grid
var bits = sampleGrid(image,
bullsEyeCorners[shift % 4],
bullsEyeCorners[(shift + 1) % 4],
bullsEyeCorners[(shift + 2) % 4],
bullsEyeCorners[(shift + 3) % 4]);
if (bits == null)
{
return null;
}
// 5. Get the corners of the matrix.
var corners = getMatrixCornerPoints(bullsEyeCorners);
if (corners == null)
{
return null;
}
return new AztecDetectorResult(bits, corners, compact, nbDataBlocks, nbLayers);
}
/// <summary>
/// Extracts the number of data layers and data blocks from the layer around the bull's eye
/// </summary>
/// <param name="bullsEyeCorners">bullEyeCornerPoints the array of bull's eye corners</param>
/// <returns></returns>
private bool extractParameters(ResultPoint[] bullsEyeCorners)
{
if (!isValid(bullsEyeCorners[0]) || !isValid(bullsEyeCorners[1]) ||
!isValid(bullsEyeCorners[2]) || !isValid(bullsEyeCorners[3]))
{
return false;
}
int length = 2 * nbCenterLayers;
// Get the bits around the bull's eye
int[] sides =
{
sampleLine(bullsEyeCorners[0], bullsEyeCorners[1], length), // Right side
sampleLine(bullsEyeCorners[1], bullsEyeCorners[2], length), // Bottom
sampleLine(bullsEyeCorners[2], bullsEyeCorners[3], length), // Left side
sampleLine(bullsEyeCorners[3], bullsEyeCorners[0], length) // Top
};
// bullsEyeCorners[shift] is the corner of the bulls'eye that has three
// orientation marks.
// sides[shift] is the row/column that goes from the corner with three
// orientation marks to the corner with two.
shift = getRotation(sides, length);
if (shift < 0)
return false;
// Flatten the parameter bits into a single 28- or 40-bit long
long parameterData = 0;
for (int i = 0; i < 4; i++)
{
int side = sides[(shift + i) % 4];
if (compact)
{
// Each side of the form ..XXXXXXX. where Xs are parameter data
parameterData <<= 7;
parameterData += (side >> 1) & 0x7F;
}
else
{
// Each side of the form ..XXXXX.XXXXX. where Xs are parameter data
parameterData <<= 10;
parameterData += ((side >> 2) & (0x1f << 5)) + ((side >> 1) & 0x1F);
}
}
// Corrects parameter data using RS. Returns just the data portion
// without the error correction.
int correctedData = getCorrectedParameterData(parameterData, compact);
if (correctedData < 0)
return false;
if (compact)
{
// 8 bits: 2 bits layers and 6 bits data blocks
nbLayers = (correctedData >> 6) + 1;
nbDataBlocks = (correctedData & 0x3F) + 1;
}
else
{
// 16 bits: 5 bits layers and 11 bits data blocks
nbLayers = (correctedData >> 11) + 1;
nbDataBlocks = (correctedData & 0x7FF) + 1;
}
return true;
}
private static int getRotation(int[] sides, int length)
{
// In a normal pattern, we expect to See
// ** .* D A
// * *
//
// . *
// .. .. C B
//
// Grab the 3 bits from each of the sides the form the locator pattern and concatenate
// into a 12-bit integer. Start with the bit at A
int cornerBits = 0;
foreach (int side in sides)
{
// XX......X where X's are orientation marks
int t = ((side >> (length - 2)) << 1) + (side & 1);
cornerBits = (cornerBits << 3) + t;
}
// Mov the bottom bit to the top, so that the three bits of the locator pattern at A are
// together. cornerBits is now:
// 3 orientation bits at A || 3 orientation bits at B || ... || 3 orientation bits at D
cornerBits = ((cornerBits & 1) << 11) + (cornerBits >> 1);
// The result shift indicates which element of BullsEyeCorners[] goes into the top-left
// corner. Since the four rotation values have a Hamming distance of 8, we
// can easily tolerate two errors.
for (int shift = 0; shift < 4; shift++)
{
if (SupportClass.bitCount(cornerBits ^ EXPECTED_CORNER_BITS[shift]) <= 2)
{
return shift;
}
}
return -1;
}
/// <summary>
/// Corrects the parameter bits using Reed-Solomon algorithm
/// </summary>
/// <param name="parameterData">paremeter bits</param>
/// <param name="compact">compact true if this is a compact Aztec code</param>
/// <returns></returns>
private static int getCorrectedParameterData(long parameterData, bool compact)
{
int numCodewords;
int numDataCodewords;
if (compact)
{
numCodewords = 7;
numDataCodewords = 2;
}
else
{
numCodewords = 10;
numDataCodewords = 4;
}
int numECCodewords = numCodewords - numDataCodewords;
int[] parameterWords = new int[numCodewords];
for (int i = numCodewords - 1; i >= 0; --i)
{
parameterWords[i] = (int)parameterData & 0xF;
parameterData >>= 4;
}
var rsDecoder = new ReedSolomonDecoder(GenericGF.AZTEC_PARAM);
if (!rsDecoder.decode(parameterWords, numECCodewords))
return -1;
// Toss the error correction. Just return the data as an integer
int result = 0;
for (int i = 0; i < numDataCodewords; i++)
{
result = (result << 4) + parameterWords[i];
}
return result;
}
/// <summary>
/// Finds the corners of a bull-eye centered on the passed point
/// This returns the centers of the diagonal points just outside the bull's eye
/// Returns [topRight, bottomRight, bottomLeft, topLeft]
/// </summary>
/// <param name="pCenter">Center point</param>
/// <returns>The corners of the bull-eye</returns>
private ResultPoint[] getBullsEyeCorners(Point pCenter)
{
Point pina = pCenter;
Point pinb = pCenter;
Point pinc = pCenter;
Point pind = pCenter;
bool color = true;
for (nbCenterLayers = 1; nbCenterLayers < 9; nbCenterLayers++)
{
Point pouta = getFirstDifferent(pina, color, 1, -1);
Point poutb = getFirstDifferent(pinb, color, 1, 1);
Point poutc = getFirstDifferent(pinc, color, -1, 1);
Point poutd = getFirstDifferent(pind, color, -1, -1);
//d a
//
//c b
if (nbCenterLayers > 2)
{
float q = distance(poutd, pouta) * nbCenterLayers / (distance(pind, pina) * (nbCenterLayers + 2));
if (q < 0.75 || q > 1.25 || !isWhiteOrBlackRectangle(pouta, poutb, poutc, poutd))
{
break;
}
}
pina = pouta;
pinb = poutb;
pinc = poutc;
pind = poutd;
color = !color;
}
if (nbCenterLayers != 5 && nbCenterLayers != 7)
{
return null;
}
compact = nbCenterLayers == 5;
// Expand the square by .5 pixel in each direction so that we're on the border
// between the white square and the black square
var pinax = new ResultPoint(pina.X + 0.5f, pina.Y - 0.5f);
var pinbx = new ResultPoint(pinb.X + 0.5f, pinb.Y + 0.5f);
var pincx = new ResultPoint(pinc.X - 0.5f, pinc.Y + 0.5f);
var pindx = new ResultPoint(pind.X - 0.5f, pind.Y - 0.5f);
// Expand the square so that its corners are the centers of the points
// just outside the bull's eye.
return expandSquare(new[] { pinax, pinbx, pincx, pindx },
2 * nbCenterLayers - 3,
2 * nbCenterLayers);
}
/// <summary>
/// Finds a candidate center point of an Aztec code from an image
/// </summary>
/// <returns>the center point</returns>
private Point getMatrixCenter()
{
ResultPoint pointA;
ResultPoint pointB;
ResultPoint pointC;
ResultPoint pointD;
int cx;
int cy;
//Get a white rectangle that can be the border of the matrix in center bull's eye or
var whiteDetector = WhiteRectangleDetector.Create(image);
if (whiteDetector == null)
return null;
ResultPoint[] cornerPoints = whiteDetector.detect();
if (cornerPoints != null)
{
pointA = cornerPoints[0];
pointB = cornerPoints[1];
pointC = cornerPoints[2];
pointD = cornerPoints[3];
}
else
{
// This exception can be in case the initial rectangle is white
// In that case, surely in the bull's eye, we try to expand the rectangle.
cx = image.Width / 2;
cy = image.Height / 2;
pointA = getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
pointB = getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();
pointC = getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint();
pointD = getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();
}
//Compute the center of the rectangle
cx = MathUtils.round((pointA.X + pointD.X + pointB.X + pointC.X) / 4.0f);
cy = MathUtils.round((pointA.Y + pointD.Y + pointB.Y + pointC.Y) / 4.0f);
// Redetermine the white rectangle starting from previously computed center.
// This will ensure that we end up with a white rectangle in center bull's eye
// in order to compute a more accurate center.
whiteDetector = WhiteRectangleDetector.Create(image, 15, cx, cy);
if (whiteDetector == null)
return null;
cornerPoints = whiteDetector.detect();
if (cornerPoints != null)
{
pointA = cornerPoints[0];
pointB = cornerPoints[1];
pointC = cornerPoints[2];
pointD = cornerPoints[3];
}
else
{
// This exception can be in case the initial rectangle is white
// In that case we try to expand the rectangle.
pointA = getFirstDifferent(new Point(cx + 7, cy - 7), false, 1, -1).toResultPoint();
pointB = getFirstDifferent(new Point(cx + 7, cy + 7), false, 1, 1).toResultPoint();
pointC = getFirstDifferent(new Point(cx - 7, cy + 7), false, -1, 1).toResultPoint();
pointD = getFirstDifferent(new Point(cx - 7, cy - 7), false, -1, -1).toResultPoint();
}
// Recompute the center of the rectangle
cx = MathUtils.round((pointA.X + pointD.X + pointB.X + pointC.X) / 4.0f);
cy = MathUtils.round((pointA.Y + pointD.Y + pointB.Y + pointC.Y) / 4.0f);
return new Point(cx, cy);
}
/// <summary>
/// Gets the Aztec code corners from the bull's eye corners and the parameters.
/// </summary>
/// <param name="bullsEyeCorners">the array of bull's eye corners</param>
/// <returns>the array of aztec code corners</returns>
private ResultPoint[] getMatrixCornerPoints(ResultPoint[] bullsEyeCorners)
{
return expandSquare(bullsEyeCorners, 2 * nbCenterLayers, getDimension());
}
/// <summary>
/// Creates a BitMatrix by sampling the provided image.
/// topLeft, topRight, bottomRight, and bottomLeft are the centers of the squares on the
/// diagonal just outside the bull's eye.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="topLeft">The top left.</param>
/// <param name="bottomLeft">The bottom left.</param>
/// <param name="bottomRight">The bottom right.</param>
/// <param name="topRight">The top right.</param>
/// <returns></returns>
private BitMatrix sampleGrid(BitMatrix image,
ResultPoint topLeft,
ResultPoint topRight,
ResultPoint bottomRight,
ResultPoint bottomLeft)
{
GridSampler sampler = GridSampler.Instance;
int dimension = getDimension();
float low = dimension / 2.0f - nbCenterLayers;
float high = dimension / 2.0f + nbCenterLayers;
return sampler.sampleGrid(image,
dimension,
dimension,
low, low, // topleft
high, low, // topright
high, high, // bottomright
low, high, // bottomleft
topLeft.X, topLeft.Y,
topRight.X, topRight.Y,
bottomRight.X, bottomRight.Y,
bottomLeft.X, bottomLeft.Y);
}
/// <summary>
/// Samples a line
/// </summary>
/// <param name="p1">start point (inclusive)</param>
/// <param name="p2">end point (exclusive)</param>
/// <param name="size">number of bits</param>
/// <returns> the array of bits as an int (first bit is high-order bit of result)</returns>
private int sampleLine(ResultPoint p1, ResultPoint p2, int size)
{
int result = 0;
float d = distance(p1, p2);
float moduleSize = d / size;
float px = p1.X;
float py = p1.Y;
float dx = moduleSize * (p2.X - p1.X) / d;
float dy = moduleSize * (p2.Y - p1.Y) / d;
for (int i = 0; i < size; i++)
{
if (image[MathUtils.round(px + i * dx), MathUtils.round(py + i * dy)])
{
result |= 1 << (size - i - 1);
}
}
return result;
}
/// <summary>
/// Determines whether [is white or black rectangle] [the specified p1].
/// </summary>
/// <param name="p1">The p1.</param>
/// <param name="p2">The p2.</param>
/// <param name="p3">The p3.</param>
/// <param name="p4">The p4.</param>
/// <returns>true if the border of the rectangle passed in parameter is compound of white points only
/// or black points only</returns>
private bool isWhiteOrBlackRectangle(Point p1, Point p2, Point p3, Point p4)
{
const int corr = 3;
p1 = new Point(Math.Max(0, p1.X - corr), Math.Min(image.Height - 1, p1.Y + corr));
p2 = new Point(Math.Max(0, p2.X - corr), Math.Max(0, p2.Y - corr));
p3 = new Point(Math.Min(image.Width - 1, p3.X + corr),
Math.Max(0, Math.Min(image.Height - 1, p3.Y - corr)));
p4 = new Point(Math.Min(image.Width - 1, p4.X + corr),
Math.Min(image.Height - 1, p4.Y + corr));
int cInit = getColor(p4, p1);
if (cInit == 0)
{
return false;
}
int c = getColor(p1, p2);
if (c != cInit)
{
return false;
}
c = getColor(p2, p3);
if (c != cInit)
{
return false;
}
c = getColor(p3, p4);
return c == cInit;
}
/// <summary>
/// Gets the color of a segment
/// </summary>
/// <param name="p1">The p1.</param>
/// <param name="p2">The p2.</param>
/// <returns>1 if segment more than 90% black, -1 if segment is more than 90% white, 0 else</returns>
private int getColor(Point p1, Point p2)
{
float d = distance(p1, p2);
if (d == 0.0f)
{
return 0;
}
float dx = (p2.X - p1.X) / d;
float dy = (p2.Y - p1.Y) / d;
int error = 0;
float px = p1.X;
float py = p1.Y;
bool colorModel = image[p1.X, p1.Y];
int iMax = (int)Math.Floor(d);
for (int i = 0; i < iMax; i++)
{
if (image[MathUtils.round(px), MathUtils.round(py)] != colorModel)
{
error++;
}
px += dx;
py += dy;
}
float errRatio = error / d;
if (errRatio > 0.1f && errRatio < 0.9f)
{
return 0;
}
return (errRatio <= 0.1f) == colorModel ? 1 : -1;
}
/// <summary>
/// Gets the coordinate of the first point with a different color in the given direction
/// </summary>
/// <param name="init">The init.</param>
/// <param name="color">if set to <c>true</c> [color].</param>
/// <param name="dx">The dx.</param>
/// <param name="dy">The dy.</param>
/// <returns></returns>
private Point getFirstDifferent(Point init, bool color, int dx, int dy)
{
int x = init.X + dx;
int y = init.Y + dy;
while (isValid(x, y) && image[x, y] == color)
{
x += dx;
y += dy;
}
x -= dx;
y -= dy;
while (isValid(x, y) && image[x, y] == color)
{
x += dx;
}
x -= dx;
while (isValid(x, y) && image[x, y] == color)
{
y += dy;
}
y -= dy;
return new Point(x, y);
}
/// <summary>
/// Expand the square represented by the corner points by pushing out equally in all directions
/// </summary>
/// <param name="cornerPoints">the corners of the square, which has the bull's eye at its center</param>
/// <param name="oldSide">the original length of the side of the square in the target bit matrix</param>
/// <param name="newSide">the new length of the size of the square in the target bit matrix</param>
/// <returns>the corners of the expanded square</returns>
private static ResultPoint[] expandSquare(ResultPoint[] cornerPoints, int oldSide, int newSide)
{
float ratio = newSide / (2.0f * oldSide);
float dx = cornerPoints[0].X - cornerPoints[2].X;
float dy = cornerPoints[0].Y - cornerPoints[2].Y;
float centerx = (cornerPoints[0].X + cornerPoints[2].X) / 2.0f;
float centery = (cornerPoints[0].Y + cornerPoints[2].Y) / 2.0f;
var result0 = new ResultPoint(centerx + ratio * dx, centery + ratio * dy);
var result2 = new ResultPoint(centerx - ratio * dx, centery - ratio * dy);
dx = cornerPoints[1].X - cornerPoints[3].X;
dy = cornerPoints[1].Y - cornerPoints[3].Y;
centerx = (cornerPoints[1].X + cornerPoints[3].X) / 2.0f;
centery = (cornerPoints[1].Y + cornerPoints[3].Y) / 2.0f;
var result1 = new ResultPoint(centerx + ratio * dx, centery + ratio * dy);
var result3 = new ResultPoint(centerx - ratio * dx, centery - ratio * dy);
return new ResultPoint[] { result0, result1, result2, result3 };
}
private bool isValid(int x, int y)
{
return x >= 0 && x < image.Width && y >= 0 && y < image.Height;
}
private bool isValid(ResultPoint point)
{
int x = MathUtils.round(point.X);
int y = MathUtils.round(point.Y);
return isValid(x, y);
}
// L2 distance
private static float distance(Point a, Point b)
{
return MathUtils.distance(a.X, a.Y, b.X, b.Y);
}
private static float distance(ResultPoint a, ResultPoint b)
{
return MathUtils.distance(a.X, a.Y, b.X, b.Y);
}
private int getDimension()
{
if (compact)
{
return 4 * nbLayers + 11;
}
return 4 * nbLayers + 2 * ((2 * nbLayers + 6) / 15) + 15;
}
internal sealed class Point
{
public int X { get; private set; }
public int Y { get; private set; }
public ResultPoint toResultPoint()
{
return new ResultPoint(X, Y);
}
internal Point(int x, int y)
{
X = x;
Y = y;
}
public override String ToString()
{
return "<" + X + ' ' + Y + '>';
}
}
}
}
| |
// ControlFile.cs
//
// Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Review documentation at http://www.yourothermind.com for updated implementation notes, license updates
// or other general information/
//
// Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW
// Full source code: https://github.com/BrentKnowles/YourOtherMind
//###
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.ComponentModel;
using CoreUtilities;
namespace SendTextAway
{
/// <summary>
/// Contains the data (serializable) that influences how the
/// automation shoudl behave (templates, et cetera)
/// </summary>
public class ControlFile
{
public ControlFile()
{
}
const string GENERAL = "General";
const string EPUB = "Format - ePub";
const string WORD = "Format - Word";
// for epub -- skippreface is there is not supposed to be one.
private bool skipPreface = false;
[Category(EPUB)]
public bool SkipPreface {
get { return skipPreface;}
set { skipPreface = value;}
}
private string overrideStyleSheet=String.Empty;
//user can specify a different stylesheet to use
public string OverrideStyleSheet {
get {
return overrideStyleSheet;
}
set {
overrideStyleSheet = value;
}
}
private string overridesectionbreak=Constants.BLANK;
[Category(EPUB)]
[Description("Put the CODE in for image break, i.e., src=\".\\images\fleuron.png\" height=\"39px\" width=\"100px\" ")]
public string Overridesectionbreak {
get {
return overridesectionbreak;
}
set {
overridesectionbreak = value;
}
}
private bool emdash_removespacesbeforeafter=false;
public bool Emdash_removespacesbeforeafter {
get {
return emdash_removespacesbeforeafter;
}
set {
emdash_removespacesbeforeafter = value;
}
}
private bool customEllip=false;
/// <summary>
/// if true then epub will convert .... to ... but fancy like
/// </summary>
/// <value>
/// <c>true</c> if custom ellip; otherwise, <c>false</c>.
/// </value>
[Category(EPUB)]
[Description("Will replace four periods with a fancy ellipsis but only if NOvelMode=true")]
public bool CustomEllip {
get {
return customEllip;
}
set {
customEllip = value;
}
}
private int chapterTitleOffset = -1;
/// <summary>
/// Gets or sets the chapter title offset.
///
/// For books that start with a Prelude (no title), we use this to offset the titling
///
/// </summary>
/// <value>
/// The chapter title offset.
/// </value>
public int ChapterTitleOffset {
get {
return chapterTitleOffset;
}
set {
chapterTitleOffset = value;
}
}
private bool arealValidatorSafe_Align = false;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="SendTextAway.ControlFile"/> areal validator safe_ align.
///
/// 14/07/2014 -- Added this to pass HTMl autotesting
/// Defaults to false so unit tests don't break
///
/// </summary>
/// <value>
/// <c>true</c> if areal validator safe_ align; otherwise, <c>false</c>.
/// </value>
[Category(EPUB)]
public bool ArealValidatorSafe_Align {
get {
return arealValidatorSafe_Align;
}
set {
arealValidatorSafe_Align = value;
}
}
private bool novelMode = false;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="SendTextAway.ControlFile"/> novel mode.
///
/// Use this to KEEP LINE INDENTS (re: tabs)
/// </summary>
/// <value>
/// <c>true</c> if novel mode; otherwise, <c>false</c>.
/// </value>
[Category(EPUB)]
public bool NovelMode {
get {
return novelMode;
}
set {
novelMode = value;
}
}
private bool _RemoveExcessSpaces=false;
[Category(GENERAL)]
[Description("false = leave them, true = remove strings of 5 spaces")]
public bool RemoveExcessSpaces
{
get { return _RemoveExcessSpaces; }
set { _RemoveExcessSpaces = value; }
}
private bool epubRemoveDoublePageTags=false;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="SendTextAway.ControlFile"/> epub remove double page tags.
///
/// For mobi format <p></p> is ignored as linefeed so we convert to <br/> (Incomplete as I write this comment but putting hooks in place just in case)
/// </summary>
/// <value>
/// <c>true</c> if epub remove double page tags; otherwise, <c>false</c>.
/// </value>
[Category(EPUB)]
public bool EpubRemoveDoublePageTags {
get { return epubRemoveDoublePageTags;}
set { epubRemoveDoublePageTags = value;}
}
private bool _KeepUnderscore = false;
// we hide this because were setting it on main form and can't update it
[Browsable(false)]
[Category(GENERAL)]
[Description("set to true if you want to keep underscores (no formatting)")]
public bool UnderscoreKeep
{
get { return _KeepUnderscore; }
set { _KeepUnderscore = value; }
}
public enum convertertype { word, epub, text };
private convertertype _convertype = convertertype.word;
// we hide this because were setting it on main form and can't update it
[Browsable(false)]
[Description("What type of conversion to do on the text (word, epub, text)")]
[Category(GENERAL)]
public convertertype ConverterType
{
get { return _convertype; }
set { _convertype = value; }
}
private int chatmode = 0;
/// <summary>
/// 0 = Uunderline
/// 1 = Italic
/// 2 = Bold
///
/// We use this markup (<<<blah<<<) for chat transcrips
/// </summary>
[Category(GENERAL)]
[Description("0 = underline; 1 = italic 2 = bold.")]
public int ChatMode
{
get { return chatmode; }
set { chatmode = value; }
}
private string _description;
[Category(GENERAL)]
public string Description
{
get { return _description; }
set { _description = value; }
}
// text message to display at end
private string _endmessage ="";
[Category(GENERAL)]
public string EndMessage
{
get { return _endmessage; }
set { _endmessage = value; }
}
private bool mRemoveTabs = false;
[Description("Smashwords does not want Tabs. This runs a processor removing all tab characters found.")]
[Category(GENERAL)]
public bool RemoveTabs
{
get { return mRemoveTabs; }
set { mRemoveTabs = value; }
}
private bool mUnderlineShouldBeItalicInstead = false;
// we hide this because were setting it on main form and can't update it
[Browsable(false)]
[Description("For Smashwords. Underscore text will be italic instead of underline.")]
[Category(GENERAL)]
public bool UnderlineShouldBeItalicInstead
{
get { return mUnderlineShouldBeItalicInstead; }
set { mUnderlineShouldBeItalicInstead = value; }
}
private bool mSceneBreakHasTab = true;
[Description("If set to false there won't be a tab added after scene break (for Smashwords).")]
[Category(GENERAL)]
public bool SceneBreakHasTab
{
get { return mSceneBreakHasTab; }
set { mSceneBreakHasTab = value; }
}
/// <summary>
/// i.e., [[~center]]\r\n#\r\n[[~left]]
/// </summary>
private string mSceneBreak;
[Description("Characters to use to indicate a scene break (like #). For HTML based exports this can be a full image path.")]
[Category(GENERAL)]
public string SceneBreak
{
get { return @mSceneBreak; }
set { mSceneBreak = @value; }
}
private int optionalcode = 1; // bold
[Description("If you want special formating when the marker [[optional]] is used, i.e., to indicate an optional feature in a game design document indicate 1 for bold or a 2 for italics. A 0 will not format things flaged as optional")]
[Category(GENERAL)]
public int OptionalCode
{
get { return optionalcode; }
set { optionalcode = value; }
}
private string optional = "(Optional)";
[Description("Will add this text beside any sentence flagged with the marker [[optional]]")]
[Category(GENERAL)]
public string Optional
{
get { return optional; }
set { optional = value; }
}
private bool showFootNoteChapter = false;
[Description("If set to true where the footnote is written will indicate the chapter it appeared in. Usually a debug feature.")]
[Category(GENERAL)]
public bool ShowFootNoteChapter
{
get { return showFootNoteChapter; }
set { showFootNoteChapter = value; }
}
/////////////////////////////////////// EPUB
/// <summary>
/// ////////////////////////////
/// </summary>
#region epubonly
private string outputdirectory=Constants.BLANK;
/// <summary>
/// For things like epub we can specify where the file should go
/// </summary>
[Description("Specify where the files should go. Will create a date-named folder therein and a zipped .epub file.")]
[Category(EPUB)]
public string OutputDirectory
{
get { return outputdirectory; }
set { outputdirectory = value; }
}
private int startingchapter=1;
/// <summary>
/// For things like epub we can specify where the file should go
/// </summary>
[Description("Start chapter numbering at this.")]
[Category(EPUB)]
public int StartingChapter
{
get { return startingchapter; }
set { startingchapter = value; }
}
bool copyTitleAndLegalTemplates = false;
[Description("If true will copy templates over for copyright, legal, and title page. User must add them manually to the .opf file however. These files are not requires, so only set this option if you really want them.")]
[Category(EPUB)]
public bool CopyTitleAndLegalTemplates {
get {
return copyTitleAndLegalTemplates;
}
set {
copyTitleAndLegalTemplates = value;
}
}
private string templatedirectory;
/// <summary>
/// For things like epub we can specify where the file should go
/// </summary>
[Description("Specify the directory containing source files, footer, and header files, et cetera.")]
[Category(EPUB)]
public string TemplateDirectory
{
get { return templatedirectory; }
set { templatedirectory = value; }
}
private string zipfile;
/// <summary>
/// For things like epub we can specify where the file should go
/// </summary>
[Description("Path to .exe that can zip the files after epub creation.")]
[Category(EPUB)]
public string Zipper
{
get { return zipfile; }
set { zipfile = value; }
}
#endregion
//////////////////////////////////////////////// WORD
#region WordOnly
/// <summary>
/// object reference to the body text style
/// </summary>
public object oBodyText; // object reference
private string bodyText;
// we hide this because were setting it on main form and can't update it
[Browsable(false)]
[Description("object reference to the body text style")]
[Category(WORD)]
public string BodyText
{
get { return bodyText; }
set
{
bodyText = value;
oBodyText = bodyText;
}
}
private bool fancyCharacters = false;
/// <summary>
/// Set to true if want ellipsis and quote to be replaced by fancy versions
/// </summary>
///
[Description("Set to true if want ellipsis and quote to be replaced by fancy versions")]
[Category(WORD)]
public bool FancyCharacters
{
get { return fancyCharacters; }
set { fancyCharacters = value; }
}
private string bullet;
[Description("The style 'List Bullet' is the default")]
[Category(WORD)]
public string Bullet
{
get { return bullet; }
set { bullet = value; }
}
private string bulletNumber;
[Description("The style 'List Number' is the default")]
[Category(WORD)]
public string BulletNumber
{
get { return bulletNumber; }
set { bulletNumber = value; }
}
// UNSORTED BELOW THIS
private string tableStyle;
/// <summary>
/// style to use for ||aa|| tables
/// </summary>
public string TableStyle
{
get { return tableStyle; }
set { tableStyle = value; }
}
/*
disabled, lost text between page breaks
private float linespace = 3F;
[Description("2 = double space")]
public float Linespace
{
get { return linespace; }
set { linespace = value; }
}*/
private string[] fixnumberlist;
/// <summary>
/// This is a bit of a hack but you specify second
/// and third level entrie like
/// i.
/// a.
/// In this type of list
/// </summary>
[Description("Help list numbers reset by specifying 2nd, 3rd tier list#s")]
public string[] FixNumberList
{
get { return fixnumberlist; }
set { fixnumberlist = value; }
}
private string[] listOfTags=null;
/// <summary>
/// Gets or sets the list of tags.
///
/// This are of the format of tag (without punctuation) | format code to use
/// Basic string replacement occurs before processing.
///
/// So:
///
/// game|'''
/// would replace text enclosed in <game>this</game> with '''this'''
///
/// </summary>
/// <value>
/// The list of tags.
/// </value>
public string[] ListOfTags {
get { return listOfTags;}
set { listOfTags = value;}
}
private string heading1;
public string Heading1
{
get { return heading1; }
set { heading1 = value; }
}
private string heading2;
public string Heading2
{
get { return heading2; }
set { heading2 = value; }
}
private string heading3;
public string Heading3
{
get { return heading3; }
set { heading3 = value; }
}
private string heading4;
public string Heading4
{
get { return heading4; }
set { heading4 = value; }
}
private string heading5;
public string Heading5
{
get { return heading5; }
set { heading5 = value; }
}
private string[] multiLineFormats;
public string[] MultiLineFormats
{
get { return multiLineFormats; }
set { multiLineFormats = value; }
}
private string[] multiLineFormatsValues;
public string[] MultiLineFormatsValues
{
get { return multiLineFormatsValues; }
set { multiLineFormatsValues = value; }
}
private string chaptertitle;
public string ChapterTitle
{
get { return chaptertitle; }
set { chaptertitle = value; }
}
private bool convertToEmDash = false;
// if true will convert -- to emdash
public bool ConvertToEmDash {
get {
return convertToEmDash;
}
set {
convertToEmDash = value;
}
}
private string template;
// we hide this because were setting it on main form and can't update it
[Browsable(false)]
/// <summary>
/// base template to use
/// </summary>
public string Template
{
get { return template; }
set { template = value; }
}
public static ControlFile Default {
get {
ControlFile returnControl = new ControlFile();
// MAIN CANDIATES
//*MAJOR*
returnControl.BodyText = "Body Text Courier";
returnControl.UnderlineShouldBeItalicInstead = false;
returnControl.UnderscoreKeep = false;
returnControl.Template="standardmanuscript.dotx";
//OTHER STUFF
returnControl.Bullet = "List Bullet";
returnControl.BulletNumber = "List Number";
returnControl.FancyCharacters = false;
returnControl.ChatMode = 0;
returnControl.ConverterType = convertertype.word;
returnControl.Description = "For standard story subs like Analog and Asimov";
returnControl.EndMessage = "REMEMBER to put space between Address and Title (about 1/3 page)";
returnControl.Optional = "(Optional)";
returnControl.OptionalCode = 1;
returnControl.RemoveExcessSpaces = false;
returnControl.RemoveTabs = false;
returnControl.SceneBreak = "#";
returnControl.SceneBreakHasTab = true;
returnControl.ShowFootNoteChapter = false;
returnControl.ChapterTitle = "Heading Document Top";
returnControl.FixNumberList = new string[0];
returnControl.Heading1 = "Heading2 Black Bar";
returnControl.Heading2 = "Heading3 Lined";
returnControl.Heading3 = "Heading3 Lined";
returnControl.Heading4 = "Heading3 Lined";
returnControl.Heading5 = "Heading 4";
returnControl.MultiLineFormats = new string[4] {"code","quote", "note", "past"};
returnControl.MultiLineFormatsValues = new string[4] {"Example", "Subtitle", "Subtitle", "bodytext2past_underline"};
returnControl.TableStyle = "Table Grid 2";
// build programmatically the 'standard' object
return returnControl;
}
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="WindowsSpinner.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Win32 Spinner Proxy
//
// History:
// [....]
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Text;
using System.ComponentModel;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
using System.Windows;
using MS.Win32;
namespace MS.Internal.AutomationProxies
{
// Proxy for a Windows NumericUpDown control with Windows Edit control, called a Spinner
class WindowsSpinner : ProxyHwnd, IRangeValueProvider
{
// ------------------------------------------------------
//
// Constructors
//
// ------------------------------------------------------
#region Constructors
// Contructor for WindownsSpinner class. Calls the base class constructor.
internal WindowsSpinner(IntPtr hwndUpDown, IntPtr hwndEdit, ProxyFragment parent, int item)
: base(hwndUpDown, parent, item)
{
_elEdit = new WindowsEditBox(hwndEdit, this, 0);
_elUpDown = new WindowsUpDown(hwndUpDown, this, 0);
// Set the strings to return properly the properties.
_cControlType = ControlType.Spinner;
// support for events
_createOnEvent = new WinEventTracker.ProxyRaiseEvents(RaiseEvents);
}
#endregion Constructors
#region Proxy Create
// Static Create method called by UIAutomation to create this proxy.
// returns null if unsuccessful
internal static IRawElementProviderSimple Create(IntPtr hwnd, int idChild, int idObject)
{
return Create(hwnd, idChild);
}
internal static IRawElementProviderSimple Create(IntPtr hwnd, int idChild)
{
// Something is wrong if idChild is not zero
if (idChild != 0)
{
System.Diagnostics.Debug.Assert (idChild == 0, "Invalid Child Id, idChild != 0");
throw new ArgumentOutOfRangeException("idChild", idChild, SR.Get(SRID.ShouldBeZero));
}
IntPtr hwndBuddy;
try
{
// Only use spinner class if we find a buddy that's an EDIT, otherwise return
// null to defer to the WindowsUpDown entry in the proxy table
hwndBuddy = Misc.ProxySendMessage(hwnd, NativeMethods.UDM_GETBUDDY, IntPtr.Zero, IntPtr.Zero);
if (hwndBuddy == IntPtr.Zero)
{
return null;
}
if (Misc.ProxyGetClassName(hwndBuddy).IndexOf("EDIT", StringComparison.OrdinalIgnoreCase) == -1)
{
return null;
}
}
catch (ElementNotAvailableException)
{
return null;
}
return new WindowsSpinner(hwnd, hwndBuddy, null, 0);
}
// Static Create method called by the event tracker system
internal static void RaiseEvents(IntPtr hwnd, int eventId, object idProp, int idObject, int idChild)
{
if (idObject == NativeMethods.OBJID_VSCROLL || idObject == NativeMethods.OBJID_HSCROLL)
{
return;
}
// ChildId will be non-0 if the event is due to operating on the updown part of the spinner.
// Events on non-content parts of a control are not necessary so don't raise an event in that case.
if ( idChild != 0 )
{
return;
}
ProxySimple ps = (ProxySimple)Create( hwnd, idChild, idObject );
if ( ps == null )
return;
ps.DispatchEvents( eventId, idProp, idObject, idChild );
}
#endregion Proxy Create
//------------------------------------------------------
//
// Patterns Implementation
//
//------------------------------------------------------
#region ProxySimple Interface
// Returns a pattern interface if supported.
internal override object GetPatternProvider (AutomationPattern iid)
{
return (iid == RangeValuePattern.Pattern) ? this : null;
}
// Gets the bounding rectangle for this element
internal override Rect BoundingRectangle
{
get
{
Rect rcUpDown = _elUpDown.BoundingRectangle;
Rect rcEdit = _elEdit.BoundingRectangle;
return Rect.Union(rcEdit, rcUpDown);
}
}
internal override object GetElementProperty(AutomationProperty idProp)
{
if (idProp == AutomationElement.ClickablePointProperty)
{
return _elEdit.GetElementProperty(idProp);
}
else if (idProp == AutomationElement.HasKeyboardFocusProperty)
{
return _elEdit.GetElementProperty(idProp);
}
return base.GetElementProperty(idProp);
}
#endregion ProxySimple Interface
#region ProxyFragment Interface
// Returns a Proxy element corresponding to the specified screen coordinates.
internal override ProxySimple ElementProviderFromPoint(int x, int y)
{
Rect rcUpDown = _elUpDown.BoundingRectangle;
Rect rcEdit = _elEdit.BoundingRectangle;
Point pt = new Point(x, y);
if (rcUpDown.Contains(pt))
{
return _elUpDown.ElementProviderFromPoint(x, y);
}
else if (rcEdit.Contains(pt))
{
return this;
}
return base.ElementProviderFromPoint(x, y);
}
// Returns the next sibling element in the raw hierarchy.
// Peripheral controls have always negative values.
// Returns null if no next child.
internal override ProxySimple GetNextSibling(ProxySimple child)
{
return _elUpDown.GetNextSibling(child);
}
// Returns the previous sibling element in the raw hierarchy.
// Peripheral controls have always negative values.
// Returns null is no previous.
internal override ProxySimple GetPreviousSibling(ProxySimple child)
{
return _elUpDown.GetPreviousSibling(child);
}
// Returns the first child element in the raw hierarchy.
internal override ProxySimple GetFirstChild()
{
return _elUpDown.GetFirstChild();
}
// Returns the last child element in the raw hierarchy.
internal override ProxySimple GetLastChild()
{
return _elUpDown.GetLastChild();
}
#endregion
#region RangeValue Pattern
// Sets a new position for the edit part of the spinner.
void IRangeValueProvider.SetValue (double obj)
{
((IRangeValueProvider)_elUpDown).SetValue(obj);
}
// Request to get the value that this UI element is representing in a native format
double IRangeValueProvider.Value
{
get
{
return ((IRangeValueProvider)_elUpDown).Value;
}
}
bool IRangeValueProvider.IsReadOnly
{
get
{
return (bool)((IRangeValueProvider)_elUpDown).IsReadOnly &&
(bool)((IValueProvider)_elEdit).IsReadOnly;
}
}
double IRangeValueProvider.Maximum
{
get
{
return ((IRangeValueProvider) _elUpDown).Maximum;
}
}
double IRangeValueProvider.Minimum
{
get
{
return ((IRangeValueProvider) _elUpDown).Minimum;
}
}
double IRangeValueProvider.SmallChange
{
get
{
return ((IRangeValueProvider)_elUpDown).SmallChange;
}
}
double IRangeValueProvider.LargeChange
{
get
{
return ((IRangeValueProvider)_elUpDown).LargeChange;
}
}
#endregion RangeValuePattern
// ------------------------------------------------------
//
// Internal methods
//
// ------------------------------------------------------
#region Internal Methods
// if there is an UpDown control that its buddy window is the same as the given edit hwnd
// the edit is part of the spinner.
internal static bool IsSpinnerEdit(IntPtr hwnd)
{
return GetUpDownFromEdit(hwnd) != IntPtr.Zero;
}
// Try to find a sibling of the edit control that is an UpDown control that has the
// edit contol as its buddy window. If one is found return the hwnd of the UpDown control.
internal static IntPtr GetUpDownFromEdit(IntPtr hwnd)
{
IntPtr hwndParent = Misc.GetParent(hwnd);
if (hwndParent != IntPtr.Zero)
{
IntPtr hwndChild = Misc.GetWindow(hwndParent, NativeMethods.GW_CHILD);
while (hwndChild != IntPtr.Zero)
{
string className = Misc.ProxyGetClassName(hwndChild);
if (className.IndexOf("msctls_updown32", StringComparison.OrdinalIgnoreCase) != -1)
{
IntPtr hwndBuddy = Misc.ProxySendMessage(hwndChild, NativeMethods.UDM_GETBUDDY, IntPtr.Zero, IntPtr.Zero);
if (hwnd == hwndBuddy)
{
return hwndChild;
}
}
hwndChild = Misc.GetWindow(hwndChild, NativeMethods.GW_HWNDNEXT);
}
}
return IntPtr.Zero;
}
#endregion Internal Methods
// ------------------------------------------------------
//
// Private Fields
//
// ------------------------------------------------------
#region Private Fields
private WindowsEditBox _elEdit;
private WindowsUpDown _elUpDown;
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IdentityModel.Claims;
using System.Security.Principal;
using System.ServiceModel;
namespace System.IdentityModel.Policy
{
internal interface IIdentityInfo
{
IIdentity Identity { get; }
}
internal class UnconditionalPolicy : IAuthorizationPolicy, IDisposable
{
private SecurityUniqueId _id;
private ClaimSet _issuer;
private ClaimSet _issuance;
private ReadOnlyCollection<ClaimSet> _issuances;
private DateTime _expirationTime;
private IIdentity _primaryIdentity;
private bool _disposable = false;
private bool _disposed = false;
public UnconditionalPolicy(ClaimSet issuance)
: this(issuance, SecurityUtils.MaxUtcDateTime)
{
}
public UnconditionalPolicy(ClaimSet issuance, DateTime expirationTime)
{
if (issuance == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuance");
Initialize(ClaimSet.System, issuance, null, expirationTime);
}
public UnconditionalPolicy(ReadOnlyCollection<ClaimSet> issuances, DateTime expirationTime)
{
if (issuances == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuances");
Initialize(ClaimSet.System, null, issuances, expirationTime);
}
internal UnconditionalPolicy(IIdentity primaryIdentity, ClaimSet issuance)
: this(issuance)
{
_primaryIdentity = primaryIdentity;
}
internal UnconditionalPolicy(IIdentity primaryIdentity, ClaimSet issuance, DateTime expirationTime)
: this(issuance, expirationTime)
{
_primaryIdentity = primaryIdentity;
}
internal UnconditionalPolicy(IIdentity primaryIdentity, ReadOnlyCollection<ClaimSet> issuances, DateTime expirationTime)
: this(issuances, expirationTime)
{
_primaryIdentity = primaryIdentity;
}
private UnconditionalPolicy(UnconditionalPolicy from)
{
_disposable = from._disposable;
_primaryIdentity = from._disposable ? SecurityUtils.CloneIdentityIfNecessary(from._primaryIdentity) : from._primaryIdentity;
if (from._issuance != null)
{
_issuance = from._disposable ? SecurityUtils.CloneClaimSetIfNecessary(from._issuance) : from._issuance;
}
else
{
_issuances = from._disposable ? SecurityUtils.CloneClaimSetsIfNecessary(from._issuances) : from._issuances;
}
_issuer = from._issuer;
_expirationTime = from._expirationTime;
}
private void Initialize(ClaimSet issuer, ClaimSet issuance, ReadOnlyCollection<ClaimSet> issuances, DateTime expirationTime)
{
_issuer = issuer;
_issuance = issuance;
_issuances = issuances;
_expirationTime = expirationTime;
if (issuance != null)
{
_disposable = issuance is WindowsClaimSet;
}
else
{
for (int i = 0; i < issuances.Count; ++i)
{
if (issuances[i] is WindowsClaimSet)
{
_disposable = true;
break;
}
}
}
}
public string Id
{
get
{
if (_id == null)
_id = SecurityUniqueId.Create();
return _id.Value;
}
}
public ClaimSet Issuer
{
get { return _issuer; }
}
internal IIdentity PrimaryIdentity
{
get
{
ThrowIfDisposed();
if (_primaryIdentity == null)
{
IIdentity identity = null;
if (_issuance != null)
{
if (_issuance is IIdentityInfo)
{
identity = ((IIdentityInfo)_issuance).Identity;
}
}
else
{
for (int i = 0; i < _issuances.Count; ++i)
{
ClaimSet issuance = _issuances[i];
if (issuance is IIdentityInfo)
{
identity = ((IIdentityInfo)issuance).Identity;
// Preferably Non-Anonymous
if (identity != null && identity != SecurityUtils.AnonymousIdentity)
{
break;
}
}
}
}
_primaryIdentity = identity ?? SecurityUtils.AnonymousIdentity;
}
return _primaryIdentity;
}
}
internal ReadOnlyCollection<ClaimSet> Issuances
{
get
{
ThrowIfDisposed();
if (_issuances == null)
{
List<ClaimSet> issuances = new List<ClaimSet>(1);
issuances.Add(_issuance);
_issuances = new ReadOnlyCollection<ClaimSet>(issuances);
}
return _issuances;
}
}
public DateTime ExpirationTime
{
get { return _expirationTime; }
}
internal bool IsDisposable
{
get { return _disposable; }
}
internal UnconditionalPolicy Clone()
{
ThrowIfDisposed();
return (_disposable) ? new UnconditionalPolicy(this) : this;
}
public virtual void Dispose()
{
if (_disposable && !_disposed)
{
_disposed = true;
SecurityUtils.DisposeIfNecessary(_primaryIdentity as IDisposable);
SecurityUtils.DisposeClaimSetIfNecessary(_issuance);
SecurityUtils.DisposeClaimSetsIfNecessary(_issuances);
}
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
}
public virtual bool Evaluate(EvaluationContext evaluationContext, ref object state)
{
ThrowIfDisposed();
if (_issuance != null)
{
evaluationContext.AddClaimSet(this, _issuance);
}
else
{
for (int i = 0; i < _issuances.Count; ++i)
{
if (_issuances[i] != null)
{
evaluationContext.AddClaimSet(this, _issuances[i]);
}
}
}
// Preferably Non-Anonymous
if (this.PrimaryIdentity != null && this.PrimaryIdentity != SecurityUtils.AnonymousIdentity)
{
IList<IIdentity> identities;
object obj;
if (!evaluationContext.Properties.TryGetValue(SecurityUtils.Identities, out obj))
{
identities = new List<IIdentity>(1);
evaluationContext.Properties.Add(SecurityUtils.Identities, identities);
}
else
{
// null if other overrides the property with something else
identities = obj as IList<IIdentity>;
}
if (identities != null)
{
identities.Add(this.PrimaryIdentity);
}
}
evaluationContext.RecordExpirationTime(_expirationTime);
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Orleans.GrainDirectory;
namespace Orleans.Runtime.GrainDirectory
{
[Serializable]
internal class ActivationInfo : IActivationInfo
{
public SiloAddress SiloAddress { get; private set; }
public DateTime TimeCreated { get; private set; }
public GrainDirectoryEntryStatus RegistrationStatus { get; set; }
public ActivationInfo(SiloAddress siloAddress, GrainDirectoryEntryStatus registrationStatus)
{
SiloAddress = siloAddress;
TimeCreated = DateTime.UtcNow;
RegistrationStatus = registrationStatus;
}
public ActivationInfo(IActivationInfo iActivationInfo)
{
SiloAddress = iActivationInfo.SiloAddress;
TimeCreated = iActivationInfo.TimeCreated;
RegistrationStatus = iActivationInfo.RegistrationStatus;
}
public bool OkToRemove(UnregistrationCause cause)
{
switch (cause)
{
case UnregistrationCause.Force:
return true;
case UnregistrationCause.CacheInvalidation:
return RegistrationStatus == GrainDirectoryEntryStatus.Cached;
case UnregistrationCause.NonexistentActivation:
{
if (RegistrationStatus == GrainDirectoryEntryStatus.Cached)
return true; // cache entries are always removed
var delayparameter = Silo.CurrentSilo.OrleansConfig.Globals.DirectoryLazyDeregistrationDelay;
if (delayparameter <= TimeSpan.Zero)
return false; // no lazy deregistration
else
return (TimeCreated <= DateTime.UtcNow - delayparameter);
}
default:
throw new OrleansException("unhandled case");
}
}
public override string ToString()
{
return String.Format("{0}, {1}", SiloAddress, TimeCreated);
}
}
[Serializable]
internal class GrainInfo : IGrainInfo
{
public Dictionary<ActivationId, IActivationInfo> Instances { get; private set; }
public int VersionTag { get; private set; }
public bool SingleInstance { get; private set; }
private static readonly SafeRandom rand;
internal const int NO_ETAG = -1;
static GrainInfo()
{
rand = new SafeRandom();
}
internal GrainInfo()
{
Instances = new Dictionary<ActivationId, IActivationInfo>();
VersionTag = 0;
SingleInstance = false;
}
public bool AddActivation(ActivationId act, SiloAddress silo)
{
if (SingleInstance && (Instances.Count > 0) && !Instances.ContainsKey(act))
{
throw new InvalidOperationException(
"Attempting to add a second activation to an existing grain in single activation mode");
}
IActivationInfo info;
if (Instances.TryGetValue(act, out info))
{
if (info.SiloAddress.Equals(silo))
{
// just refresh, no need to generate new VersionTag
return false;
}
}
Instances[act] = new ActivationInfo(silo, GrainDirectoryEntryStatus.ClusterLocal);
VersionTag = rand.Next();
return true;
}
public ActivationAddress AddSingleActivation(GrainId grain, ActivationId act, SiloAddress silo, GrainDirectoryEntryStatus registrationStatus)
{
SingleInstance = true;
if (Instances.Count > 0)
{
var item = Instances.First();
return ActivationAddress.GetAddress(item.Value.SiloAddress, grain, item.Key);
}
else
{
Instances.Add(act, new ActivationInfo(silo, registrationStatus));
VersionTag = rand.Next();
return ActivationAddress.GetAddress(silo, grain, act);
}
}
public bool RemoveActivation(ActivationId act, UnregistrationCause cause, out IActivationInfo info, out bool wasRemoved)
{
info = null;
wasRemoved = false;
if (Instances.TryGetValue(act, out info) && info.OkToRemove(cause))
{
Instances.Remove(act);
wasRemoved = true;
VersionTag = rand.Next();
}
return Instances.Count == 0;
}
public bool Merge(GrainId grain, IGrainInfo other)
{
bool modified = false;
foreach (var pair in other.Instances)
{
if (Instances.ContainsKey(pair.Key)) continue;
Instances[pair.Key] = new ActivationInfo(pair.Value.SiloAddress, pair.Value.RegistrationStatus);
modified = true;
}
if (modified)
{
VersionTag = rand.Next();
}
if (SingleInstance && (Instances.Count > 0))
{
// Grain is supposed to be in single activation mode, but we have two activations!!
// Eventually we should somehow delegate handling this to the silo, but for now, we'll arbitrarily pick one value.
var orderedActivations = Instances.OrderBy(pair => pair.Key);
var activationToKeep = orderedActivations.First();
var activationsToDrop = orderedActivations.Skip(1);
Instances.Clear();
Instances.Add(activationToKeep.Key, activationToKeep.Value);
var list = new List<ActivationAddress>(1);
foreach (var activation in activationsToDrop.Select(keyValuePair => ActivationAddress.GetAddress(keyValuePair.Value.SiloAddress, grain, keyValuePair.Key)))
{
list.Add(activation);
InsideRuntimeClient.Current.InternalGrainFactory.GetSystemTarget<ICatalog>(Constants.CatalogId, activation.Silo).
DeleteActivations(list).Ignore();
list.Clear();
}
return true;
}
return false;
}
public void CacheOrUpdateRemoteClusterRegistration(GrainId grain, ActivationId oldActivation, ActivationId activation, SiloAddress silo)
{
SingleInstance = true;
if (Instances.Count > 0)
{
Instances.Remove(oldActivation);
}
Instances.Add(activation, new ActivationInfo(silo, GrainDirectoryEntryStatus.Cached));
}
public bool UpdateClusterRegistrationStatus(ActivationId activationId, GrainDirectoryEntryStatus status, GrainDirectoryEntryStatus? compareWith = null)
{
IActivationInfo activationInfo;
if (!Instances.TryGetValue(activationId, out activationInfo))
return false;
if (compareWith.HasValue && compareWith.Value != activationInfo.RegistrationStatus)
return false;
activationInfo.RegistrationStatus = status;
return true;
}
}
internal class GrainDirectoryPartition
{
// Should we change this to SortedList<> or SortedDictionary so we can extract chunks better for shipping the full
// parition to a follower, or should we leave it as a Dictionary to get O(1) lookups instead of O(log n), figuring we do
// a lot more lookups and so can sort periodically?
/// <summary>
/// contains a map from grain to its list of activations along with the version (etag) counter for the list
/// </summary>
private Dictionary<GrainId, IGrainInfo> partitionData;
private readonly object lockable;
private readonly Logger log;
private ISiloStatusOracle membership;
internal int Count { get { return partitionData.Count; } }
internal GrainDirectoryPartition()
{
partitionData = new Dictionary<GrainId, IGrainInfo>();
lockable = new object();
log = LogManager.GetLogger("DirectoryPartition");
membership = Silo.CurrentSilo.LocalSiloStatusOracle;
}
private bool IsValidSilo(SiloAddress silo)
{
if (membership == null)
{
membership = Silo.CurrentSilo.LocalSiloStatusOracle;
}
return membership.IsFunctionalDirectory(silo);
}
internal void Clear()
{
lock (lockable)
{
partitionData.Clear();
}
}
/// <summary>
/// Returns all entries stored in the partition as an enumerable collection
/// </summary>
/// <returns></returns>
public Dictionary<GrainId, IGrainInfo> GetItems()
{
lock (lockable)
{
return partitionData.Copy();
}
}
/// <summary>
/// Adds a new activation to the directory partition
/// </summary>
/// <param name="grain"></param>
/// <param name="activation"></param>
/// <param name="silo"></param>
/// <returns>The version associated with this directory mapping</returns>
internal virtual int AddActivation(GrainId grain, ActivationId activation, SiloAddress silo)
{
if (!IsValidSilo(silo))
{
return GrainInfo.NO_ETAG;
}
lock (lockable)
{
if (!partitionData.ContainsKey(grain))
{
partitionData[grain] = new GrainInfo();
}
partitionData[grain].AddActivation(activation, silo);
}
if (log.IsVerbose3) log.Verbose3("Adding activation for grain {0}", grain.ToString());
return partitionData[grain].VersionTag;
}
/// <summary>
/// Adds a new activation to the directory partition
/// </summary>
/// <param name="grain"></param>
/// <param name="activation"></param>
/// <param name="silo"></param>
/// <param name="registrationStatus"></param>
/// <returns>The registered ActivationAddress and version associated with this directory mapping</returns>
internal virtual AddressAndTag AddSingleActivation(GrainId grain, ActivationId activation, SiloAddress silo, GrainDirectoryEntryStatus registrationStatus)
{
if (log.IsVerbose3) log.Verbose3("Adding single activation for grain {0}{1}{2}", silo, grain, activation);
AddressAndTag result = new AddressAndTag();
if (!IsValidSilo(silo))
return result;
lock (lockable)
{
if (!partitionData.ContainsKey(grain))
{
partitionData[grain] = new GrainInfo();
}
var grainInfo = partitionData[grain];
result.Address = grainInfo.AddSingleActivation(grain, activation, silo, registrationStatus);
result.VersionTag = grainInfo.VersionTag;
}
return result;
}
/// <summary>
/// Removes an activation of the given grain from the partition
/// </summary>
/// <param name="grain">the identity of the grain</param>
/// <param name="activation">the id of the activation</param>
/// <param name="cause">reason for removing the activation</param>
internal void RemoveActivation(GrainId grain, ActivationId activation, UnregistrationCause cause = UnregistrationCause.Force)
{
IActivationInfo ignore1;
bool ignore2;
RemoveActivation(grain, activation, cause, out ignore1, out ignore2);
}
/// <summary>
/// Removes an activation of the given grain from the partition
/// </summary>
/// <param name="grain">the identity of the grain</param>
/// <param name="activation">the id of the activation</param>
/// <param name="cause">reason for removing the activation</param>
/// <param name="entry">returns the entry, if found </param>
/// <param name="wasRemoved">returns whether the entry was actually removed</param>
internal void RemoveActivation(GrainId grain, ActivationId activation, UnregistrationCause cause, out IActivationInfo entry, out bool wasRemoved)
{
wasRemoved = false;
entry = null;
lock (lockable)
{
if (partitionData.ContainsKey(grain) && partitionData[grain].RemoveActivation(activation, cause, out entry, out wasRemoved))
// if the last activation for the grain was removed, we remove the entire grain info
partitionData.Remove(grain);
}
if (log.IsVerbose3)
log.Verbose3("Removing activation for grain {0} cause={1} was_removed={2}", grain.ToString(), cause, wasRemoved);
}
/// <summary>
/// Removes the grain (and, effectively, all its activations) from the diretcory
/// </summary>
/// <param name="grain"></param>
internal void RemoveGrain(GrainId grain)
{
lock (lockable)
{
partitionData.Remove(grain);
}
if (log.IsVerbose3) log.Verbose3("Removing grain {0}", grain.ToString());
}
/// <summary>
/// Returns a list of activations (along with the version number of the list) for the given grain.
/// If the grain is not found, null is returned.
/// </summary>
/// <param name="grain"></param>
/// <returns></returns>
internal AddressesAndTag LookUpActivations(GrainId grain)
{
var result = new AddressesAndTag();
lock (lockable)
{
IGrainInfo graininfo;
if (partitionData.TryGetValue(grain, out graininfo))
{
result.Addresses = new List<ActivationAddress>();
result.VersionTag = partitionData[grain].VersionTag;
foreach (var route in partitionData[grain].Instances)
{
if (IsValidSilo(route.Value.SiloAddress))
result.Addresses.Add(ActivationAddress.GetAddress(route.Value.SiloAddress, grain, route.Key));
}
}
}
return result;
}
/// <summary>
/// Returns the activation of a single-activation grain, if present.
/// </summary>
internal GrainDirectoryEntryStatus TryGetActivation(GrainId grain, out ActivationAddress address, out int version)
{
lock (lockable)
{
IGrainInfo graininfo;
if (partitionData.TryGetValue(grain, out graininfo))
{
var first = graininfo.Instances.FirstOrDefault();
if (first.Value != null)
{
address = ActivationAddress.GetAddress(first.Value.SiloAddress, grain, first.Key);
version = graininfo.VersionTag;
return first.Value.RegistrationStatus;
}
}
}
address = null;
version = 0;
return GrainDirectoryEntryStatus.Invalid;
}
/// <summary>
/// Returns the version number of the list of activations for the grain.
/// If the grain is not found, -1 is returned.
/// </summary>
/// <param name="grain"></param>
/// <returns></returns>
internal int GetGrainETag(GrainId grain)
{
lock (lockable)
{
return partitionData.ContainsKey(grain) ?
partitionData[grain].VersionTag : GrainInfo.NO_ETAG;
}
}
/// <summary>
/// Merges one partition into another, asuuming partitions are disjoint.
/// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes.
/// </summary>
/// <param name="other"></param>
internal void Merge(GrainDirectoryPartition other)
{
lock (lockable)
{
foreach (var pair in other.partitionData)
{
if (partitionData.ContainsKey(pair.Key))
{
if (log.IsVerbose) log.Verbose("While merging two disjoint partitions, same grain " + pair.Key + " was found in both partitions");
partitionData[pair.Key].Merge(pair.Key, pair.Value);
}
else
{
partitionData.Add(pair.Key, pair.Value);
}
}
}
}
/// <summary>
/// Runs through all entries in the partition and moves/copies (depending on the given flag) the
/// entries satisfying the given predicate into a new partition.
/// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes.
/// </summary>
/// <param name="predicate">filter predicate (usually if the given grain is owned by particular silo)</param>
/// <param name="modifyOrigin">flag controling whether the source partition should be modified (i.e., the entries should be moved or just copied) </param>
/// <returns>new grain directory partition containing entries satisfying the given predicate</returns>
internal GrainDirectoryPartition Split(Predicate<GrainId> predicate, bool modifyOrigin)
{
var newDirectory = new GrainDirectoryPartition();
if (modifyOrigin)
{
// SInce we use the "pairs" list to modify the underlying collection below, we need to turn it into an actual list here
List<KeyValuePair<GrainId, IGrainInfo>> pairs;
lock (lockable)
{
pairs = partitionData.Where(pair => predicate(pair.Key)).ToList();
}
foreach (var pair in pairs)
{
newDirectory.partitionData.Add(pair.Key, pair.Value);
}
lock (lockable)
{
foreach (var pair in pairs)
{
partitionData.Remove(pair.Key);
}
}
}
else
{
lock (lockable)
{
foreach (var pair in partitionData.Where(pair => predicate(pair.Key)))
{
newDirectory.partitionData.Add(pair.Key, pair.Value);
}
}
}
return newDirectory;
}
internal List<ActivationAddress> ToListOfActivations(bool singleActivation)
{
var result = new List<ActivationAddress>();
lock (lockable)
{
foreach (var pair in partitionData)
{
var grain = pair.Key;
if (pair.Value.SingleInstance == singleActivation)
{
result.AddRange(pair.Value.Instances.Select(activationPair => ActivationAddress.GetAddress(activationPair.Value.SiloAddress, grain, activationPair.Key))
.Where(addr => IsValidSilo(addr.Silo)));
}
}
}
return result;
}
/// <summary>
/// Sets the internal parition dictionary to the one given as input parameter.
/// This method is supposed to be used by handoff manager to update the old partition with a new partition.
/// </summary>
/// <param name="newPartitionData">new internal partition dictionary</param>
internal void Set(Dictionary<GrainId, IGrainInfo> newPartitionData)
{
partitionData = newPartitionData;
}
/// <summary>
/// Updates partition with a new delta of changes.
/// This method is supposed to be used by handoff manager to update the partition with a set of delta changes.
/// </summary>
/// <param name="newPartitionDelta">dictionary holding a set of delta updates to this partition.
/// If the value for a given key in the delta is valid, then existing entry in the partition is replaced.
/// Otherwise, i.e., if the value is null, the corresponding entry is removed.
/// </param>
internal void Update(Dictionary<GrainId, IGrainInfo> newPartitionDelta)
{
lock (lockable)
{
foreach (GrainId grain in newPartitionDelta.Keys)
{
if (newPartitionDelta[grain] != null)
{
partitionData[grain] = newPartitionDelta[grain];
}
else
{
partitionData.Remove(grain);
}
}
}
}
public override string ToString()
{
var sb = new StringBuilder();
lock (lockable)
{
foreach (var grainEntry in partitionData)
{
foreach (var activationEntry in grainEntry.Value.Instances)
{
sb.Append(" ").Append(grainEntry.Key.ToString()).Append("[" + grainEntry.Value.VersionTag + "]").
Append(" => ").Append(activationEntry.Key.ToString()).
Append(" @ ").AppendLine(activationEntry.Value.ToString());
}
}
}
return sb.ToString();
}
public void CacheOrUpdateRemoteClusterRegistration(GrainId grain, ActivationId oldActivation, ActivationAddress otherClusterAddress)
{
lock (lockable)
{
if (partitionData.ContainsKey(grain))
{
partitionData[grain].CacheOrUpdateRemoteClusterRegistration(grain, oldActivation,
otherClusterAddress.Activation, otherClusterAddress.Silo);
}
else
{
AddSingleActivation(grain, otherClusterAddress.Activation, otherClusterAddress.Silo,
GrainDirectoryEntryStatus.Cached);
}
}
}
public bool UpdateClusterRegistrationStatus(GrainId grain, ActivationId activationId, GrainDirectoryEntryStatus registrationStatus, GrainDirectoryEntryStatus? compareWith = null)
{
lock (lockable)
{
IGrainInfo graininfo;
if (partitionData.TryGetValue(grain, out graininfo))
{
return graininfo.UpdateClusterRegistrationStatus(activationId, registrationStatus, compareWith);
}
return false;
}
}
}
}
| |
/*
* Copyright (c) 2007-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.Text;
namespace OpenMetaverse
{
/// <summary>
/// A Name Value pair with additional settings, used in the protocol
/// primarily to transmit avatar names and active group in object packets
/// </summary>
public struct NameValue
{
#region Enums
/// <summary>Type of the value</summary>
public enum ValueType
{
/// <summary>Unknown</summary>
Unknown = -1,
/// <summary>String value</summary>
String,
/// <summary></summary>
F32,
/// <summary></summary>
S32,
/// <summary></summary>
VEC3,
/// <summary></summary>
U32,
/// <summary>Deprecated</summary>
[Obsolete]
CAMERA,
/// <summary>String value, but designated as an asset</summary>
Asset,
/// <summary></summary>
U64
}
/// <summary>
///
/// </summary>
public enum ClassType
{
/// <summary></summary>
Unknown = -1,
/// <summary></summary>
ReadOnly,
/// <summary></summary>
ReadWrite,
/// <summary></summary>
Callback
}
/// <summary>
///
/// </summary>
public enum SendtoType
{
/// <summary></summary>
Unknown = -1,
/// <summary></summary>
Sim,
/// <summary></summary>
DataSim,
/// <summary></summary>
SimViewer,
/// <summary></summary>
DataSimViewer
}
#endregion Enums
/// <summary></summary>
public string Name;
/// <summary></summary>
public ValueType Type;
/// <summary></summary>
public ClassType Class;
/// <summary></summary>
public SendtoType Sendto;
/// <summary></summary>
public object Value;
private static readonly string[] TypeStrings = new string[]
{
"STRING",
"F32",
"S32",
"VEC3",
"U32",
"ASSET",
"U64"
};
private static readonly string[] ClassStrings = new string[]
{
"R", // Read-only
"RW", // Read-write
"CB" // Callback
};
private static readonly string[] SendtoStrings = new string[]
{
"S", // Sim
"DS", // Data Sim
"SV", // Sim Viewer
"DSV" // Data Sim Viewer
};
private static readonly char[] Separators = new char[]
{
' ',
'\n',
'\t',
'\r'
};
/// <summary>
/// Constructor that takes all the fields as parameters
/// </summary>
/// <param name="name"></param>
/// <param name="valueType"></param>
/// <param name="classType"></param>
/// <param name="sendtoType"></param>
/// <param name="value"></param>
public NameValue(string name, ValueType valueType, ClassType classType, SendtoType sendtoType, object value)
{
Name = name;
Type = valueType;
Class = classType;
Sendto = sendtoType;
Value = value;
}
/// <summary>
/// Constructor that takes a single line from a NameValue field
/// </summary>
/// <param name="data"></param>
public NameValue(string data)
{
int i;
// Name
i = data.IndexOfAny(Separators);
if (i < 1)
{
Name = String.Empty;
Type = ValueType.Unknown;
Class = ClassType.Unknown;
Sendto = SendtoType.Unknown;
Value = null;
return;
}
Name = data.Substring(0, i);
data = data.Substring(i + 1);
// Type
i = data.IndexOfAny(Separators);
if (i > 0)
{
Type = GetValueType(data.Substring(0, i));
data = data.Substring(i + 1);
// Class
i = data.IndexOfAny(Separators);
if (i > 0)
{
Class = GetClassType(data.Substring(0, i));
data = data.Substring(i + 1);
// Sendto
i = data.IndexOfAny(Separators);
if (i > 0)
{
Sendto = GetSendtoType(data.Substring(0, 1));
data = data.Substring(i + 1);
}
}
}
// Value
Type = ValueType.String;
Class = ClassType.ReadOnly;
Sendto = SendtoType.Sim;
Value = null;
SetValue(data);
}
public static string NameValuesToString(NameValue[] values)
{
if (values == null || values.Length == 0)
return String.Empty;
StringBuilder output = new StringBuilder();
for (int i = 0; i < values.Length; i++)
{
NameValue value = values[i];
if (value.Value != null)
{
string newLine = (i < values.Length - 1) ? "\n" : String.Empty;
output.AppendFormat("{0} {1} {2} {3} {4}{5}", value.Name, TypeStrings[(int)value.Type],
ClassStrings[(int)value.Class], SendtoStrings[(int)value.Sendto], value.Value.ToString(), newLine);
}
}
return output.ToString();
}
private void SetValue(string value)
{
switch (Type)
{
case ValueType.Asset:
case ValueType.String:
Value = value;
break;
case ValueType.F32:
{
float temp;
Utils.TryParseSingle(value, out temp);
Value = temp;
break;
}
case ValueType.S32:
{
int temp;
Int32.TryParse(value, out temp);
Value = temp;
break;
}
case ValueType.U32:
{
uint temp;
UInt32.TryParse(value, out temp);
Value = temp;
break;
}
case ValueType.U64:
{
ulong temp;
UInt64.TryParse(value, out temp);
Value = temp;
break;
}
case ValueType.VEC3:
{
Vector3 temp;
Vector3.TryParse(value, out temp);
Value = temp;
break;
}
default:
Value = null;
break;
}
}
private static ValueType GetValueType(string value)
{
ValueType type = ValueType.Unknown;
for (int i = 0; i < TypeStrings.Length; i++)
{
if (value == TypeStrings[i])
{
type = (ValueType)i;
break;
}
}
if (type == ValueType.Unknown)
type = ValueType.String;
return type;
}
private static ClassType GetClassType(string value)
{
ClassType type = ClassType.Unknown;
for (int i = 0; i < ClassStrings.Length; i++)
{
if (value == ClassStrings[i])
{
type = (ClassType)i;
break;
}
}
if (type == ClassType.Unknown)
type = ClassType.ReadOnly;
return type;
}
private static SendtoType GetSendtoType(string value)
{
SendtoType type = SendtoType.Unknown;
for (int i = 0; i < SendtoStrings.Length; i++)
{
if (value == SendtoStrings[i])
{
type = (SendtoType)i;
break;
}
}
if (type == SendtoType.Unknown)
type = SendtoType.Sim;
return type;
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Tests.LegacyTests
{
public class AnyTests
{
public class Any003
{
private static int Any001()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
Func<int, bool> predicate = Functions.IsEven;
var rst1 = q.Any(predicate);
var rst2 = q.Any(predicate);
return ((rst1 == rst2) ? 0 : 1);
}
private static int Any002()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
select x;
Func<string, bool> predicate = Functions.IsEmpty;
var rst1 = q.Any<string>(predicate);
var rst2 = q.Any<string>(predicate);
return ((rst1 == rst2) ? 0 : 1);
}
public static int Main()
{
int ret = RunTest(Any001) + RunTest(Any002);
if (0 != ret)
Console.Write(s_errorMessage);
return ret;
}
private static string s_errorMessage = String.Empty;
private delegate int D();
private static int RunTest(D m)
{
int n = m();
if (0 != n)
s_errorMessage += m.ToString() + " - FAILED!\r\n";
return n;
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Any1a
{
// Overload without predicate, source is empty
public static int Test1a()
{
int[] source = { };
bool expected = false;
var actual = source.Any();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Any1b
{
// Overload without predicate, source has one element
public static int Test1b()
{
int[] source = { 3 };
bool expected = true;
var actual = source.Any();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Any1c
{
// Overload without predicate, source has limited elements
public static int Test1c()
{
int?[] source = { null, null, null, null };
bool expected = true;
var actual = source.Any();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Any2a
{
// Overload with predicate, source is empty
public static int Test2a()
{
int[] source = { };
Func<int, bool> predicate = Functions.IsEven;
bool expected = false;
var actual = source.Any(predicate);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Any2b
{
// Overload with predicate, source has one element and predicate is true
public static int Test2b()
{
int[] source = { 4 };
Func<int, bool> predicate = Functions.IsEven;
bool expected = true;
var actual = source.Any(predicate);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Any2c
{
// Overload with predicate, source has one element and predicate is false
public static int Test2c()
{
int[] source = { 5 };
Func<int, bool> predicate = Functions.IsEven;
bool expected = false;
var actual = source.Any(predicate);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Any2d
{
// Overload with predicate, predicate is true only for last element
public static int Test2d()
{
int[] source = { 5, 9, 3, 7, 4 };
Func<int, bool> predicate = Functions.IsEven;
bool expected = true;
var actual = source.Any(predicate);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Any2e
{
// Overload with predicate, predicate is true only for 2nd element
public static int Test2e()
{
int[] source = { 5, 8, 9, 3, 7, 11 };
Func<int, bool> predicate = Functions.IsEven;
bool expected = true;
var actual = source.Any(predicate);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
}
}
| |
using System;
namespace Free.Database.Dao.Net
{
public class Recordset
{
internal DAO.Recordset rs;
public Recordset(DAO.Recordset _rs)
{
rs=_rs;
}
[Obsolete("Use CancelUpdate instead.", false)]
public void _30_CancelUpdate()
{
rs._30_CancelUpdate();
}
[Obsolete("Use MoveLast instead.", false)]
public void _30_MoveLast()
{
rs._30_MoveLast();
}
[Obsolete("Use Update instead.", false)]
public void _30_Update()
{
rs._30_Update();
}
public void AddNew()
{
rs.AddNew();
}
public void Cancel()
{
rs.Cancel();
}
public void CancelUpdate(UpdateType type)
{
rs.CancelUpdate((int)type);
}
public Recordset Clone()
{
return new Recordset(rs.Clone());
}
public void Close()
{
rs.Close();
}
public QueryDef CopyQueryDef()
{
return new QueryDef(rs.CopyQueryDef());
}
[Obsolete("Use OpenRecordset instead.", false)]
public Recordset CreateDynaset(RecordsetOption options, bool inconsistent)
{
return new Recordset(rs.CreateDynaset(options, inconsistent));
}
[Obsolete("Use OpenRecordset instead.", false)]
public Recordset CreateSnapshot(RecordsetOption options)
{
return new Recordset(rs.CreateSnapshot(options));
}
public void Delete()
{
rs.Delete();
}
public void Edit()
{
rs.Edit();
}
public void FillCache()
{
rs.FillCache(System.Type.Missing, System.Type.Missing);
}
public void FillCache(int rows)
{
rs.FillCache(rows, System.Type.Missing);
}
public void FillCache(int rows, string startbookmark)
{
rs.FillCache(rows, startbookmark);
}
public void FillCache(string startbookmark)
{
rs.FillCache(System.Type.Missing, startbookmark);
}
public void FindFirst(string criteria)
{
rs.FindFirst(criteria);
}
public void FindLast(string criteria)
{
rs.FindLast(criteria);
}
public void FindNext(string criteria)
{
rs.FindNext(criteria);
}
public void FindPrevious(string criteria)
{
rs.FindPrevious(criteria);
}
[Obsolete("Fields[index].Value is nicer, but get_Collect is faster.", false)]
public object get_Collect(string index)
{
return rs.get_Collect(index);
}
[Obsolete("Fields[index].Value is nicer, but get_Collect is faster.", false)]
public object get_Collect(int index)
{
return rs.get_Collect(index);
}
public System.Array GetRows(int numrows)
{
return (System.Array)rs.GetRows(numrows);
}
[Obsolete("Use Fields instead.", false)]
public Recordset ListFields()
{
return new Recordset(rs.ListFields());
}
[Obsolete("Use Indexes instead.", false)]
public Recordset ListIndexes()
{
return new Recordset(rs.ListIndexes());
}
public void Move(int rows)
{
rs.Move(rows, System.Type.Missing);
}
public void Move(int rows, string startbookmark)
{
rs.Move(rows, startbookmark);
}
public void MoveFirst()
{
rs.MoveFirst();
}
public void MoveLast()
{
rs.MoveLast(0);
}
public void MoveLast(RecordsetOption options)
{
rs.MoveLast((int)options);
}
public void MoveNext()
{
rs.MoveNext();
}
public void MovePrevious()
{
rs.MovePrevious();
}
public bool NextRecordset()
{
return rs.NextRecordset();
}
public Recordset OpenRecordset()
{
return new Recordset(rs.OpenRecordset(System.Type.Missing, System.Type.Missing));
}
public Recordset OpenRecordset(RecordsetType type)
{
return new Recordset(rs.OpenRecordset(type, System.Type.Missing));
}
public Recordset OpenRecordset(RecordsetType type, RecordsetOption options)
{
return new Recordset(rs.OpenRecordset(type, options));
}
public void Requery()
{
rs.Requery(System.Type.Missing);
}
public void Requery(QueryDef newquerydef)
{
rs.Requery(newquerydef.qd);
}
[Obsolete("Fields[index].Value is nicer, but set_Collect is faster.", false)]
public void set_Collect(string index, object val)
{
rs.set_Collect(index, val);
}
[Obsolete("Fields[index].Value is nicer, but set_Collect is faster.", false)]
public void set_Collect(int index, object val)
{
rs.set_Collect(index, val);
}
[Obsolete("Fields[index].Value is nicer, but set_Collect is faster.", false)]
public void put_Collect(string index, object val)
{
rs.set_Collect(index, val);
}
[Obsolete("Fields[index].Value is nicer, but set_Collect is faster.", false)]
public void put_Collect(int index, object val)
{
rs.set_Collect(index, val);
}
public void Seek(string comparison, object key1, params object[] keys)
{
object[] k=new object[12];
keys.CopyTo(k, 0);
for(int i=keys.Length; i<12; i++) k[i]=System.Type.Missing;
rs.Seek(comparison, key1, k[0], k[1], k[2], k[3], k[4], k[5], k[6], k[7], k[8], k[9],
k[10], k[11]);
}
public void Update()
{
rs.Update((int)UpdateType.dbUpdateRegular, false);
}
public void Update(UpdateType type)
{
rs.Update((int)type, false);
}
public void Update(UpdateType type, bool force)
{
rs.Update((int)type, force);
}
public int AbsolutePosition
{
get { return rs.AbsolutePosition; }
set { rs.AbsolutePosition=value; }
}
public int BatchCollisionCount
{
get { return rs.BatchCollisionCount; }
}
// returns array of Bookmarks
public object BatchCollisions
{
get { return rs.BatchCollisions; }
}
public int BatchSize
{
get { return rs.BatchSize; }
set { rs.BatchSize=value; }
}
// returns byte[]
public System.Array Bookmark
{
get { return rs.get_Bookmark(); }
set { rs.set_Bookmark(ref value); }
}
public bool Bookmarkable
{
get { return rs.Bookmarkable; }
}
public bool BOF
{
get { return rs.BOF; }
}
public int CacheSize
{
get { return rs.CacheSize; }
set { rs.CacheSize=value; }
}
// returns byte[] ^= Bookmark's return type
public System.Array CacheStart
{
get { return rs.get_CacheStart(); }
set { rs.set_CacheStart(ref value); }
}
public Connection Connection
{
get { return new Connection(rs.Connection); }
set { rs.Connection=value.con; }
}
public DateTime DateCreated
{
get { return (DateTime)rs.DateCreated; }
}
public EditMode EditMode
{
get { return (EditMode)rs.EditMode; }
}
public bool EOF
{
get { return rs.EOF; }
}
public Fields Fields
{
get { return new Fields(rs.Fields); }
}
public string Filter
{
get { return rs.Filter; }
set { rs.Filter=value; }
}
public int hStmt
{
get { return rs.hStmt; }
}
public string Index
{
get { return rs.Index; }
set { rs.Index=value; }
}
public Indexes Indexes
{
get { return new Indexes(rs.Indexes); }
}
public System.Array LastModified
{
get { return rs.LastModified; }
}
public DateTime LastUpdated
{
get { return (DateTime)rs.LastUpdated; }
}
public bool LockEdits
{
get { return rs.LockEdits; }
set { rs.LockEdits=value; }
}
public string Name
{
get { return rs.Name; }
}
public bool NoMatch
{
get { return rs.NoMatch; }
}
public int ODBCFetchCount
{
get { return rs.ODBCFetchCount; }
}
public int ODBCFetchDelay
{
get { return rs.ODBCFetchDelay; }
}
public Database Parent
{
get { return new Database(rs.Parent); }
}
public float PercentPosition
{
get { return rs.PercentPosition; }
set { rs.PercentPosition=value; }
}
public Properties Properties
{
get { return new Properties(rs.Properties); }
}
public int RecordCount
{
get { return rs.RecordCount; }
}
public RecordStatus RecordStatus
{
get { return (RecordStatus)rs.RecordStatus; }
}
public bool Restartable
{
get { return rs.Restartable; }
}
public string Sort
{
get { return rs.Sort; }
set { rs.Sort=value; }
}
public bool StillExecuting
{
get { return rs.StillExecuting; }
}
public bool Transactions
{
get { return rs.Transactions; }
}
public RecordsetType Type
{
get { return (RecordsetType)rs.Type; }
}
public bool Updatable
{
get { return rs.Updatable; }
}
public UpdateCriteria UpdateOptions
{
get { return (UpdateCriteria)rs.UpdateOptions; }
set { rs.UpdateOptions=(int)value; }
}
public string ValidationRule
{
get { return rs.ValidationRule; }
}
public string ValidationText
{
get { return rs.ValidationText; }
}
}
class RecordsetsEnumerator : System.Collections.IEnumerator
{
internal System.Collections.IEnumerator Enmtr;
public RecordsetsEnumerator(System.Collections.IEnumerator _Enmtr) { Enmtr=_Enmtr; }
public void Reset() { Enmtr.Reset(); }
public bool MoveNext() { return Enmtr.MoveNext(); }
public object Current { get{ return new Recordset((DAO.Recordset)Enmtr.Current); } }
}
public class Recordsets
{
internal DAO.Recordsets rss;
public Recordsets(DAO.Recordsets _rss)
{
rss=_rss;
}
public short Count
{
get { return rss.Count; }
}
public System.Collections.IEnumerator GetEnumerator()
{
return new RecordsetsEnumerator(rss.GetEnumerator());
}
public void Refresh()
{
rss.Refresh();
}
public Recordset this[string index]
{
get { return new Recordset(rss[index]); }
}
public Recordset this[int index]
{
get { return new Recordset(rss[index]); }
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="NavigationWindow.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// The NavigationWindow extends the base window class to provide Navigation functionality.
//
// Using the navigation window it's possible to set the Uri of a Navigation Window, and the
// Content region of the window displays the markup at that Uri.
//
// It's also possible to change the outermost "chrome" of markup that hosts the content region
// of the window.
//
// History:
// 10/27/01: mihaii Created
// 05/21/03: marka Moved over to WCP dir. Made match spec, updated comments.
// 11/14/05: [....] "Island Frame" implementation. Journaling-related operations factored out into
// JournalNavigationScope.
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using MS.Internal.AppModel;
using MS.Internal.KnownBoxes;
using MS.Internal.Utility;
using MS.Utility;
using MS.Win32;
using MS.Internal.PresentationFramework;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Markup;
using System.Windows.Threading;
using System.Windows.Documents;
namespace System.Windows.Navigation
{
#region NavigationWindow Class
/// <summary>
/// Public class NavigationWindow
/// </summary>
/// <ExternalAPI/>
[ContentProperty]
[TemplatePart(Name = "PART_NavWinCP", Type = typeof(ContentPresenter))]
public class NavigationWindow : Window, INavigator, INavigatorImpl, IDownloader, IJournalNavigationScopeHost, IUriContext
{
#region DependencyProperties
/// <summary>
/// DependencyProperty for SandboxExternalContent property.
/// </summary>
public static readonly DependencyProperty SandboxExternalContentProperty =
Frame.SandboxExternalContentProperty.AddOwner(typeof(NavigationWindow));
/// <summary>
/// If set to true, the navigated content is isolated.
/// </summary>
public bool SandboxExternalContent
{
get { return (bool) GetValue(SandboxExternalContentProperty); }
set
{
// This feature is disabled in partial trust due to a P3P violation
bool fSandBox = (bool)value;
SecurityHelper.ThrowExceptionIfSettingTrueInPartialTrust(ref fSandBox);
SetValue(SandboxExternalContentProperty, fSandBox);
}
}
/// <summary>
/// Called when SandboxExternalContentProperty is invalidated on 'd'. If the value becomes
/// true, then the frame is refreshed to sandbox any content.
/// </summary>
private static void OnSandboxExternalContentPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
NavigationWindow window = (NavigationWindow)d;
// This feature is disabled in partial trust due to a P3P violation
bool fSandBox = (bool)e.NewValue;
SecurityHelper.ThrowExceptionIfSettingTrueInPartialTrust(ref fSandBox);
if (fSandBox && !(bool)e.OldValue)
{
window.NavigationService.Refresh();
}
}
private static object CoerceSandBoxExternalContentValue(DependencyObject d, object value)
{
// This feature is disabled in partial trust due to a P3P violation
bool fSandBox = (bool)value;
SecurityHelper.ThrowExceptionIfSettingTrueInPartialTrust(ref fSandBox);
return fSandBox;
}
/// <summary>
/// DependencyProperty for ShowsNavigationUI property.
/// </summary>
public static readonly DependencyProperty ShowsNavigationUIProperty =
DependencyProperty.Register(
"ShowsNavigationUI",
typeof(bool),
typeof(NavigationWindow),
new FrameworkPropertyMetadata(BooleanBoxes.TrueBox));
/// <summary>
/// DependencyProperty for BackStack property.
/// </summary>
public static readonly DependencyProperty BackStackProperty =
JournalNavigationScope.BackStackProperty.AddOwner(typeof(NavigationWindow));
/// <summary>
/// DependencyProperty for ForwardStack property.
/// </summary>
public static readonly DependencyProperty ForwardStackProperty =
JournalNavigationScope.ForwardStackProperty.AddOwner(typeof(NavigationWindow));
/// <summary>
/// The DependencyProperty for the CanGoBack property.
/// Flags: None
/// Default Value: false
/// Readonly: true
/// </summary>
public static readonly DependencyProperty CanGoBackProperty =
JournalNavigationScope.CanGoBackProperty.AddOwner(typeof(NavigationWindow));
/// <summary>
/// The DependencyProperty for the CanGoForward property.
/// Flags: None
/// Default Value: false
/// Readonly: true
/// </summary>
public static readonly DependencyProperty CanGoForwardProperty =
JournalNavigationScope.CanGoForwardProperty.AddOwner(typeof(NavigationWindow));
#endregion DependencyProperties
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Constructs a window object
/// </summary>
static NavigationWindow()
{
_dType = DependencyObjectType.FromSystemTypeInternal(typeof(NavigationWindow));
DefaultStyleKeyProperty.OverrideMetadata(
typeof(NavigationWindow),
new FrameworkPropertyMetadata(typeof(NavigationWindow)));
ContentProperty.OverrideMetadata(
typeof(NavigationWindow),
new FrameworkPropertyMetadata(
null,
new CoerceValueCallback(CoerceContent)));
SandboxExternalContentProperty.OverrideMetadata(
typeof(NavigationWindow),
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnSandboxExternalContentPropertyChanged),
new CoerceValueCallback(CoerceSandBoxExternalContentValue)));
CommandManager.RegisterClassCommandBinding(
typeof(NavigationWindow),
new CommandBinding(
NavigationCommands.BrowseBack,
new ExecutedRoutedEventHandler(OnGoBack),
new CanExecuteRoutedEventHandler(OnQueryGoBack)));
CommandManager.RegisterClassCommandBinding(
typeof(NavigationWindow),
new CommandBinding(
NavigationCommands.BrowseForward,
new ExecutedRoutedEventHandler(OnGoForward),
new CanExecuteRoutedEventHandler(OnQueryGoForward)));
CommandManager.RegisterClassCommandBinding(
typeof(NavigationWindow),
new CommandBinding(NavigationCommands.NavigateJournal, new ExecutedRoutedEventHandler(OnNavigateJournal)));
CommandManager.RegisterClassCommandBinding(
typeof(NavigationWindow),
new CommandBinding(
NavigationCommands.Refresh,
new ExecutedRoutedEventHandler(OnRefresh),
new CanExecuteRoutedEventHandler(OnQueryRefresh)));
CommandManager.RegisterClassCommandBinding(
typeof(NavigationWindow),
new CommandBinding(
NavigationCommands.BrowseStop,
new ExecutedRoutedEventHandler(OnBrowseStop),
new CanExecuteRoutedEventHandler(OnQueryBrowseStop)));
}
/// <summary>
/// Constructs a NavigationWindow object
/// </summary>
/// <remarks>
/// Automatic determination of current Dispatcher. Use alternative constructor
/// that accepts a Dispatcher for best performance.
///
/// Initialize set _framelet to false and init commandlinks
/// </remarks>
public NavigationWindow()
{
this.Initialize();
}
/// <SecurityNote>
/// The only scenarios where we're currently going to enable creation of Windows is with RootBrowserWindow.
/// Do not call it outside the scope of the RBW scenario
/// </SecurityNote>
[SecurityCritical]
internal NavigationWindow(bool inRbw): base(inRbw)
{
this.Initialize();
}
private void Initialize()
{
Debug.Assert(_navigationService == null && _JNS == null);
_navigationService = new NavigationService(this);
_navigationService.BPReady += new BPReadyEventHandler(OnBPReady);
_JNS = new JournalNavigationScope(this);
_fFramelet = false;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
#region IDownloader implementation
NavigationService IDownloader.Downloader
{
get { return _navigationService; }
}
#endregion IDownloader implementation
#region INavigator Methods
/// <summary>
/// Navigates to the Uri and downloads the content.
/// </summary>
/// <param name="source">URI of the application or content being navigated to.</param>
/// <returns>bool indicating whether the navigation was successfully started or not</returns>
public bool Navigate(Uri source)
{
VerifyContextAndObjectState();
return NavigationService.Navigate(source);
}
/// <summary>
/// This method navigates this window to the given Uri.
/// </summary>
/// <param name="source">The URI to be navigated to.</param>
/// <param name="extraData">
/// Enables the develeoper to supply an extra object, that will be returned in the NavigatedEventArgs of the Navigated event. The extra data enables the developer
/// to identify the source of the navigation, in the presence of
/// multiple navigations.
/// </param>
/// <returns>bool indicating whether the navigation was successfully started or not</returns>
public bool Navigate(Uri source, Object extraData)
{
VerifyContextAndObjectState();
// Close/update PS844614 to investigate why we need to delay create WNC instead of
// creating and calling Navigate immediately here
return NavigationService.Navigate(source, extraData);
}
/// <summary>
/// Navigates to an existing element tree.
/// </summary>
/// <param name="content">Root of the element tree being navigated to.</param>
/// <returns>bool indicating whether the navigation was successfully started or not</returns>
public bool Navigate(Object content)
{
VerifyContextAndObjectState();
// Close/update PS844614 to investigate why we need to delay create WNC instead of
// creating and calling Navigate immediately here
return NavigationService.Navigate(content);
}
/// <summary>
/// This method navigates this window to the
/// given Element.
/// </summary>
/// <param name="content">The Element to be navigated to.</param>
/// <param name="extraData">enables the develeoper to supply an extra object, that will be returned in the NavigatedEventArgs of the Navigated event. The extra data enables the developer
/// to identify the source of the navigation, in the presence of
/// multiple navigations.
/// </param>
/// <returns>bool indicating whether the navigation was successfully started or not</returns>
public bool Navigate(Object content, Object extraData)
{
VerifyContextAndObjectState();
// Close/update PS844614 to investigate why we need to delay create WNC instead of
// creating and calling Navigate immediately here
return NavigationService.Navigate(content, extraData);
}
JournalNavigationScope INavigator.GetJournal(bool create)
{
Debug.Assert(_JNS != null);
return _JNS;
}
/// <summary>
/// Navigates to the next entry in the Forward branch of the Journal, if one exists.
/// If there is no entry in the Forward stack of the journal, the method throws an
/// exception. The behavior is the same as clicking the Forward button.
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// There is no entry in the Forward stack of the journal to navigate to.
/// </exception>
public void GoForward()
{
_JNS.GoForward();
}
/// <summary>
/// Navigates to the previous entry in the Back branch of the Journal, if one exists.
/// The behavior is the same as clicking the Back button.
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// There is no entry in the Back stack of the journal to navigate to.
/// </exception>
public void GoBack()
{
_JNS.GoBack();
}
/// <summary>
/// StopLoading aborts asynchronous navigations that haven't been processed yet or that are
/// still being downloaded. SopLoading does not abort parsing of the downloaded streams.
/// The NavigationStopped event is fired only if the navigation was aborted.
/// The behavior is the same as clicking the Stop button.
/// </summary>
public void StopLoading()
{
VerifyContextAndObjectState();
if (InAppShutdown)
return;
NavigationService.StopLoading();
}
/// <summary>
/// Reloads the current content. The behavior is the same as clicking the Refresh button.
/// </summary>
public void Refresh()
{
VerifyContextAndObjectState();
if (InAppShutdown)
{
return;
}
NavigationService.Refresh();
}
/// <summary>
/// Adds a new journal entry to NavigationWindow's back history.
/// </summary>
/// <param name="state"> The custom content state (or view state) to be encapsulated in the
/// journal entry. If null, IProvideCustomContentState.GetContentState() will be called on
/// the NavigationWindow.Content or Frame.Content object.
/// </param>
public void AddBackEntry(CustomContentState state)
{
VerifyContextAndObjectState();
NavigationService.AddBackEntry(state);
}
/// <summary>
/// Remove the first JournalEntry from NavigationWindow's back history
/// </summary>
public JournalEntry RemoveBackEntry()
{
return _JNS.RemoveBackEntry();
}
#endregion INavigator Methods
#region IUriContext Members
Uri IUriContext.BaseUri
{
get
{
return (Uri)GetValue(BaseUriHelper.BaseUriProperty);
}
set
{
SetValue(BaseUriHelper.BaseUriProperty, value);
}
}
#endregion
/// <summary>
/// Called when style is actually applied.
/// </summary>
/// <remarks>
/// [....]
[SecurityCritical]
public override void OnApplyTemplate()
{
VerifyContextAndObjectState( );
base.OnApplyTemplate();
// base actually changed something. sniff
// around to see if there are any framelet
// objects we need to hook up.
// Get the root element of the style
FrameworkElement root = (this.GetVisualChild(0)) as FrameworkElement;
if (_navigationService != null)
{
_navigationService.VisualTreeAvailable(root);
}
// did we just apply the framelet style?
if ((root != null) && (root.Name == "NavigationBarRoot"))
{
if (!_fFramelet)
{
// transitioning to Framelet style
// [....]
#if WCP_SYSTEM_THEMES_ENABLED
NativeMethods.WTA_OPTIONS wo = new NativeMethods.WTA_OPTIONS();
wo.dwFlags = (NativeMethods.WTNCA_NODRAWCAPTION | NativeMethods.WTNCA_NODRAWICON | NativeMethods.WTNCA_NOSYSMENU);
wo.dwMask = NativeMethods.WTNCA_VALIDBITS;
// call to turn off theme parts
UnsafeNativeMethods.SetWindowThemeAttribute( new HandleRef(this,Handle), NativeMethods.WINDOWTHEMEATTRIBUTETYPE.WTA_NONCLIENT, wo );
#endif // WCP_SYSTEM_THEMES_ENABLED
_fFramelet = true;
}
}
else
{
if (_fFramelet)
{
//
#if WCP_SYSTEM_THEMES_ENABLED
NativeMethods.WTA_OPTIONS wo = new NativeMethods.WTA_OPTIONS();
wo.dwFlags = 0;
wo.dwMask = NativeMethods.WTNCA_VALIDBITS;
// call to turn off theme parts
UnsafeNativeMethods.SetWindowThemeAttribute( new HandleRef(this,Handle), NativeMethods.WINDOWTHEMEATTRIBUTETYPE.WTA_NONCLIENT, wo );
#endif // WCP_SYSTEM_THEMES_ENABLED
// no longer in framelet mode
_fFramelet = false;
}
}
}
/// <summary>
/// This method is used by TypeDescriptor to determine if this property should
/// be serialized.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool ShouldSerializeContent()
{
// When uri of NavigationService is valid and can be used to
// relaod, we do not serialize content
if (_navigationService != null)
{
return !_navigationService.CanReloadFromUri;
}
return true;
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// NavigationWindow's NavigationService
/// </summary>
public NavigationService NavigationService
{
#if DEBUG
[DebuggerStepThrough]
#endif
get
{
VerifyContextAndObjectState();
return _navigationService;
}
}
/// <summary>
/// List of back journal entries
/// </summary>
public IEnumerable BackStack
{
get { return _JNS.BackStack; }
}
/// <summary>
/// List of forward journal entries
/// </summary>
public IEnumerable ForwardStack
{
get { return _JNS.ForwardStack; }
}
/// <summary>
/// Determines whether to show the default navigation UI.
/// </summary>
public bool ShowsNavigationUI
{
get
{
VerifyContextAndObjectState();
return (bool)GetValue(ShowsNavigationUIProperty);
}
set
{
VerifyContextAndObjectState();
SetValue(ShowsNavigationUIProperty, value);
}
}
#region INavigator Properties
/// <summary>
///
/// </summary>
public static readonly DependencyProperty SourceProperty =
Frame.SourceProperty.AddOwner(
typeof(NavigationWindow),
new FrameworkPropertyMetadata(
(Uri)null,
new PropertyChangedCallback(OnSourcePropertyChanged)));
/// <summary>
/// Called when SourceProperty is invalidated on 'd'
/// </summary>
private static void OnSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
NavigationWindow navWin = (NavigationWindow)d;
// Don't navigate if the Source value change is from NavService as a result of a navigation happening.
if (! navWin._sourceUpdatedFromNavService )
{
// We used not to need to resolve the Uri here because we did not allow navigating to a xaml rooted inside a NavWin.
// Now after we allow this, we will need to support navigating to the following xaml,
// <NavigationWindow ... Source="a relative uri." ...>
// When the xaml is rooted in a NavigationWindow with source pointing to a relative uri, the relative uri will need
// to be resolved with its baseuri unless it is a fragment navigation or there is no baseuri.
// In this case NavWin is always the root, parser will set the BaseUriProperty for the root element so NavWin doesn't need to
// implement IUriContext.
Uri uriToNavigate = BindUriHelper.GetUriToNavigate(navWin, d.GetValue(BaseUriHelper.BaseUriProperty) as Uri, (Uri)e.NewValue);
// Calling the internal Navigate from Frame and NavWin's Source DP's property changed callbacks
// We would not set value back in this case.
navWin._navigationService.Navigate(uriToNavigate, null, false, true/* navigateOnSourceChanged */);
}
}
// This method is called from NavService whenever the NavService's Source value is updated.
// The INavigator uses this to update its SourceProperty.
// <param name="journalOrCancel">It indicates whether the NavService's Source value is as a result of
// calling Navigate API directly or from GoBack/GoForward, journal navigation, a cancellation</param>
void INavigatorImpl.OnSourceUpdatedFromNavService(bool journalOrCancel)
{
try
{
_sourceUpdatedFromNavService = true;
SetCurrentValueInternal(SourceProperty, _navigationService.Source);
}
finally
{
_sourceUpdatedFromNavService = false;
}
}
/// <summary>
/// Uri for the page currently contained by the NavigationWindow
/// - Setting this property performs a navigation to the specified Uri.
/// - Getting this property when a navigation is not in progress returns the URI of
/// the current page. Getting this property when a navigation is in progress returns
/// the URI of the page being navigated to.
/// </summary>
/// <remarks>
/// Supporting navigation via setting a property makes it possible to write
/// a NavigationWindow in markup and specify its initial content.
/// </remarks>
[DefaultValue(null)]
public Uri Source
{
get { return (Uri)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
/// <summary>
/// Uri for the current page in the window. Getting this property always
/// returns the URI of the content thats currently displayed in the window,
/// regardless of whether a navigation is in progress or not.
/// </summary>
public Uri CurrentSource
{
get
{
VerifyContextAndObjectState( );
return (_navigationService == null ? null : _navigationService.CurrentSource);
}
}
/// <summary>
/// Tells whether there are any entries in the Forward branch of the Journal.
/// This property can be used to enable the Forward button.
/// </summary>
public bool CanGoForward
{
get
{
return _JNS.CanGoForward;
}
}
/// <summary>
/// Tells whether there are any entries in the Back branch of the Journal.
/// This property can be used to enable the Back button.
/// </summary>
public bool CanGoBack
{
get
{
return _JNS.CanGoBack;
}
}
#endregion INavigator Properties
#endregion Public Properties
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
#region Public Events
/// <summary>
/// Raised just before a navigation takes place. This event is fired for frame
/// navigations as well as top-level page navigations, so may fire multiple times
/// during the download of a page.
/// The NavigatingCancelEventArgs contain the uri or root element of the content
/// being navigated to and an enum value that indicates the type of navigation.
/// Canceling this event prevents the application from navigating.
/// Note: An application hosted in the browser cannot prevent navigation away from
/// the application by canceling this event.
/// Note: In the PDC build, if an application hosts the WebOC, this event is not raised
/// for navigations within the WebOC.
/// </summary>
public event NavigatingCancelEventHandler Navigating
{
add
{
VerifyContextAndObjectState( );
NavigationService.Navigating += value;
}
remove
{
VerifyContextAndObjectState( );
NavigationService.Navigating -= value;
}
}
/// <summary>
/// Raised at periodic intervals while a navigation is taking place.
/// The NavigationProgressEventArgs tell how many total bytes need to be downloaded and
/// how many have been sent at the moment the event is fired. This event can be used to provide
/// a progress indicator to the user.
/// </summary>
public event NavigationProgressEventHandler NavigationProgress
{
add
{
VerifyContextAndObjectState( );
NavigationService.NavigationProgress += value;
}
remove
{
VerifyContextAndObjectState( );
NavigationService.NavigationProgress -= value;
}
}
/// <summary>
/// Raised when an error is encountered during a navigation.
/// The NavigationFailedEventArgs contains
/// the exception that was thrown. By default Handled property is set to false,
/// which allows the exception to be rethrown.
/// The event handler can prevent exception from throwing
/// to the user by setting the Handled property to true.
/// </summary>
public event NavigationFailedEventHandler NavigationFailed
{
add
{
VerifyContextAndObjectState();
NavigationService.NavigationFailed += value;
}
remove
{
VerifyContextAndObjectState();
NavigationService.NavigationFailed -= value;
}
}
/// <summary>
/// Raised after navigation the target has been found and the download has begun. This event
/// is fired for frame navigations as well as top-level page navigations, so may fire
/// multiple times during the download of a page.
/// For an asynchronous navigation, this event indicates that a partial element tree
/// has been handed to the parser, but more bits are still coming.
/// For a synchronous navigation, this event indicates the entire tree has been
/// handed to the parser.
/// The NavigationEventArgs contain the uri or root element of the content being navigated to.
/// This event is informational only, and cannot be canceled.
/// </summary>
public event NavigatedEventHandler Navigated
{
add
{
VerifyContextAndObjectState( );
NavigationService.Navigated += value;
}
remove
{
VerifyContextAndObjectState( );
NavigationService.Navigated -= value;
}
}
/// <summary>
/// Raised after the entire page, including all images and frames, has been downloaded
/// and parsed. This is the event to handle to stop spinning the globe. The developer
/// should check the IsNavigationInitiator property on the NavigationEventArgs to determine
/// whether to stop spinning the globe.
/// The NavigationEventArgs contain the uri or root element of the content being navigated to,
/// and a IsNavigationInitiator property that indicates whether this is a new navigation
/// initiated by this window, or whether this navigation is being propagated down
/// from a higher level navigation taking place in a containing window or frame.
/// This event is informational only, and cannot be canceled.
/// </summary>
public event LoadCompletedEventHandler LoadCompleted
{
add
{
VerifyContextAndObjectState( );
NavigationService.LoadCompleted += value;
}
remove
{
VerifyContextAndObjectState( );
NavigationService.LoadCompleted -= value;
}
}
/// <summary>
/// Raised when a navigation or download has been interrupted because the user clicked
/// the Stop button, or the Stop method was invoked.
/// The NavigationEventArgs contain the uri or root element of the content being navigated to.
/// This event is informational only, and cannot be canceled.
/// </summary>
public event NavigationStoppedEventHandler NavigationStopped
{
add
{
VerifyContextAndObjectState( );
NavigationService.NavigationStopped += value;
}
remove
{
VerifyContextAndObjectState( );
NavigationService.NavigationStopped -= value;
}
}
/// <summary>
/// Raised when a navigation uri contains a fragment. This event is fired before the element is scrolled
/// into view and allows the listener to respond to the fragment in a custom way.
/// </summary>
public event FragmentNavigationEventHandler FragmentNavigation
{
add
{
VerifyContextAndObjectState();
NavigationService.FragmentNavigation += value;
}
remove
{
VerifyContextAndObjectState();
NavigationService.FragmentNavigation -= value;
}
}
#endregion Public Events
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>)
/// </summary>
protected override AutomationPeer OnCreateAutomationPeer()
{
return new NavigationWindowAutomationPeer(this);
}
/// <summary>
/// Add an object child to this control
/// </summary>
protected override void AddChild(object value)
{
throw new InvalidOperationException(SR.Get(SRID.NoAddChild));
}
/// <summary>
/// Add a text string to this control
/// </summary>
protected override void AddText(string text)
{
XamlSerializerUtil.ThrowIfNonWhiteSpaceInAddText(text, this);
}
/// <summary>
/// This even fires when window is closed. This event is non cancelable and is
/// for user infromational purposes
/// </summary>
/// <remarks>
/// This method follows the .Net programming guideline of having a protected virtual
/// method that raises an event, to provide a convenience for developers that subclass
/// the event. If you override this method - you need to call Base.OnClosed(...) for
/// the corresponding event to be raised.
/// </remarks>
protected override void OnClosed(EventArgs args)
{
VerifyContextAndObjectState( );
// We override OnClosed here to Dispose of the NCTree.
base.OnClosed( args ) ;
// detach the event handlers on the NC
if(_navigationService != null)
_navigationService.Dispose();
}
#endregion Protected Methods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
internal override void OnPreApplyTemplate()
{
base.OnPreApplyTemplate();
// This causes the Journal instance to be created. BackStackProperty and ForwardStackProperty
// have to be set before the navigation chrome data-binds to them but after RootBrowserWindow
// .SetJournalForBrowserInterop() is called.
_JNS.EnsureJournal();
}
#region IJournalNavigationScopeHost Members
void IJournalNavigationScopeHost.VerifyContextAndObjectState()
{
VerifyContextAndObjectState();
}
void IJournalNavigationScopeHost.OnJournalAvailable()
{
}
bool IJournalNavigationScopeHost.GoBackOverride()
{
return false; // not overriding here; RBW does
}
bool IJournalNavigationScopeHost.GoForwardOverride()
{
return false;
}
NavigationService IJournalNavigationScopeHost.NavigationService
{
get { return _navigationService; }
}
#endregion
#region INavigatorImpl members
// Note: OnSourceUpdatedFromNavService is next to the other Source-related members of NW.
Visual INavigatorImpl.FindRootViewer()
{
return NavigationHelper.FindRootViewer(this, "PART_NavWinCP");
}
#endregion INavigatorImpl
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// Journal for the window. Maintains Back/Forward navigation history.
/// </summary>
#if DEBUG
// to prevent creating the Journal instance prematurely while debugging
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
internal Journal Journal
{
get
{
return _JNS.Journal;
}
}
internal JournalNavigationScope JournalNavigationScope
{
#if DEBUG
[DebuggerStepThrough]
#endif
get
{
return _JNS;
}
}
#endregion Internal Properties
#region Private Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
private static object CoerceContent(DependencyObject d, object value)
{
// whenever content changes, defer the change until the Navigate comes in
NavigationWindow w = (NavigationWindow) d;
if (w.NavigationService.Content == value)
{
return value;
}
w.Navigate(value);
return DependencyProperty.UnsetValue;
}
private void OnBPReady(Object sender, BPReadyEventArgs e)
{
// set Window.ContentProperty
Content = e.Content;
}
private static void OnGoBack(object sender, ExecutedRoutedEventArgs args)
{
NavigationWindow nw = sender as NavigationWindow;
Debug.Assert(nw != null, "sender must be of type NavigationWindow.");
nw.GoBack();
}
private static void OnQueryGoBack(object sender, CanExecuteRoutedEventArgs e)
{
NavigationWindow nw = sender as NavigationWindow;
Debug.Assert(nw != null, "sender must be of type NavigationWindow.");
e.CanExecute = nw.CanGoBack;
e.ContinueRouting = !nw.CanGoBack;
}
private static void OnGoForward(object sender, ExecutedRoutedEventArgs e)
{
NavigationWindow nw = sender as NavigationWindow;
Debug.Assert(nw != null, "sender must be of type NavigationWindow.");
nw.GoForward();
}
private static void OnQueryGoForward(object sender, CanExecuteRoutedEventArgs e)
{
NavigationWindow nw = sender as NavigationWindow;
Debug.Assert(nw != null, "sender must be of type NavigationWindow.");
e.CanExecute = nw.CanGoForward;
e.ContinueRouting = !nw.CanGoForward;
}
private static void OnRefresh(object sender, ExecutedRoutedEventArgs e)
{
NavigationWindow nw = sender as NavigationWindow;
Debug.Assert(nw != null, "sender must be of type NavigationWindow.");
nw.Refresh();
}
private static void OnQueryRefresh(object sender, CanExecuteRoutedEventArgs e)
{
NavigationWindow nw = sender as NavigationWindow;
Debug.Assert(nw != null, "sender must be of type NavigationWindow.");
e.CanExecute = nw.Content != null;
}
private static void OnBrowseStop(object sender, ExecutedRoutedEventArgs e)
{
NavigationWindow nw = sender as NavigationWindow;
Debug.Assert(nw != null, "sender must be of type NavigationWindow.");
nw.StopLoading();
}
private static void OnQueryBrowseStop(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private static void OnNavigateJournal(object sender, ExecutedRoutedEventArgs e)
{
NavigationWindow nw = sender as NavigationWindow;
Debug.Assert(nw != null, "sender must be of type NavigationWindow.");
FrameworkElement journalEntryUIElem = e.Parameter as FrameworkElement;
if (journalEntryUIElem != null)
{
// Get journal entry from MenuItem
JournalEntry je = journalEntryUIElem.DataContext as JournalEntry;
if (je != null)
{
nw.JournalNavigationScope.NavigateToEntry(je);
}
}
}
#endregion Private Methods
#region Private Properties
//------------------------------------------------------
//
// Private Properties
//
//------------------------------------------------------
private bool InAppShutdown
{
get
{
return System.Windows.Application.IsShuttingDown;
}
}
//
// This property
// 1. Finds the correct initial size for the _effectiveValues store on the current DependencyObject
// 2. This is a performance optimization
//
internal override int EffectiveValuesInitialSize
{
get { return 42; }
}
#endregion Private Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private NavigationService _navigationService;
private JournalNavigationScope _JNS;
private bool _sourceUpdatedFromNavService;
// Framelet stuff
private bool _fFramelet;
#endregion Private Fields
#region DTypeThemeStyleKey
// Returns the DependencyObjectType for the registered ThemeStyleKey's default
// value. Controls will override this method to return approriate types.
internal override DependencyObjectType DTypeThemeStyleKey
{
get { return _dType; }
}
private static DependencyObjectType _dType;
#endregion DTypeThemeStyleKey
}
#endregion NavigationWindow Class
}
| |
#region License
/*
* EndPointListener.cs
*
* This code is derived from System.Net.EndPointListener.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <[email protected]>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace WebSocketSharp.Net
{
internal sealed class EndPointListener
{
#region Private Fields
private List<HttpListenerPrefix> _all; // host == '+'
private ServerSslAuthConfiguration _sslAuthenticationConfig;
private static readonly string _defaultCertFolderPath;
private IPEndPoint _endpoint;
private Dictionary<HttpListenerPrefix, HttpListener> _prefixes;
private bool _secure;
private Socket _socket;
private List<HttpListenerPrefix> _unhandled; // host == '*'
private Dictionary<HttpConnection, HttpConnection> _unregistered;
private object _unregisteredSync;
#endregion
#region Static Constructor
static EndPointListener ()
{
_defaultCertFolderPath =
Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
}
#endregion
#region Public Constructors
public EndPointListener (
IPAddress address,
int port,
bool secure,
string certificateFolderPath,
ServerSslAuthConfiguration defaultCertificate,
bool reuseAddress)
{
if (secure) {
_secure = secure;
_sslAuthenticationConfig = getCertificate(port, certificateFolderPath, defaultCertificate);
if (_sslAuthenticationConfig == null)
throw new ArgumentException ("No server certificate could be found.");
}
_prefixes = new Dictionary<HttpListenerPrefix, HttpListener> ();
_unregistered = new Dictionary<HttpConnection, HttpConnection> ();
_unregisteredSync = ((ICollection) _unregistered).SyncRoot;
_socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (reuseAddress)
_socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_endpoint = new IPEndPoint (address, port);
_socket.Bind (_endpoint);
_socket.Listen (500);
var args = new SocketAsyncEventArgs ();
args.UserToken = this;
args.Completed += onAccept;
_socket.AcceptAsync (args);
}
#endregion
#region Public Properties
public ServerSslAuthConfiguration CertificateConfig
{
get {
return _sslAuthenticationConfig;
}
}
public bool IsSecure {
get {
return _secure;
}
}
#endregion
#region Private Methods
private static void addSpecial (List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix)
{
if (prefixes == null)
return;
var path = prefix.Path;
foreach (var pref in prefixes)
if (pref.Path == path)
throw new HttpListenerException (400, "The prefix is already in use."); // TODO: Code?
prefixes.Add (prefix);
}
private void checkIfRemove ()
{
if (_prefixes.Count > 0)
return;
if (_unhandled != null && _unhandled.Count > 0)
return;
if (_all != null && _all.Count > 0)
return;
EndPointManager.RemoveEndPoint (this, _endpoint);
}
private static RSACryptoServiceProvider createRSAFromFile (string filename)
{
byte[] pvk = null;
using (var fs = File.Open (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
pvk = new byte[fs.Length];
fs.Read (pvk, 0, pvk.Length);
}
var rsa = new RSACryptoServiceProvider ();
rsa.ImportCspBlob (pvk);
return rsa;
}
private static ServerSslAuthConfiguration getCertificate(
int port, string certificateFolderPath, ServerSslAuthConfiguration defaultCertificate)
{
if (certificateFolderPath == null || certificateFolderPath.Length == 0)
certificateFolderPath = _defaultCertFolderPath;
try {
var cer = Path.Combine (certificateFolderPath, String.Format ("{0}.cer", port));
var key = Path.Combine (certificateFolderPath, String.Format ("{0}.key", port));
if (File.Exists (cer) && File.Exists (key)) {
var cert = new X509Certificate2 (cer);
cert.PrivateKey = createRSAFromFile (key);
return new ServerSslAuthConfiguration(cert);
}
}
catch {
}
return defaultCertificate;
}
private static HttpListener matchFromList (
string host, string path, List<HttpListenerPrefix> list, out HttpListenerPrefix prefix)
{
prefix = null;
if (list == null)
return null;
HttpListener bestMatch = null;
var bestLen = -1;
foreach (var pref in list) {
var ppath = pref.Path;
if (ppath.Length < bestLen)
continue;
if (path.StartsWith (ppath)) {
bestLen = ppath.Length;
bestMatch = pref.Listener;
prefix = pref;
}
}
return bestMatch;
}
private static void onAccept (object sender, EventArgs e)
{
var args = (SocketAsyncEventArgs) e;
var epl = (EndPointListener) args.UserToken;
Socket accepted = null;
if (args.SocketError == SocketError.Success) {
accepted = args.AcceptSocket;
args.AcceptSocket = null;
}
try {
epl._socket.AcceptAsync (args);
}
catch {
if (accepted != null)
accepted.Close ();
return;
}
if (accepted == null)
return;
HttpConnection conn = null;
try {
conn = new HttpConnection (accepted, epl);
lock (epl._unregisteredSync)
epl._unregistered[conn] = conn;
conn.BeginReadRequest ();
}
catch {
if (conn != null) {
conn.Close (true);
return;
}
accepted.Close ();
}
}
private static bool removeSpecial (List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix)
{
if (prefixes == null)
return false;
var path = prefix.Path;
var cnt = prefixes.Count;
for (var i = 0; i < cnt; i++) {
if (prefixes[i].Path == path) {
prefixes.RemoveAt (i);
return true;
}
}
return false;
}
private HttpListener searchListener (Uri uri, out HttpListenerPrefix prefix)
{
prefix = null;
if (uri == null)
return null;
var host = uri.Host;
var port = uri.Port;
var path = HttpUtility.UrlDecode (uri.AbsolutePath);
var pathSlash = path[path.Length - 1] == '/' ? path : path + "/";
HttpListener bestMatch = null;
var bestLen = -1;
if (host != null && host.Length > 0) {
foreach (var pref in _prefixes.Keys) {
var ppath = pref.Path;
if (ppath.Length < bestLen)
continue;
if (pref.Host != host || pref.Port != port)
continue;
if (path.StartsWith (ppath) || pathSlash.StartsWith (ppath)) {
bestLen = ppath.Length;
bestMatch = _prefixes[pref];
prefix = pref;
}
}
if (bestLen != -1)
return bestMatch;
}
var list = _unhandled;
bestMatch = matchFromList (host, path, list, out prefix);
if (path != pathSlash && bestMatch == null)
bestMatch = matchFromList (host, pathSlash, list, out prefix);
if (bestMatch != null)
return bestMatch;
list = _all;
bestMatch = matchFromList (host, path, list, out prefix);
if (path != pathSlash && bestMatch == null)
bestMatch = matchFromList (host, pathSlash, list, out prefix);
if (bestMatch != null)
return bestMatch;
return null;
}
#endregion
#region Internal Methods
internal static bool CertificateExists (int port, string certificateFolderPath)
{
if (certificateFolderPath == null || certificateFolderPath.Length == 0)
certificateFolderPath = _defaultCertFolderPath;
var cer = Path.Combine (certificateFolderPath, String.Format ("{0}.cer", port));
var key = Path.Combine (certificateFolderPath, String.Format ("{0}.key", port));
return File.Exists (cer) && File.Exists (key);
}
internal void RemoveConnection (HttpConnection connection)
{
lock (_unregisteredSync)
_unregistered.Remove (connection);
}
#endregion
#region Public Methods
public void AddPrefix (HttpListenerPrefix prefix, HttpListener httpListener)
{
List<HttpListenerPrefix> current, future;
if (prefix.Host == "*") {
do {
current = _unhandled;
future = current != null
? new List<HttpListenerPrefix> (current)
: new List<HttpListenerPrefix> ();
prefix.Listener = httpListener;
addSpecial (future, prefix);
}
while (Interlocked.CompareExchange (ref _unhandled, future, current) != current);
return;
}
if (prefix.Host == "+") {
do {
current = _all;
future = current != null
? new List<HttpListenerPrefix> (current)
: new List<HttpListenerPrefix> ();
prefix.Listener = httpListener;
addSpecial (future, prefix);
}
while (Interlocked.CompareExchange (ref _all, future, current) != current);
return;
}
Dictionary<HttpListenerPrefix, HttpListener> prefs, prefs2;
do {
prefs = _prefixes;
if (prefs.ContainsKey (prefix)) {
var other = prefs[prefix];
if (other != httpListener)
throw new HttpListenerException (
400, String.Format ("There's another listener for {0}.", prefix)); // TODO: Code?
return;
}
prefs2 = new Dictionary<HttpListenerPrefix, HttpListener> (prefs);
prefs2[prefix] = httpListener;
}
while (Interlocked.CompareExchange (ref _prefixes, prefs2, prefs) != prefs);
}
public bool BindContext (HttpListenerContext context)
{
HttpListenerPrefix pref;
var httpl = searchListener (context.Request.Url, out pref);
if (httpl == null)
return false;
context.Listener = httpl;
context.Connection.Prefix = pref;
return true;
}
public void Close ()
{
_socket.Close ();
lock (_unregisteredSync) {
var conns = new List<HttpConnection> (_unregistered.Keys);
_unregistered.Clear ();
foreach (var conn in conns)
conn.Close (true);
conns.Clear ();
}
}
public void RemovePrefix (HttpListenerPrefix prefix, HttpListener httpListener)
{
List<HttpListenerPrefix> current, future;
if (prefix.Host == "*") {
do {
current = _unhandled;
future = current != null
? new List<HttpListenerPrefix> (current)
: new List<HttpListenerPrefix> ();
if (!removeSpecial (future, prefix))
break; // Prefix not found.
}
while (Interlocked.CompareExchange (ref _unhandled, future, current) != current);
checkIfRemove ();
return;
}
if (prefix.Host == "+") {
do {
current = _all;
future = current != null
? new List<HttpListenerPrefix> (current)
: new List<HttpListenerPrefix> ();
if (!removeSpecial (future, prefix))
break; // Prefix not found.
}
while (Interlocked.CompareExchange (ref _all, future, current) != current);
checkIfRemove ();
return;
}
Dictionary<HttpListenerPrefix, HttpListener> prefs, prefs2;
do {
prefs = _prefixes;
if (!prefs.ContainsKey (prefix))
break;
prefs2 = new Dictionary<HttpListenerPrefix, HttpListener> (prefs);
prefs2.Remove (prefix);
}
while (Interlocked.CompareExchange (ref _prefixes, prefs2, prefs) != prefs);
checkIfRemove ();
}
public void UnbindContext (HttpListenerContext context)
{
if (context == null || context.Listener == null)
return;
context.Listener.UnregisterContext (context);
}
#endregion
}
}
| |
// Copyright(c) DEVSENSE s.r.o.
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace Devsense.PHP.Syntax.Ast
{
#region FormalParam
/// <summary>
/// Represents a formal parameter definition.
/// </summary>
public sealed class FormalParam : LangElement
{
[Flags]
public enum Flags : byte
{
Default = 0,
IsByRef = 1,
IsOut = 2,
IsVariadic = 4,
IsConstructorPropertyPublic = 8,
IsConstructorPropertyPrivate = 16,
IsConstructorPropertyProtected = 32,
IsConstructorPropertyReadOnly = 64,
IsConstructorPropertyMask = IsConstructorPropertyPublic | IsConstructorPropertyPrivate | IsConstructorPropertyProtected | IsConstructorPropertyReadOnly,
}
/// <summary>
/// Flags describing the parameter.
/// </summary>
private Flags _flags;
/// <summary>
/// Name of the argument.
/// </summary>
public VariableNameRef Name { get; }
/// <summary>
/// Whether the parameter is &-modified.
/// </summary>
public bool PassedByRef => (_flags & Flags.IsByRef) != 0;
/// <summary>
/// Whether the parameter is an out-parameter. Set by applying the [Out] attribute.
/// </summary>
public bool IsOut
{
get
{
return (_flags & Flags.IsOut) != 0;
}
internal set
{
if (value) _flags |= Flags.IsOut;
else _flags &= ~Flags.IsOut;
}
}
/// <summary>
/// Gets value indicating whether the parameter is variadic and so passed parameters will be packed into the array as passed as one parameter.
/// </summary>
public bool IsVariadic => (_flags & Flags.IsVariadic) != 0;
/// <summary>
/// Gets value indicating the parameter is a constructor property (PHP8).
/// </summary>
public bool IsConstructorProperty => (_flags & Flags.IsConstructorPropertyMask) != 0;
/// <summary>
/// In case the parameter is <see cref="IsConstructorProperty"/>, gets the member visibility.
/// </summary>
public PhpMemberAttributes ConstructorPropertyFlags
{
get
{
var result = (PhpMemberAttributes)0;
if ((_flags & Flags.IsConstructorPropertyPublic) != 0) result |= PhpMemberAttributes.Public; // 0
if ((_flags & Flags.IsConstructorPropertyPrivate) != 0) result |= PhpMemberAttributes.Private;
if ((_flags & Flags.IsConstructorPropertyProtected) != 0) result |= PhpMemberAttributes.Protected;
if ((_flags & Flags.IsConstructorPropertyReadOnly) != 0) result |= PhpMemberAttributes.ReadOnly;
return result;
}
}
/// <summary>
/// Initial value expression. Can be <B>null</B>.
/// </summary>
public Expression InitValue { get; internal set; }
/// <summary>
/// Either <see cref="TypeRef"/> or <B>null</B>.
/// </summary>
public TypeRef TypeHint { get; }
#region Construction
public FormalParam(
Text.Span span, string/*!*/ name, Text.Span nameSpan,
TypeRef typeHint, Flags flags,
Expression initValue,
PhpMemberAttributes constructorPropertyVisibility = 0)
: base(span)
{
this.Name = new VariableNameRef(nameSpan, name);
this.TypeHint = typeHint;
this.InitValue = initValue;
_flags = flags;
if (constructorPropertyVisibility != 0)
{
Debug.Assert((constructorPropertyVisibility & PhpMemberAttributes.Constructor) != 0);
_flags |= (constructorPropertyVisibility & PhpMemberAttributes.VisibilityMask) switch
{
PhpMemberAttributes.Private => Flags.IsConstructorPropertyPrivate,
PhpMemberAttributes.Protected => Flags.IsConstructorPropertyProtected,
//PhpMemberAttributes.Public => Flags.IsConstructorPropertyPublic,
_ => Flags.IsConstructorPropertyPublic,
};
if (constructorPropertyVisibility.IsReadOnly())
{
_flags |= Flags.IsConstructorPropertyReadOnly;
}
}
}
#endregion
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitFormalParam(this);
}
}
#endregion
#region Signature
public struct Signature
{
public bool AliasReturn { get { return aliasReturn; } }
private readonly bool aliasReturn;
public FormalParam[]/*!*/ FormalParams { get { return formalParams; } }
private readonly FormalParam[]/*!*/ formalParams;
/// <summary>
/// Signature position including the parentheses.
/// </summary>
public Text.Span Span { get { return _span; } }
private Text.Span _span;
public Signature(bool aliasReturn, IList<FormalParam>/*!*/ formalParams, Text.Span position)
{
this.aliasReturn = aliasReturn;
this.formalParams = formalParams.AsArray();
_span = position;
}
}
#endregion
#region FunctionDecl
/// <summary>
/// Represents a function declaration.
/// </summary>
public sealed class FunctionDecl : Statement
{
internal override bool IsDeclaration { get { return true; } }
public NameRef Name { get { return name; } }
private readonly NameRef name;
public Signature Signature { get { return signature; } }
private readonly Signature signature;
public TypeSignature TypeSignature { get { return typeSignature; } }
private readonly TypeSignature typeSignature;
public BlockStmt/*!*/ Body { get { return body; } }
private readonly BlockStmt/*!*/ body;
/// <summary>
/// Gets value indicating whether the function is declared conditionally.
/// </summary>
public bool IsConditional { get; internal set; }
/// <summary>
/// Gets function declaration attributes.
/// </summary>
public PhpMemberAttributes MemberAttributes { get; private set; }
public Text.Span ParametersSpan { get { return Signature.Span; } }
/// <summary>
/// Span of the entire method header.
/// </summary>
public Text.Span HeadingSpan
{
get
{
if (Span.IsValid)
{
var endspan = returnType != null ? returnType.Span : Signature.Span;
if (endspan.IsValid)
{
return Text.Span.FromBounds(Span.Start, endspan.End);
}
}
//
return Text.Span.Invalid;
}
}
public TypeRef ReturnType { get { return returnType; } }
private TypeRef returnType;
#region Construction
public FunctionDecl(
Text.Span span,
bool isConditional, PhpMemberAttributes memberAttributes, NameRef/*!*/ name,
bool aliasReturn, IList<FormalParam>/*!*/ formalParams, Text.Span paramsSpan, IList<FormalTypeParam>/*!*/ genericParams,
BlockStmt/*!*/ body, TypeRef returnType)
: base(span)
{
Debug.Assert(genericParams != null && formalParams != null && body != null);
this.name = name;
this.signature = new Signature(aliasReturn, formalParams, paramsSpan);
this.typeSignature = new TypeSignature(genericParams);
this.body = body;
this.IsConditional = isConditional;
this.MemberAttributes = memberAttributes;
this.returnType = returnType;
}
#endregion
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitFunctionDecl(this);
}
/// <summary>
/// <see cref="PHPDocBlock"/> instance or <c>null</c> reference.
/// </summary>
public PHPDocBlock PHPDoc
{
get { return this.GetPHPDoc(); }
set { this.SetPHPDoc(value); }
}
}
#endregion
}
| |
//
// MassStorageSource.cs
//
// Author:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.Collections;
using Banshee.IO;
using Banshee.Dap;
using Banshee.Base;
using Banshee.ServiceStack;
using Banshee.Library;
using Banshee.Query;
using Banshee.Sources;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Hardware;
using Banshee.Playlists.Formats;
using Banshee.Playlist;
namespace Banshee.Dap.MassStorage
{
public class MassStorageSource : DapSource
{
private Banshee.Collection.Gui.ArtworkManager artwork_manager
= ServiceManager.Get<Banshee.Collection.Gui.ArtworkManager> ();
private MassStorageDevice ms_device;
private IVolume volume;
private IUsbDevice usb_device;
public override void DeviceInitialize (IDevice device)
{
base.DeviceInitialize (device);
volume = device as IVolume;
if (volume == null || !volume.IsMounted || (usb_device = volume.ResolveRootUsbDevice ()) == null) {
throw new InvalidDeviceException ();
}
ms_device = DeviceMapper.Map (this);
try {
if (ms_device.ShouldIgnoreDevice () || !ms_device.LoadDeviceConfiguration ()) {
ms_device = null;
}
} catch {
ms_device = null;
}
if (!HasMediaCapabilities && ms_device == null) {
throw new InvalidDeviceException ();
}
// Ignore iPods, except ones with .is_audio_player files
if (MediaCapabilities != null && MediaCapabilities.IsType ("ipod")) {
if (ms_device != null && ms_device.HasIsAudioPlayerFile) {
Log.Information (
"Mass Storage Support Loading iPod",
"The USB mass storage audio player support is loading an iPod because it has an .is_audio_player file. " +
"If you aren't running Rockbox or don't know what you're doing, things might not behave as expected."
);
} else {
throw new InvalidDeviceException ();
}
}
Name = ms_device == null ? volume.Name : ms_device.Name;
mount_point = volume.MountPoint;
Initialize ();
if (ms_device != null) {
ms_device.SourceInitialize ();
}
AddDapProperties ();
// TODO differentiate between Audio Players and normal Disks, and include the size, eg "2GB Audio Player"?
//GenericName = Catalog.GetString ("Audio Player");
}
private void AddDapProperties ()
{
if (AudioFolders.Length > 0 && !String.IsNullOrEmpty (AudioFolders[0])) {
AddDapProperty (String.Format (
Catalog.GetPluralString ("Audio Folder", "Audio Folders", AudioFolders.Length), AudioFolders.Length),
System.String.Join ("\n", AudioFolders)
);
}
if (VideoFolders.Length > 0 && !String.IsNullOrEmpty (VideoFolders[0])) {
AddDapProperty (String.Format (
Catalog.GetPluralString ("Video Folder", "Video Folders", VideoFolders.Length), VideoFolders.Length),
System.String.Join ("\n", VideoFolders)
);
}
if (FolderDepth != -1) {
AddDapProperty (Catalog.GetString ("Required Folder Depth"), FolderDepth.ToString ());
}
AddYesNoDapProperty (Catalog.GetString ("Supports Playlists"), PlaylistTypes.Count > 0);
/*if (AcceptableMimeTypes.Length > 0) {
AddDapProperty (String.Format (
Catalog.GetPluralString ("Audio Format", "Audio Formats", PlaybackFormats.Length), PlaybackFormats.Length),
System.String.Join (", ", PlaybackFormats)
);
}*/
}
private System.Threading.ManualResetEvent import_reset_event;
private DatabaseImportManager importer;
// WARNING: This will be called from a thread!
protected override void LoadFromDevice ()
{
import_reset_event = new System.Threading.ManualResetEvent (false);
importer = new DatabaseImportManager (this) {
KeepUserJobHidden = true,
SkipHiddenChildren = false
};
importer.Finished += OnImportFinished;
foreach (string audio_folder in BaseDirectories) {
importer.Enqueue (audio_folder);
}
import_reset_event.WaitOne ();
}
private void OnImportFinished (object o, EventArgs args)
{
importer.Finished -= OnImportFinished;
if (CanSyncPlaylists) {
var insert_cmd = new Hyena.Data.Sqlite.HyenaSqliteCommand (
"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID) VALUES (?, ?)");
foreach (string playlist_path in PlaylistFiles) {
// playlist_path has a file:// prefix, and GetDirectoryName messes it up,
// so we need to convert it to a regular path
string base_folder = ms_device.RootPath != null ? BaseDirectory :
System.IO.Path.GetDirectoryName (SafeUri.UriToFilename (playlist_path));
IPlaylistFormat loaded_playlist = PlaylistFileUtil.Load (playlist_path,
new Uri (base_folder),
ms_device.RootPath);
if (loaded_playlist == null)
continue;
string name = System.IO.Path.GetFileNameWithoutExtension (SafeUri.UriToFilename (playlist_path));
PlaylistSource playlist = new PlaylistSource (name, this);
playlist.Save ();
//Hyena.Data.Sqlite.HyenaSqliteCommand.LogAll = true;
foreach (PlaylistElement element in loaded_playlist.Elements) {
string track_path = element.Uri.LocalPath;
long track_id = DatabaseTrackInfo.GetTrackIdForUri (new SafeUri (track_path), DbId);
if (track_id == 0) {
Log.DebugFormat ("Failed to find track {0} in DAP library to load it into playlist {1}", track_path, playlist_path);
} else {
ServiceManager.DbConnection.Execute (insert_cmd, playlist.DbId, track_id);
}
}
//Hyena.Data.Sqlite.HyenaSqliteCommand.LogAll = false;
playlist.UpdateCounts ();
AddChildSource (playlist);
}
}
import_reset_event.Set ();
}
public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job)
{
if (track.PrimarySourceId == DbId) {
Banshee.IO.File.Copy (track.Uri, uri, false);
}
}
public override void Import ()
{
var importer = new LibraryImportManager (true) {
SkipHiddenChildren = false
};
foreach (string audio_folder in BaseDirectories) {
importer.Enqueue (audio_folder);
}
}
public IVolume Volume {
get { return volume; }
}
public IUsbDevice UsbDevice {
get { return usb_device; }
}
private string mount_point;
public override string BaseDirectory {
get { return mount_point; }
}
protected override IDeviceMediaCapabilities MediaCapabilities {
get {
return ms_device ?? (
volume.Parent == null
? base.MediaCapabilities
: volume.Parent.MediaCapabilities ?? base.MediaCapabilities
);
}
}
#region Properties and Methods for Supporting Syncing of Playlists
private string [] playlists_paths;
private string [] PlaylistsPaths {
get {
if (playlists_paths == null) {
if (MediaCapabilities == null || MediaCapabilities.PlaylistPaths == null
|| MediaCapabilities.PlaylistPaths.Length == 0) {
playlists_paths = new string [] { WritePath };
} else {
playlists_paths = new string [MediaCapabilities.PlaylistPaths.Length];
for (int i = 0; i < MediaCapabilities.PlaylistPaths.Length; i++) {
playlists_paths[i] = Paths.Combine (BaseDirectory, MediaCapabilities.PlaylistPaths[i]);
playlists_paths[i] = playlists_paths[i].Replace ("%File", String.Empty);
}
}
}
return playlists_paths;
}
}
private string playlists_write_path;
private string PlaylistsWritePath {
get {
if (playlists_write_path == null) {
playlists_write_path = WritePath;
// We write playlists to the first folder listed in the PlaylistsPath property
if (PlaylistsPaths.Length > 0) {
playlists_write_path = PlaylistsPaths[0];
}
if (!Directory.Exists (playlists_write_path)) {
Directory.Create (playlists_write_path);
}
}
return playlists_write_path;
}
}
private string [] playlist_formats;
private string [] PlaylistFormats {
get {
if (playlist_formats == null && MediaCapabilities != null) {
playlist_formats = MediaCapabilities.PlaylistFormats;
}
return playlist_formats;
}
set { playlist_formats = value; }
}
private List<PlaylistFormatDescription> playlist_types;
private IList<PlaylistFormatDescription> PlaylistTypes {
get {
if (playlist_types == null) {
playlist_types = new List<PlaylistFormatDescription> ();
if (PlaylistFormats != null) {
foreach (PlaylistFormatDescription desc in Banshee.Playlist.PlaylistFileUtil.ExportFormats) {
foreach (string mimetype in desc.MimeTypes) {
if (Array.IndexOf (PlaylistFormats, mimetype) != -1) {
playlist_types.Add (desc);
break;
}
}
}
}
}
SupportsPlaylists &= CanSyncPlaylists;
return playlist_types;
}
}
private IEnumerable<string> PlaylistFiles {
get {
foreach (string folder_name in PlaylistsPaths) {
if (!Directory.Exists (folder_name)) {
continue;
}
foreach (string file_name in Directory.GetFiles (folder_name)) {
foreach (PlaylistFormatDescription desc in playlist_types) {
if (file_name.EndsWith (desc.FileExtension)) {
yield return file_name;
break;
}
}
}
}
}
}
private bool CanSyncPlaylists {
get {
return PlaylistsWritePath != null && playlist_types.Count > 0;
}
}
public override void SyncPlaylists ()
{
if (!CanSyncPlaylists) {
return;
}
foreach (string file_name in PlaylistFiles) {
try {
Banshee.IO.File.Delete (new SafeUri (file_name));
} catch (Exception e) {
Log.Exception (e);
}
}
// Add playlists from Banshee to the device
PlaylistFormatBase playlist_format = null;
List<Source> children = new List<Source> (Children);
foreach (Source child in children) {
PlaylistSource from = child as PlaylistSource;
string escaped_name = StringUtil.EscapeFilename (child.Name);
if (from != null && !String.IsNullOrEmpty (escaped_name)) {
from.Reload ();
if (playlist_format == null) {
playlist_format = Activator.CreateInstance (PlaylistTypes[0].Type) as PlaylistFormatBase;
playlist_format.FolderSeparator = MediaCapabilities.FolderSeparator;
}
SafeUri playlist_path = new SafeUri (System.IO.Path.Combine (
PlaylistsWritePath, String.Format ("{0}.{1}", escaped_name, PlaylistTypes[0].FileExtension)));
System.IO.Stream stream = null;
try {
stream = Banshee.IO.File.OpenWrite (playlist_path, true);
if (ms_device.RootPath == null) {
playlist_format.BaseUri = new Uri (PlaylistsWritePath);
} else {
playlist_format.RootPath = ms_device.RootPath;
playlist_format.BaseUri = new Uri (BaseDirectory);
}
playlist_format.Save (stream, from);
} catch (Exception e) {
Log.Exception (e);
} finally {
stream.Close ();
}
}
}
}
#endregion
protected override string [] GetIconNames ()
{
string [] names = ms_device != null ? ms_device.GetIconNames () : null;
return names == null ? base.GetIconNames () : names;
}
public override long BytesUsed {
get { return BytesCapacity - volume.Available; }
}
public override long BytesCapacity {
get { return (long) volume.Capacity; }
}
private bool had_write_error = false;
public override bool IsReadOnly {
get { return volume.IsReadOnly || had_write_error; }
}
private string write_path = null;
public string WritePath {
get {
if (write_path == null) {
write_path = BaseDirectory;
// According to the HAL spec, the first folder listed in the audio_folders property
// is the folder to write files to.
if (AudioFolders.Length > 0) {
write_path = Hyena.Paths.Combine (write_path, AudioFolders[0]);
}
}
return write_path;
}
set { write_path = value; }
}
private string write_path_video = null;
public string WritePathVideo {
get {
if (write_path_video == null) {
write_path_video = BaseDirectory;
// Some Devices May Have a Separate Video Directory
if (VideoFolders.Length > 0) {
write_path_video = Hyena.Paths.Combine (write_path_video, VideoFolders[0]);
} else if (AudioFolders.Length > 0) {
write_path_video = Hyena.Paths.Combine (write_path_video, AudioFolders[0]);
write_path_video = Hyena.Paths.Combine (write_path_video, "Videos");
}
}
return write_path_video;
}
set { write_path_video = value; }
}
private string [] audio_folders;
protected string [] AudioFolders {
get {
if (audio_folders == null) {
audio_folders = HasMediaCapabilities ? MediaCapabilities.AudioFolders : new string[0];
}
return audio_folders;
}
set { audio_folders = value; }
}
private string [] video_folders;
protected string [] VideoFolders {
get {
if (video_folders == null) {
video_folders = HasMediaCapabilities ? MediaCapabilities.VideoFolders : new string[0];
}
return video_folders;
}
set { video_folders = value; }
}
protected IEnumerable<string> BaseDirectories {
get {
if (AudioFolders.Length == 0) {
yield return BaseDirectory;
} else {
foreach (string audio_folder in AudioFolders) {
yield return Paths.Combine (BaseDirectory, audio_folder);
}
}
}
}
private int folder_depth = -1;
protected int FolderDepth {
get {
if (folder_depth == -1) {
folder_depth = HasMediaCapabilities ? MediaCapabilities.FolderDepth : -1;
}
return folder_depth;
}
set { folder_depth = value; }
}
private int cover_art_size = -1;
protected int CoverArtSize {
get {
if (cover_art_size == -1) {
cover_art_size = HasMediaCapabilities ? MediaCapabilities.CoverArtSize : 0;
}
return cover_art_size;
}
set { cover_art_size = value; }
}
private string cover_art_file_name = null;
protected string CoverArtFileName {
get {
if (cover_art_file_name == null) {
cover_art_file_name = HasMediaCapabilities ? MediaCapabilities.CoverArtFileName : null;
}
return cover_art_file_name;
}
set { cover_art_file_name = value; }
}
private string cover_art_file_type = null;
protected string CoverArtFileType {
get {
if (cover_art_file_type == null) {
cover_art_file_type = HasMediaCapabilities ? MediaCapabilities.CoverArtFileType : null;
}
return cover_art_file_type;
}
set { cover_art_file_type = value; }
}
public override void UpdateMetadata (DatabaseTrackInfo track)
{
SafeUri new_uri = new SafeUri (GetTrackPath (track, System.IO.Path.GetExtension (track.Uri)));
if (new_uri.ToString () != track.Uri.ToString ()) {
Directory.Create (System.IO.Path.GetDirectoryName (new_uri.LocalPath));
Banshee.IO.File.Move (track.Uri, new_uri);
//to remove the folder if it's not needed anymore:
DeleteTrackFile (track);
track.Uri = new_uri;
track.Save (true, BansheeQuery.UriField);
}
base.UpdateMetadata (track);
}
protected override void AddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri)
{
if (track.PrimarySourceId == DbId)
return;
SafeUri new_uri = new SafeUri (GetTrackPath (track, System.IO.Path.GetExtension (fromUri)));
// If it already is on the device but it's out of date, remove it
//if (File.Exists(new_uri) && File.GetLastWriteTime(track.Uri.LocalPath) > File.GetLastWriteTime(new_uri))
//RemoveTrack(new MassStorageTrackInfo(new SafeUri(new_uri)));
if (!File.Exists (new_uri)) {
Directory.Create (System.IO.Path.GetDirectoryName (new_uri.LocalPath));
File.Copy (fromUri, new_uri, false);
DatabaseTrackInfo copied_track = new DatabaseTrackInfo (track);
copied_track.PrimarySource = this;
copied_track.Uri = new_uri;
// Write the metadata in db to the file on the DAP if it has changed since file was modified
// to ensure that when we load it next time, it's data will match what's in the database
// and the MetadataHash will actually match. We do this by comparing the time
// stamps on files for last update of the db metadata vs the sync to file.
// The equals on the inequality below is necessary for podcasts who often have a sync and
// update time that are the same to the second, even though the album metadata has changed in the
// DB to the feedname instead of what is in the file. It should be noted that writing the metadata
// is a small fraction of the total copy time anyway.
if (track.LastSyncedStamp >= Hyena.DateTimeUtil.ToDateTime (track.FileModifiedStamp)) {
Log.DebugFormat ("Copying Metadata to File Since Sync time >= Updated Time");
bool write_metadata = Metadata.SaveTrackMetadataService.WriteMetadataEnabled.Value;
bool write_ratings = Metadata.SaveTrackMetadataService.WriteRatingsEnabled.Value;
bool write_playcounts = Metadata.SaveTrackMetadataService.WritePlayCountsEnabled.Value;
Banshee.Streaming.StreamTagger.SaveToFile (copied_track, write_metadata, write_ratings, write_playcounts);
}
copied_track.Save (false);
}
if (CoverArtSize > -1 && !String.IsNullOrEmpty (CoverArtFileType) &&
!String.IsNullOrEmpty (CoverArtFileName) && (FolderDepth == -1 || FolderDepth > 0)) {
SafeUri cover_uri = new SafeUri (System.IO.Path.Combine (System.IO.Path.GetDirectoryName (new_uri.LocalPath),
CoverArtFileName));
string coverart_id = track.ArtworkId;
if (!File.Exists (cover_uri) && CoverArtSpec.CoverExists (coverart_id)) {
Gdk.Pixbuf pic = null;
if (CoverArtSize == 0) {
if (CoverArtFileType == "jpg" || CoverArtFileType == "jpeg") {
SafeUri local_cover_uri = new SafeUri (Banshee.Base.CoverArtSpec.GetPath (coverart_id));
Banshee.IO.File.Copy (local_cover_uri, cover_uri, false);
} else {
pic = artwork_manager.LookupPixbuf (coverart_id);
}
} else {
pic = artwork_manager.LookupScalePixbuf (coverart_id, CoverArtSize);
}
if (pic != null) {
try {
byte [] bytes = pic.SaveToBuffer (CoverArtFileType);
System.IO.Stream cover_art_file = File.OpenWrite (cover_uri, true);
cover_art_file.Write (bytes, 0, bytes.Length);
cover_art_file.Close ();
} catch (GLib.GException){
Log.DebugFormat ("Could not convert cover art to {0}, unsupported filetype?", CoverArtFileType);
} finally {
Banshee.Collection.Gui.ArtworkManager.DisposePixbuf (pic);
}
}
}
}
}
protected override bool DeleteTrack (DatabaseTrackInfo track)
{
if (ms_device != null && !ms_device.DeleteTrackHook (track)) {
return false;
}
DeleteTrackFile (track);
return true;
}
private void DeleteTrackFile (DatabaseTrackInfo track)
{
try {
string track_file = System.IO.Path.GetFileName (track.Uri.LocalPath);
string track_dir = System.IO.Path.GetDirectoryName (track.Uri.LocalPath);
int files = 0;
// Count how many files remain in the track's directory,
// excluding self or cover art
foreach (string file in System.IO.Directory.GetFiles (track_dir)) {
string relative = System.IO.Path.GetFileName (file);
if (relative != track_file && relative != CoverArtFileName) {
files++;
}
}
// If we are the last track, go ahead and delete the artwork
// to ensure that the directory tree can get trimmed away too
if (files == 0 && CoverArtFileName != null) {
System.IO.File.Delete (Paths.Combine (track_dir, CoverArtFileName));
}
if (Banshee.IO.File.Exists (track.Uri)) {
Banshee.IO.Utilities.DeleteFileTrimmingParentDirectories (track.Uri);
} else {
Banshee.IO.Utilities.TrimEmptyDirectories (track.Uri);
}
} catch (System.IO.FileNotFoundException) {
} catch (System.IO.DirectoryNotFoundException) {
}
}
protected override void Eject ()
{
base.Eject ();
if (volume.CanUnmount) {
volume.Unmount ();
}
if (volume.CanEject) {
volume.Eject ();
}
}
protected override bool CanHandleDeviceCommand (DeviceCommand command)
{
try {
SafeUri uri = new SafeUri (command.DeviceId);
return BaseDirectory.StartsWith (uri.LocalPath);
} catch {
return false;
}
}
private string GetTrackPath (TrackInfo track, string ext)
{
string file_path = null;
if (track.HasAttribute (TrackMediaAttributes.Podcast)) {
string album = FileNamePattern.Escape (track.DisplayAlbumTitle);
string title = FileNamePattern.Escape (track.DisplayTrackTitle);
file_path = System.IO.Path.Combine ("Podcasts", album);
file_path = System.IO.Path.Combine (file_path, title);
} else if (track.HasAttribute (TrackMediaAttributes.VideoStream)) {
string album = FileNamePattern.Escape (track.DisplayAlbumTitle);
string title = FileNamePattern.Escape (track.DisplayTrackTitle);
file_path = System.IO.Path.Combine (album, title);
} else if (ms_device == null || !ms_device.GetTrackPath (track, out file_path)) {
// If the folder_depth property exists, we have to put the files in a hiearchy of
// the exact given depth (not including the mount point/audio_folder).
if (FolderDepth != -1) {
int depth = FolderDepth;
bool is_album_unknown = String.IsNullOrEmpty (track.AlbumTitle);
string album_artist = FileNamePattern.Escape (track.DisplayAlbumArtistName);
string track_album = FileNamePattern.Escape (track.DisplayAlbumTitle);
string track_number = FileNamePattern.Escape (String.Format ("{0:00}", track.TrackNumber));
string track_title = FileNamePattern.Escape (track.DisplayTrackTitle);
if (depth == 0) {
// Artist - Album - 01 - Title
string track_artist = FileNamePattern.Escape (track.DisplayArtistName);
file_path = is_album_unknown ?
String.Format ("{0} - {1} - {2}", track_artist, track_number, track_title) :
String.Format ("{0} - {1} - {2} - {3}", track_artist, track_album, track_number, track_title);
} else if (depth == 1) {
// Artist - Album/01 - Title
file_path = is_album_unknown ?
album_artist :
String.Format ("{0} - {1}", album_artist, track_album);
file_path = System.IO.Path.Combine (file_path, String.Format ("{0} - {1}", track_number, track_title));
} else if (depth == 2) {
// Artist/Album/01 - Title
file_path = album_artist;
if (!is_album_unknown || ms_device.MinimumFolderDepth == depth) {
file_path = System.IO.Path.Combine (file_path, track_album);
}
file_path = System.IO.Path.Combine (file_path, String.Format ("{0} - {1}", track_number, track_title));
} else {
// If the *required* depth is more than 2..go nuts!
for (int i = 0; i < depth - 2; i++) {
if (i == 0) {
file_path = album_artist.Substring (0, Math.Min (i+1, album_artist.Length)).Trim ();
} else {
file_path = System.IO.Path.Combine (file_path, album_artist.Substring (0, Math.Min (i+1, album_artist.Length)).Trim ());
}
}
// Finally add on the Artist/Album/01 - Track
file_path = System.IO.Path.Combine (file_path, album_artist);
file_path = System.IO.Path.Combine (file_path, track_album);
file_path = System.IO.Path.Combine (file_path, String.Format ("{0} - {1}", track_number, track_title));
}
} else {
file_path = MusicLibrarySource.MusicFileNamePattern.CreateFromTrackInfo (track);
}
}
if (track.HasAttribute (TrackMediaAttributes.VideoStream)) {
file_path = System.IO.Path.Combine (WritePathVideo, file_path);
} else {
file_path = System.IO.Path.Combine (WritePath, file_path);
}
file_path += ext;
return file_path;
}
public override bool HasEditableTrackProperties {
get { return true; }
}
}
}
| |
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Word;
using Microsoft.Vbe.Interop;
using Application = Microsoft.Office.Interop.Word.Application;
using Shape = Microsoft.Office.Interop.Word.Shape;
using Shapes = Microsoft.Office.Interop.Word.Shapes;
using Window = Microsoft.Office.Interop.Word.Window;
using Windows = Microsoft.Office.Interop.Word.Windows;
namespace Word.TestDoubles
{
#pragma warning disable 0067
public class DocumentTestDouble : Document
{
public DocumentTestDouble(ApplicationTestDouble application, WindowTestDouble window)
{
Windows = new WindowsTestDouble(application);
Windows.Add(window);
Application = application;
}
void _Document.Close(ref object saveChanges, ref object originalFormat, ref object routeDocument)
{
throw new System.NotImplementedException();
}
public void SaveAs2000(ref object fileName, ref object fileFormat, ref object lockComments, ref object password,
ref object addToRecentFiles, ref object writePassword, ref object readOnlyRecommended, ref object embedTrueTypeFonts,
ref object saveNativePictureFormat, ref object saveFormsData, ref object saveAsAoceLetter)
{
throw new System.NotImplementedException();
}
public void Repaginate()
{
throw new System.NotImplementedException();
}
public void FitToPages()
{
throw new System.NotImplementedException();
}
public void ManualHyphenation()
{
throw new System.NotImplementedException();
}
public void Select()
{
throw new System.NotImplementedException();
}
public void DataForm()
{
throw new System.NotImplementedException();
}
public void Route()
{
throw new System.NotImplementedException();
}
public void Save()
{
throw new System.NotImplementedException();
}
public void PrintOutOld(ref object background, ref object append, ref object range, ref object outputFileName, ref object @from,
ref object to, ref object item, ref object copies, ref object pages, ref object pageType, ref object printToFile,
ref object collate, ref object activePrinterMacGx, ref object manualDuplexPrint)
{
throw new System.NotImplementedException();
}
public void SendMail()
{
throw new System.NotImplementedException();
}
public Range Range(ref object start, ref object end)
{
throw new System.NotImplementedException();
}
public void RunAutoMacro(WdAutoMacros which)
{
throw new System.NotImplementedException();
}
public void Activate()
{
throw new System.NotImplementedException();
}
public void PrintPreview()
{
throw new System.NotImplementedException();
}
public Range GoTo(ref object what, ref object which, ref object count, ref object name)
{
throw new System.NotImplementedException();
}
public bool Undo(ref object times)
{
throw new System.NotImplementedException();
}
public bool Redo(ref object Times)
{
throw new System.NotImplementedException();
}
public int ComputeStatistics(WdStatistic Statistic, ref object IncludeFootnotesAndEndnotes)
{
throw new System.NotImplementedException();
}
public void MakeCompatibilityDefault()
{
throw new System.NotImplementedException();
}
public void Protect2002(WdProtectionType Type, ref object NoReset, ref object Password)
{
throw new System.NotImplementedException();
}
public void Unprotect(ref object Password)
{
throw new System.NotImplementedException();
}
public void EditionOptions(WdEditionType Type, WdEditionOption Option, string Name, ref object Format)
{
throw new System.NotImplementedException();
}
public void RunLetterWizard(ref object LetterContent, ref object WizardMode)
{
throw new System.NotImplementedException();
}
public LetterContent GetLetterContent()
{
throw new System.NotImplementedException();
}
public void SetLetterContent(ref object LetterContent)
{
throw new System.NotImplementedException();
}
public void CopyStylesFromTemplate(string Template)
{
throw new System.NotImplementedException();
}
public void UpdateStyles()
{
throw new System.NotImplementedException();
}
public void CheckGrammar()
{
throw new System.NotImplementedException();
}
public void CheckSpelling(ref object CustomDictionary, ref object IgnoreUppercase, ref object AlwaysSuggest,
ref object CustomDictionary2, ref object CustomDictionary3, ref object CustomDictionary4,
ref object CustomDictionary5, ref object CustomDictionary6, ref object CustomDictionary7,
ref object CustomDictionary8, ref object CustomDictionary9, ref object CustomDictionary10)
{
throw new System.NotImplementedException();
}
public void FollowHyperlink(ref object Address, ref object SubAddress, ref object NewWindow, ref object AddHistory,
ref object ExtraInfo, ref object Method, ref object HeaderInfo)
{
throw new System.NotImplementedException();
}
public void AddToFavorites()
{
throw new System.NotImplementedException();
}
public void Reload()
{
throw new System.NotImplementedException();
}
public Range AutoSummarize(ref object Length, ref object Mode, ref object UpdateProperties)
{
throw new System.NotImplementedException();
}
public void RemoveNumbers(ref object NumberType)
{
throw new System.NotImplementedException();
}
public void ConvertNumbersToText(ref object NumberType)
{
throw new System.NotImplementedException();
}
public int CountNumberedItems(ref object NumberType, ref object Level)
{
throw new System.NotImplementedException();
}
public void Post()
{
throw new System.NotImplementedException();
}
public void ToggleFormsDesign()
{
throw new System.NotImplementedException();
}
public void Compare2000(string Name)
{
throw new System.NotImplementedException();
}
public void UpdateSummaryProperties()
{
throw new System.NotImplementedException();
}
public object GetCrossReferenceItems(ref object ReferenceType)
{
throw new System.NotImplementedException();
}
public void AutoFormat()
{
throw new System.NotImplementedException();
}
public void ViewCode()
{
throw new System.NotImplementedException();
}
public void ViewPropertyBrowser()
{
throw new System.NotImplementedException();
}
public void ForwardMailer()
{
throw new System.NotImplementedException();
}
public void Reply()
{
throw new System.NotImplementedException();
}
public void ReplyAll()
{
throw new System.NotImplementedException();
}
public void SendMailer(ref object FileFormat, ref object Priority)
{
throw new System.NotImplementedException();
}
public void UndoClear()
{
throw new System.NotImplementedException();
}
public void PresentIt()
{
throw new System.NotImplementedException();
}
public void SendFax(string Address, ref object Subject)
{
throw new System.NotImplementedException();
}
public void Merge2000(string FileName)
{
throw new System.NotImplementedException();
}
public void ClosePrintPreview()
{
throw new System.NotImplementedException();
}
public void CheckConsistency()
{
throw new System.NotImplementedException();
}
public LetterContent CreateLetterContent(string DateFormat, bool IncludeHeaderFooter, string PageDesign,
WdLetterStyle LetterStyle, bool Letterhead, WdLetterheadLocation LetterheadLocation, float LetterheadSize,
string RecipientName, string RecipientAddress, string Salutation, WdSalutationType SalutationType,
string RecipientReference, string MailingInstructions, string AttentionLine, string Subject, string CCList,
string ReturnAddress, string SenderName, string Closing, string SenderCompany, string SenderJobTitle,
string SenderInitials, int EnclosureNumber, ref object InfoBlock, ref object RecipientCode,
ref object RecipientGender, ref object ReturnAddressShortForm, ref object SenderCity, ref object SenderCode,
ref object SenderGender, ref object SenderReference)
{
throw new System.NotImplementedException();
}
public void AcceptAllRevisions()
{
throw new System.NotImplementedException();
}
public void RejectAllRevisions()
{
throw new System.NotImplementedException();
}
public void DetectLanguage()
{
throw new System.NotImplementedException();
}
public void ApplyTheme(string Name)
{
throw new System.NotImplementedException();
}
public void RemoveTheme()
{
throw new System.NotImplementedException();
}
public void WebPagePreview()
{
throw new System.NotImplementedException();
}
public void ReloadAs(MsoEncoding Encoding)
{
throw new System.NotImplementedException();
}
public void PrintOut2000(ref object Background, ref object Append, ref object Range, ref object OutputFileName, ref object From,
ref object To, ref object Item, ref object Copies, ref object Pages, ref object PageType, ref object PrintToFile,
ref object Collate, ref object ActivePrinterMacGX, ref object ManualDuplexPrint, ref object PrintZoomColumn,
ref object PrintZoomRow, ref object PrintZoomPaperWidth, ref object PrintZoomPaperHeight)
{
throw new System.NotImplementedException();
}
public void sblt(string s)
{
throw new System.NotImplementedException();
}
public void ConvertVietDoc(int CodePageOrigin)
{
throw new System.NotImplementedException();
}
public void PrintOut(ref object Background, ref object Append, ref object Range, ref object OutputFileName, ref object From,
ref object To, ref object Item, ref object Copies, ref object Pages, ref object PageType, ref object PrintToFile,
ref object Collate, ref object ActivePrinterMacGX, ref object ManualDuplexPrint, ref object PrintZoomColumn,
ref object PrintZoomRow, ref object PrintZoomPaperWidth, ref object PrintZoomPaperHeight)
{
throw new System.NotImplementedException();
}
public void Compare2002(string Name, ref object AuthorName, ref object CompareTarget, ref object DetectFormatChanges,
ref object IgnoreAllComparisonWarnings, ref object AddToRecentFiles)
{
throw new System.NotImplementedException();
}
public void CheckIn(bool SaveChanges, ref object Comments, bool MakePublic = false)
{
throw new System.NotImplementedException();
}
public bool CanCheckin()
{
throw new System.NotImplementedException();
}
public void Merge(string FileName, ref object MergeTarget, ref object DetectFormatChanges, ref object UseFormattingFrom,
ref object AddToRecentFiles)
{
throw new System.NotImplementedException();
}
public void SendForReview(ref object Recipients, ref object Subject, ref object ShowMessage, ref object IncludeAttachment)
{
throw new System.NotImplementedException();
}
public void ReplyWithChanges(ref object ShowMessage)
{
throw new System.NotImplementedException();
}
public void EndReview()
{
throw new System.NotImplementedException();
}
public void SetPasswordEncryptionOptions(string PasswordEncryptionProvider, string PasswordEncryptionAlgorithm,
int PasswordEncryptionKeyLength, ref object PasswordEncryptionFileProperties)
{
throw new System.NotImplementedException();
}
public void RecheckSmartTags()
{
throw new System.NotImplementedException();
}
public void RemoveSmartTags()
{
throw new System.NotImplementedException();
}
public void SetDefaultTableStyle(ref object Style, bool SetInTemplate)
{
throw new System.NotImplementedException();
}
public void DeleteAllComments()
{
throw new System.NotImplementedException();
}
public void AcceptAllRevisionsShown()
{
throw new System.NotImplementedException();
}
public void RejectAllRevisionsShown()
{
throw new System.NotImplementedException();
}
public void DeleteAllCommentsShown()
{
throw new System.NotImplementedException();
}
public void ResetFormFields()
{
throw new System.NotImplementedException();
}
public void SaveAs(ref object FileName, ref object FileFormat, ref object LockComments, ref object Password,
ref object AddToRecentFiles, ref object WritePassword, ref object ReadOnlyRecommended, ref object EmbedTrueTypeFonts,
ref object SaveNativePictureFormat, ref object SaveFormsData, ref object SaveAsAOCELetter, ref object Encoding,
ref object InsertLineBreaks, ref object AllowSubstitutions, ref object LineEnding, ref object AddBiDiMarks)
{
throw new System.NotImplementedException();
}
public void CheckNewSmartTags()
{
throw new System.NotImplementedException();
}
public void SendFaxOverInternet(ref object Recipients, ref object Subject, ref object ShowMessage)
{
throw new System.NotImplementedException();
}
public void TransformDocument(string Path, bool DataOnly = true)
{
throw new System.NotImplementedException();
}
public void Protect(WdProtectionType Type, ref object NoReset, ref object Password, ref object UseIRM,
ref object EnforceStyleLock)
{
throw new System.NotImplementedException();
}
public void SelectAllEditableRanges(ref object EditorID)
{
throw new System.NotImplementedException();
}
public void DeleteAllEditableRanges(ref object EditorID)
{
throw new System.NotImplementedException();
}
public void DeleteAllInkAnnotations()
{
throw new System.NotImplementedException();
}
public void AddDocumentWorkspaceHeader(bool RichFormat, string Url, string Title, string Description, string ID)
{
throw new System.NotImplementedException();
}
public void RemoveDocumentWorkspaceHeader(string ID)
{
throw new System.NotImplementedException();
}
public void Compare(string Name, ref object AuthorName, ref object CompareTarget, ref object DetectFormatChanges,
ref object IgnoreAllComparisonWarnings, ref object AddToRecentFiles, ref object RemovePersonalInformation,
ref object RemoveDateAndTime)
{
throw new System.NotImplementedException();
}
public void RemoveLockedStyles()
{
throw new System.NotImplementedException();
}
public XMLNode SelectSingleNode(string XPath, string PrefixMapping = "", bool FastSearchSkippingTextNodes = true)
{
throw new System.NotImplementedException();
}
public XMLNodes SelectNodes(string XPath, string PrefixMapping = "", bool FastSearchSkippingTextNodes = true)
{
throw new System.NotImplementedException();
}
public void Dummy1()
{
throw new System.NotImplementedException();
}
public void RemoveDocumentInformation(WdRemoveDocInfoType RemoveDocInfoType)
{
throw new System.NotImplementedException();
}
public void CheckInWithVersion(bool SaveChanges, ref object Comments, bool MakePublic, ref object VersionType)
{
throw new System.NotImplementedException();
}
public void Dummy2()
{
throw new System.NotImplementedException();
}
public void Dummy3()
{
throw new System.NotImplementedException();
}
public void LockServerFile()
{
throw new System.NotImplementedException();
}
public WorkflowTasks GetWorkflowTasks()
{
throw new System.NotImplementedException();
}
public WorkflowTemplates GetWorkflowTemplates()
{
throw new System.NotImplementedException();
}
public void Dummy4()
{
throw new System.NotImplementedException();
}
public void AddMeetingWorkspaceHeader(bool SkipIfAbsent, string Url, string Title, string Description, string ID)
{
throw new System.NotImplementedException();
}
public void SaveAsQuickStyleSet(string FileName)
{
throw new System.NotImplementedException();
}
public void ApplyQuickStyleSet(string Name)
{
throw new System.NotImplementedException();
}
public void ApplyDocumentTheme(string FileName)
{
throw new System.NotImplementedException();
}
public ContentControls SelectLinkedControls(CustomXMLNode Node)
{
throw new System.NotImplementedException();
}
public ContentControls SelectUnlinkedControls(CustomXMLPart Stream = null)
{
throw new System.NotImplementedException();
}
public ContentControls SelectContentControlsByTitle(string Title)
{
throw new System.NotImplementedException();
}
public void ExportAsFixedFormat(string OutputFileName, WdExportFormat ExportFormat, bool OpenAfterExport,
WdExportOptimizeFor OptimizeFor, WdExportRange Range, int From,
int To, WdExportItem Item, bool IncludeDocProps, bool KeepIRM,
WdExportCreateBookmarks CreateBookmarks, bool DocStructureTags,
bool BitmapMissingFonts, bool UseISO19005_1, ref object FixedFormatExtClassPtr)
{
throw new System.NotImplementedException();
}
public void FreezeLayout()
{
throw new System.NotImplementedException();
}
public void UnfreezeLayout()
{
throw new System.NotImplementedException();
}
public void DowngradeDocument()
{
throw new System.NotImplementedException();
}
public void Convert()
{
throw new System.NotImplementedException();
}
public ContentControls SelectContentControlsByTag(string Tag)
{
throw new System.NotImplementedException();
}
public void ConvertAutoHyphens()
{
throw new System.NotImplementedException();
}
public void ApplyQuickStyleSet2(ref object Style)
{
throw new System.NotImplementedException();
}
public void SaveAs2(ref object FileName, ref object FileFormat, ref object LockComments, ref object Password,
ref object AddToRecentFiles, ref object WritePassword, ref object ReadOnlyRecommended, ref object EmbedTrueTypeFonts,
ref object SaveNativePictureFormat, ref object SaveFormsData, ref object SaveAsAOCELetter, ref object Encoding,
ref object InsertLineBreaks, ref object AllowSubstitutions, ref object LineEnding, ref object AddBiDiMarks,
ref object CompatibilityMode)
{
throw new System.NotImplementedException();
}
public void SetCompatibilityMode(int Mode)
{
throw new System.NotImplementedException();
}
public int ReturnToLastReadPosition()
{
throw new System.NotImplementedException();
}
public void SaveCopyAs(ref object FileName, ref object FileFormat, ref object LockComments, ref object Password,
ref object AddToRecentFiles, ref object WritePassword, ref object ReadOnlyRecommended, ref object EmbedTrueTypeFonts,
ref object SaveNativePictureFormat, ref object SaveFormsData, ref object SaveAsAOCELetter, ref object Encoding,
ref object InsertLineBreaks, ref object AllowSubstitutions, ref object LineEnding, ref object AddBiDiMarks,
ref object CompatibilityMode)
{
throw new System.NotImplementedException();
}
public string Name { get; private set; }
public Application Application { get; private set; }
public int Creator { get; private set; }
public object Parent { get; private set; }
public object BuiltInDocumentProperties { get; private set; }
public object CustomDocumentProperties { get; private set; }
public string Path { get; private set; }
public Bookmarks Bookmarks { get; private set; }
public Tables Tables { get; private set; }
public Footnotes Footnotes { get; private set; }
public Endnotes Endnotes { get; private set; }
public Comments Comments { get; private set; }
public WdDocumentType Type { get; private set; }
public bool AutoHyphenation { get; set; }
public bool HyphenateCaps { get; set; }
public int HyphenationZone { get; set; }
public int ConsecutiveHyphensLimit { get; set; }
public Sections Sections { get; private set; }
public Paragraphs Paragraphs { get; private set; }
public Words Words { get; private set; }
public Sentences Sentences { get; private set; }
public Characters Characters { get; private set; }
public Fields Fields { get; private set; }
public FormFields FormFields { get; private set; }
public Styles Styles { get; private set; }
public Frames Frames { get; private set; }
public TablesOfFigures TablesOfFigures { get; private set; }
public Variables Variables { get; private set; }
public MailMerge MailMerge { get; private set; }
public Envelope Envelope { get; private set; }
public string FullName { get; private set; }
public Revisions Revisions { get; private set; }
public TablesOfContents TablesOfContents { get; private set; }
public TablesOfAuthorities TablesOfAuthorities { get; private set; }
public PageSetup PageSetup { get; set; }
public Windows Windows { get; private set; }
public bool HasRoutingSlip { get; set; }
public RoutingSlip RoutingSlip { get; private set; }
public bool Routed { get; private set; }
public TablesOfAuthoritiesCategories TablesOfAuthoritiesCategories { get; private set; }
public Indexes Indexes { get; private set; }
public bool Saved { get; set; }
public Range Content { get; private set; }
public Window ActiveWindow { get; private set; }
public WdDocumentKind Kind { get; set; }
public bool ReadOnly { get; private set; }
public Subdocuments Subdocuments { get; private set; }
public bool IsMasterDocument { get; private set; }
public float DefaultTabStop { get; set; }
public bool EmbedTrueTypeFonts { get; set; }
public bool SaveFormsData { get; set; }
public bool ReadOnlyRecommended { get; set; }
public bool SaveSubsetFonts { get; set; }
public bool get_Compatibility(WdCompatibility Type)
{
throw new System.NotImplementedException();
}
public void set_Compatibility(WdCompatibility Type, bool prop)
{
throw new System.NotImplementedException();
}
public StoryRanges StoryRanges { get; private set; }
public CommandBars CommandBars { get; private set; }
public bool IsSubdocument { get; private set; }
public int SaveFormat { get; private set; }
public WdProtectionType ProtectionType { get; private set; }
public Hyperlinks Hyperlinks { get; private set; }
public Shapes Shapes { get; private set; }
public ListTemplates ListTemplates { get; private set; }
public Lists Lists { get; private set; }
public bool UpdateStylesOnOpen { get; set; }
public object get_AttachedTemplate()
{
throw new System.NotImplementedException();
}
public void set_AttachedTemplate(ref object prop)
{
throw new System.NotImplementedException();
}
public InlineShapes InlineShapes { get; private set; }
public Shape Background { get; set; }
public bool GrammarChecked { get; set; }
public bool SpellingChecked { get; set; }
public bool ShowGrammaticalErrors { get; set; }
public bool ShowSpellingErrors { get; set; }
public Versions Versions { get; private set; }
public bool ShowSummary { get; set; }
public WdSummaryMode SummaryViewMode { get; set; }
public int SummaryLength { get; set; }
public bool PrintFractionalWidths { get; set; }
public bool PrintPostScriptOverText { get; set; }
public object Container { get; private set; }
public bool PrintFormsData { get; set; }
public ListParagraphs ListParagraphs { get; private set; }
public string Password { set; private get; }
public string WritePassword { set; private get; }
public bool HasPassword { get; private set; }
public bool WriteReserved { get; private set; }
public string get_ActiveWritingStyle(ref object LanguageID)
{
throw new System.NotImplementedException();
}
public void set_ActiveWritingStyle(ref object LanguageID, string prop)
{
throw new System.NotImplementedException();
}
public bool UserControl { get; set; }
public bool HasMailer { get; set; }
public Mailer Mailer { get; private set; }
public ReadabilityStatistics ReadabilityStatistics { get; private set; }
public ProofreadingErrors GrammaticalErrors { get; private set; }
public ProofreadingErrors SpellingErrors { get; private set; }
public VBProject VBProject { get; private set; }
public bool FormsDesign { get; private set; }
public string _CodeName { get; set; }
public string CodeName { get; private set; }
public bool SnapToGrid { get; set; }
public bool SnapToShapes { get; set; }
public float GridDistanceHorizontal { get; set; }
public float GridDistanceVertical { get; set; }
public float GridOriginHorizontal { get; set; }
public float GridOriginVertical { get; set; }
public int GridSpaceBetweenHorizontalLines { get; set; }
public int GridSpaceBetweenVerticalLines { get; set; }
public bool GridOriginFromMargin { get; set; }
public bool KerningByAlgorithm { get; set; }
public WdJustificationMode JustificationMode { get; set; }
public WdFarEastLineBreakLevel FarEastLineBreakLevel { get; set; }
public string NoLineBreakBefore { get; set; }
public string NoLineBreakAfter { get; set; }
public bool TrackRevisions { get; set; }
public bool PrintRevisions { get; set; }
public bool ShowRevisions { get; set; }
public string ActiveTheme { get; private set; }
public string ActiveThemeDisplayName { get; private set; }
public Email Email { get; private set; }
public Scripts Scripts { get; private set; }
public bool LanguageDetected { get; set; }
public WdFarEastLineBreakLanguageID FarEastLineBreakLanguage { get; set; }
public Frameset Frameset { get; private set; }
public object get_ClickAndTypeParagraphStyle()
{
throw new System.NotImplementedException();
}
public void set_ClickAndTypeParagraphStyle(ref object prop)
{
throw new System.NotImplementedException();
}
public HTMLProject HTMLProject { get; private set; }
public WebOptions WebOptions { get; private set; }
public MsoEncoding OpenEncoding { get; private set; }
public MsoEncoding SaveEncoding { get; set; }
public bool OptimizeForWord97 { get; set; }
public bool VBASigned { get; private set; }
public MsoEnvelope MailEnvelope { get; private set; }
public bool DisableFeatures { get; set; }
public bool DoNotEmbedSystemFonts { get; set; }
public SignatureSet Signatures { get; private set; }
public string DefaultTargetFrame { get; set; }
public HTMLDivisions HTMLDivisions { get; private set; }
public WdDisableFeaturesIntroducedAfter DisableFeaturesIntroducedAfter { get; set; }
public bool RemovePersonalInformation { get; set; }
public SmartTags SmartTags { get; private set; }
public bool EmbedSmartTags { get; set; }
public bool SmartTagsAsXMLProps { get; set; }
public MsoEncoding TextEncoding { get; set; }
public WdLineEndingType TextLineEnding { get; set; }
public StyleSheets StyleSheets { get; private set; }
public object DefaultTableStyle { get; private set; }
public string PasswordEncryptionProvider { get; private set; }
public string PasswordEncryptionAlgorithm { get; private set; }
public int PasswordEncryptionKeyLength { get; private set; }
public bool PasswordEncryptionFileProperties { get; private set; }
public bool EmbedLinguisticData { get; set; }
public bool FormattingShowFont { get; set; }
public bool FormattingShowClear { get; set; }
public bool FormattingShowParagraph { get; set; }
public bool FormattingShowNumbering { get; set; }
public WdShowFilter FormattingShowFilter { get; set; }
public Permission Permission { get; private set; }
public XMLNodes XMLNodes { get; private set; }
public XMLSchemaReferences XMLSchemaReferences { get; private set; }
public SmartDocument SmartDocument { get; private set; }
public SharedWorkspace SharedWorkspace { get; private set; }
Sync _Document.Sync
{
get { throw new System.NotImplementedException(); }
}
public bool EnforceStyle { get; set; }
public bool AutoFormatOverride { get; set; }
public bool XMLSaveDataOnly { get; set; }
public bool XMLHideNamespaces { get; set; }
public bool XMLShowAdvancedErrors { get; set; }
public bool XMLUseXSLTWhenSaving { get; set; }
public string XMLSaveThroughXSLT { get; set; }
public DocumentLibraryVersions DocumentLibraryVersions { get; private set; }
public bool ReadingModeLayoutFrozen { get; set; }
public bool RemoveDateAndTime { get; set; }
public XMLChildNodeSuggestions ChildNodeSuggestions { get; private set; }
public XMLNodes XMLSchemaViolations { get; private set; }
public int ReadingLayoutSizeX { get; set; }
public int ReadingLayoutSizeY { get; set; }
public WdStyleSort StyleSortMethod { get; set; }
public MetaProperties ContentTypeProperties { get; private set; }
public bool TrackMoves { get; set; }
public bool TrackFormatting { get; set; }
public OMaths OMaths { get; private set; }
public ServerPolicy ServerPolicy { get; private set; }
public ContentControls ContentControls { get; private set; }
public DocumentInspectors DocumentInspectors { get; private set; }
public Bibliography Bibliography { get; private set; }
public bool LockTheme { get; set; }
public bool LockQuickStyleSet { get; set; }
public string OriginalDocumentTitle { get; private set; }
public string RevisedDocumentTitle { get; private set; }
public CustomXMLParts CustomXMLParts { get; private set; }
public bool FormattingShowNextLevel { get; set; }
public bool FormattingShowUserStyleName { get; set; }
public Research Research { get; private set; }
public bool Final { get; set; }
public WdOMathBreakBin OMathBreakBin { get; set; }
public WdOMathBreakSub OMathBreakSub { get; set; }
public WdOMathJc OMathJc { get; set; }
public float OMathLeftMargin { get; set; }
public float OMathRightMargin { get; set; }
public float OMathWrap { get; set; }
public bool OMathIntSubSupLim { get; set; }
public bool OMathNarySupSubLim { get; set; }
public bool OMathSmallFrac { get; set; }
public string WordOpenXML { get; private set; }
public OfficeTheme DocumentTheme { get; private set; }
public bool HasVBProject { get; private set; }
public string OMathFontName { get; set; }
public string EncryptionProvider { get; set; }
public bool UseMathDefaults { get; set; }
public int CurrentRsid { get; private set; }
public int DocID { get; private set; }
public int CompatibilityMode { get; private set; }
public CoAuthoring CoAuthoring { get; private set; }
public Broadcast Broadcast { get; private set; }
public bool ChartDataPointTrack { get; set; }
public bool IsInAutosave { get; private set; }
public event DocumentEvents2_NewEventHandler New;
public event DocumentEvents2_OpenEventHandler Open;
public event DocumentEvents2_CloseEventHandler Close;
event DocumentEvents2_SyncEventHandler DocumentEvents2_Event.Sync
{
add { throw new System.NotImplementedException(); }
remove { throw new System.NotImplementedException(); }
}
public event DocumentEvents2_XMLAfterInsertEventHandler XMLAfterInsert;
public event DocumentEvents2_XMLBeforeDeleteEventHandler XMLBeforeDelete;
public event DocumentEvents2_ContentControlAfterAddEventHandler ContentControlAfterAdd;
public event DocumentEvents2_ContentControlBeforeDeleteEventHandler ContentControlBeforeDelete;
public event DocumentEvents2_ContentControlOnExitEventHandler ContentControlOnExit;
public event DocumentEvents2_ContentControlOnEnterEventHandler ContentControlOnEnter;
public event DocumentEvents2_ContentControlBeforeStoreUpdateEventHandler ContentControlBeforeStoreUpdate;
public event DocumentEvents2_ContentControlBeforeContentUpdateEventHandler ContentControlBeforeContentUpdate;
public event DocumentEvents2_BuildingBlockInsertEventHandler BuildingBlockInsert;
}
}
| |
////////////////////////////////////////////////////////////////////////////
//
// This file is part of RTIMULibCS
//
// Copyright (c) 2015, richards-tech, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Threading;
namespace RTIMULibCS.Devices.LSM9DS1
{
/// <summary>
/// The LSM9DS1 IMU-sensor.
/// </summary>
public class LSM9DS1ImuSensor : ImuSensor
{
private readonly byte _accelGyroI2CAddress;
private readonly byte _magI2CAddress;
private readonly LSM9DS1Config _config;
private II2C _accelGyroI2CDevice;
private II2C _magI2CDevice;
private double _gyroScale;
private double _accelerationScale;
private double _magneticFieldScale;
public LSM9DS1ImuSensor(
byte accelGyroI2CAddress,
byte magI2CAddress,
LSM9DS1Config config,
SensorFusion fusion)
: base(fusion)
{
_accelGyroI2CAddress = accelGyroI2CAddress;
_magI2CAddress = magI2CAddress;
_config = config;
SampleRate = 100;
}
protected override bool InitDevice()
{
ConnectToI2CDevices();
BootDevice();
VerifyDeviceAccelGyroId();
SetGyroSampleRate();
SetGyroCtrl3();
VerifyDeviceMagId();
SetAccelCtrl6();
SetAccelCtrl7();
SetMagCtrl1();
SetMagCtrl2();
SetMagCtrl3();
return true;
}
private void ConnectToI2CDevices()
{
try
{
_accelGyroI2CDevice = I2CDeviceFactory.Singleton.Create(_accelGyroI2CAddress);
_magI2CDevice = I2CDeviceFactory.Singleton.Create(_magI2CAddress);
}
catch (Exception exception)
{
throw new SensorException("Failed to connect to LSM9DS1", exception);
}
}
private void BootDevice()
{
I2CSupport.Write(_accelGyroI2CDevice, LSM9DS1Defines.CTRL8, 0x81, "Failed to boot LSM9DS1");
Thread.Sleep(100);
}
private void VerifyDeviceAccelGyroId()
{
byte id = I2CSupport.Read8Bits(_accelGyroI2CDevice, LSM9DS1Defines.WHO_AM_I, "Failed to read LSM9DS1 accel/gyro id");
if (id != LSM9DS1Defines.ID)
{
throw new SensorException($"Incorrect LSM9DS1 gyro id {id}");
}
}
private void VerifyDeviceMagId()
{
byte id = I2CSupport.Read8Bits(_magI2CDevice, LSM9DS1Defines.MAG_WHO_AM_I, "Failed to read LSM9DS1 mag id");
if (id != LSM9DS1Defines.MAG_ID)
{
throw new SensorException($"Incorrect LSM9DS1 mag id {id}");
}
}
private void SetGyroSampleRate()
{
byte ctrl1;
switch (_config.GyroSampleRate)
{
case GyroSampleRate.Freq14_9Hz:
ctrl1 = 0x20;
SampleRate = 15;
break;
case GyroSampleRate.Freq59_5Hz:
ctrl1 = 0x40;
SampleRate = 60;
break;
case GyroSampleRate.Freq119Hz:
ctrl1 = 0x60;
SampleRate = 119;
break;
case GyroSampleRate.Freq238Hz:
ctrl1 = 0x80;
SampleRate = 238;
break;
case GyroSampleRate.Freq476Hz:
ctrl1 = 0xa0;
SampleRate = 476;
break;
case GyroSampleRate.Freq952Hz:
ctrl1 = 0xc0;
SampleRate = 952;
break;
default:
throw new SensorException($"Illegal LSM9DS1 gyro sample rate code {_config.GyroSampleRate}");
}
SampleInterval = (long)1000000 / SampleRate;
switch (_config.GyroBandwidthCode)
{
case GyroBandwidthCode.BandwidthCode0:
ctrl1 |= 0x00;
break;
case GyroBandwidthCode.BandwidthCode1:
ctrl1 |= 0x01;
break;
case GyroBandwidthCode.BandwidthCode2:
ctrl1 |= 0x02;
break;
case GyroBandwidthCode.BandwidthCode3:
ctrl1 |= 0x03;
break;
default:
throw new SensorException($"Illegal LSM9DS1 gyro BW code {_config.GyroBandwidthCode}");
}
switch (_config.GyroFullScaleRange)
{
case GyroFullScaleRange.Range245:
ctrl1 |= 0x00;
_gyroScale = 0.00875 * MathSupport.DegreeToRad;
break;
case GyroFullScaleRange.Range500:
ctrl1 |= 0x08;
_gyroScale = 0.0175 * MathSupport.DegreeToRad;
break;
case GyroFullScaleRange.Range2000:
ctrl1 |= 0x18;
_gyroScale = 0.07 * MathSupport.DegreeToRad;
break;
default:
throw new SensorException($"Illegal LSM9DS1 gyro FSR code {_config.GyroFullScaleRange}");
}
I2CSupport.Write(_accelGyroI2CDevice, LSM9DS1Defines.CTRL1, ctrl1, "Failed to set LSM9DS1 gyro CTRL1");
}
private void SetGyroCtrl3()
{
int gyroHighPassFilterCodeValue = (int)_config.GyroHighPassFilterCode;
if ((gyroHighPassFilterCodeValue < 0) || (gyroHighPassFilterCodeValue > 9))
{
throw new SensorException($"Illegal LSM9DS1 gyro high pass filter code {_config.GyroHighPassFilterCode}");
}
byte ctrl3 = (byte)gyroHighPassFilterCodeValue;
// Turn on hpf
ctrl3 |= 0x40;
I2CSupport.Write(_accelGyroI2CDevice, LSM9DS1Defines.CTRL3, ctrl3, "Failed to set LSM9DS1 gyro CTRL3");
}
private void SetAccelCtrl6()
{
int accelSampleRateValue = (int)_config.AccelSampleRate;
if ((accelSampleRateValue < 1) || (accelSampleRateValue > 6))
{
throw new SensorException($"Illegal LSM9DS1 accel sample rate code {_config.AccelSampleRate}");
}
int accelLowPassFilterValue = (int)_config.AccelLowPassFilter;
if ((accelLowPassFilterValue < 0) || (accelLowPassFilterValue > 3))
{
throw new SensorException($"Illegal LSM9DS1 accel low pass fiter code {_config.AccelLowPassFilter}");
}
byte ctrl6 = (byte)(accelSampleRateValue << 5);
switch (_config.AccelFullScaleRange)
{
case AccelFullScaleRange.Range2g:
_accelerationScale = 0.000061;
break;
case AccelFullScaleRange.Range4g:
_accelerationScale = 0.000122;
break;
case AccelFullScaleRange.Range8g:
_accelerationScale = 0.000244;
break;
case AccelFullScaleRange.Range16g:
_accelerationScale = 0.000732;
break;
default:
throw new SensorException($"Illegal LSM9DS1 accel FSR code {_config.AccelFullScaleRange}");
}
ctrl6 |= (byte)((accelLowPassFilterValue) | (accelSampleRateValue << 3));
I2CSupport.Write(_accelGyroI2CDevice, LSM9DS1Defines.CTRL6, ctrl6, "Failed to set LSM9DS1 accel CTRL6");
}
private void SetAccelCtrl7()
{
byte ctrl7 = 0x00;
//Bug: Bad things happen.
//byte ctrl7 = 0x05;
I2CSupport.Write(_accelGyroI2CDevice, LSM9DS1Defines.CTRL7, ctrl7, "Failed to set LSM9DS1 accel CTRL7");
}
private void SetMagCtrl1()
{
int compassSampleRateValue = (int)_config.CompassSampleRate;
if ((compassSampleRateValue < 0) || (compassSampleRateValue > 7))
{
throw new SensorException($"Illegal LSM9DS1 compass sample rate code {_config.CompassSampleRate}");
}
byte ctrl1 = (byte)(compassSampleRateValue << 2);
I2CSupport.Write(_magI2CDevice, LSM9DS1Defines.MAG_CTRL1, ctrl1, "Failed to set LSM9DS1 compass CTRL5");
}
private void SetMagCtrl2()
{
byte ctrl2;
// convert FSR to uT
switch (_config.MagneticFullScaleRange)
{
case MagneticFullScaleRange.Range4Gauss:
ctrl2 = 0;
_magneticFieldScale = 0.014;
break;
case MagneticFullScaleRange.Range8Gauss:
ctrl2 = 0x20;
_magneticFieldScale = 0.029;
break;
case MagneticFullScaleRange.Range12Gauss:
ctrl2 = 0x40;
_magneticFieldScale = 0.043;
break;
case MagneticFullScaleRange.Range16Gauss:
ctrl2 = 0x60;
_magneticFieldScale = 0.058;
break;
default:
throw new SensorException($"Illegal LSM9DS1 compass FSR code {_config.MagneticFullScaleRange}");
}
I2CSupport.Write(_magI2CDevice, LSM9DS1Defines.MAG_CTRL2, ctrl2, "Failed to set LSM9DS1 compass CTRL6");
}
private void SetMagCtrl3()
{
I2CSupport.Write(_magI2CDevice, LSM9DS1Defines.MAG_CTRL3, 0x00, "Failed to set LSM9DS1 compass CTRL3");
}
public int GetPollInterval()
{
return (400 / SampleRate);
}
/// <summary>
/// Tries to update the readings.
/// Returns true if new readings are available, otherwise false.
/// An exception is thrown if something goes wrong.
/// </summary>
public override bool Update()
{
byte status = I2CSupport.Read8Bits(_accelGyroI2CDevice, LSM9DS1Defines.STATUS, "Failed to read LSM9DS1 status");
if ((status & 0x03) != 0x03)
{
// Data not yet available
return false;
}
byte[] gyroData = I2CSupport.ReadBytes(_accelGyroI2CDevice, 0x80 + LSM9DS1Defines.OUT_X_L_G, 6, "Failed to read LSM9DS1 gyro data");
byte[] accelData = I2CSupport.ReadBytes(_accelGyroI2CDevice, 0x80 + LSM9DS1Defines.OUT_X_L_XL, 6, "Failed to read LSM9DS1 accel data");
byte[] magData = I2CSupport.ReadBytes(_magI2CDevice, 0x80 + LSM9DS1Defines.MAG_OUT_X_L, 6, "Failed to read LSM9DS1 compass data");
var readings = new SensorReadings
{
Timestamp = DateTime.Now,
Gyro = MathSupport.ConvertToVector(gyroData, _gyroScale, ByteOrder.LittleEndian),
GyroValid = true,
Acceleration = MathSupport.ConvertToVector(accelData, _accelerationScale, ByteOrder.LittleEndian),
AccelerationValid = true,
MagneticField = MathSupport.ConvertToVector(magData, _magneticFieldScale, ByteOrder.LittleEndian),
MagneticFieldValid = true
};
// Sort out gyro axes and correct for bias
readings.Gyro.Z = -readings.Gyro.Z;
// Sort out accel data;
readings.Acceleration.X = -readings.Acceleration.X;
readings.Acceleration.Y = -readings.Acceleration.Y;
// Sort out mag axes
readings.MagneticField.X = -readings.MagneticField.X;
readings.MagneticField.Z = -readings.MagneticField.Z;
AssignNewReadings(readings);
return true;
}
}
}
| |
/*
Copyright (c) 2004-2009 Krzysztof Ostrowski. All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S)
AND ALL OTHER CONTRIBUTORS AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace QS.Fx.Base
{
[QS.Fx.Reflection.ValueClass(QS.Fx.Reflection.ValueClasses.UINT128)]
[QS.Fx.Printing.Printable(QS.Fx.Printing.PrintingStyle.Native)]
[QS.Fx.Serialization.ClassID(QS.ClassID.Fx_Base_Unsigned_128)]
[XmlType(TypeName = "UINT128")]
public sealed class UINT128 : QS.Fx.Serialization.ISerializable, IComparable<UINT128>, IComparable, IEquatable<UINT128>, QS.Fx.Serialization.IStringSerializable
{
#region Constructor
public UINT128(ulong u1, ulong u2)
{
this.u1 = u1;
this.u2 = u2;
}
public UINT128(string s)
{
this.String = s;
}
public unsafe UINT128(Guid guid)
{
ulong u1, u2;
fixed (byte* pguid = guid.ToByteArray())
{
byte* pu1 = (byte*)(&u1);
byte* pu2 = (byte*)(&u2);
pu1[0] = pguid[6];
pu1[1] = pguid[7];
pu1[2] = pguid[4];
pu1[3] = pguid[5];
pu1[4] = pguid[0];
pu1[5] = pguid[1];
pu1[6] = pguid[2];
pu1[7] = pguid[3];
pu2[0] = pguid[15];
pu2[1] = pguid[14];
pu2[2] = pguid[13];
pu2[3] = pguid[12];
pu2[4] = pguid[11];
pu2[5] = pguid[10];
pu2[6] = pguid[9];
pu2[7] = pguid[8];
}
this.u1 = u1;
this.u2 = u2;
}
public UINT128()
{
}
#endregion
#region Fields
private ulong u1, u2;
#endregion
#region Accessors
[XmlAttribute("value")]
public string String
{
get
{
return (u1 != 0UL) ? (u1.ToString("x") + u2.ToString("x16")) : u2.ToString("x");
}
set
{
if (value.Length > 16)
{
int i = value.Length - 16;
this.u1 = Convert.ToUInt64(value.Substring(0, i));
this.u2 = Convert.ToUInt64(value.Substring(i));
}
else
{
this.u1 = 0UL;
this.u2 = Convert.ToUInt64(value);
}
}
}
#endregion
#region Casting
public static explicit operator UINT128(string number)
{
return new UINT128(number);
}
public static explicit operator string(UINT128 number)
{
return number.String;
}
#endregion
#region ISerializable Members
public unsafe QS.Fx.Serialization.SerializableInfo SerializableInfo
{
get { return new QS.Fx.Serialization.SerializableInfo((ushort) QS.ClassID.Fx_Base_Unsigned_128, 2 * sizeof(ulong)); }
}
public unsafe void SerializeTo(ref QS.Fx.Base.ConsumableBlock header, ref IList<QS.Fx.Base.Block> data)
{
fixed (byte* parray = header.Array)
{
byte* pheader = parray + header.Offset;
*((ulong*)pheader) = u1;
*((ulong*)(pheader + sizeof(ulong))) = u2;
}
header.consume(2 * sizeof(ulong));
}
public unsafe void DeserializeFrom(ref QS.Fx.Base.ConsumableBlock header, ref QS.Fx.Base.ConsumableBlock data)
{
fixed (byte* parray = header.Array)
{
byte* pheader = parray + header.Offset;
u1 = *((ulong*)pheader);
u2 = *((ulong*)(pheader + sizeof(ulong)));
}
header.consume(2 * sizeof(ulong));
}
#endregion
#region Overridden from System.Object
public override string ToString()
{
return this.String;
}
public override int GetHashCode()
{
return u1.GetHashCode() ^ u2.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj is UINT128)
{
UINT128 other = (UINT128) obj;
return u1.Equals(other.u1) && u2.Equals(other.u2);
}
else
return false;
}
#endregion
#region IComparable<Unsigned_128> Members
public int CompareTo(UINT128 other)
{
int comparison_result = u1.CompareTo(other.u1);
return (comparison_result != 0) ? comparison_result : u2.CompareTo(other.u2);
}
#endregion
#region IEquatable<Unsigned_128> Members
public bool Equals(UINT128 other)
{
return u1.Equals(other.u1) && u2.Equals(other.u2);
}
#endregion
#region IComparable Members
int IComparable.CompareTo(object obj)
{
if (obj is UINT128)
{
UINT128 other = (UINT128) obj;
int comparison_result = u1.CompareTo(other.u1);
return (comparison_result != 0) ? comparison_result : u2.CompareTo(other.u2);
}
else
throw new Exception("Cannot compare to something that is not Unsigned_128");
}
#endregion
#region IStringSerializable Members
ushort QS.Fx.Serialization.IStringSerializable.ClassID
{
get { return (ushort) QS.ClassID.Fx_Base_Unsigned_128; }
}
string QS.Fx.Serialization.IStringSerializable.AsString
{
get { return this.String; }
set { this.String = value; }
}
#endregion
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.IO;
using System.Globalization;
using Newtonsoft.Json.Utilities;
#if !JSONNET_XMLDISABLE || UNITY_EDITOR
using System.Xml;
#endif
using Newtonsoft.Json.Converters;
using System.Text;
namespace Newtonsoft.Json
{
/// <summary>
/// Provides methods for converting between common language runtime types and JSON types.
/// </summary>
public static class JsonConvert
{
/// <summary>
/// Represents JavaScript's boolean value true as a string. This field is read-only.
/// </summary>
public static readonly string True = "true";
/// <summary>
/// Represents JavaScript's boolean value false as a string. This field is read-only.
/// </summary>
public static readonly string False = "false";
/// <summary>
/// Represents JavaScript's null as a string. This field is read-only.
/// </summary>
public static readonly string Null = "null";
/// <summary>
/// Represents JavaScript's undefined as a string. This field is read-only.
/// </summary>
public static readonly string Undefined = "undefined";
/// <summary>
/// Represents JavaScript's positive infinity as a string. This field is read-only.
/// </summary>
public static readonly string PositiveInfinity = "Infinity";
/// <summary>
/// Represents JavaScript's negative infinity as a string. This field is read-only.
/// </summary>
public static readonly string NegativeInfinity = "-Infinity";
/// <summary>
/// Represents JavaScript's NaN as a string. This field is read-only.
/// </summary>
public static readonly string NaN = "NaN";
internal static readonly long InitialJavaScriptDateTicks = 621355968000000000;
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
WriteDateTimeString(writer, value, GetUtcOffset(value), value.Kind);
return writer.ToString();
}
}
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
WriteDateTimeString(writer, value.UtcDateTime, value.Offset, DateTimeKind.Local);
return writer.ToString();
}
}
private static TimeSpan GetUtcOffset(DateTime dateTime)
{
#if((UNITY_WP8 || UNITY_WP_8_1) && !UNITY_EDITOR)
return TimeZoneInfo.Local.GetUtcOffset(dateTime);
#else
return TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
#endif
}
internal static void WriteDateTimeString(TextWriter writer, DateTime value)
{
WriteDateTimeString(writer, value, GetUtcOffset(value), value.Kind);
}
internal static void WriteDateTimeString(TextWriter writer, DateTime value, TimeSpan offset, DateTimeKind kind)
{
long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value, offset);
writer.Write(@"""\/Date(");
writer.Write(javaScriptTicks);
switch (kind)
{
case DateTimeKind.Local:
case DateTimeKind.Unspecified:
writer.Write((offset.Ticks >= 0L) ? "+" : "-");
int absHours = Math.Abs(offset.Hours);
if (absHours < 10)
writer.Write(0);
writer.Write(absHours);
int absMinutes = Math.Abs(offset.Minutes);
if (absMinutes < 10)
writer.Write(0);
writer.Write(absMinutes);
break;
}
writer.Write(@")\/""");
}
private static long ToUniversalTicks(DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Utc)
return dateTime.Ticks;
return ToUniversalTicks(dateTime, GetUtcOffset(dateTime));
}
private static long ToUniversalTicks(DateTime dateTime, TimeSpan offset)
{
if (dateTime.Kind == DateTimeKind.Utc)
return dateTime.Ticks;
long ticks = dateTime.Ticks - offset.Ticks;
if (ticks > 3155378975999999999L)
return 3155378975999999999L;
if (ticks < 0L)
return 0L;
return ticks;
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, TimeSpan offset)
{
long universialTicks = ToUniversalTicks(dateTime, offset);
return UniversialTicksToJavaScriptTicks(universialTicks);
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime)
{
return ConvertDateTimeToJavaScriptTicks(dateTime, true);
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, bool convertToUtc)
{
long ticks = (convertToUtc) ? ToUniversalTicks(dateTime) : dateTime.Ticks;
return UniversialTicksToJavaScriptTicks(ticks);
}
private static long UniversialTicksToJavaScriptTicks(long universialTicks)
{
long javaScriptTicks = (universialTicks - InitialJavaScriptDateTicks) / 10000;
return javaScriptTicks;
}
internal static DateTime ConvertJavaScriptTicksToDateTime(long javaScriptTicks)
{
DateTime dateTime = new DateTime((javaScriptTicks * 10000) + InitialJavaScriptDateTicks, DateTimeKind.Utc);
return dateTime;
}
/// <summary>
/// Converts the <see cref="Boolean"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Boolean"/>.</returns>
public static string ToString(bool value)
{
return (value) ? True : False;
}
/// <summary>
/// Converts the <see cref="Char"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Char"/>.</returns>
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
/// <summary>
/// Converts the <see cref="Enum"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString("D");
}
/// <summary>
/// Converts the <see cref="Int32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int32"/>.</returns>
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int16"/>.</returns>
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt16"/>.</returns>
//
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt32"/>.</returns>
//
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int64"/>.</returns>
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt64"/>.</returns>
//
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Single"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Single"/>.</returns>
public static string ToString(float value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Double"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
private static string EnsureDecimalPlace(double value, string text)
{
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1)
return text;
return text + ".0";
}
private static string EnsureDecimalPlace(string text)
{
if (text.IndexOf('.') != -1)
return text;
return text + ".0";
}
/// <summary>
/// Converts the <see cref="Byte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Byte"/>.</returns>
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="SByte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
//
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Decimal"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
public static string ToString(decimal value)
{
return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Guid"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
public static string ToString(Guid value)
{
return '"' + value.ToString("D", CultureInfo.InvariantCulture) + '"';
}
/// <summary>
/// Converts the <see cref="TimeSpan"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="TimeSpan"/>.</returns>
public static string ToString(TimeSpan value)
{
return '"' + value.ToString() + '"';
}
/// <summary>
/// Converts the <see cref="Uri"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Uri"/>.</returns>
public static string ToString(Uri value)
{
return '"' + value.ToString() + '"';
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value)
{
return ToString(value, '"');
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimter">The string delimiter character.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimter)
{
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimter, true);
}
/// <summary>
/// Converts the <see cref="Object"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Object"/>.</returns>
public static string ToString(object value)
{
if (value == null)
return Null;
IConvertible convertible = value as IConvertible;
if (convertible != null)
{
switch (convertible.GetTypeCode())
{
case TypeCode.String:
return ToString(convertible.ToString(CultureInfo.InvariantCulture));
case TypeCode.Char:
return ToString(convertible.ToChar(CultureInfo.InvariantCulture));
case TypeCode.Boolean:
return ToString(convertible.ToBoolean(CultureInfo.InvariantCulture));
case TypeCode.SByte:
return ToString(convertible.ToSByte(CultureInfo.InvariantCulture));
case TypeCode.Int16:
return ToString(convertible.ToInt16(CultureInfo.InvariantCulture));
case TypeCode.UInt16:
return ToString(convertible.ToUInt16(CultureInfo.InvariantCulture));
case TypeCode.Int32:
return ToString(convertible.ToInt32(CultureInfo.InvariantCulture));
case TypeCode.Byte:
return ToString(convertible.ToByte(CultureInfo.InvariantCulture));
case TypeCode.UInt32:
return ToString(convertible.ToUInt32(CultureInfo.InvariantCulture));
case TypeCode.Int64:
return ToString(convertible.ToInt64(CultureInfo.InvariantCulture));
case TypeCode.UInt64:
return ToString(convertible.ToUInt64(CultureInfo.InvariantCulture));
case TypeCode.Single:
return ToString(convertible.ToSingle(CultureInfo.InvariantCulture));
case TypeCode.Double:
return ToString(convertible.ToDouble(CultureInfo.InvariantCulture));
case TypeCode.DateTime:
return ToString(convertible.ToDateTime(CultureInfo.InvariantCulture));
case TypeCode.Decimal:
return ToString(convertible.ToDecimal(CultureInfo.InvariantCulture));
case TypeCode.DBNull:
return Null;
}
}
else if (value is DateTimeOffset)
{
return ToString((DateTimeOffset)value);
}
else if (value is Guid)
{
return ToString((Guid) value);
}
else if (value is Uri)
{
return ToString((Uri) value);
}
else if (value is TimeSpan)
{
return ToString((TimeSpan) value);
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
private static bool IsJsonPrimitiveTypeCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.String:
case TypeCode.Char:
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.Byte:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.DateTime:
case TypeCode.Decimal:
case TypeCode.DBNull:
return true;
default:
return false;
}
}
internal static bool IsJsonPrimitiveType(Type type)
{
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
if (type == typeof(DateTimeOffset))
return true;
if (type == typeof(byte[]))
return true;
if (type == typeof(Uri))
return true;
if (type == typeof(TimeSpan))
return true;
if (type == typeof(Guid))
return true;
return IsJsonPrimitiveTypeCode(Type.GetTypeCode(type));
}
internal static bool IsJsonPrimitive(object value)
{
if (value == null)
return true;
IConvertible convertible = value as IConvertible;
if (convertible != null)
return IsJsonPrimitiveTypeCode(convertible.GetTypeCode());
if (value is DateTimeOffset)
return true;
if (value is byte[])
return true;
if (value is Uri)
return true;
if (value is TimeSpan)
return true;
if (value is Guid)
return true;
return false;
}
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value)
{
return SerializeObject(value, Formatting.None, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings)null);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, params JsonConverter[] converters)
{
return SerializeObject(value, Formatting.None, converters);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return SerializeObject(value, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
StringBuilder sb = new StringBuilder(128);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = formatting;
jsonSerializer.Serialize(jsonWriter, value);
}
return sw.ToString();
}
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, JsonSerializerSettings settings)
{
return DeserializeObject(value, null, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, (JsonSerializerSettings)null);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be infered from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
{
return DeserializeObject<T>(value);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
{
return (T)DeserializeObject(value, typeof(T), converters);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
{
return (T)DeserializeObject(value, typeof(T), settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings { Converters = converters }
: null;
return DeserializeObject(value, type, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
{
StringReader sr = new StringReader(value);
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
object deserializedValue;
using (JsonReader jsonReader = new JsonTextReader(sr))
{
deserializedValue = jsonSerializer.Deserialize(jsonReader, type);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
}
return deserializedValue;
}
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public static void PopulateObject(string value, object target)
{
PopulateObject(value, target, null);
}
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
{
var sr = new StringReader(value);
var jsonSerializer = JsonSerializer.Create(settings);
using (JsonReader jsonReader = new JsonTextReader(sr))
{
jsonSerializer.Populate(jsonReader, target);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
}
}
#if !(JSONNET_XMLDISABLE || (UNITY_WP8 || UNITY_WP_8_1) || UNITY_WINRT) || UNITY_EDITOR
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node)
{
return SerializeXmlNode(node, Formatting.None);
}
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting)
{
XmlNodeConverter converter = new XmlNodeConverter();
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject)
{
var converter = new XmlNodeConverter { OmitRootObject = omitRootObject };
return SerializeObject(node, formatting, converter);
}
#if !(UNITY_WP8 || UNITY_WP_8_1) || UNITY_EDITOR
/// <summary>
/// Deserializes the XmlNode from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value)
{
return DeserializeXmlNode(value, null);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName)
{
return DeserializeXmlNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
var converter = new XmlNodeConverter
{
DeserializeRootElementName = deserializeRootElementName,
WriteArrayAttribute = writeArrayAttribute
};
return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), converter);
}
#endif
#endif
}
}
#endif
| |
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using Android.App;
using Android.Content;
using Android.Util;
using Android.Views;
using Android.Widget;
using AView = Android.Views.View;
using AListView = Android.Widget.ListView;
namespace Xamarin.Forms.Platform.Android
{
public abstract class CellAdapter : BaseAdapter<object>, AdapterView.IOnItemLongClickListener, ActionMode.ICallback, AdapterView.IOnItemClickListener,
global::Android.Support.V7.View.ActionMode.ICallback
{
readonly Context _context;
ActionMode _actionMode;
Cell _actionModeContext;
bool _actionModeNeedsUpdates;
AView _contextView;
global::Android.Support.V7.View.ActionMode _supportActionMode;
protected CellAdapter(Context context)
{
if (context == null)
throw new ArgumentNullException("context");
_context = context;
}
internal Cell ActionModeContext
{
get { return _actionModeContext; }
set
{
if (_actionModeContext == value)
return;
if (_actionModeContext != null)
((INotifyCollectionChanged)_actionModeContext.ContextActions).CollectionChanged -= OnContextItemsChanged;
ActionModeObject = null;
_actionModeContext = value;
if (_actionModeContext != null)
{
((INotifyCollectionChanged)_actionModeContext.ContextActions).CollectionChanged += OnContextItemsChanged;
ActionModeObject = _actionModeContext.BindingContext;
}
}
}
internal object ActionModeObject { get; set; }
internal AView ContextView
{
get { return _contextView; }
set
{
if (_contextView == value)
return;
if (_contextView != null)
{
var isSelected = (bool)ActionModeContext.GetValue(ListViewAdapter.IsSelectedProperty);
if (isSelected)
SetSelectedBackground(_contextView);
else
UnsetSelectedBackground(_contextView);
}
_contextView = value;
if (_contextView != null)
SetSelectedBackground(_contextView, true);
}
}
public bool OnActionItemClicked(ActionMode mode, IMenuItem item)
{
OnActionItemClickedImpl(item);
if (mode != null && mode.Handle != IntPtr.Zero)
mode.Finish();
return true;
}
bool global::Android.Support.V7.View.ActionMode.ICallback.OnActionItemClicked(global::Android.Support.V7.View.ActionMode mode, IMenuItem item)
{
OnActionItemClickedImpl(item);
mode.Finish();
return true;
}
public bool OnCreateActionMode(ActionMode mode, IMenu menu)
{
CreateContextMenu(menu);
return true;
}
bool global::Android.Support.V7.View.ActionMode.ICallback.OnCreateActionMode(global::Android.Support.V7.View.ActionMode mode, IMenu menu)
{
CreateContextMenu(menu);
return true;
}
public void OnDestroyActionMode(ActionMode mode)
{
OnDestroyActionModeImpl();
_actionMode.Dispose();
_actionMode = null;
}
void global::Android.Support.V7.View.ActionMode.ICallback.OnDestroyActionMode(global::Android.Support.V7.View.ActionMode mode)
{
OnDestroyActionModeImpl();
_supportActionMode.Dispose();
_supportActionMode = null;
}
public bool OnPrepareActionMode(ActionMode mode, IMenu menu)
{
return OnPrepareActionModeImpl(menu);
}
bool global::Android.Support.V7.View.ActionMode.ICallback.OnPrepareActionMode(global::Android.Support.V7.View.ActionMode mode, IMenu menu)
{
return OnPrepareActionModeImpl(menu);
}
public void OnItemClick(AdapterView parent, AView view, int position, long id)
{
if (_actionMode != null || _supportActionMode != null)
{
var listView = parent as AListView;
if (listView != null)
position -= listView.HeaderViewsCount;
HandleContextMode(view, position);
}
else
HandleItemClick(parent, view, position, id);
}
public bool OnItemLongClick(AdapterView parent, AView view, int position, long id)
{
var listView = parent as AListView;
if (listView != null)
position -= listView.HeaderViewsCount;
return HandleContextMode(view, position);
}
protected abstract Cell GetCellForPosition(int position);
protected virtual void HandleItemClick(AdapterView parent, AView view, int position, long id)
{
}
protected void SetSelectedBackground(AView view, bool isContextTarget = false)
{
int attribute = isContextTarget ? global::Android.Resource.Attribute.ColorLongPressedHighlight : global::Android.Resource.Attribute.ColorActivatedHighlight;
using (var value = new TypedValue())
{
if (_context.Theme.ResolveAttribute(attribute, value, true))
view.SetBackgroundResource(value.ResourceId);
else
view.SetBackgroundResource(global::Android.Resource.Color.HoloBlueDark);
}
}
protected void UnsetSelectedBackground(AView view)
{
view.SetBackgroundResource(0);
}
internal void CloseContextAction()
{
if (_actionMode != null)
_actionMode.Finish();
if (_supportActionMode != null)
_supportActionMode.Finish();
}
void CreateContextMenu(IMenu menu)
{
var changed = new PropertyChangedEventHandler(OnContextActionPropertyChanged);
var changing = new PropertyChangingEventHandler(OnContextActionPropertyChanging);
var commandChanged = new EventHandler(OnContextActionCommandCanExecuteChanged);
for (var i = 0; i < ActionModeContext.ContextActions.Count; i++)
{
MenuItem action = ActionModeContext.ContextActions[i];
IMenuItem item = menu.Add(Menu.None, i, Menu.None, action.Text);
if (action.Icon != null)
item.SetIcon(_context.Resources.GetDrawable(action.Icon));
action.PropertyChanged += changed;
action.PropertyChanging += changing;
if (action.Command != null)
action.Command.CanExecuteChanged += commandChanged;
if (!action.IsEnabled)
item.SetEnabled(false);
}
}
bool HandleContextMode(AView view, int position)
{
Cell cell = GetCellForPosition(position);
if (_actionMode != null || _supportActionMode != null)
{
if (!cell.HasContextActions)
{
_actionMode?.Finish();
_supportActionMode?.Finish();
return false;
}
ActionModeContext = cell;
_actionMode?.Invalidate();
_supportActionMode?.Invalidate();
}
else
{
if (!cell.HasContextActions)
return false;
ActionModeContext = cell;
var appCompatActivity = Forms.Context as FormsAppCompatActivity;
if (appCompatActivity == null)
_actionMode = ((Activity)Forms.Context).StartActionMode(this);
else
_supportActionMode = appCompatActivity.StartSupportActionMode(this);
}
ContextView = view;
return true;
}
void OnActionItemClickedImpl(IMenuItem item)
{
int index = item.ItemId;
MenuItem action = ActionModeContext.ContextActions[index];
action.Activate();
}
void OnContextActionCommandCanExecuteChanged(object sender, EventArgs eventArgs)
{
_actionModeNeedsUpdates = true;
_actionMode.Invalidate();
}
void OnContextActionPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var action = (MenuItem)sender;
if (e.PropertyName == MenuItem.CommandProperty.PropertyName)
{
if (action.Command != null)
action.Command.CanExecuteChanged += OnContextActionCommandCanExecuteChanged;
}
else
_actionModeNeedsUpdates = true;
}
void OnContextActionPropertyChanging(object sender, PropertyChangingEventArgs e)
{
var action = (MenuItem)sender;
if (e.PropertyName == MenuItem.CommandProperty.PropertyName)
{
if (action.Command != null)
action.Command.CanExecuteChanged -= OnContextActionCommandCanExecuteChanged;
}
}
void OnContextItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
_actionModeNeedsUpdates = true;
_actionMode.Invalidate();
}
void OnDestroyActionModeImpl()
{
var changed = new PropertyChangedEventHandler(OnContextActionPropertyChanged);
var changing = new PropertyChangingEventHandler(OnContextActionPropertyChanging);
var commandChanged = new EventHandler(OnContextActionCommandCanExecuteChanged);
((INotifyCollectionChanged)ActionModeContext.ContextActions).CollectionChanged -= OnContextItemsChanged;
for (var i = 0; i < ActionModeContext.ContextActions.Count; i++)
{
MenuItem action = ActionModeContext.ContextActions[i];
action.PropertyChanged -= changed;
action.PropertyChanging -= changing;
if (action.Command != null)
action.Command.CanExecuteChanged -= commandChanged;
}
ContextView = null;
ActionModeContext = null;
_actionModeNeedsUpdates = false;
}
bool OnPrepareActionModeImpl(IMenu menu)
{
if (_actionModeNeedsUpdates)
{
_actionModeNeedsUpdates = false;
menu.Clear();
CreateContextMenu(menu);
}
return false;
}
}
}
| |
// 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.Net.Test.Common;
using System.Threading;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public class DnsEndPointTest : DualModeBase
{
private void OnConnectAsyncCompleted(object sender, SocketAsyncEventArgs args)
{
ManualResetEvent complete = (ManualResetEvent)args.UserToken;
complete.Set();
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void Socket_ConnectDnsEndPoint_Success(SocketImplementationType type)
{
int port;
using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port))
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new DnsEndPoint("localhost", port));
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void Socket_ConnectDnsEndPoint_SetSocketProperties_Success(SocketImplementationType type)
{
int port;
using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port))
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
sock.LingerState = new LingerOption(false, 0);
sock.NoDelay = true;
sock.ReceiveBufferSize = 1024;
sock.ReceiveTimeout = 100;
sock.SendBufferSize = 1024;
sock.SendTimeout = 100;
sock.Connect(new DnsEndPoint("localhost", port));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_ConnectDnsEndPoint_Failure()
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
SocketException ex = Assert.ThrowsAny<SocketException>(() =>
{
sock.Connect(new DnsEndPoint("notahostname.invalid.corp.microsoft.com", UnusedPort));
});
SocketError errorCode = ex.SocketErrorCode;
Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData),
$"SocketErrorCode: {errorCode}");
ex = Assert.ThrowsAny<SocketException>(() =>
{
sock.Connect(new DnsEndPoint("localhost", UnusedPort));
});
Assert.Equal(SocketError.ConnectionRefused, ex.SocketErrorCode);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_SendToDnsEndPoint_ArgumentException()
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
Assert.Throws<ArgumentException>(() =>
{
sock.SendTo(new byte[10], new DnsEndPoint("localhost", UnusedPort));
});
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_ReceiveFromDnsEndPoint_ArgumentException()
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
int port = sock.BindToAnonymousPort(IPAddress.Loopback);
EndPoint endpoint = new DnsEndPoint("localhost", port);
Assert.Throws<ArgumentException>(() =>
{
sock.ReceiveFrom(new byte[10], ref endpoint);
});
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void Socket_BeginConnectDnsEndPoint_Success(SocketImplementationType type)
{
int port;
using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port))
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
IAsyncResult result = sock.BeginConnect(new DnsEndPoint("localhost", port), null, null);
sock.EndConnect(result);
Assert.Throws<InvalidOperationException>(() => sock.EndConnect(result)); // validate can't call end twice
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void Socket_BeginConnectDnsEndPoint_SetSocketProperties_Success(SocketImplementationType type)
{
int port;
using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port))
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
sock.LingerState = new LingerOption(false, 0);
sock.NoDelay = true;
sock.ReceiveBufferSize = 1024;
sock.ReceiveTimeout = 100;
sock.SendBufferSize = 1024;
sock.SendTimeout = 100;
IAsyncResult result = sock.BeginConnect(new DnsEndPoint("localhost", port), null, null);
sock.EndConnect(result);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_BeginConnectDnsEndPoint_Failure()
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
SocketException ex = Assert.ThrowsAny<SocketException>(() =>
{
IAsyncResult result = sock.BeginConnect(new DnsEndPoint("notahostname.invalid.corp.microsoft.com", UnusedPort), null, null);
sock.EndConnect(result);
});
SocketError errorCode = ex.SocketErrorCode;
Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData),
"SocketErrorCode: {0}" + errorCode);
ex = Assert.ThrowsAny<SocketException>(() =>
{
IAsyncResult result = sock.BeginConnect(new DnsEndPoint("localhost", UnusedPort), null, null);
sock.EndConnect(result);
});
Assert.Equal(SocketError.ConnectionRefused, ex.SocketErrorCode);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_BeginSendToDnsEndPoint_ArgumentException()
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
Assert.Throws<ArgumentException>(() =>
{
sock.BeginSendTo(new byte[10], 0, 0, SocketFlags.None, new DnsEndPoint("localhost", UnusedPort), null, null);
});
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[Trait("IPv4", "true")]
public void Socket_ConnectAsyncDnsEndPoint_Success(SocketImplementationType type)
{
Assert.True(Capability.IPv4Support());
int port;
using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port))
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (ManualResetEvent complete = new ManualResetEvent(false))
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("localhost", port);
args.Completed += OnConnectAsyncCompleted;
args.UserToken = complete;
bool willRaiseEvent = sock.ConnectAsync(args);
if (willRaiseEvent)
{
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Null(args.ConnectByNameError);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[Trait("IPv4", "true")]
public void Socket_ConnectAsyncDnsEndPoint_SetSocketProperties_Success(SocketImplementationType type)
{
Assert.True(Capability.IPv4Support());
int port;
using (SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port))
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (ManualResetEvent complete = new ManualResetEvent(false))
{
sock.LingerState = new LingerOption(false, 0);
sock.NoDelay = true;
sock.ReceiveBufferSize = 1024;
sock.ReceiveTimeout = 100;
sock.SendBufferSize = 1024;
sock.SendTimeout = 100;
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("localhost", port);
args.Completed += OnConnectAsyncCompleted;
args.UserToken = complete;
bool willRaiseEvent = sock.ConnectAsync(args);
if (willRaiseEvent)
{
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Null(args.ConnectByNameError);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[Trait("IPv4", "true")]
public void Socket_ConnectAsyncDnsEndPoint_HostNotFound()
{
Assert.True(Capability.IPv4Support());
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("notahostname.invalid.corp.microsoft.com", UnusedPort);
args.Completed += OnConnectAsyncCompleted;
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (ManualResetEvent complete = new ManualResetEvent(false))
{
args.UserToken = complete;
bool willRaiseEvent = sock.ConnectAsync(args);
if (willRaiseEvent)
{
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
}
AssertHostNotFoundOrNoData(args);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[Trait("IPv4", "true")]
public void Socket_ConnectAsyncDnsEndPoint_ConnectionRefused()
{
Assert.True(Capability.IPv4Support());
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("localhost", UnusedPort);
args.Completed += OnConnectAsyncCompleted;
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (ManualResetEvent complete = new ManualResetEvent(false))
{
args.UserToken = complete;
bool willRaiseEvent = sock.ConnectAsync(args);
if (willRaiseEvent)
{
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
}
Assert.Equal(SocketError.ConnectionRefused, args.SocketError);
Assert.True(args.ConnectByNameError is SocketException);
Assert.Equal(SocketError.ConnectionRefused, ((SocketException)args.ConnectByNameError).SocketErrorCode);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(LocalhostIsBothIPv4AndIPv6))]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[Trait("IPv4", "true")]
[Trait("IPv6", "true")]
public void Socket_StaticConnectAsync_Success(SocketImplementationType type)
{
Assert.True(Capability.IPv4Support() && Capability.IPv6Support());
int port4, port6;
using (SocketTestServer server4 = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port4))
using (SocketTestServer server6 = SocketTestServer.SocketTestServerFactory(type, IPAddress.IPv6Loopback, out port6))
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("localhost", port4);
args.Completed += OnConnectAsyncCompleted;
ManualResetEvent complete = new ManualResetEvent(false);
args.UserToken = complete;
Assert.True(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args));
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Null(args.ConnectByNameError);
Assert.NotNull(args.ConnectSocket);
Assert.True(args.ConnectSocket.AddressFamily == AddressFamily.InterNetwork);
Assert.True(args.ConnectSocket.Connected);
args.ConnectSocket.Dispose();
args.RemoteEndPoint = new DnsEndPoint("localhost", port6);
complete.Reset();
Assert.True(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args));
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Null(args.ConnectByNameError);
Assert.NotNull(args.ConnectSocket);
Assert.True(args.ConnectSocket.AddressFamily == AddressFamily.InterNetworkV6);
Assert.True(args.ConnectSocket.Connected);
args.ConnectSocket.Dispose();
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_StaticConnectAsync_HostNotFound()
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("notahostname.invalid.corp.microsoft.com", UnusedPort);
args.Completed += OnConnectAsyncCompleted;
ManualResetEvent complete = new ManualResetEvent(false);
args.UserToken = complete;
bool willRaiseEvent = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args);
if (!willRaiseEvent)
{
OnConnectAsyncCompleted(null, args);
}
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
AssertHostNotFoundOrNoData(args);
Assert.Null(args.ConnectSocket);
complete.Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Socket_StaticConnectAsync_ConnectionRefused()
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("localhost", UnusedPort);
args.Completed += OnConnectAsyncCompleted;
ManualResetEvent complete = new ManualResetEvent(false);
args.UserToken = complete;
bool willRaiseEvent = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args);
if (!willRaiseEvent)
{
OnConnectAsyncCompleted(null, args);
}
Assert.True(complete.WaitOne(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
Assert.Equal(SocketError.ConnectionRefused, args.SocketError);
Assert.True(args.ConnectByNameError is SocketException);
Assert.Equal(SocketError.ConnectionRefused, ((SocketException)args.ConnectByNameError).SocketErrorCode);
Assert.Null(args.ConnectSocket);
complete.Dispose();
}
public void CallbackThatShouldNotBeCalled(object sender, SocketAsyncEventArgs args)
{
throw new ShouldNotBeInvokedException();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[Trait("IPv6", "true")]
public void Socket_StaticConnectAsync_SyncFailure()
{
Assert.True(Capability.IPv6Support()); // IPv6 required because we use AF.InterNetworkV6
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = new DnsEndPoint("127.0.0.1", UnusedPort, AddressFamily.InterNetworkV6);
args.Completed += CallbackThatShouldNotBeCalled;
Assert.False(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args));
Assert.Equal(SocketError.NoData, args.SocketError);
Assert.Null(args.ConnectSocket);
}
private static void AssertHostNotFoundOrNoData(SocketAsyncEventArgs args)
{
SocketError errorCode = args.SocketError;
Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData),
"SocketError: " + errorCode);
Assert.True(args.ConnectByNameError is SocketException);
errorCode = ((SocketException)args.ConnectByNameError).SocketErrorCode;
Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData),
"SocketError: " + errorCode);
}
}
}
| |
// Copyright (C) 2002 The Npgsql Development Team
// [email protected]
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//
// Connector.cs
// ------------------------------------------------------------------
// Project
// Npgsql
// Status
// 0.00.0000 - 06/17/2002 - ulrich sprick - created
// - 06/??/2004 - Glen Parker<[email protected]> rewritten
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using Mono.Security.Protocol.Tls;
using Revenj.DatabasePersistence.Postgres.NpgsqlTypes;
namespace Revenj.DatabasePersistence.Postgres.Npgsql
{
/// <summary>
/// Represents the method that allows the application to provide a certificate collection to be used for SSL clien authentication
/// </summary>
/// <param name="certificates">A <see cref="System.Security.Cryptography.X509Certificates.X509CertificateCollection">X509CertificateCollection</see> to be filled with one or more client certificates.</param>
public delegate void ProvideClientCertificatesCallback(X509CertificateCollection certificates);
/// <summary>
/// !!! Helper class, for compilation only.
/// Connector implements the logic for the Connection Objects to
/// access the physical connection to the database, and isolate
/// the application developer from connection pooling internals.
/// </summary>
internal class NpgsqlConnector
{
// Immutable.
private readonly NpgsqlConnectionStringBuilder settings;
/// <summary>
/// Occurs on NoticeResponses from the PostgreSQL backend.
/// </summary>
internal event NoticeEventHandler Notice;
/// <summary>
/// Occurs on NotificationResponses from the PostgreSQL backend.
/// </summary>
internal event NotificationEventHandler Notification;
/// <summary>
/// Called to provide client certificates for SSL handshake.
/// </summary>
internal event ProvideClientCertificatesCallback ProvideClientCertificatesCallback;
/// <summary>
/// Mono.Security.Protocol.Tls.CertificateSelectionCallback delegate.
/// </summary>
internal event CertificateSelectionCallback CertificateSelectionCallback;
/// <summary>
/// Mono.Security.Protocol.Tls.CertificateValidationCallback delegate.
/// </summary>
internal event CertificateValidationCallback CertificateValidationCallback;
/// <summary>
/// Mono.Security.Protocol.Tls.PrivateKeySelectionCallback delegate.
/// </summary>
internal event PrivateKeySelectionCallback PrivateKeySelectionCallback;
private ConnectionState _connection_state;
private readonly HashSet<string> CachedPlans = new HashSet<string>();
// The physical network connection to the backend.
private Stream _stream;
private Socket _socket;
// Mediator which will hold data generated from backend.
private readonly NpgsqlMediator _mediator;
private Version _serverVersion;
// Values for possible CancelRequest messages.
private NpgsqlBackEndKeyData _backend_keydata;
private NpgsqlTransaction _transaction = null;
private Boolean _supportsPrepare = false;
private Boolean _supportsSavepoint = false;
private NpgsqlBackendTypeMapping _oidToNameMapping = null;
private Boolean _isInitialized;
private readonly Boolean _pooled;
private readonly Boolean _shared;
private NpgsqlState _state;
private Int32 _planIndex;
private Int32 _portalIndex;
private const String _planNamePrefix = "npgsqlplan";
private const String _portalNamePrefix = "npgsqlportal";
private Thread _notificationThread;
// The AutoResetEvent to synchronize processing threads.
internal AutoResetEvent _notificationAutoResetEvent;
// Counter of notification thread start/stop requests in order to
internal Int16 _notificationThreadStopCount;
private Exception _notificationException;
internal ForwardsOnlyDataReader CurrentReader;
// Some kinds of messages only get one response, and do not
// expect a ready_for_query response.
private bool _requireReadyForQuery = true;
private bool? _useConformantStrings;
private readonly Dictionary<string, NpgsqlParameterStatus> _serverParameters =
new Dictionary<string, NpgsqlParameterStatus>(StringComparer.InvariantCultureIgnoreCase);
public readonly byte[] TmpBuffer = new byte[4];
public readonly ByteBuffer ArrayBuffer = new ByteBuffer();
#if WINDOWS && UNMANAGED
private SSPIHandler _sspi;
internal SSPIHandler SSPI
{
get { return _sspi; }
set { _sspi = value; }
}
#endif
/// <summary>
/// Constructor.
/// </summary>
/// <param name="Shared">Controls whether the connector can be shared.</param>
public NpgsqlConnector(NpgsqlConnectionStringBuilder ConnectionString, bool Pooled, bool Shared)
{
this.settings = ConnectionString;
State = ConnectionState.Closed;
_pooled = Pooled;
_shared = Shared;
_isInitialized = false;
_state = NpgsqlClosedState.Instance;
_mediator = new NpgsqlMediator();
_oidToNameMapping = new NpgsqlBackendTypeMapping();
_planIndex = 0;
_portalIndex = 0;
_notificationThreadStopCount = 1;
_notificationAutoResetEvent = new AutoResetEvent(true);
}
public NpgsqlConnector(NpgsqlConnection Connection)
: this(Connection.ConnectionStringValues.Clone(), Connection.Pooling, false)
{ }
internal String Host
{
get { return settings.Host; }
}
internal Int32 Port
{
get { return settings.Port; }
}
internal String Database
{
get { return settings.ContainsKey(Keywords.Database) ? settings.Database : settings.UserName; }
}
internal String UserName
{
get { return settings.UserName; }
}
internal byte[] Password
{
get { return settings.PasswordAsByteArray; }
}
internal Boolean SSL
{
get { return settings.SSL; }
}
internal SslMode SslMode
{
get { return settings.SslMode; }
}
internal Int32 ConnectionTimeout
{
get { return settings.Timeout; }
}
internal Int32 CommandTimeout
{
get { return settings.CommandTimeout; }
}
internal Boolean Enlist
{
get { return settings.Enlist; }
}
public bool UseExtendedTypes
{
get { return settings.UseExtendedTypes; }
}
internal Boolean IntegratedSecurity
{
get { return settings.IntegratedSecurity; }
}
/// <summary>
/// Gets the current state of the connection.
/// </summary>
internal ConnectionState State
{
get
{
if (_connection_state != ConnectionState.Closed && CurrentReader != null && !CurrentReader._cleanedUp)
{
return ConnectionState.Open | ConnectionState.Fetching;
}
return _connection_state;
}
private set
{
if (_connection_state != value)
{
var old = _connection_state;
_connection_state = value;
var sc = StateChanged;
if (sc != null)
sc(this, new StateChangeEventArgs(old, value));
}
}
}
internal event StateChangeEventHandler StateChanged;
/// <summary>
/// Return Connection String.
/// </summary>
internal string ConnectionString
{
get { return settings.ConnectionString; }
}
// State
internal void Query(NpgsqlCommand queryCommand)
{
CurrentState.Query(this, queryCommand);
}
internal void PrepareOrAdd(string planName, string types, string query)
{
if (!CachedPlans.Contains(planName))
{
using (NpgsqlCommand cmd = new NpgsqlCommand("PREPARE \"" + planName + "\"(" + types + ") AS " + query, this))
Query(cmd);
CachedPlans.Add(planName);
}
}
internal IEnumerable<IServerResponseObject> QueryEnum(NpgsqlCommand queryCommand)
{
if (CurrentReader != null)
{
if (!CurrentReader._cleanedUp)
{
throw new InvalidOperationException(
"There is already an open DataReader associated with this Command which must be closed first.");
}
CurrentReader.Close();
}
return CurrentState.QueryEnum(this, queryCommand);
}
internal void Authenticate(byte[] password)
{
CurrentState.Authenticate(this, password);
}
internal void Parse(NpgsqlParse parse)
{
CurrentState.Parse(this, parse);
}
internal void Flush()
{
CurrentState.Flush(this);
}
internal void TestConnector()
{
CurrentState.TestConnector(this);
}
internal NpgsqlRowDescription Sync()
{
return CurrentState.Sync(this);
}
internal void Bind(NpgsqlBind bind)
{
CurrentState.Bind(this, bind);
}
internal void Describe(NpgsqlDescribe describe)
{
CurrentState.Describe(this, describe);
}
internal void Execute(NpgsqlExecute execute)
{
CurrentState.Execute(this, execute);
}
internal IEnumerable<IServerResponseObject> ExecuteEnum(NpgsqlExecute execute)
{
return CurrentState.ExecuteEnum(this, execute);
}
private static int ValidCounter;
/// <summary>
/// This method checks if the connector is still ok.
/// We try to send a simple query text, select 1 as ConnectionTest;
/// </summary>
internal Boolean IsValid()//TODO: WTF!?
{
try
{
// Here we use a fake NpgsqlCommand, just to send the test query string.
var testValue = (ValidCounter++).ToString();
string compareValue = string.Empty;
using (NpgsqlCommand cmd = new NpgsqlCommand("select '" + testValue + "'", this))
{
compareValue = (string)cmd.ExecuteScalar();
}
if (compareValue != testValue)
return false;
// Clear mediator.
Mediator.ResetResponses();
this.RequireReadyForQuery = true;
}
catch
{
return false;
}
return true;
}
/// <summary>
/// This method is responsible for releasing all resources associated with this Connector.
/// </summary>
internal void ReleaseResources()
{
if (_connection_state != ConnectionState.Closed)
{
ReleasePlansPortals();
ReleaseRegisteredListen();
}
}
internal void ReleaseRegisteredListen()
{
//Query(new NpgsqlCommand("unlisten *", this));
using (NpgsqlCommand cmd = new NpgsqlCommand("unlisten *", this))
{
Query(cmd);
}
}
/// <summary>
/// This method is responsible to release all portals used by this Connector.
/// </summary>
internal void ReleasePlansPortals()
{
Int32 i = 0;
if (_planIndex > 0)
{
for (i = 1; i <= _planIndex; i++)
{
try
{
//Query(new NpgsqlCommand(String.Format("deallocate \"{0}\";", _planNamePrefix + i), this));
using (NpgsqlCommand cmd = new NpgsqlCommand(String.Format("deallocate \"{0}\";", _planNamePrefix + i.ToString()), this))
{
Query(cmd);
}
}
// Ignore any error which may occur when releasing portals as this portal name may not be valid anymore. i.e.: the portal name was used on a prepared query which had errors.
catch { }
}
}
foreach (var cp in CachedPlans)
{
try
{
using (NpgsqlCommand cmd = new NpgsqlCommand("deallocate \"" + cp + "\";", this))
Query(cmd);
}
// Ignore any error which may occur when releasing portals as this portal name may not be valid anymore. i.e.: the portal name was used on a prepared query which had errors.
catch { }
}
CachedPlans.Clear();
_portalIndex = 0;
_planIndex = 0;
}
internal void FireNotice(NpgsqlError e)
{
if (Notice != null)
{
try
{
Notice(this, new NpgsqlNoticeEventArgs(e));
}
catch
{
} //Eat exceptions from user code.
}
}
internal void FireNotification(NpgsqlNotificationEventArgs e)
{
if (Notification != null)
{
try
{
Notification(this, e);
}
catch
{
} //Eat exceptions from user code.
}
}
/// <summary>
/// Default SSL CertificateSelectionCallback implementation.
/// </summary>
internal X509Certificate DefaultCertificateSelectionCallback(X509CertificateCollection clientCertificates,
X509Certificate serverCertificate, string targetHost,
X509CertificateCollection serverRequestedCertificates)
{
if (CertificateSelectionCallback != null)
{
return CertificateSelectionCallback(clientCertificates, serverCertificate, targetHost, serverRequestedCertificates);
}
else
{
return null;
}
}
/// <summary>
/// Default SSL CertificateValidationCallback implementation.
/// </summary>
internal bool DefaultCertificateValidationCallback(X509Certificate certificate, int[] certificateErrors)
{
if (CertificateValidationCallback != null)
{
return CertificateValidationCallback(certificate, certificateErrors);
}
else
{
return true;
}
}
/// <summary>
/// Default SSL PrivateKeySelectionCallback implementation.
/// </summary>
internal AsymmetricAlgorithm DefaultPrivateKeySelectionCallback(X509Certificate certificate, string targetHost)
{
if (PrivateKeySelectionCallback != null)
{
return PrivateKeySelectionCallback(certificate, targetHost);
}
else
{
return null;
}
}
/// <summary>
/// Default SSL ProvideClientCertificatesCallback implementation.
/// </summary>
internal void DefaultProvideClientCertificatesCallback(X509CertificateCollection certificates)
{
if (ProvideClientCertificatesCallback != null)
{
ProvideClientCertificatesCallback(certificates);
}
}
/// <summary>
/// Version of backend server this connector is connected to.
/// </summary>
internal Version ServerVersion
{
get { return _serverVersion; }
set { _serverVersion = value; }
}
/// <summary>
/// The physical connection stream to the backend.
/// </summary>
internal Stream Stream
{
get { return _stream; }
set { _stream = value; }
}
/// <summary>
/// The physical connection socket to the backend.
/// </summary>
internal Socket Socket
{
get { return _socket; }
set { _socket = value; }
}
/// <summary>
/// Reports if this connector is fully connected.
/// </summary>
internal Boolean IsInitialized
{
get { return _isInitialized; }
set { _isInitialized = value; }
}
internal NpgsqlState CurrentState
{
get { return _state; }
set { _state = value; }
}
internal bool Pooled
{
get { return _pooled; }
}
internal bool Shared
{
get { return _shared; }
}
internal NpgsqlBackEndKeyData BackEndKeyData
{
get { return _backend_keydata; }
set { _backend_keydata = value; }
}
internal NpgsqlBackendTypeMapping OidToNameMapping
{
get { return _oidToNameMapping; }
}
internal Version CompatVersion
{
get
{
return settings.Compatible;
}
}
/// <summary>
/// The connection mediator.
/// </summary>
internal NpgsqlMediator Mediator
{
get { return _mediator; }
}
/// <summary>
/// Report if the connection is in a transaction.
/// </summary>
internal NpgsqlTransaction Transaction
{
get { return _transaction; }
set { _transaction = value; }
}
internal Boolean SupportsApplicationName
{
get { return ServerVersion >= new Version(9, 0, 0); }
}
/// <summary>
/// Report whether the current connection can support prepare functionality.
/// </summary>
internal Boolean SupportsPrepare
{
get { return _supportsPrepare; }
set { _supportsPrepare = value; }
}
internal Boolean SupportsSavepoint
{
get { return _supportsSavepoint; }
set { _supportsSavepoint = value; }
}
/// <summary>
/// This method is required to set all the version dependent features flags.
/// SupportsPrepare means the server can use prepared query plans (7.3+)
/// </summary>
// FIXME - should be private
internal void ProcessServerVersion()
{
this._supportsPrepare = (ServerVersion >= new Version(7, 3, 0));
this._supportsSavepoint = (ServerVersion >= new Version(8, 0, 0));
}
/// <summary>
/// Opens the physical connection to the server.
/// </summary>
/// <remarks>Usually called by the RequestConnector
/// Method of the connection pool manager.</remarks>
internal void Open()
{
ServerVersion = null;
// If Connection.ConnectionString specifies a protocol version, we will
// not try to fall back to version 2 on failure.
// Reset state to initialize new connector in pool.
CurrentState = NpgsqlClosedState.Instance;
// Get a raw connection, possibly SSL...
CurrentState.Open(this);
try
{
// Establish protocol communication and handle authentication...
CurrentState.Startup(this);
}
catch (NpgsqlException)
{
throw;
}
// Change the state of connection to open and ready.
State = ConnectionState.Open;
CurrentState = NpgsqlReadyState.Instance;
// Fall back to the old way, SELECT VERSION().
// This should not happen for protocol version 3+.
if (ServerVersion == null)
{
using (NpgsqlCommand command = new NpgsqlCommand("set DATESTYLE TO ISO;select version();", this))
{
ServerVersion = new Version(PGUtil.ExtractServerVersion((string)command.ExecuteScalar()));
}
}
StringBuilder sbInit = new StringBuilder();
// Adjust client encoding.
NpgsqlParameterStatus clientEncodingParam = null;
if (!ServerParameters.TryGetValue("client_encoding", out clientEncodingParam)
|| !string.Equals(clientEncodingParam.ParameterValue, "UTF8", StringComparison.OrdinalIgnoreCase) && !string.Equals(clientEncodingParam.ParameterValue, "UNICODE", StringComparison.OrdinalIgnoreCase))
sbInit.AppendLine("SET CLIENT_ENCODING TO UTF8;");
if (!string.IsNullOrEmpty(settings.SearchPath))
{
// TODO: Add proper message when finding a semicolon in search_path.
// This semicolon could lead to a sql injection security hole as someone could write in connection string:
// searchpath=public;delete from table; and it would be executed.
if (settings.SearchPath.Contains(";"))
{
throw new InvalidOperationException();
}
sbInit.AppendLine("SET SEARCH_PATH=" + settings.SearchPath + ";");
}
if (!string.IsNullOrEmpty(settings.ApplicationName))
{
if (!SupportsApplicationName)
{
//TODO
//throw new InvalidOperationException(resman.GetString("Exception_ApplicationNameNotSupported"));
throw new InvalidOperationException("ApplicationName not supported.");
}
if (settings.ApplicationName.Contains(";"))
{
throw new InvalidOperationException();
}
sbInit.AppendLine("SET APPLICATION_NAME='" + settings.ApplicationName.Replace('\'', '-') + "';");
}
/*
* Try to set SSL negotiation to 0. As of 2010-03-29, recent problems in SSL library implementations made
* postgresql to add a parameter to set a value when to do this renegotiation or 0 to disable it.
* Currently, Npgsql has a problem with renegotiation so, we are trying to disable it here.
* This only works on postgresql servers where the ssl renegotiation settings is supported of course.
* See http://lists.pgfoundry.org/pipermail/npgsql-devel/2010-February/001065.html for more information.
*/
sbInit.AppendLine("SET ssl_renegotiation_limit=0;");
/*
* Set precision digits to maximum value possible. For postgresql before 9 it was 2, after that, it is 3.
* This way, we set first to 2 and then to 3. If there is an error because of 3, it will have been set to 2 at least.
* Check bug report #1010992 for more information.
*/
sbInit.AppendLine("SET extra_float_digits=3;");
try
{
new NpgsqlCommand(sbInit.ToString(), this).ExecuteBlind();
}
catch
{
foreach (var line in sbInit.ToString().Split(Environment.NewLine.ToCharArray()))
{
try
{
if (line.Length > 0)
{
new NpgsqlCommand(line, this).ExecuteBlind();
}
}
catch { }
}
}
// Make a shallow copy of the type mapping that the connector will own.
// It is possible that the connector may add types to its private
// mapping that will not be valid to another connector, even
// if connected to the same backend version.
_oidToNameMapping = NpgsqlTypesHelper.CreateAndLoadInitialTypesMapping(this).Clone();
ProcessServerVersion();
// The connector is now fully initialized. Beyond this point, it is
// safe to release it back to the pool rather than closing it.
IsInitialized = true;
}
/// <summary>
/// Closes the physical connection to the server.
/// </summary>
internal void Close()
{
try
{
if (_connection_state != ConnectionState.Closed)
{
State = ConnectionState.Closed;
this.CurrentState.Close(this);
_serverParameters.Clear();
ServerVersion = null;
}
}
catch
{
}
}
internal void CancelRequest()
{
NpgsqlConnector cancelConnector = new NpgsqlConnector(settings, false, false);
cancelConnector._backend_keydata = BackEndKeyData;
try
{
// Get a raw connection, possibly SSL...
cancelConnector.CurrentState.Open(cancelConnector);
// Cancel current request.
cancelConnector.CurrentState.CancelRequest(cancelConnector);
}
finally
{
cancelConnector.CurrentState.Close(cancelConnector);
}
}
///<summary>
/// Returns next portal index.
///</summary>
internal String NextPortalName()
{
return _portalNamePrefix + Interlocked.Increment(ref _portalIndex).ToString();
}
///<summary>
/// Returns next plan index.
///</summary>
internal String NextPlanName()
{
return _planNamePrefix + Interlocked.Increment(ref _planIndex).ToString();
}
internal void RemoveNotificationThread()
{
// Wait notification thread finish its work.
_notificationAutoResetEvent.WaitOne();
// Kill notification thread.
_notificationThread.Abort();
_notificationThread = null;
// Special case in order to not get problems with thread synchronization.
// It will be turned to 0 when synch thread is created.
_notificationThreadStopCount = 1;
}
internal void AddNotificationThread()
{
_notificationThreadStopCount = 0;
_notificationAutoResetEvent.Set();
NpgsqlContextHolder contextHolder = new NpgsqlContextHolder(this, CurrentState);
_notificationThread = new Thread(new ThreadStart(contextHolder.ProcessServerMessages));
_notificationThread.Start();
}
//Use with using(){} to perform the sentry pattern
//on stopping and starting notification thread
//(The sentry pattern is a generalisation of RAII where we
//have a pair of actions - one "undoing" the previous
//and we want to execute the first and second around other code,
//then we treat it much like resource mangement in RAII.
//try{}finally{} also does execute-around, but sentry classes
//have some extra flexibility (e.g. they can be "owned" by
//another object and then cleaned up when that object is
//cleaned up), and can act as the sole gate-way
//to the code in question, guaranteeing that using code can't be written
//so that the "undoing" is forgotten.
internal class NotificationThreadBlock : IDisposable
{
private NpgsqlConnector _connector;
public NotificationThreadBlock(NpgsqlConnector connector)
{
(_connector = connector).StopNotificationThread();
}
public void Dispose()
{
if (_connector != null)
{
_connector.ResumeNotificationThread();
}
_connector = null;
}
}
internal NotificationThreadBlock BlockNotificationThread()
{
return new NotificationThreadBlock(this);
}
private void StopNotificationThread()
{
// first check to see if an exception has
// been thrown by the notification thread.
if (_notificationException != null)
throw _notificationException;
_notificationThreadStopCount++;
if (_notificationThreadStopCount == 1) // If this call was the first to increment.
{
_notificationAutoResetEvent.WaitOne();
}
}
private void ResumeNotificationThread()
{
_notificationThreadStopCount--;
if (_notificationThreadStopCount == 0)
{
// Release the synchronization handle.
_notificationAutoResetEvent.Set();
}
}
internal Boolean IsNotificationThreadRunning
{
get { return _notificationThreadStopCount <= 0; }
}
internal class NpgsqlContextHolder
{
private readonly NpgsqlConnector connector;
private readonly NpgsqlState state;
internal NpgsqlContextHolder(NpgsqlConnector connector, NpgsqlState state)
{
this.connector = connector;
this.state = state;
}
internal void ProcessServerMessages()
{
try
{
while (true)
{
Thread.Sleep(1);
//To give runtime chance to release correctly the lock. See http://pgfoundry.org/forum/message.php?msg_id=1002650 for more information.
this.connector._notificationAutoResetEvent.WaitOne();
if (this.connector.Socket.Poll(100, SelectMode.SelectRead))
{
// reset any responses just before getting new ones
this.connector.Mediator.ResetResponses();
this.state.ProcessBackendResponses(this.connector);
}
this.connector._notificationAutoResetEvent.Set();
}
}
catch (IOException ex)
{
this.connector._notificationException = ex;
this.connector._notificationAutoResetEvent.Set();
this.connector.Close();
}
}
}
public bool RequireReadyForQuery
{
get { return _requireReadyForQuery; }
set { _requireReadyForQuery = value; }
}
public void AddParameterStatus(NpgsqlParameterStatus ps)
{
if (_serverParameters.ContainsKey(ps.Parameter))
{
_serverParameters[ps.Parameter] = ps;
}
else
{
_serverParameters.Add(ps.Parameter, ps);
}
_useConformantStrings = null;
}
public IDictionary<string, NpgsqlParameterStatus> ServerParameters
{
get { return new ReadOnlyDictionary<string, NpgsqlParameterStatus>(_serverParameters); }
}
public string CheckParameter(string paramName)
{
NpgsqlParameterStatus ps = null;
if (_serverParameters.TryGetValue(paramName, out ps))
return ps.ParameterValue;
try
{
using (NpgsqlCommand cmd = new NpgsqlCommand("show " + paramName, this))
{
string paramValue = (string)cmd.ExecuteScalar();
AddParameterStatus(new NpgsqlParameterStatus(paramName, paramValue));
return paramValue;
}
}
/*
* In case of problems with the command above, we simply return null in order to
* say we don't support it.
*/
catch (NpgsqlException)
{
return null;
}
/*
* Original catch handler by Jon Hanna.
* 7.3 version doesn't support error code. Only 7.4+
* catch(NpgsqlException ne)
{
if(ne.Code == "42704")//unrecognized configuration parameter
return null;
else
throw;
}*/
}
private bool CheckStringConformanceRequirements()
{
//If standards_conforming_strings is "on" then postgres will handle \ in strings differently to how we expect, unless
//an escaped-string literal is use (E'example\n' rather than 'example\n'. At time of writing this defaults
//to "off", but documentation says this will change to default "on" in the future, and it can still be "on" now.
//escape_string_warning being "on" (current default) will result in a warning, but not an error, on every such
//string, which is not ideal.
//On the other hand, earlier versions of postgres do not have the escaped-literal syntax and will error if it
//is used. Version numbers could be checked, but here the approach taken is to check on what the server is
//explicitly requesting.
NpgsqlParameterStatus warning = null;
if (_serverParameters.TryGetValue("escape_string_warning", out warning) && warning.ParameterValue == "on")//try the most commonly set at time of coding first
return true;
NpgsqlParameterStatus insist = null;
if (_serverParameters.TryGetValue("standard_conforming_strings", out insist) && insist.ParameterValue == "on")
return true;
if (warning != null && insist != null)//both where present and "off".
return false;
//We need to check at least one of these on the server.
return CheckParameter("standard_conforming_strings") == "on" || CheckParameter("escape_string_warning") == "on";
}
public bool UseConformantStrings
{
get
{
return _useConformantStrings ?? (_useConformantStrings = CheckStringConformanceRequirements()).Value;
}
}
}
}
| |
// 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.
// --------------------------------------------------------------------------------------
//
// A class that provides a simple, lightweight implementation of lazy initialization,
// obviating the need for a developer to implement a custom, thread-safe lazy initialization
// solution.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#pragma warning disable 0420
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace System
{
internal enum LazyState
{
NoneViaConstructor = 0,
NoneViaFactory = 1,
NoneException = 2,
PublicationOnlyViaConstructor = 3,
PublicationOnlyViaFactory = 4,
PublicationOnlyWait = 5,
PublicationOnlyException = 6,
ExecutionAndPublicationViaConstructor = 7,
ExecutionAndPublicationViaFactory = 8,
ExecutionAndPublicationException = 9,
}
/// <summary>
/// LazyHelper serves multiples purposes
/// - minimizing code size of Lazy<T> by implementing as much of the code that is not generic
/// this reduces generic code bloat, making faster class initialization
/// - contains singleton objects that are used to handle threading primitives for PublicationOnly mode
/// - allows for instantiation for ExecutionAndPublication so as to create an object for locking on
/// - holds exception information.
/// </summary>
internal class LazyHelper
{
internal readonly static LazyHelper NoneViaConstructor = new LazyHelper(LazyState.NoneViaConstructor);
internal readonly static LazyHelper NoneViaFactory = new LazyHelper(LazyState.NoneViaFactory);
internal readonly static LazyHelper PublicationOnlyViaConstructor = new LazyHelper(LazyState.PublicationOnlyViaConstructor);
internal readonly static LazyHelper PublicationOnlyViaFactory = new LazyHelper(LazyState.PublicationOnlyViaFactory);
internal readonly static LazyHelper PublicationOnlyWaitForOtherThreadToPublish = new LazyHelper(LazyState.PublicationOnlyWait);
internal LazyState State { get; }
private readonly ExceptionDispatchInfo _exceptionDispatch;
/// <summary>
/// Constructor that defines the state
/// </summary>
internal LazyHelper(LazyState state)
{
State = state;
}
/// <summary>
/// Constructor used for exceptions
/// </summary>
internal LazyHelper(LazyThreadSafetyMode mode, Exception exception)
{
switch(mode)
{
case LazyThreadSafetyMode.ExecutionAndPublication:
State = LazyState.ExecutionAndPublicationException;
break;
case LazyThreadSafetyMode.None:
State = LazyState.NoneException;
break;
case LazyThreadSafetyMode.PublicationOnly:
State = LazyState.PublicationOnlyException;
break;
default:
Debug.Fail("internal constructor, this should never occur");
break;
}
_exceptionDispatch = ExceptionDispatchInfo.Capture(exception);
}
internal void ThrowException()
{
Debug.Assert(_exceptionDispatch != null, "execution path is invalid");
_exceptionDispatch.Throw();
}
private LazyThreadSafetyMode GetMode()
{
switch (State)
{
case LazyState.NoneViaConstructor:
case LazyState.NoneViaFactory:
case LazyState.NoneException:
return LazyThreadSafetyMode.None;
case LazyState.PublicationOnlyViaConstructor:
case LazyState.PublicationOnlyViaFactory:
case LazyState.PublicationOnlyWait:
case LazyState.PublicationOnlyException:
return LazyThreadSafetyMode.PublicationOnly;
case LazyState.ExecutionAndPublicationViaConstructor:
case LazyState.ExecutionAndPublicationViaFactory:
case LazyState.ExecutionAndPublicationException:
return LazyThreadSafetyMode.ExecutionAndPublication;
default:
Debug.Fail("Invalid logic; State should always have a valid value");
return default;
}
}
internal static LazyThreadSafetyMode? GetMode(LazyHelper state)
{
if (state == null)
return null; // we don't know the mode anymore
return state.GetMode();
}
internal static bool GetIsValueFaulted(LazyHelper state) => state?._exceptionDispatch != null;
internal static LazyHelper Create(LazyThreadSafetyMode mode, bool useDefaultConstructor)
{
switch (mode)
{
case LazyThreadSafetyMode.None:
return useDefaultConstructor ? NoneViaConstructor : NoneViaFactory;
case LazyThreadSafetyMode.PublicationOnly:
return useDefaultConstructor ? PublicationOnlyViaConstructor : PublicationOnlyViaFactory;
case LazyThreadSafetyMode.ExecutionAndPublication:
// we need to create an object for ExecutionAndPublication because we use Monitor-based locking
var state = useDefaultConstructor ? LazyState.ExecutionAndPublicationViaConstructor : LazyState.ExecutionAndPublicationViaFactory;
return new LazyHelper(state);
default:
throw new ArgumentOutOfRangeException(nameof(mode), SR.Lazy_ctor_ModeInvalid);
}
}
internal static object CreateViaDefaultConstructor(Type type)
{
try
{
return Activator.CreateInstance(type);
}
catch (MissingMethodException)
{
throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
}
}
internal static LazyThreadSafetyMode GetModeFromIsThreadSafe(bool isThreadSafe)
{
return isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None;
}
}
/// <summary>
/// Provides support for lazy initialization.
/// </summary>
/// <typeparam name="T">Specifies the type of element being lazily initialized.</typeparam>
/// <remarks>
/// <para>
/// By default, all public and protected members of <see cref="Lazy{T}"/> are thread-safe and may be used
/// concurrently from multiple threads. These thread-safety guarantees may be removed optionally and per instance
/// using parameters to the type's constructors.
/// </para>
/// </remarks>
[DebuggerTypeProxy(typeof(LazyDebugView<>))]
[DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")]
public class Lazy<T>
{
private static T CreateViaDefaultConstructor()
{
return (T)LazyHelper.CreateViaDefaultConstructor(typeof(T));
}
// _state, a volatile reference, is set to null after _value has been set
private volatile LazyHelper _state;
// we ensure that _factory when finished is set to null to allow garbage collector to clean up
// any referenced items
private Func<T> _factory;
// _value eventually stores the lazily created value. It is valid when _state = null.
private T _value;
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that
/// uses <typeparamref name="T"/>'s default constructor for lazy initialization.
/// </summary>
/// <remarks>
/// An instance created with this constructor may be used concurrently from multiple threads.
/// </remarks>
public Lazy()
: this(null, LazyThreadSafetyMode.ExecutionAndPublication, useDefaultConstructor:true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that
/// uses a pre-initialized specified value.
/// </summary>
/// <remarks>
/// An instance created with this constructor should be usable by multiple threads
// concurrently.
/// </remarks>
public Lazy(T value)
{
_value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that uses a
/// specified initialization function.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is
/// needed.
/// </param>
/// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <remarks>
/// An instance created with this constructor may be used concurrently from multiple threads.
/// </remarks>
public Lazy(Func<T> valueFactory)
: this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication, useDefaultConstructor:false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/>
/// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode.
/// </summary>
/// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time.
/// </param>
public Lazy(bool isThreadSafe) :
this(null, LazyHelper.GetModeFromIsThreadSafe(isThreadSafe), useDefaultConstructor:true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/>
/// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode.
/// </summary>
/// <param name="mode">The lazy thread-safety mode</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid valuee</exception>
public Lazy(LazyThreadSafetyMode mode) :
this(null, mode, useDefaultConstructor:true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class
/// that uses a specified initialization function and a specified thread-safety mode.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed.
/// </param>
/// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time.
/// </param>
/// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is
/// a null reference (Nothing in Visual Basic).</exception>
public Lazy(Func<T> valueFactory, bool isThreadSafe) :
this(valueFactory, LazyHelper.GetModeFromIsThreadSafe(isThreadSafe), useDefaultConstructor:false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class
/// that uses a specified initialization function and a specified thread-safety mode.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed.
/// </param>
/// <param name="mode">The lazy thread-safety mode.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is
/// a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid value.</exception>
public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode)
: this(valueFactory, mode, useDefaultConstructor:false)
{
}
private Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode, bool useDefaultConstructor)
{
if (valueFactory == null && !useDefaultConstructor)
throw new ArgumentNullException(nameof(valueFactory));
_factory = valueFactory;
_state = LazyHelper.Create(mode, useDefaultConstructor);
}
private void ViaConstructor()
{
_value = CreateViaDefaultConstructor();
_state = null; // volatile write, must occur after setting _value
}
private void ViaFactory(LazyThreadSafetyMode mode)
{
try
{
Func<T> factory = _factory;
if (factory == null)
throw new InvalidOperationException(SR.Lazy_Value_RecursiveCallsToValue);
_factory = null;
_value = factory();
_state = null; // volatile write, must occur after setting _value
}
catch (Exception exception)
{
_state = new LazyHelper(mode, exception);
throw;
}
}
private void ExecutionAndPublication(LazyHelper executionAndPublication, bool useDefaultConstructor)
{
lock (executionAndPublication)
{
// it's possible for multiple calls to have piled up behind the lock, so we need to check
// to see if the ExecutionAndPublication object is still the current implementation.
if (ReferenceEquals(_state, executionAndPublication))
{
if (useDefaultConstructor)
{
ViaConstructor();
}
else
{
ViaFactory(LazyThreadSafetyMode.ExecutionAndPublication);
}
}
}
}
private void PublicationOnly(LazyHelper publicationOnly, T possibleValue)
{
LazyHelper previous = Interlocked.CompareExchange(ref _state, LazyHelper.PublicationOnlyWaitForOtherThreadToPublish, publicationOnly);
if (previous == publicationOnly)
{
_factory = null;
_value = possibleValue;
_state = null; // volatile write, must occur after setting _value
}
}
private void PublicationOnlyViaConstructor(LazyHelper initializer)
{
PublicationOnly(initializer, CreateViaDefaultConstructor());
}
private void PublicationOnlyViaFactory(LazyHelper initializer)
{
Func<T> factory = _factory;
if (factory == null)
{
PublicationOnlyWaitForOtherThreadToPublish();
}
else
{
PublicationOnly(initializer, factory());
}
}
private void PublicationOnlyWaitForOtherThreadToPublish()
{
var spinWait = new SpinWait();
while (!ReferenceEquals(_state, null))
{
// We get here when PublicationOnly temporarily sets _state to LazyHelper.PublicationOnlyWaitForOtherThreadToPublish.
// This temporary state should be quickly followed by _state being set to null.
spinWait.SpinOnce();
}
}
private T CreateValue()
{
// we have to create a copy of state here, and use the copy exclusively from here on in
// so as to ensure thread safety.
var state = _state;
if (state != null)
{
switch (state.State)
{
case LazyState.NoneViaConstructor:
ViaConstructor();
break;
case LazyState.NoneViaFactory:
ViaFactory(LazyThreadSafetyMode.None);
break;
case LazyState.PublicationOnlyViaConstructor:
PublicationOnlyViaConstructor(state);
break;
case LazyState.PublicationOnlyViaFactory:
PublicationOnlyViaFactory(state);
break;
case LazyState.PublicationOnlyWait:
PublicationOnlyWaitForOtherThreadToPublish();
break;
case LazyState.ExecutionAndPublicationViaConstructor:
ExecutionAndPublication(state, useDefaultConstructor:true);
break;
case LazyState.ExecutionAndPublicationViaFactory:
ExecutionAndPublication(state, useDefaultConstructor:false);
break;
default:
state.ThrowException();
break;
}
}
return Value;
}
/// <summary>Creates and returns a string representation of this instance.</summary>
/// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see
/// cref="Value"/>.</returns>
/// <exception cref="T:System.NullReferenceException">
/// The <see cref="Value"/> is null.
/// </exception>
public override string ToString()
{
return IsValueCreated ? Value.ToString() : SR.Lazy_ToString_ValueNotCreated;
}
/// <summary>Gets the value of the Lazy<T> for debugging display purposes.</summary>
internal T ValueForDebugDisplay
{
get
{
if (!IsValueCreated)
{
return default;
}
return _value;
}
}
/// <summary>
/// Gets a value indicating whether this instance may be used concurrently from multiple threads.
/// </summary>
internal LazyThreadSafetyMode? Mode => LazyHelper.GetMode(_state);
/// <summary>
/// Gets whether the value creation is faulted or not
/// </summary>
internal bool IsValueFaulted => LazyHelper.GetIsValueFaulted(_state);
/// <summary>Gets a value indicating whether the <see cref="T:System.Lazy{T}"/> has been initialized.
/// </summary>
/// <value>true if the <see cref="T:System.Lazy{T}"/> instance has been initialized;
/// otherwise, false.</value>
/// <remarks>
/// The initialization of a <see cref="T:System.Lazy{T}"/> instance may result in either
/// a value being produced or an exception being thrown. If an exception goes unhandled during initialization,
/// <see cref="IsValueCreated"/> will return false.
/// </remarks>
public bool IsValueCreated => _state == null;
/// <summary>Gets the lazily initialized value of the current <see
/// cref="T:System.Threading.Lazy{T}"/>.</summary>
/// <value>The lazily initialized value of the current <see
/// cref="T:System.Threading.Lazy{T}"/>.</value>
/// <exception cref="T:System.MissingMemberException">
/// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor
/// of the type being lazily initialized, and that type does not have a public, parameterless constructor.
/// </exception>
/// <exception cref="T:System.MemberAccessException">
/// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor
/// of the type being lazily initialized, and permissions to access the constructor were missing.
/// </exception>
/// <exception cref="T:System.InvalidOperationException">
/// The <see cref="T:System.Threading.Lazy{T}"/> was constructed with the <see cref="T:System.Threading.LazyThreadSafetyMode.ExecutionAndPublication"/> or
/// <see cref="T:System.Threading.LazyThreadSafetyMode.None"/> and the initialization function attempted to access <see cref="Value"/> on this instance.
/// </exception>
/// <remarks>
/// If <see cref="IsValueCreated"/> is false, accessing <see cref="Value"/> will force initialization.
/// Please <see cref="System.Threading.LazyThreadSafetyMode"> for more information on how <see cref="T:System.Threading.Lazy{T}"/> will behave if an exception is thrown
/// from initialization delegate.
/// </remarks>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Value => _state == null ? _value : CreateValue();
}
/// <summary>A debugger view of the Lazy<T> to surface additional debugging properties and
/// to ensure that the Lazy<T> does not become initialized if it was not already.</summary>
internal sealed class LazyDebugView<T>
{
//The Lazy object being viewed.
private readonly Lazy<T> _lazy;
/// <summary>Constructs a new debugger view object for the provided Lazy object.</summary>
/// <param name="lazy">A Lazy object to browse in the debugger.</param>
public LazyDebugView(Lazy<T> lazy)
{
_lazy = lazy;
}
/// <summary>Returns whether the Lazy object is initialized or not.</summary>
public bool IsValueCreated
{
get { return _lazy.IsValueCreated; }
}
/// <summary>Returns the value of the Lazy object.</summary>
public T Value
{
get
{ return _lazy.ValueForDebugDisplay; }
}
/// <summary>Returns the execution mode of the Lazy object</summary>
public LazyThreadSafetyMode? Mode
{
get { return _lazy.Mode; }
}
/// <summary>Returns the execution mode of the Lazy object</summary>
public bool IsValueFaulted
{
get { return _lazy.IsValueFaulted; }
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using System.IO;
[CustomEditor( typeof( GoDummyPath ) )]
public class GoDummyPathEditor : Editor
{
private GoDummyPath _target;
private GUIStyle _labelStyle;
private GUIStyle _indexStyle;
private int _insertIndex = 0;
private float _snapDistance = 5f;
private bool _showNodeDetails;
private bool _fileLoadSaveDetails;
private int _selectedNodeIndex = -1;
#region Monobehaviour and Editor
void OnEnable()
{
// setup the font for the 'begin' 'end' text
_labelStyle = new GUIStyle();
_labelStyle.fontStyle = FontStyle.Bold;
_labelStyle.normal.textColor = Color.white;
_labelStyle.fontSize = 16;
_indexStyle = new GUIStyle();
_indexStyle.fontStyle = FontStyle.Bold;
_indexStyle.normal.textColor = Color.white;
_indexStyle.fontSize = 12;
_target = (GoDummyPath)target;
}
public override void OnInspectorGUI()
{
// what kind of handles shall we use?
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel( "Use Standard Handles" );
_target.useStandardHandles = EditorGUILayout.Toggle( _target.useStandardHandles );
EditorGUILayout.EndHorizontal();
// path name:
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel( "Route Name" );
_target.pathName = EditorGUILayout.TextField( _target.pathName );
EditorGUILayout.EndHorizontal();
if( _target.pathName == string.Empty )
_target.pathName = "route" + Random.Range( 1, 100000 );
// path color:
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel( "Route Color" );
_target.pathColor = EditorGUILayout.ColorField( _target.pathColor );
EditorGUILayout.EndHorizontal();
// force straight lines:
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel( "Force Straight Line Path" );
_target.forceStraightLinePath = EditorGUILayout.Toggle( _target.forceStraightLinePath );
EditorGUILayout.EndHorizontal();
// resolution
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel( "Editor Drawing Resolution" );
_target.pathResolution = EditorGUILayout.IntSlider( _target.pathResolution, 2, 100 );
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
// insert node - we need 3 or more nodes for insert to make sense
if( _target.nodes.Count > 2 )
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel( "Insert Node" );
_insertIndex = EditorGUILayout.IntField( _insertIndex );
if( GUILayout.Button( "Insert" ) )
{
// validate the index
if( _insertIndex >= 0 && _insertIndex < _target.nodes.Count )
{
// insert the node offsetting it a bit from the previous node
var copyNodeIndex = _insertIndex == 0 ? 0 : _insertIndex;
var copyNode = _target.nodes[copyNodeIndex];
copyNode.x += 10;
copyNode.z += 10;
insertNodeAtIndex( copyNode, _insertIndex );
}
}
EditorGUILayout.EndHorizontal();
}
// close route?
if( GUILayout.Button( "Close Path" ) )
{
Undo.RecordObject( _target, "Path Vector Changed" );
closeRoute();
GUI.changed = true;
}
// shift the start point to the origin
if( GUILayout.Button( "Shift Path to Start at Origin" ) )
{
Undo.RecordObject( _target, "Path Vector Changed" );
var offset = Vector3.zero;
// see what kind of path we are. the simplest case is just a straight line
var path = new GoSpline( _target.nodes, _target.forceStraightLinePath );
if( path.splineType == GoSplineType.StraightLine || _target.nodes.Count < 5 )
offset = Vector3.zero - _target.nodes[0];
else
offset = Vector3.zero - _target.nodes[1];
for( var i = 0; i < _target.nodes.Count; i++ )
_target.nodes[i] += offset;
GUI.changed = true;
}
// reverse
if( GUILayout.Button( "Reverse Path" ) )
{
Undo.RecordObject( _target, "Path Vector Changed" );
_target.nodes.Reverse();
GUI.changed = true;
}
// persist to disk
EditorGUILayout.Space();
EditorGUILayout.LabelField( "Save to/Read from Disk" );
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel( "Serialize and Save Path" );
if( GUILayout.Button( "Save" ) )
{
var path = EditorUtility.SaveFilePanel( "Save path", Application.dataPath + "/StreamingAssets", _target.pathName + ".asset", "asset" );
if( path != string.Empty )
{
persistRouteToDisk( path );
// fetch the filename and set it as the routeName
_target.pathName = Path.GetFileName( path ).Replace( ".asset", string.Empty );
GUI.changed = true;
}
}
EditorGUILayout.EndHorizontal();
// load from disk
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel( "Load saved path" );
if( GUILayout.Button( "Load" ) )
{
var path = EditorUtility.OpenFilePanel( "Choose path to load", Path.Combine( Application.dataPath, "StreamingAssets" ), "asset" );
if( path != string.Empty )
{
if( !File.Exists( path ) )
{
EditorUtility.DisplayDialog( "File does not exist", "Path couldn't find the file you specified", "Close" );
}
else
{
_target.nodes = GoSpline.bytesToVector3List( File.ReadAllBytes( path ) );
_target.pathName = Path.GetFileName( path ).Replace( ".asset", string.Empty );
GUI.changed = true;
}
}
}
EditorGUILayout.EndHorizontal();
// node display
EditorGUILayout.Space();
_showNodeDetails = EditorGUILayout.Foldout( _showNodeDetails, "Show Node Values" );
if( _showNodeDetails )
{
EditorGUI.indentLevel++;
for( int i = 0; i < _target.nodes.Count; i++ )
_target.nodes[i] = EditorGUILayout.Vector3Field( "Node " + ( i + 1 ), _target.nodes[i] );
EditorGUI.indentLevel--;
}
// instructions
EditorGUILayout.Space();
EditorGUILayout.HelpBox( "While dragging a node, hold down Ctrl and slowly move the cursor to snap to a nearby point\n\n" +
"Click the 'Close Path' button to add a new node that will close out the current path.\n\n" +
"Hold Command while dragging a node to snap in 5 point increments\n\n" +
"Double click to add a new node at the end of the path\n\n" +
"Hold down alt while adding a node to prepend the new node at the front of the route\n\n" +
"Press delete or backspace to delete the selected node\n\n" +
"NOTE: make sure you have the pan tool selected while editing paths", MessageType.None );
// update and redraw:
if( GUI.changed )
{
EditorUtility.SetDirty( _target );
Repaint();
}
}
void OnSceneGUI()
{
if( !_target.gameObject.activeSelf )
return;
// handle current selection and node addition via double click or ctrl click
if( Event.current.type == EventType.mouseDown )
{
var nearestIndex = getNearestNodeForMousePosition( Event.current.mousePosition );
_selectedNodeIndex = nearestIndex;
// double click to add
if( Event.current.clickCount > 1 )
{
var translatedPoint = HandleUtility.GUIPointToWorldRay( Event.current.mousePosition )
.GetPoint( ( _target.transform.position - Camera.current.transform.position ).magnitude );
Undo.RecordObject( _target, "Path Node Added" );
// if alt is down then prepend the node to the beginning
if( Event.current.alt )
insertNodeAtIndex( translatedPoint, 0 );
else
appendNodeAtPoint( translatedPoint );
}
}
if( _selectedNodeIndex >= 0 )
{
// shall we delete the selected node?
if( Event.current.keyCode == KeyCode.Delete || Event.current.keyCode == KeyCode.Backspace )
{
if (_target.nodes.Count > 2) {
Undo.RecordObject( _target, "Path Node Deleted" );
Event.current.Use();
removeNodeAtIndex( _selectedNodeIndex );
_selectedNodeIndex = -1;
}
}
}
if( _target.nodes.Count > 1 )
{
// allow path adjustment undo:
Undo.RecordObject( _target, "Path Vector Changed" );
// path begin and end labels or just one if the path is closed
if( Vector3.Distance( _target.nodes[0], _target.nodes[_target.nodes.Count - 1] ) == 0 )
{
Handles.Label( _target.nodes[0], " Begin and End", _labelStyle );
}
else
{
Handles.Label( _target.nodes[0], " Begin", _labelStyle );
Handles.Label( _target.nodes[_target.nodes.Count - 1], " End", _labelStyle );
}
// draw the handles, arrows and lines
drawRoute();
for( var i = 0; i < _target.nodes.Count; i++ )
{
Handles.color = _target.pathColor;
// dont label the first and last nodes
if( i > 0 && i < _target.nodes.Count - 1 )
Handles.Label( _target.nodes[i] + new Vector3( 3f, 0, 1.5f ), i.ToString(), _indexStyle );
Handles.color = Color.white;
if( _target.useStandardHandles )
{
_target.nodes[i] = Handles.PositionHandle( _target.nodes[i], Quaternion.identity );
}
else
{
// how big shall we draw the handles?
var distanceToTarget = Vector3.Distance( SceneView.lastActiveSceneView.camera.transform.position, _target.transform.position );
distanceToTarget = Mathf.Abs( distanceToTarget );
var handleSize = Mathf.Ceil( distanceToTarget / 75 );
_target.nodes[i] = Handles.FreeMoveHandle( _target.nodes[i],
Quaternion.identity,
handleSize,
new Vector3( 5, 0, 5 ),
Handles.SphereCap );
}
// should we snap? we need at least 4 nodes because we dont snap to the previous and next nodes
if( Event.current.control && _target.nodes.Count > 3 )
{
// dont even bother checking for snapping to the previous/next nodes
var index = getNearestNode( _target.nodes[i], i, i + 1, i - 1 );
var nearest = _target.nodes[index];
var distanceToNearestNode = Vector3.Distance( nearest, _target.nodes[i] );
// is it close enough to snap?
if( distanceToNearestNode <= _snapDistance )
{
GUI.changed = true;
_target.nodes[i] = nearest;
}
else if( distanceToNearestNode <= _snapDistance * 2 )
{
// show which nodes are getting close enough to snap to
var color = Color.red;
color.a = 0.3f;
Handles.color = color;
Handles.SphereCap( 0, _target.nodes[i], Quaternion.identity, _snapDistance * 2 );
//Handles.DrawWireDisc( _target.nodes[i], Vector3.up, _snapDistance );
Handles.color = Color.white;
}
}
} // end for
if( GUI.changed )
{
Repaint();
EditorUtility.SetDirty( _target );
}
} // end if
}
#endregion
#region Private methods
private void appendNodeAtPoint( Vector3 node )
{
_target.nodes.Add( node );
GUI.changed = true;
}
private void removeNodeAtIndex( int index )
{
if( index >= _target.nodes.Count || index < 0 )
return;
_target.nodes.RemoveAt( index );
GUI.changed = true;
}
private void insertNodeAtIndex( Vector3 node, int index )
{
// validate the index
if( index >= 0 && index < _target.nodes.Count )
{
_target.nodes.Insert( index, node );
GUI.changed = true;
}
}
private void drawArrowBetweenPoints( Vector3 point1, Vector3 point2 )
{
// no need to draw arrows for tiny segments
var distance = Vector3.Distance( point1, point2 );
if( distance < 40 )
return;
// we dont want to be exactly in the middle so we offset the length of the arrow
var lerpModifier = ( distance * 0.5f - 25 ) / distance;
Handles.color = _target.pathColor;
// get the midpoint between the 2 points
var dir = Vector3.Lerp( point1, point2, lerpModifier );
var quat = Quaternion.LookRotation( point2 - point1 );
Handles.ArrowCap( 0, dir, quat, 25 );
Handles.color = Color.white;
}
private int getNearestNode( Vector3 pos, params int[] excludeNodes )
{
var excludeNodesList = new System.Collections.Generic.List<int>( excludeNodes );
var bestDistance = float.MaxValue;
var index = -1;
var distance = float.MaxValue;
for( var i = _target.nodes.Count - 1; i >= 0; i-- )
{
if( excludeNodesList.Contains( i ) )
continue;
distance = Vector3.Distance( pos, _target.nodes[i] );
if( distance < bestDistance )
{
bestDistance = distance;
index = i;
}
}
return index;
}
private int getNearestNodeForMousePosition( Vector3 mousePos )
{
var bestDistance = float.MaxValue;
var index = -1;
var distance = float.MaxValue;
for( var i = _target.nodes.Count - 1; i >= 0; i-- )
{
var nodeToGui = HandleUtility.WorldToGUIPoint( _target.nodes[i] );
distance = Vector2.Distance( nodeToGui, mousePos );
if( distance < bestDistance )
{
bestDistance = distance;
index = i;
}
}
// make sure we are close enough to a node
if( bestDistance < 10 )
return index;
return -1;
}
private void closeRoute()
{
// we will use the GoSpline class to handle the dirtywork of closing the path
var path = new GoSpline( _target.nodes, _target.forceStraightLinePath );
path.closePath();
_target.nodes = path.nodes;
GUI.changed = true;
}
private void persistRouteToDisk( string path )
{
var bytes = new List<byte>();
for( int k = 0; k < _target.nodes.Count; ++k )
{
Vector3 vec = _target.nodes[k];
bytes.AddRange( System.BitConverter.GetBytes( vec.x ) );
bytes.AddRange( System.BitConverter.GetBytes( vec.y ) );
bytes.AddRange( System.BitConverter.GetBytes( vec.z ) );
}
File.WriteAllBytes( path, bytes.ToArray() );
}
private void drawRoute()
{
// if we are forcing straight lines just use this setup
if( _target.forceStraightLinePath )
{
// draw just the route here and optional arrows
for( var i = 0; i < _target.nodes.Count; i++ )
{
Handles.color = _target.pathColor;
if( i < _target.nodes.Count - 1 )
{
Handles.DrawLine( _target.nodes[i], _target.nodes[i + 1] );
drawArrowBetweenPoints( _target.nodes[i], _target.nodes[i + 1] );
}
}
}
}
#endregion
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// ServiceResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Sync.V1
{
public class ServiceResource : Resource
{
private static Request BuildFetchRequest(FetchServiceOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Sync,
"/v1/Services/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Service parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Service </returns>
public static ServiceResource Fetch(FetchServiceOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch Service parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Service </returns>
public static async System.Threading.Tasks.Task<ServiceResource> FetchAsync(FetchServiceOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathSid"> The SID of the Service resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Service </returns>
public static ServiceResource Fetch(string pathSid, ITwilioRestClient client = null)
{
var options = new FetchServiceOptions(pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathSid"> The SID of the Service resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Service </returns>
public static async System.Threading.Tasks.Task<ServiceResource> FetchAsync(string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchServiceOptions(pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteServiceOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Sync,
"/v1/Services/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Service parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Service </returns>
public static bool Delete(DeleteServiceOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete Service parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Service </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteServiceOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathSid"> The SID of the Service resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Service </returns>
public static bool Delete(string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteServiceOptions(pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathSid"> The SID of the Service resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Service </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteServiceOptions(pathSid);
return await DeleteAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateServiceOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Sync,
"/v1/Services",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Service parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Service </returns>
public static ServiceResource Create(CreateServiceOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Service parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Service </returns>
public static async System.Threading.Tasks.Task<ServiceResource> CreateAsync(CreateServiceOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="friendlyName"> A string that you assign to describe the resource </param>
/// <param name="webhookUrl"> The URL we should call when Sync objects are manipulated </param>
/// <param name="reachabilityWebhooksEnabled"> Whether the service instance should call webhook_url when client
/// endpoints connect to Sync </param>
/// <param name="aclEnabled"> Whether token identities in the Service must be granted access to Sync objects by using
/// the Permissions resource </param>
/// <param name="reachabilityDebouncingEnabled"> Whether every endpoint_disconnected event occurs after a configurable
/// delay </param>
/// <param name="reachabilityDebouncingWindow"> The reachability event delay in milliseconds </param>
/// <param name="webhooksFromRestEnabled"> Whether the Service instance should call webhook_url when the REST API is
/// used to update Sync objects </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Service </returns>
public static ServiceResource Create(string friendlyName = null,
Uri webhookUrl = null,
bool? reachabilityWebhooksEnabled = null,
bool? aclEnabled = null,
bool? reachabilityDebouncingEnabled = null,
int? reachabilityDebouncingWindow = null,
bool? webhooksFromRestEnabled = null,
ITwilioRestClient client = null)
{
var options = new CreateServiceOptions(){FriendlyName = friendlyName, WebhookUrl = webhookUrl, ReachabilityWebhooksEnabled = reachabilityWebhooksEnabled, AclEnabled = aclEnabled, ReachabilityDebouncingEnabled = reachabilityDebouncingEnabled, ReachabilityDebouncingWindow = reachabilityDebouncingWindow, WebhooksFromRestEnabled = webhooksFromRestEnabled};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="friendlyName"> A string that you assign to describe the resource </param>
/// <param name="webhookUrl"> The URL we should call when Sync objects are manipulated </param>
/// <param name="reachabilityWebhooksEnabled"> Whether the service instance should call webhook_url when client
/// endpoints connect to Sync </param>
/// <param name="aclEnabled"> Whether token identities in the Service must be granted access to Sync objects by using
/// the Permissions resource </param>
/// <param name="reachabilityDebouncingEnabled"> Whether every endpoint_disconnected event occurs after a configurable
/// delay </param>
/// <param name="reachabilityDebouncingWindow"> The reachability event delay in milliseconds </param>
/// <param name="webhooksFromRestEnabled"> Whether the Service instance should call webhook_url when the REST API is
/// used to update Sync objects </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Service </returns>
public static async System.Threading.Tasks.Task<ServiceResource> CreateAsync(string friendlyName = null,
Uri webhookUrl = null,
bool? reachabilityWebhooksEnabled = null,
bool? aclEnabled = null,
bool? reachabilityDebouncingEnabled = null,
int? reachabilityDebouncingWindow = null,
bool? webhooksFromRestEnabled = null,
ITwilioRestClient client = null)
{
var options = new CreateServiceOptions(){FriendlyName = friendlyName, WebhookUrl = webhookUrl, ReachabilityWebhooksEnabled = reachabilityWebhooksEnabled, AclEnabled = aclEnabled, ReachabilityDebouncingEnabled = reachabilityDebouncingEnabled, ReachabilityDebouncingWindow = reachabilityDebouncingWindow, WebhooksFromRestEnabled = webhooksFromRestEnabled};
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadServiceOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Sync,
"/v1/Services",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Service parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Service </returns>
public static ResourceSet<ServiceResource> Read(ReadServiceOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<ServiceResource>.FromJson("services", response.Content);
return new ResourceSet<ServiceResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Service parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Service </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ServiceResource>> ReadAsync(ReadServiceOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<ServiceResource>.FromJson("services", response.Content);
return new ResourceSet<ServiceResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Service </returns>
public static ResourceSet<ServiceResource> Read(int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadServiceOptions(){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Service </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ServiceResource>> ReadAsync(int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadServiceOptions(){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<ServiceResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<ServiceResource>.FromJson("services", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<ServiceResource> NextPage(Page<ServiceResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Sync)
);
var response = client.Request(request);
return Page<ServiceResource>.FromJson("services", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<ServiceResource> PreviousPage(Page<ServiceResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Sync)
);
var response = client.Request(request);
return Page<ServiceResource>.FromJson("services", response.Content);
}
private static Request BuildUpdateRequest(UpdateServiceOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Sync,
"/v1/Services/" + options.PathSid + "",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Service parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Service </returns>
public static ServiceResource Update(UpdateServiceOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="options"> Update Service parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Service </returns>
public static async System.Threading.Tasks.Task<ServiceResource> UpdateAsync(UpdateServiceOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// update
/// </summary>
/// <param name="pathSid"> The SID of the Service resource to update </param>
/// <param name="webhookUrl"> The URL we should call when Sync objects are manipulated </param>
/// <param name="friendlyName"> A string that you assign to describe the resource </param>
/// <param name="reachabilityWebhooksEnabled"> Whether the service instance should call webhook_url when client
/// endpoints connect to Sync </param>
/// <param name="aclEnabled"> Whether token identities in the Service must be granted access to Sync objects by using
/// the Permissions resource </param>
/// <param name="reachabilityDebouncingEnabled"> Whether every endpoint_disconnected event occurs after a configurable
/// delay </param>
/// <param name="reachabilityDebouncingWindow"> The reachability event delay in milliseconds </param>
/// <param name="webhooksFromRestEnabled"> Whether the Service instance should call webhook_url when the REST API is
/// used to update Sync objects </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Service </returns>
public static ServiceResource Update(string pathSid,
Uri webhookUrl = null,
string friendlyName = null,
bool? reachabilityWebhooksEnabled = null,
bool? aclEnabled = null,
bool? reachabilityDebouncingEnabled = null,
int? reachabilityDebouncingWindow = null,
bool? webhooksFromRestEnabled = null,
ITwilioRestClient client = null)
{
var options = new UpdateServiceOptions(pathSid){WebhookUrl = webhookUrl, FriendlyName = friendlyName, ReachabilityWebhooksEnabled = reachabilityWebhooksEnabled, AclEnabled = aclEnabled, ReachabilityDebouncingEnabled = reachabilityDebouncingEnabled, ReachabilityDebouncingWindow = reachabilityDebouncingWindow, WebhooksFromRestEnabled = webhooksFromRestEnabled};
return Update(options, client);
}
#if !NET35
/// <summary>
/// update
/// </summary>
/// <param name="pathSid"> The SID of the Service resource to update </param>
/// <param name="webhookUrl"> The URL we should call when Sync objects are manipulated </param>
/// <param name="friendlyName"> A string that you assign to describe the resource </param>
/// <param name="reachabilityWebhooksEnabled"> Whether the service instance should call webhook_url when client
/// endpoints connect to Sync </param>
/// <param name="aclEnabled"> Whether token identities in the Service must be granted access to Sync objects by using
/// the Permissions resource </param>
/// <param name="reachabilityDebouncingEnabled"> Whether every endpoint_disconnected event occurs after a configurable
/// delay </param>
/// <param name="reachabilityDebouncingWindow"> The reachability event delay in milliseconds </param>
/// <param name="webhooksFromRestEnabled"> Whether the Service instance should call webhook_url when the REST API is
/// used to update Sync objects </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Service </returns>
public static async System.Threading.Tasks.Task<ServiceResource> UpdateAsync(string pathSid,
Uri webhookUrl = null,
string friendlyName = null,
bool? reachabilityWebhooksEnabled = null,
bool? aclEnabled = null,
bool? reachabilityDebouncingEnabled = null,
int? reachabilityDebouncingWindow = null,
bool? webhooksFromRestEnabled = null,
ITwilioRestClient client = null)
{
var options = new UpdateServiceOptions(pathSid){WebhookUrl = webhookUrl, FriendlyName = friendlyName, ReachabilityWebhooksEnabled = reachabilityWebhooksEnabled, AclEnabled = aclEnabled, ReachabilityDebouncingEnabled = reachabilityDebouncingEnabled, ReachabilityDebouncingWindow = reachabilityDebouncingWindow, WebhooksFromRestEnabled = webhooksFromRestEnabled};
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a ServiceResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> ServiceResource object represented by the provided JSON </returns>
public static ServiceResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<ServiceResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// An application-defined string that uniquely identifies the resource
/// </summary>
[JsonProperty("unique_name")]
public string UniqueName { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The string that you assigned to describe the resource
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The absolute URL of the Service resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The URL we call when Sync objects are manipulated
/// </summary>
[JsonProperty("webhook_url")]
public Uri WebhookUrl { get; private set; }
/// <summary>
/// Whether the Service instance should call webhook_url when the REST API is used to update Sync objects
/// </summary>
[JsonProperty("webhooks_from_rest_enabled")]
public bool? WebhooksFromRestEnabled { get; private set; }
/// <summary>
/// Whether the service instance calls webhook_url when client endpoints connect to Sync
/// </summary>
[JsonProperty("reachability_webhooks_enabled")]
public bool? ReachabilityWebhooksEnabled { get; private set; }
/// <summary>
/// Whether token identities in the Service must be granted access to Sync objects by using the Permissions resource
/// </summary>
[JsonProperty("acl_enabled")]
public bool? AclEnabled { get; private set; }
/// <summary>
/// Whether every endpoint_disconnected event occurs after a configurable delay
/// </summary>
[JsonProperty("reachability_debouncing_enabled")]
public bool? ReachabilityDebouncingEnabled { get; private set; }
/// <summary>
/// The reachability event delay in milliseconds
/// </summary>
[JsonProperty("reachability_debouncing_window")]
public int? ReachabilityDebouncingWindow { get; private set; }
/// <summary>
/// The URLs of related resources
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private ServiceResource()
{
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Edit.Checks;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Editing.Checks
{
[TestFixture]
public class CheckMutedObjectsTest
{
private CheckMutedObjects check;
private ControlPointInfo cpi;
private const int volume_regular = 50;
private const int volume_low = 15;
private const int volume_muted = 5;
[SetUp]
public void Setup()
{
check = new CheckMutedObjects();
cpi = new LegacyControlPointInfo();
cpi.Add(0, new SampleControlPoint { SampleVolume = volume_regular });
cpi.Add(1000, new SampleControlPoint { SampleVolume = volume_low });
cpi.Add(2000, new SampleControlPoint { SampleVolume = volume_muted });
}
[Test]
public void TestNormalControlPointVolume()
{
var hitCircle = new HitCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
hitCircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertOk(new List<HitObject> { hitCircle });
}
[Test]
public void TestLowControlPointVolume()
{
var hitCircle = new HitCircle
{
StartTime = 1000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
hitCircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertLowVolume(new List<HitObject> { hitCircle });
}
[Test]
public void TestMutedControlPointVolume()
{
var hitCircle = new HitCircle
{
StartTime = 2000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
hitCircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMuted(new List<HitObject> { hitCircle });
}
[Test]
public void TestNormalSampleVolume()
{
// The sample volume should take precedence over the control point volume.
var hitCircle = new HitCircle
{
StartTime = 2000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_regular) }
};
hitCircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertOk(new List<HitObject> { hitCircle });
}
[Test]
public void TestLowSampleVolume()
{
var hitCircle = new HitCircle
{
StartTime = 2000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_low) }
};
hitCircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertLowVolume(new List<HitObject> { hitCircle });
}
[Test]
public void TestMutedSampleVolume()
{
var hitCircle = new HitCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_muted) }
};
hitCircle.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMuted(new List<HitObject> { hitCircle });
}
[Test]
public void TestNormalSampleVolumeSlider()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick", volume: volume_muted) } // Should be fine.
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 0, endTime: 500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertOk(new List<HitObject> { slider });
}
[Test]
public void TestMutedSampleVolumeSliderHead()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_muted) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick") }
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 0, endTime: 500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) } // Applies to the tail.
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMuted(new List<HitObject> { slider });
}
[Test]
public void TestMutedSampleVolumeSliderTail()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick") }
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 0, endTime: 2500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_muted) } // Applies to the tail.
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMutedPassive(new List<HitObject> { slider });
}
[Test]
public void TestMutedControlPointVolumeSliderHead()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 2000,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 2250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick") }
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 2000, endTime: 2500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL, volume: volume_regular) }
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMuted(new List<HitObject> { slider });
}
[Test]
public void TestMutedControlPointVolumeSliderTail()
{
var sliderHead = new SliderHeadCircle
{
StartTime = 0,
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
sliderHead.ApplyDefaults(cpi, new BeatmapDifficulty());
var sliderTick = new SliderTick
{
StartTime = 250,
Samples = new List<HitSampleInfo> { new HitSampleInfo("slidertick") }
};
sliderTick.ApplyDefaults(cpi, new BeatmapDifficulty());
// Ends after the 5% control point.
var slider = new MockNestableHitObject(new List<HitObject> { sliderHead, sliderTick, }, startTime: 0, endTime: 2500)
{
Samples = new List<HitSampleInfo> { new HitSampleInfo(HitSampleInfo.HIT_NORMAL) }
};
slider.ApplyDefaults(cpi, new BeatmapDifficulty());
assertMutedPassive(new List<HitObject> { slider });
}
private void assertOk(List<HitObject> hitObjects)
{
Assert.That(check.Run(getContext(hitObjects)), Is.Empty);
}
private void assertLowVolume(List<HitObject> hitObjects, int count = 1)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(count));
Assert.That(issues.All(issue => issue.Template is CheckMutedObjects.IssueTemplateLowVolumeActive));
}
private void assertMuted(List<HitObject> hitObjects, int count = 1)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(count));
Assert.That(issues.All(issue => issue.Template is CheckMutedObjects.IssueTemplateMutedActive));
}
private void assertMutedPassive(List<HitObject> hitObjects)
{
var issues = check.Run(getContext(hitObjects)).ToList();
Assert.That(issues, Has.Count.EqualTo(1));
Assert.That(issues.Any(issue => issue.Template is CheckMutedObjects.IssueTemplateMutedPassive));
}
private BeatmapVerifierContext getContext(List<HitObject> hitObjects)
{
var beatmap = new Beatmap<HitObject>
{
ControlPointInfo = cpi,
HitObjects = hitObjects
};
return new BeatmapVerifierContext(beatmap, new TestWorkingBeatmap(beatmap));
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace Hydra.Framework.Geometric
{
public class CircleObject : IMapviewObject,IPersist, ICloneable
{
#region Private Members of Circle Object
public event GraphicEvents GraphicSelected;
private float x;
private float y;
private float width;
private float height;
private bool isselected = false;
private bool isfilled=true;
private bool visible=true;
private bool showtooptip=false;
private bool iscurrent=true;
private bool islocked=false;
private bool isdisabled=false;
private bool showhandle=false;
private int handlesize=6;
private Color fillcolor=Color.Red;
private Color normalcolor= Color.Yellow;
private Color selectcolor= Color.Red;
private Color disabledcolor= Color.Gray;
private int linewidth=2;
private string xml="";
public PointF[] points;
private PointF center;
private float radius;
#endregion
#region Constructors of Circle Object
public CircleObject(float px,float py,float nx,float ny)
{
x = px;
y = py;
width = nx;
height = ny;
center=new PointF(nx/2,ny/2);
radius=nx/2;
PointF[] points={new PointF(x,y),new PointF(x+nx,y),new PointF(x+nx,y+ny),new PointF(x,y+ny)};
}
public CircleObject(PointF pt1, PointF pt2)
{
x=pt1.X;
y=pt1.Y;
width=Math.Abs(pt2.X-pt1.X);
height=Math.Abs(pt2.Y-pt1.Y);
center=new PointF(width/2,height/2);
radius=width/2;
}
public CircleObject(PointF pt1, PointF pt2, PointF pt3, PointF pt4)
{
x=pt1.X;
y=pt1.Y;
}
public CircleObject(PointF c, float r)
{
center=c;
radius=r;
x=2*(c.X-r);
y=2*(c.Y-r);
width=2*(c.X+r);
height=2*(c.Y+r);
}
public CircleObject(CircleObject co){}
#endregion
#region Properties of Circle Object
public PointF[] Vertices
{
get{return points;}
set{points=value;}
}
[Category("Colors" ),Description("The disabled graphic object will be drawn using this pen")]
public Color DisabledColor
{
get{return disabledcolor;}
set{disabledcolor=value;}
}
[Category("Colors" ),Description("The selected graphic object willbe drawn using this pen")]
public Color SelectColor
{
get{return selectcolor;}
set{selectcolor=value;}
}
[Category("Colors" ),Description("The graphic object willbe drawn using this pen")]
public Color NormalColor
{
get{return normalcolor;}
set{normalcolor=value;}
}
[DefaultValue(2),Category("AbstractStyle"),Description("The gives the line thickness of the graphic object")]
public int LineWidth
{
get{return linewidth;}
set{linewidth=value;}
}
[Category("Appearance"),Description("The graphic object will be filled with a given color or pattern")]
public bool IsFilled{get{return isfilled;}set{isfilled=value;}
}
[Category("Appearance"), Description("Determines whether the object is visible or hidden")]
public bool Visible
{
get{return visible;}
set{visible=value;}
}
[Category("Appearance"), Description("Determines whether the tooltip information to be shown or not")]
public bool ShowToopTip
{
get{return showtooptip;}
set{showtooptip=value;}
}
[Category("Appearance"), Description("Determines whether the object is in current selected legend or not")]
public bool IsCurrent
{
get{return iscurrent;}
set{iscurrent=value;}
}
[Category("Appearance"), Description("Determines whether the object is locked from the current user or not")]
public bool IsLocked
{
get{return islocked;}
set{islocked=value;}
}
[Category("Appearance"), Description("Determines whether the object is disabled from editing")]
public bool IsDisabled
{
get{return isdisabled;}
set{isdisabled=value;}
}
[Category("Appearance"), Description("Determines whether the object is in edit mode")]
public bool IsEdit
{
get{return showhandle;}
set{isselected=true;
showhandle=value;}
}
#endregion
#region Methods of ICloneable
public object Clone()
{
return new CircleObject( this );
}
#endregion
#region Methods of Circle Object
public bool IsSelected()
{
return isselected;
}
public void Select(bool m)
{
isselected = m;
}
public bool IsObjectAt(PointF pnt,float dist)
{
RectangleF rect1 = new RectangleF(x-dist,y-dist,width+dist*2,
dist*2);
if(rect1.Contains(pnt))
return true;
RectangleF rect2 = new RectangleF(x-dist,y-dist+height,
width+dist*2,dist*2);
if(rect2.Contains(pnt))
return true;
RectangleF rect3 = new RectangleF(x-dist,y-dist,
dist*2,dist*2+height);
if(rect3.Contains(pnt))
return true;
RectangleF rect4 = new RectangleF(x-dist+width,y-dist,
dist*2,dist*2+height);
if(rect4.Contains(pnt))
return true;
return false;
}
// public Rectangle BoundingBox(int i)
// {
// return new Rectangle((int)x,(int)y,(int)width,(int)height);
// }
public Rectangle BoundingBox()
{
return new Rectangle((int)x,(int)y,(int)width,(int)height);
}
public float X()
{
return x;
}
public float Y()
{
return y;
}
public void Move(PointF p)
{
x = p.X;
y = p.Y;
}
public void MoveBy(float xs,float ys)
{
x+=xs;
y+=ys;
}
public void Scale(int scale)
{
x*=scale;
y*=scale;
}
public void Rotate(float radians)
{
//
}
public void RotateAt(PointF pt)
{
//
}
public void RoateAt(Point pt)
{
//
}
public void Draw(Graphics graph,System.Drawing.Drawing2D.Matrix trans)
{
// create 0,0 and width,height points
if (visible)
{
PointF [] points = {new PointF(x,y), new PointF(x+width,y+height)};
trans.TransformPoints(points);
int w = (int)(points[1].X - points[0].X);
//int h = (int)(points[1].Y - points[0].Y);
if (isdisabled || islocked)
{
graph.DrawEllipse(new Pen(disabledcolor,linewidth),(int)points[0].X,(int)points[0].Y,w,w);
}
else if(isselected)
{
graph.DrawEllipse(new Pen(selectcolor,linewidth),(int)points[0].X,(int)points[0].Y,w,w);
if (showhandle)
{
for (int i=0; i<2; i++)
{
graph.FillRectangle(new SolidBrush(fillcolor),points[i].X-handlesize/2,points[i].Y-handlesize/2,handlesize,handlesize);
graph.DrawRectangle(new Pen(Color.Black,1),points[i].X-handlesize/2,points[i].Y-handlesize/2,handlesize,handlesize);
}
}
}
else if(isfilled)
{
graph.FillEllipse(new SolidBrush(fillcolor),(int)points[0].X,(int)points[0].Y,w,w);
graph.DrawEllipse(new Pen(normalcolor,linewidth),(int)points[0].X,(int)points[0].Y,w,w);
}
else
{
graph.DrawEllipse(new Pen(normalcolor,linewidth),(int)points[0].X,(int)points[0].Y,w,w);
}
}
}
#endregion
#region Methods of IPersist
public string ToXML
{
get{return "";}
set{xml=value;}
}
public string ToGML
{
get{return "";}
set{xml=value;}
}
public string ToVML
{
get{return "";}
set{xml=value;}
}
public string ToSVG
{
get{return "<circle cx=" + x + " cy=" + y +" width=" + width +" height=" + height + " fill=" + fillcolor + " stroke=" + normalcolor +" stroke-width=" + linewidth +"/>";}
set{xml=value;}
}
#endregion
}
}
| |
namespace WindowsFormsRichTextEditor
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.toolStrip = new System.Windows.Forms.ToolStrip();
this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel();
this.btnOpen = new System.Windows.Forms.ToolStripButton();
this.btnSave = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnGemBoxCut = new System.Windows.Forms.ToolStripButton();
this.btnGemBoxCopy = new System.Windows.Forms.ToolStripButton();
this.btnGemBoxPastePrepend = new System.Windows.Forms.ToolStripButton();
this.btnGemBoxPasteAppend = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel();
this.btnUndo = new System.Windows.Forms.ToolStripButton();
this.btnRedo = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.btnCut = new System.Windows.Forms.ToolStripButton();
this.btnCopy = new System.Windows.Forms.ToolStripButton();
this.btnPaste = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.btnBold = new System.Windows.Forms.ToolStripButton();
this.btnItalic = new System.Windows.Forms.ToolStripButton();
this.btnUnderline = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.btnIncreaseFontSize = new System.Windows.Forms.ToolStripButton();
this.btnDecreaseFontSize = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.btnToggleBullets = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.btnDecreaseIndentation = new System.Windows.Forms.ToolStripButton();
this.btnIncreaseIndentation = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.btnAlignLeft = new System.Windows.Forms.ToolStripButton();
this.btnAlignCenter = new System.Windows.Forms.ToolStripButton();
this.btnAlignRight = new System.Windows.Forms.ToolStripButton();
this.richTextBox = new System.Windows.Forms.RichTextBox();
this.toolStrip.SuspendLayout();
this.SuspendLayout();
//
// toolStrip
//
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripLabel1,
this.btnOpen,
this.btnSave,
this.toolStripSeparator1,
this.btnGemBoxCut,
this.btnGemBoxCopy,
this.btnGemBoxPastePrepend,
this.btnGemBoxPasteAppend,
this.toolStripSeparator2,
this.toolStripLabel2,
this.btnUndo,
this.btnRedo,
this.toolStripSeparator3,
this.btnCut,
this.btnCopy,
this.btnPaste,
this.toolStripSeparator4,
this.btnBold,
this.btnItalic,
this.btnUnderline,
this.toolStripSeparator5,
this.btnIncreaseFontSize,
this.btnDecreaseFontSize,
this.toolStripSeparator6,
this.btnToggleBullets,
this.toolStripSeparator7,
this.btnDecreaseIndentation,
this.btnIncreaseIndentation,
this.toolStripSeparator8,
this.btnAlignLeft,
this.btnAlignCenter,
this.btnAlignRight});
this.toolStrip.Location = new System.Drawing.Point(0, 0);
this.toolStrip.Name = "toolStrip";
this.toolStrip.Size = new System.Drawing.Size(824, 25);
this.toolStrip.TabIndex = 0;
this.toolStrip.Text = "toolStrip";
//
// toolStripLabel1
//
this.toolStripLabel1.Name = "toolStripLabel1";
this.toolStripLabel1.Size = new System.Drawing.Size(95, 22);
this.toolStripLabel1.Text = "GemBox ToolBar";
//
// btnOpen
//
this.btnOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnOpen.Image = ((System.Drawing.Image)(resources.GetObject("btnOpen.Image")));
this.btnOpen.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnOpen.Name = "btnOpen";
this.btnOpen.Size = new System.Drawing.Size(23, 22);
this.btnOpen.Text = "toolStripButton1";
this.btnOpen.ToolTipText = "Open";
this.btnOpen.Click += new System.EventHandler(this.btnOpen_Click);
//
// btnSave
//
this.btnSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnSave.Image = ((System.Drawing.Image)(resources.GetObject("btnSave.Image")));
this.btnSave.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(23, 22);
this.btnSave.Text = "toolStripButton2";
this.btnSave.ToolTipText = "Save";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// btnGemBoxCut
//
this.btnGemBoxCut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnGemBoxCut.Image = ((System.Drawing.Image)(resources.GetObject("btnGemBoxCut.Image")));
this.btnGemBoxCut.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnGemBoxCut.Name = "btnGemBoxCut";
this.btnGemBoxCut.Size = new System.Drawing.Size(23, 22);
this.btnGemBoxCut.Text = "toolStripButton1";
this.btnGemBoxCut.ToolTipText = "Cut with GemBox.Document";
this.btnGemBoxCut.Click += new System.EventHandler(this.btnGemBoxCut_Click);
//
// btnGemBoxCopy
//
this.btnGemBoxCopy.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnGemBoxCopy.Image = ((System.Drawing.Image)(resources.GetObject("btnGemBoxCopy.Image")));
this.btnGemBoxCopy.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnGemBoxCopy.Name = "btnGemBoxCopy";
this.btnGemBoxCopy.Size = new System.Drawing.Size(23, 22);
this.btnGemBoxCopy.Text = "toolStripButton1";
this.btnGemBoxCopy.ToolTipText = "Copy with GemBox.Document";
this.btnGemBoxCopy.Click += new System.EventHandler(this.btnGemBoxCopy_Click);
//
// btnGemBoxPastePrepend
//
this.btnGemBoxPastePrepend.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnGemBoxPastePrepend.Image = ((System.Drawing.Image)(resources.GetObject("btnGemBoxPastePrepend.Image")));
this.btnGemBoxPastePrepend.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnGemBoxPastePrepend.Name = "btnGemBoxPastePrepend";
this.btnGemBoxPastePrepend.Size = new System.Drawing.Size(23, 22);
this.btnGemBoxPastePrepend.Text = "toolStripButton1";
this.btnGemBoxPastePrepend.ToolTipText = "Paste prepend with GemBox.Document";
this.btnGemBoxPastePrepend.Click += new System.EventHandler(this.btnGemBoxPastePrepend_Click);
//
// btnGemBoxPasteAppend
//
this.btnGemBoxPasteAppend.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnGemBoxPasteAppend.Image = ((System.Drawing.Image)(resources.GetObject("btnGemBoxPasteAppend.Image")));
this.btnGemBoxPasteAppend.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnGemBoxPasteAppend.Name = "btnGemBoxPasteAppend";
this.btnGemBoxPasteAppend.Size = new System.Drawing.Size(23, 22);
this.btnGemBoxPasteAppend.Text = "toolStripButton1";
this.btnGemBoxPasteAppend.ToolTipText = "Paste append with GemBox.Document";
this.btnGemBoxPasteAppend.Click += new System.EventHandler(this.btnGemBoxPasteAppend_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
//
// toolStripLabel2
//
this.toolStripLabel2.Name = "toolStripLabel2";
this.toolStripLabel2.Size = new System.Drawing.Size(131, 22);
this.toolStripLabel2.Text = "Window Forms ToolBar";
//
// btnUndo
//
this.btnUndo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnUndo.Image = ((System.Drawing.Image)(resources.GetObject("btnUndo.Image")));
this.btnUndo.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnUndo.Name = "btnUndo";
this.btnUndo.Size = new System.Drawing.Size(23, 22);
this.btnUndo.Text = "toolStripButton1";
this.btnUndo.ToolTipText = "Undo";
this.btnUndo.Click += new System.EventHandler(this.btnUndo_Click);
//
// btnRedo
//
this.btnRedo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnRedo.Image = ((System.Drawing.Image)(resources.GetObject("btnRedo.Image")));
this.btnRedo.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnRedo.Name = "btnRedo";
this.btnRedo.Size = new System.Drawing.Size(23, 22);
this.btnRedo.Text = "toolStripButton1";
this.btnRedo.ToolTipText = "Redo";
this.btnRedo.Click += new System.EventHandler(this.btnRedo_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25);
//
// btnCut
//
this.btnCut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnCut.Image = ((System.Drawing.Image)(resources.GetObject("btnCut.Image")));
this.btnCut.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnCut.Name = "btnCut";
this.btnCut.Size = new System.Drawing.Size(23, 22);
this.btnCut.Text = "toolStripButton1";
this.btnCut.ToolTipText = "Cut";
this.btnCut.Click += new System.EventHandler(this.btnCut_Click);
//
// btnCopy
//
this.btnCopy.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnCopy.Image = ((System.Drawing.Image)(resources.GetObject("btnCopy.Image")));
this.btnCopy.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnCopy.Name = "btnCopy";
this.btnCopy.Size = new System.Drawing.Size(23, 22);
this.btnCopy.Text = "toolStripButton1";
this.btnCopy.ToolTipText = "Copy";
this.btnCopy.Click += new System.EventHandler(this.btnCopy_Click);
//
// btnPaste
//
this.btnPaste.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnPaste.Image = ((System.Drawing.Image)(resources.GetObject("btnPaste.Image")));
this.btnPaste.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnPaste.Name = "btnPaste";
this.btnPaste.Size = new System.Drawing.Size(23, 22);
this.btnPaste.Text = "toolStripButton1";
this.btnPaste.ToolTipText = "Paste";
this.btnPaste.Click += new System.EventHandler(this.btnPaste_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(6, 25);
//
// btnBold
//
this.btnBold.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnBold.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.btnBold.Image = ((System.Drawing.Image)(resources.GetObject("btnBold.Image")));
this.btnBold.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnBold.Name = "btnBold";
this.btnBold.Size = new System.Drawing.Size(23, 22);
this.btnBold.Text = "B";
this.btnBold.ToolTipText = "Bold";
this.btnBold.Click += new System.EventHandler(this.btnBold_Click);
//
// btnItalic
//
this.btnItalic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnItalic.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.btnItalic.Image = ((System.Drawing.Image)(resources.GetObject("btnItalic.Image")));
this.btnItalic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnItalic.Name = "btnItalic";
this.btnItalic.Size = new System.Drawing.Size(23, 22);
this.btnItalic.Text = "I";
this.btnItalic.ToolTipText = "Italic";
this.btnItalic.Click += new System.EventHandler(this.btnItalic_Click);
//
// btnUnderline
//
this.btnUnderline.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnUnderline.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.btnUnderline.Image = ((System.Drawing.Image)(resources.GetObject("btnUnderline.Image")));
this.btnUnderline.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnUnderline.Name = "btnUnderline";
this.btnUnderline.Size = new System.Drawing.Size(23, 22);
this.btnUnderline.Text = "U";
this.btnUnderline.ToolTipText = "Underline";
this.btnUnderline.Click += new System.EventHandler(this.btnUnderline_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(6, 25);
//
// btnIncreaseFontSize
//
this.btnIncreaseFontSize.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnIncreaseFontSize.Image = ((System.Drawing.Image)(resources.GetObject("btnIncreaseFontSize.Image")));
this.btnIncreaseFontSize.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnIncreaseFontSize.Name = "btnIncreaseFontSize";
this.btnIncreaseFontSize.Size = new System.Drawing.Size(23, 22);
this.btnIncreaseFontSize.Text = "toolStripButton1";
this.btnIncreaseFontSize.ToolTipText = "Increase Font Size";
this.btnIncreaseFontSize.Click += new System.EventHandler(this.btnIncreaseFontSize_Click);
//
// btnDecreaseFontSize
//
this.btnDecreaseFontSize.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnDecreaseFontSize.Image = ((System.Drawing.Image)(resources.GetObject("btnDecreaseFontSize.Image")));
this.btnDecreaseFontSize.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnDecreaseFontSize.Name = "btnDecreaseFontSize";
this.btnDecreaseFontSize.Size = new System.Drawing.Size(23, 22);
this.btnDecreaseFontSize.Text = "toolStripButton1";
this.btnDecreaseFontSize.ToolTipText = "Decrease Font Size";
this.btnDecreaseFontSize.Click += new System.EventHandler(this.btnDecreaseFontSize_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25);
//
// btnToggleBullets
//
this.btnToggleBullets.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnToggleBullets.Image = ((System.Drawing.Image)(resources.GetObject("btnToggleBullets.Image")));
this.btnToggleBullets.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnToggleBullets.Name = "btnToggleBullets";
this.btnToggleBullets.Size = new System.Drawing.Size(23, 22);
this.btnToggleBullets.Text = "toolStripButton1";
this.btnToggleBullets.ToolTipText = "Bullets";
this.btnToggleBullets.Click += new System.EventHandler(this.btnToggleBullets_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(6, 25);
//
// btnDecreaseIndentation
//
this.btnDecreaseIndentation.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnDecreaseIndentation.Image = ((System.Drawing.Image)(resources.GetObject("btnDecreaseIndentation.Image")));
this.btnDecreaseIndentation.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnDecreaseIndentation.Name = "btnDecreaseIndentation";
this.btnDecreaseIndentation.Size = new System.Drawing.Size(23, 22);
this.btnDecreaseIndentation.Text = "toolStripButton1";
this.btnDecreaseIndentation.ToolTipText = "Decrease Indentation";
this.btnDecreaseIndentation.Click += new System.EventHandler(this.btnDecreaseIndentation_Click);
//
// btnIncreaseIndentation
//
this.btnIncreaseIndentation.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnIncreaseIndentation.Image = ((System.Drawing.Image)(resources.GetObject("btnIncreaseIndentation.Image")));
this.btnIncreaseIndentation.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnIncreaseIndentation.Name = "btnIncreaseIndentation";
this.btnIncreaseIndentation.Size = new System.Drawing.Size(23, 22);
this.btnIncreaseIndentation.Text = "toolStripButton1";
this.btnIncreaseIndentation.ToolTipText = "Increase Indentation";
this.btnIncreaseIndentation.Click += new System.EventHandler(this.btnIncreaseIndentation_Click);
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
this.toolStripSeparator8.Size = new System.Drawing.Size(6, 25);
//
// btnAlignLeft
//
this.btnAlignLeft.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnAlignLeft.Image = ((System.Drawing.Image)(resources.GetObject("btnAlignLeft.Image")));
this.btnAlignLeft.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnAlignLeft.Name = "btnAlignLeft";
this.btnAlignLeft.Size = new System.Drawing.Size(23, 22);
this.btnAlignLeft.Text = "toolStripButton1";
this.btnAlignLeft.ToolTipText = "Align Left";
this.btnAlignLeft.Click += new System.EventHandler(this.btnAlignLeft_Click);
//
// btnAlignCenter
//
this.btnAlignCenter.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnAlignCenter.Image = ((System.Drawing.Image)(resources.GetObject("btnAlignCenter.Image")));
this.btnAlignCenter.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnAlignCenter.Name = "btnAlignCenter";
this.btnAlignCenter.Size = new System.Drawing.Size(23, 22);
this.btnAlignCenter.Text = "toolStripButton1";
this.btnAlignCenter.ToolTipText = "Align Center";
this.btnAlignCenter.Click += new System.EventHandler(this.btnAlignCenter_Click);
//
// btnAlignRight
//
this.btnAlignRight.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnAlignRight.Image = ((System.Drawing.Image)(resources.GetObject("btnAlignRight.Image")));
this.btnAlignRight.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnAlignRight.Name = "btnAlignRight";
this.btnAlignRight.Size = new System.Drawing.Size(23, 22);
this.btnAlignRight.Text = "toolStripButton1";
this.btnAlignRight.ToolTipText = "Align Right";
this.btnAlignRight.Click += new System.EventHandler(this.btnAlignRight_Click);
//
// richTextBox
//
this.richTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox.Location = new System.Drawing.Point(0, 25);
this.richTextBox.Name = "richTextBox";
this.richTextBox.Size = new System.Drawing.Size(824, 593);
this.richTextBox.TabIndex = 1;
this.richTextBox.Text = "";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(824, 618);
this.Controls.Add(this.richTextBox);
this.Controls.Add(this.toolStrip);
this.Name = "Form1";
this.Text = "Rich Text Editor";
this.toolStrip.ResumeLayout(false);
this.toolStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStrip toolStrip;
private System.Windows.Forms.ToolStripLabel toolStripLabel1;
private System.Windows.Forms.ToolStripButton btnOpen;
private System.Windows.Forms.ToolStripButton btnSave;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton btnGemBoxCut;
private System.Windows.Forms.ToolStripButton btnGemBoxCopy;
private System.Windows.Forms.ToolStripButton btnGemBoxPastePrepend;
private System.Windows.Forms.ToolStripButton btnGemBoxPasteAppend;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripLabel toolStripLabel2;
private System.Windows.Forms.ToolStripButton btnUndo;
private System.Windows.Forms.ToolStripButton btnRedo;
private System.Windows.Forms.ToolStripButton btnCut;
private System.Windows.Forms.ToolStripButton btnCopy;
private System.Windows.Forms.ToolStripButton btnPaste;
private System.Windows.Forms.ToolStripButton btnBold;
private System.Windows.Forms.ToolStripButton btnItalic;
private System.Windows.Forms.ToolStripButton btnUnderline;
private System.Windows.Forms.ToolStripButton btnIncreaseFontSize;
private System.Windows.Forms.ToolStripButton btnDecreaseFontSize;
private System.Windows.Forms.ToolStripButton btnToggleBullets;
private System.Windows.Forms.ToolStripButton btnDecreaseIndentation;
private System.Windows.Forms.ToolStripButton btnIncreaseIndentation;
private System.Windows.Forms.ToolStripButton btnAlignLeft;
private System.Windows.Forms.ToolStripButton btnAlignCenter;
private System.Windows.Forms.ToolStripButton btnAlignRight;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.RichTextBox richTextBox;
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// WindowsPrincipal.cs
//
// Group membership checks.
//
namespace System.Security.Principal
{
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
#if !FEATURE_CORECLR
using System.Runtime.Serialization;
using System.Security.Claims;
using System.Collections.Generic;
#endif
using System.Security.Permissions;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using Hashtable = System.Collections.Hashtable;
[Serializable]
[ComVisible(true)]
public enum WindowsBuiltInRole {
Administrator = 0x220,
User = 0x221,
Guest = 0x222,
PowerUser = 0x223,
AccountOperator = 0x224,
SystemOperator = 0x225,
PrintOperator = 0x226,
BackupOperator = 0x227,
Replicator = 0x228
}
[Serializable]
[HostProtection(SecurityInfrastructure=true)]
[ComVisible(true)]
#if !FEATURE_CORECLR
public class WindowsPrincipal : ClaimsPrincipal {
#else
public class WindowsPrincipal : IPrincipal {
#endif
private WindowsIdentity m_identity = null;
// Following 3 fields are present purely for serialization compatability with Everett: not used in Whidbey
#pragma warning disable 169
private String[] m_roles;
private Hashtable m_rolesTable;
private bool m_rolesLoaded;
#pragma warning restore 169
//
// Constructors.
//
private WindowsPrincipal () {}
public WindowsPrincipal (WindowsIdentity ntIdentity)
#if !FEATURE_CORECLR
: base (ntIdentity)
#endif
{
if (ntIdentity == null)
throw new ArgumentNullException("ntIdentity");
Contract.EndContractBlock();
m_identity = ntIdentity;
}
#if !FEATURE_CORECLR
[OnDeserialized()]
[SecuritySafeCritical]
private void OnDeserializedMethod(StreamingContext context)
{
// Here it the matrix of possible serializations
//
// Version From | Version To | ClaimsIdentities | Roles
// ============ ========== ================ ========================================================
// 4.0 4.5 None We always need to add a ClaimsIdentity
//
// 4.5 4.5 Yes There should be a ClaimsIdentity
ClaimsIdentity firstNonNullIdentity = null;
foreach (var identity in base.Identities)
{
if (identity != null)
{
firstNonNullIdentity = identity;
break;
}
}
if (firstNonNullIdentity == null)
{
base.AddIdentity(m_identity);
}
}
#endif //!FEATURE_CORECLR
//
// Properties.
//
#if !FEATURE_CORECLR
public override IIdentity Identity {
#else
public virtual IIdentity Identity {
#endif
get {
return m_identity;
}
}
//
// Public methods.
//
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Demand, ControlPrincipal = true)]
#if !FEATURE_CORECLR
public override bool IsInRole (string role) {
#else
public virtual bool IsInRole (string role) {
#endif
if (role == null || role.Length == 0)
return false;
NTAccount ntAccount = new NTAccount(role);
IdentityReferenceCollection source = new IdentityReferenceCollection(1);
source.Add(ntAccount);
IdentityReferenceCollection target = NTAccount.Translate(source, typeof(SecurityIdentifier), false);
SecurityIdentifier sid = target[0] as SecurityIdentifier;
#if !FEATURE_CORECLR
if (sid != null) {
if ( IsInRole(sid) ) {
return true;
}
}
// possible that identity has other role claims that match
return base.IsInRole(role);
#else
if (sid == null)
return false;
return IsInRole(sid);
#endif
}
#if !FEATURE_CORECLR
// <summary
// Returns all of the claims from all of the identities that are windows user claims
// found in the NT token.
// </summary>
public virtual IEnumerable<Claim> UserClaims
{
get
{
foreach (ClaimsIdentity identity in Identities)
{
WindowsIdentity wi = identity as WindowsIdentity;
if ( wi!=null)
{
foreach (Claim claim in wi.UserClaims)
{
yield return claim;
}
}
}
}
}
// <summary
// Returns all of the claims from all of the identities that are windows device claims
// found in the NT token.
// </summary>
public virtual IEnumerable<Claim> DeviceClaims
{
get
{
foreach (ClaimsIdentity identity in Identities)
{
WindowsIdentity wi = identity as WindowsIdentity;
if (wi != null)
{
foreach (Claim claim in wi.DeviceClaims)
{
yield return claim;
}
}
}
}
}
#endif
public virtual bool IsInRole (WindowsBuiltInRole role) {
if (role < WindowsBuiltInRole.Administrator || role > WindowsBuiltInRole.Replicator)
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)role), "role");
Contract.EndContractBlock();
return IsInRole((int) role);
}
public virtual bool IsInRole (int rid) {
SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority,
new int[] {Win32Native.SECURITY_BUILTIN_DOMAIN_RID, rid});
return IsInRole(sid);
}
// This methods (with a SID parameter) is more general than the 2 overloads that accept a WindowsBuiltInRole or
// a rid (as an int). It is also better from a performance standpoint than the overload that accepts a string.
// The aformentioned overloads remain in this class since we do not want to introduce a
// breaking change. However, this method should be used in all new applications and we should document this.
[System.Security.SecuritySafeCritical] // auto-generated
[ComVisible(false)]
public virtual bool IsInRole (SecurityIdentifier sid) {
if (sid == null)
throw new ArgumentNullException("sid");
Contract.EndContractBlock();
// special case the anonymous identity.
if (m_identity.AccessToken.IsInvalid)
return false;
// CheckTokenMembership expects an impersonation token
SafeAccessTokenHandle token = SafeAccessTokenHandle.InvalidHandle;
if (m_identity.ImpersonationLevel == TokenImpersonationLevel.None) {
if (!Win32Native.DuplicateTokenEx(m_identity.AccessToken,
(uint) TokenAccessLevels.Query,
IntPtr.Zero,
(uint) TokenImpersonationLevel.Identification,
(uint) TokenType.TokenImpersonation,
ref token))
throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
}
bool isMember = false;
// CheckTokenMembership will check if the SID is both present and enabled in the access token.
if (!Win32Native.CheckTokenMembership((m_identity.ImpersonationLevel != TokenImpersonationLevel.None ? m_identity.AccessToken : token),
sid.BinaryForm,
ref isMember))
throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
token.Dispose();
return isMember;
}
}
}
| |
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 IdentityManagerTest.Areas.HelpPage.ModelDescriptions;
using IdentityManagerTest.Areas.HelpPage.Models;
namespace IdentityManagerTest.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);
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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.Globalization;
using System.Net.Mail;
using System.Runtime.Serialization;
using ASC.Common.Logging;
using ASC.FederatedLogin;
using ASC.FederatedLogin.Helpers;
using ASC.FederatedLogin.LoginProviders;
using ASC.Mail.Authorization;
using ASC.Mail.Data.Imap;
using ASC.Mail.Enums;
using ASC.Mail.Utils;
using Newtonsoft.Json;
namespace ASC.Mail.Data.Contracts
{
[DataContract(Namespace = "")]
public class MailBoxData : IEquatable<MailBoxData>
{
public enum AuthProblemType
{
NoProblems = 0,
ConnectError = 1,
TooManyErrors = 2
}
public int TenantId { get; set; }
[DataMember(Name = "id")]
public int MailBoxId { get; set; }
private string _userId;
public string UserId
{
get { return _userId; }
set { _userId = value.ToLowerInvariant(); }
}
[IgnoreDataMember]
public MailAddress EMail { get; set; }
[DataMember(Name = "email")]
public string EMailView
{
get { return EMail == null ? string.Empty : EMail.ToString(); }
set
{
if (!string.IsNullOrEmpty(value))
{
EMail = new MailAddress(value);
}
}
}
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "account")]
public string Account { get; set; }
[DataMember(Name = "password")]
public string Password { get; set; }
[DataMember(Name = "server")]
public string Server { get; set; }
[DataMember(Name = "smtp_server")]
public string SmtpServer { get; set; }
public int SmtpPort
{
get
{
int port;
if (!string.IsNullOrEmpty(SmtpPortStr) && int.TryParse(SmtpPortStr, out port))
{
return port;
}
return SmtpEncryption != EncryptionType.None ? WellKnownPorts.SMTP_SSL : WellKnownPorts.SMTP;
}
set { SmtpPortStr = value.ToString(CultureInfo.InvariantCulture); }
}
[DataMember(Name = "smtp_port")]
public string SmtpPortStr { get; set; }
[DataMember(Name = "smtp_account")]
public string SmtpAccount { get; set; }
[DataMember(Name = "smtp_password")]
public string SmtpPassword { get; set; }
[DataMember(Name = "smtp_auth")]
public bool SmtpAuth
{
get { return SmtpAuthentication != SaslMechanism.None; }
}
public int Port
{
get
{
int port;
if (!string.IsNullOrEmpty(PortStr) && int.TryParse(PortStr, out port))
{
return port;
}
return Encryption != EncryptionType.None ? WellKnownPorts.POP3_SSL : WellKnownPorts.POP3;
}
set { PortStr = value.ToString(CultureInfo.InvariantCulture); }
}
[DataMember(Name = "port")]
public string PortStr { get; set; }
[DataMember(Name = "incoming_encryption_type")]
public EncryptionType Encryption { get; set; }
[DataMember(Name = "outcoming_encryption_type")]
public EncryptionType SmtpEncryption { get; set; }
[DataMember(Name = "auth_type_in")]
public SaslMechanism Authentication { get; set; }
[DataMember(Name = "auth_type_smtp")]
public SaslMechanism SmtpAuthentication { get; set; }
public long Size { get; set; }
public int MessagesCount { get; set; }
public bool Enabled { get; set; }
public bool Active { get; set; }
public bool QuotaError { get; set; }
public bool QuotaErrorChanged { get; set; }
public DateTime? AuthErrorDate { get; set; }
/// <summary>
/// This value is the initialized while testing a created mail account.
/// It is obtained from "LOGIN-DELAY" tag of CAPA command
/// Measured in seconds
/// </summary>
public int ServerLoginDelay { get; set; }
/// <summary>
/// Limiting the period of time when limiting download emails
/// Measured in seconds
/// </summary>
public Int64 MailLimitedTimeDelta { get; set; }
/// <summary>
/// Begin timestamp loading mails
/// </summary>
public DateTime MailBeginTimestamp { get; set; }
/// <summary>
/// This default value is assumed based on experiments on the following mail servers: qip.ru,
/// </summary>
// ReSharper disable InconsistentNaming
public const int DefaultServerLoginDelay = 30;
// ReSharper restore InconsistentNaming
/// <summary>
/// Limiting the period of time when limiting download emails
/// </summary>
// ReSharper disable InconsistentNaming
public const Int64 DefaultMailLimitedTimeDelta = 25920000000000; // 30 days;
// ReSharper restore InconsistentNaming
/// <summary>
/// Default begin timestamp loading emails
/// </summary>
// ReSharper disable InconsistentNaming
public const Int64 DefaultMailBeginTimestamp = 622933632000000000; // 01/01/1975 00:00:00
// ReSharper restore InconsistentNaming
public int AuthorizeTimeoutInMilliseconds
{
get { return 10000; }
}
private string _oAuthToken;
private OAuth20Token _token;
[DataMember(Name = "imap")]
public bool Imap { get; set; }
[DataMember(Name = "begin_date")]
public DateTime BeginDate { get; set; }
[DataMember(Name = "is_oauth")]
public bool IsOAuth
{
get { return !string.IsNullOrEmpty(_oAuthToken); }
}
[IgnoreDataMember]
public byte OAuthType { get; set; }
[IgnoreDataMember]
public string OAuthToken
{
get { return _oAuthToken; }
set
{
_oAuthToken = value;
try
{
_token = OAuth20Token.FromJson(_oAuthToken);
}
catch (Exception)
{
try
{
if ((AuthorizationServiceType)OAuthType != AuthorizationServiceType.Google)
return;
// If it is old refresh token then change to oAuthToken
var auth = new GoogleOAuth2Authorization(new NullLog());
_token = auth.RequestAccessToken(_oAuthToken);
AccessTokenRefreshed = true;
}
catch (Exception)
{
// skip
}
}
}
}
[IgnoreDataMember]
public string AccessToken
{
get
{
if (_token == null)
throw new Exception("Cannot create OAuth session with given token");
if (!_token.IsExpired)
return _token.AccessToken;
switch ((AuthorizationServiceType)OAuthType)
{
case AuthorizationServiceType.Google:
_token = OAuth20TokenHelper.RefreshToken<GoogleLoginProvider>(_token);
break;
case AuthorizationServiceType.None:
_token = OAuth20TokenHelper.RefreshToken("", _token);
break;
default:
_token = OAuth20TokenHelper.RefreshToken("", _token);
break;
}
OAuthToken = _token.ToJson();
AccessTokenRefreshed = true;
return _token.AccessToken;
}
}
[IgnoreDataMember]
public bool AccessTokenRefreshed { get; set; }
[DataMember(Name = "restrict")]
public bool Restrict
{
get { return !(BeginDate.Equals(MailBeginTimestamp)); }
}
public bool ImapFolderChanged { get; set; }
public bool BeginDateChanged { get; set; }
public Dictionary<string, ImapFolderUids> ImapIntervals { get; set; }
public int SmtpServerId { get; set; }
public int InServerId { get; set; }
public string ImapIntervalsJson
{
get
{
var contentJson = JsonConvert.SerializeObject(ImapIntervals);
return contentJson;
}
set
{
if (string.IsNullOrEmpty(value))
return;
try
{
ImapIntervals = MailUtil.ParseImapIntervals(value);
}
catch (Exception)
{
// skip
}
}
}
[DataMember(Name = "email_in_folder")]
public string EMailInFolder { get; set; }
[DataMember(Name = "is_teamlab")]
public bool IsTeamlab { get; set; }
public bool IsRemoved { get; set; }
[IgnoreDataMember]
public MailSignatureData MailSignature { get; set; }
[IgnoreDataMember]
public MailAutoreplyData MailAutoreply { get; set; }
[IgnoreDataMember]
public List<string> MailAutoreplyHistory { get; set; }
[IgnoreDataMember]
public List<MailAddressInfo> Aliases { get; set; }
[IgnoreDataMember]
public List<MailAddressInfo> Groups { get; set; }
[IgnoreDataMember]
public DateTime? LastSignalrNotify { get; set; }
[IgnoreDataMember]
public bool LastSignalrNotifySkipped { get; set; }
public MailBoxData()
{
ServerLoginDelay = DefaultServerLoginDelay; //This value can be changed in test mailbox connection
ImapIntervals = new Dictionary<string, ImapFolderUids>();
}
public MailBoxData(int tenant, string user, int mailboxId, string name,
MailAddress email, string account, string password, string server,
EncryptionType encryption, SaslMechanism authentication, bool imap,
string smtpAccount, string smtpPassword, string smtpServer,
EncryptionType smtpEncryption, SaslMechanism smtpAuthentication,
byte oAuthType, string oAuthToken)
{
if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user");
if (email == null) throw new ArgumentNullException("email");
if (string.IsNullOrEmpty(account)) throw new ArgumentNullException("account");
if (string.IsNullOrEmpty(server)) throw new ArgumentNullException("server");
if (!server.Contains(":")) throw new FormatException("Invalid server string format is <server:port>");
if (!smtpServer.Contains(":")) throw new FormatException("Invalid smtp server string format is <server:port>");
TenantId = tenant;
UserId = user;
MailBoxId = mailboxId;
Name = name;
EMail = email;
Account = account;
Password = password;
Server = server.Split(':')[0];
Port = int.Parse(server.Split(':')[1]);
Encryption = encryption;
Authentication = authentication;
Imap = imap;
SmtpAccount = smtpAccount;
SmtpPassword = smtpPassword;
SmtpServer = smtpServer.Split(':')[0];
SmtpPort = int.Parse(smtpServer.Split(':')[1]);
SmtpEncryption = smtpEncryption;
SmtpAuthentication = smtpAuthentication;
OAuthType = oAuthType;
OAuthToken = oAuthToken;
MailLimitedTimeDelta = DefaultMailLimitedTimeDelta;
MailBeginTimestamp = new DateTime(DefaultMailBeginTimestamp);
ServerLoginDelay = DefaultServerLoginDelay;
BeginDate = MailBeginTimestamp;
ImapIntervals = new Dictionary<string, ImapFolderUids>();
}
public override string ToString()
{
return EMail.ToString();
}
public override int GetHashCode()
{
return (TenantId.GetHashCode() + UserId.GetHashCode()) ^ EMail.Address.ToLowerInvariant().GetHashCode();
}
public bool Equals(MailBoxData other)
{
if (ReferenceEquals(this, other)) return true;
if (ReferenceEquals(null, other)) return false;
return
TenantId == other.TenantId &&
string.Compare(UserId, other.UserId, StringComparison.InvariantCultureIgnoreCase) == 0 &&
string.Compare(EMail.Address, other.EMail.Address, StringComparison.InvariantCultureIgnoreCase) == 0;
}
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj) || Equals(obj as MailBoxData);
}
//TODO: Remove this struct
public struct MailboxInfo
{
public FolderType folder_id;
public bool skip;
}
}
}
| |
// 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;
/// <summary>
/// String.Insert(Int32, String)
/// Inserts a specified instance of String at a specified index position in this instance.
/// </summary>
class StringInsert
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars)
private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars)
private const int c_MAX_LONG_STR_LEN = 65535;
public static int Main()
{
StringInsert si = new StringInsert();
TestLibrary.TestFramework.BeginTestCase("for method: System.String.Insert(Int32, string)");
if (si.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive test scenarios
public bool PosTest1() // new update 8-8-2006 Noter(v-yaduoj)
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Start index is 0";
const string c_TEST_ID = "P001";
int index;
string strSrc, strInserting;
bool condition1 = false; //Verify the inserting string
bool condition2 = false; //Verify the source string
bool expectedValue = true;
bool actualValue = false;
index = 0;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
//strSrc = "AABBB";
strInserting = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
//strInserting = "%%";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strNew = strSrc.Insert(index, strInserting);
condition1 = (0 == string.CompareOrdinal(strInserting, strNew.Substring(index, strInserting.Length)));
condition2 = (0 == string.CompareOrdinal(strSrc, strNew.Substring(0, index) + strNew.Substring(index + strInserting.Length)));
actualValue = condition1 && condition2;
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("001" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
// new update 8-8-2006 Noter(v-yaduoj)
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "Start index equals the length of instance ";
const string c_TEST_ID = "P002";
int index;
string strSrc, strInserting;
bool condition1 = false; //Verify the inserting string
bool condition2 = false; //Verify the source string
bool expectedValue = true;
bool actualValue = false;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
index = strSrc.Length;
strInserting = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strNew = strSrc.Insert(index, strInserting);
condition1 = (0 == string.CompareOrdinal(strInserting, strNew.Substring(index, strInserting.Length)));
condition2 = (0 == string.CompareOrdinal(strSrc, strNew.Substring(0, index) + strNew.Substring(index + strInserting.Length)));
actualValue = condition1 && condition2;
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("003" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
// new update 8-8-2006 Noter(v-yaduoj)
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "Start index is a value between 1 and Instance.Length - 1 ";
const string c_TEST_ID = "P003";
int index;
string strSrc, strInserting;
bool condition1 = false; //Verify the inserting string
bool condition2 = false; //Verify the source string
bool expectedValue = true;
bool actualValue = false;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
index = GetInt32(1, strSrc.Length - 1);
strInserting = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strNew = strSrc.Insert(index, strInserting);
condition1 = (0 == string.CompareOrdinal(strInserting, strNew.Substring(index, strInserting.Length)));
condition2 = (0 == string.CompareOrdinal(strSrc, strNew.Substring(0, index) + strNew.Substring(index + strInserting.Length)));
actualValue = condition1 && condition2;
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("005" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
// new update 8-8-2006 Noter(v-yaduoj)
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "String inserted is Sting.Empty";
const string c_TEST_ID = "P004";
int index;
string strSrc, strInserting;
bool condition1 = false; //Verify the inserting string
bool condition2 = false; //Verify the source string
bool expectedValue = true;
bool actualValue = false;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
index = GetInt32(0, strSrc.Length);
strInserting = String.Empty;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strNew = strSrc.Insert(index, strInserting);
condition1 = (0 == string.CompareOrdinal(strInserting, strNew.Substring(index, strInserting.Length)));
condition2 = (0 == string.CompareOrdinal(strSrc, strNew.Substring(0, index) + strNew.Substring(index + strInserting.Length)));
actualValue = condition1 && condition2;
if (expectedValue != actualValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
TestLibrary.TestFramework.LogError("007" + "TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region Negative test scenairos
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "The string inserted is null";
const string c_TEST_ID = "N001";
int index;
string strSource, str;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSource = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
index = GetInt32(0, strSource.Length);
str = null;
strSource.Insert(index, str);
TestLibrary.TestFramework.LogError("009" + "TestId-" + c_TEST_ID, "ArgumentNullException is not thrown as expected");
retVal = false;
}
catch (ArgumentNullException)
{}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "The start index is greater than the length of instance.";
const string c_TEST_ID = "N002";
int index;
string strSource, str;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSource = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
index = GetInt32(strSource.Length + 1, Int32.MaxValue);
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strSource.Insert(index, str);
TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "The start index is a negative integer";
const string c_TEST_ID = "N003";
int index;
string strSource, str;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSource = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
index = -1 * GetInt32(0, Int32.MaxValue) - 1;
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
strSource.Insert(index, str);
TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "ArgumentOutOfRangeException is not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region helper methods for generating test data
private bool GetBoolean()
{
Int32 i = this.GetInt32(1, 2);
return (i == 1) ? true : false;
}
//Get a non-negative integer between minValue and maxValue
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
private Int32 Min(Int32 i1, Int32 i2)
{
return (i1 <= i2) ? i1 : i2;
}
private Int32 Max(Int32 i1, Int32 i2)
{
return (i1 >= i2) ? i1 : i2;
}
#endregion
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Timetable Quilt Entries Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class THTQDataSet : EduHubDataSet<THTQ>
{
/// <inheritdoc />
public override string Name { get { return "THTQ"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal THTQDataSet(EduHubContext Context)
: base(Context)
{
Index_EXTRA_ROOM = new Lazy<NullDictionary<string, IReadOnlyList<THTQ>>>(() => this.ToGroupedNullDictionary(i => i.EXTRA_ROOM));
Index_EXTRA_TEACH = new Lazy<NullDictionary<string, IReadOnlyList<THTQ>>>(() => this.ToGroupedNullDictionary(i => i.EXTRA_TEACH));
Index_GKEY = new Lazy<NullDictionary<string, IReadOnlyList<THTQ>>>(() => this.ToGroupedNullDictionary(i => i.GKEY));
Index_IDENT = new Lazy<NullDictionary<int?, IReadOnlyList<THTQ>>>(() => this.ToGroupedNullDictionary(i => i.IDENT));
Index_LW_DATE = new Lazy<NullDictionary<DateTime?, IReadOnlyList<THTQ>>>(() => this.ToGroupedNullDictionary(i => i.LW_DATE));
Index_QKEY = new Lazy<Dictionary<string, IReadOnlyList<THTQ>>>(() => this.ToGroupedDictionary(i => i.QKEY));
Index_R1ROOM = new Lazy<NullDictionary<string, IReadOnlyList<THTQ>>>(() => this.ToGroupedNullDictionary(i => i.R1ROOM));
Index_R2ROOM = new Lazy<NullDictionary<string, IReadOnlyList<THTQ>>>(() => this.ToGroupedNullDictionary(i => i.R2ROOM));
Index_SUBJ = new Lazy<NullDictionary<string, IReadOnlyList<THTQ>>>(() => this.ToGroupedNullDictionary(i => i.SUBJ));
Index_T1TEACH = new Lazy<NullDictionary<string, IReadOnlyList<THTQ>>>(() => this.ToGroupedNullDictionary(i => i.T1TEACH));
Index_T2TEACH = new Lazy<NullDictionary<string, IReadOnlyList<THTQ>>>(() => this.ToGroupedNullDictionary(i => i.T2TEACH));
Index_TID = new Lazy<Dictionary<int, THTQ>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="THTQ" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="THTQ" /> fields for each CSV column header</returns>
internal override Action<THTQ, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<THTQ, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "QKEY":
mapper[i] = (e, v) => e.QKEY = v;
break;
case "GKEY":
mapper[i] = (e, v) => e.GKEY = v;
break;
case "SUBJ":
mapper[i] = (e, v) => e.SUBJ = v;
break;
case "CLASS":
mapper[i] = (e, v) => e.CLASS = v == null ? (short?)null : short.Parse(v);
break;
case "OCCUR":
mapper[i] = (e, v) => e.OCCUR = v == null ? (short?)null : short.Parse(v);
break;
case "FREQ":
mapper[i] = (e, v) => e.FREQ = v == null ? (short?)null : short.Parse(v);
break;
case "ROW_LABEL":
mapper[i] = (e, v) => e.ROW_LABEL = v;
break;
case "TIED":
mapper[i] = (e, v) => e.TIED = v == null ? (short?)null : short.Parse(v);
break;
case "IDENT":
mapper[i] = (e, v) => e.IDENT = v == null ? (int?)null : int.Parse(v);
break;
case "CLASS_SIZE":
mapper[i] = (e, v) => e.CLASS_SIZE = v == null ? (short?)null : short.Parse(v);
break;
case "T1TEACH":
mapper[i] = (e, v) => e.T1TEACH = v;
break;
case "T2TEACH":
mapper[i] = (e, v) => e.T2TEACH = v;
break;
case "R1ROOM":
mapper[i] = (e, v) => e.R1ROOM = v;
break;
case "R2ROOM":
mapper[i] = (e, v) => e.R2ROOM = v;
break;
case "RESOURCES01":
mapper[i] = (e, v) => e.RESOURCES01 = v;
break;
case "RESOURCES02":
mapper[i] = (e, v) => e.RESOURCES02 = v;
break;
case "RESOURCES03":
mapper[i] = (e, v) => e.RESOURCES03 = v;
break;
case "RESOURCES04":
mapper[i] = (e, v) => e.RESOURCES04 = v;
break;
case "RESOURCES05":
mapper[i] = (e, v) => e.RESOURCES05 = v;
break;
case "RESOURCES06":
mapper[i] = (e, v) => e.RESOURCES06 = v;
break;
case "RESOURCES07":
mapper[i] = (e, v) => e.RESOURCES07 = v;
break;
case "RESOURCES08":
mapper[i] = (e, v) => e.RESOURCES08 = v;
break;
case "RESOURCES09":
mapper[i] = (e, v) => e.RESOURCES09 = v;
break;
case "EXTRA_TEACH":
mapper[i] = (e, v) => e.EXTRA_TEACH = v;
break;
case "EXTRA_ROOM":
mapper[i] = (e, v) => e.EXTRA_ROOM = v;
break;
case "QROW":
mapper[i] = (e, v) => e.QROW = v == null ? (short?)null : short.Parse(v);
break;
case "QCOL":
mapper[i] = (e, v) => e.QCOL = v == null ? (short?)null : short.Parse(v);
break;
case "GROW":
mapper[i] = (e, v) => e.GROW = v == null ? (short?)null : short.Parse(v);
break;
case "GCOL":
mapper[i] = (e, v) => e.GCOL = v == null ? (short?)null : short.Parse(v);
break;
case "LINK":
mapper[i] = (e, v) => e.LINK = v == null ? (short?)null : short.Parse(v);
break;
case "COMPOSITE":
mapper[i] = (e, v) => e.COMPOSITE = v == null ? (short?)null : short.Parse(v);
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="THTQ" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="THTQ" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="THTQ" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{THTQ}"/> of entities</returns>
internal override IEnumerable<THTQ> ApplyDeltaEntities(IEnumerable<THTQ> Entities, List<THTQ> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.QKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.QKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<THTQ>>> Index_EXTRA_ROOM;
private Lazy<NullDictionary<string, IReadOnlyList<THTQ>>> Index_EXTRA_TEACH;
private Lazy<NullDictionary<string, IReadOnlyList<THTQ>>> Index_GKEY;
private Lazy<NullDictionary<int?, IReadOnlyList<THTQ>>> Index_IDENT;
private Lazy<NullDictionary<DateTime?, IReadOnlyList<THTQ>>> Index_LW_DATE;
private Lazy<Dictionary<string, IReadOnlyList<THTQ>>> Index_QKEY;
private Lazy<NullDictionary<string, IReadOnlyList<THTQ>>> Index_R1ROOM;
private Lazy<NullDictionary<string, IReadOnlyList<THTQ>>> Index_R2ROOM;
private Lazy<NullDictionary<string, IReadOnlyList<THTQ>>> Index_SUBJ;
private Lazy<NullDictionary<string, IReadOnlyList<THTQ>>> Index_T1TEACH;
private Lazy<NullDictionary<string, IReadOnlyList<THTQ>>> Index_T2TEACH;
private Lazy<Dictionary<int, THTQ>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find THTQ by EXTRA_ROOM field
/// </summary>
/// <param name="EXTRA_ROOM">EXTRA_ROOM value used to find THTQ</param>
/// <returns>List of related THTQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> FindByEXTRA_ROOM(string EXTRA_ROOM)
{
return Index_EXTRA_ROOM.Value[EXTRA_ROOM];
}
/// <summary>
/// Attempt to find THTQ by EXTRA_ROOM field
/// </summary>
/// <param name="EXTRA_ROOM">EXTRA_ROOM value used to find THTQ</param>
/// <param name="Value">List of related THTQ entities</param>
/// <returns>True if the list of related THTQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByEXTRA_ROOM(string EXTRA_ROOM, out IReadOnlyList<THTQ> Value)
{
return Index_EXTRA_ROOM.Value.TryGetValue(EXTRA_ROOM, out Value);
}
/// <summary>
/// Attempt to find THTQ by EXTRA_ROOM field
/// </summary>
/// <param name="EXTRA_ROOM">EXTRA_ROOM value used to find THTQ</param>
/// <returns>List of related THTQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> TryFindByEXTRA_ROOM(string EXTRA_ROOM)
{
IReadOnlyList<THTQ> value;
if (Index_EXTRA_ROOM.Value.TryGetValue(EXTRA_ROOM, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find THTQ by EXTRA_TEACH field
/// </summary>
/// <param name="EXTRA_TEACH">EXTRA_TEACH value used to find THTQ</param>
/// <returns>List of related THTQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> FindByEXTRA_TEACH(string EXTRA_TEACH)
{
return Index_EXTRA_TEACH.Value[EXTRA_TEACH];
}
/// <summary>
/// Attempt to find THTQ by EXTRA_TEACH field
/// </summary>
/// <param name="EXTRA_TEACH">EXTRA_TEACH value used to find THTQ</param>
/// <param name="Value">List of related THTQ entities</param>
/// <returns>True if the list of related THTQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByEXTRA_TEACH(string EXTRA_TEACH, out IReadOnlyList<THTQ> Value)
{
return Index_EXTRA_TEACH.Value.TryGetValue(EXTRA_TEACH, out Value);
}
/// <summary>
/// Attempt to find THTQ by EXTRA_TEACH field
/// </summary>
/// <param name="EXTRA_TEACH">EXTRA_TEACH value used to find THTQ</param>
/// <returns>List of related THTQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> TryFindByEXTRA_TEACH(string EXTRA_TEACH)
{
IReadOnlyList<THTQ> value;
if (Index_EXTRA_TEACH.Value.TryGetValue(EXTRA_TEACH, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find THTQ by GKEY field
/// </summary>
/// <param name="GKEY">GKEY value used to find THTQ</param>
/// <returns>List of related THTQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> FindByGKEY(string GKEY)
{
return Index_GKEY.Value[GKEY];
}
/// <summary>
/// Attempt to find THTQ by GKEY field
/// </summary>
/// <param name="GKEY">GKEY value used to find THTQ</param>
/// <param name="Value">List of related THTQ entities</param>
/// <returns>True if the list of related THTQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByGKEY(string GKEY, out IReadOnlyList<THTQ> Value)
{
return Index_GKEY.Value.TryGetValue(GKEY, out Value);
}
/// <summary>
/// Attempt to find THTQ by GKEY field
/// </summary>
/// <param name="GKEY">GKEY value used to find THTQ</param>
/// <returns>List of related THTQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> TryFindByGKEY(string GKEY)
{
IReadOnlyList<THTQ> value;
if (Index_GKEY.Value.TryGetValue(GKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find THTQ by IDENT field
/// </summary>
/// <param name="IDENT">IDENT value used to find THTQ</param>
/// <returns>List of related THTQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> FindByIDENT(int? IDENT)
{
return Index_IDENT.Value[IDENT];
}
/// <summary>
/// Attempt to find THTQ by IDENT field
/// </summary>
/// <param name="IDENT">IDENT value used to find THTQ</param>
/// <param name="Value">List of related THTQ entities</param>
/// <returns>True if the list of related THTQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByIDENT(int? IDENT, out IReadOnlyList<THTQ> Value)
{
return Index_IDENT.Value.TryGetValue(IDENT, out Value);
}
/// <summary>
/// Attempt to find THTQ by IDENT field
/// </summary>
/// <param name="IDENT">IDENT value used to find THTQ</param>
/// <returns>List of related THTQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> TryFindByIDENT(int? IDENT)
{
IReadOnlyList<THTQ> value;
if (Index_IDENT.Value.TryGetValue(IDENT, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find THTQ by LW_DATE field
/// </summary>
/// <param name="LW_DATE">LW_DATE value used to find THTQ</param>
/// <returns>List of related THTQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> FindByLW_DATE(DateTime? LW_DATE)
{
return Index_LW_DATE.Value[LW_DATE];
}
/// <summary>
/// Attempt to find THTQ by LW_DATE field
/// </summary>
/// <param name="LW_DATE">LW_DATE value used to find THTQ</param>
/// <param name="Value">List of related THTQ entities</param>
/// <returns>True if the list of related THTQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByLW_DATE(DateTime? LW_DATE, out IReadOnlyList<THTQ> Value)
{
return Index_LW_DATE.Value.TryGetValue(LW_DATE, out Value);
}
/// <summary>
/// Attempt to find THTQ by LW_DATE field
/// </summary>
/// <param name="LW_DATE">LW_DATE value used to find THTQ</param>
/// <returns>List of related THTQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> TryFindByLW_DATE(DateTime? LW_DATE)
{
IReadOnlyList<THTQ> value;
if (Index_LW_DATE.Value.TryGetValue(LW_DATE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find THTQ by QKEY field
/// </summary>
/// <param name="QKEY">QKEY value used to find THTQ</param>
/// <returns>List of related THTQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> FindByQKEY(string QKEY)
{
return Index_QKEY.Value[QKEY];
}
/// <summary>
/// Attempt to find THTQ by QKEY field
/// </summary>
/// <param name="QKEY">QKEY value used to find THTQ</param>
/// <param name="Value">List of related THTQ entities</param>
/// <returns>True if the list of related THTQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByQKEY(string QKEY, out IReadOnlyList<THTQ> Value)
{
return Index_QKEY.Value.TryGetValue(QKEY, out Value);
}
/// <summary>
/// Attempt to find THTQ by QKEY field
/// </summary>
/// <param name="QKEY">QKEY value used to find THTQ</param>
/// <returns>List of related THTQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> TryFindByQKEY(string QKEY)
{
IReadOnlyList<THTQ> value;
if (Index_QKEY.Value.TryGetValue(QKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find THTQ by R1ROOM field
/// </summary>
/// <param name="R1ROOM">R1ROOM value used to find THTQ</param>
/// <returns>List of related THTQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> FindByR1ROOM(string R1ROOM)
{
return Index_R1ROOM.Value[R1ROOM];
}
/// <summary>
/// Attempt to find THTQ by R1ROOM field
/// </summary>
/// <param name="R1ROOM">R1ROOM value used to find THTQ</param>
/// <param name="Value">List of related THTQ entities</param>
/// <returns>True if the list of related THTQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByR1ROOM(string R1ROOM, out IReadOnlyList<THTQ> Value)
{
return Index_R1ROOM.Value.TryGetValue(R1ROOM, out Value);
}
/// <summary>
/// Attempt to find THTQ by R1ROOM field
/// </summary>
/// <param name="R1ROOM">R1ROOM value used to find THTQ</param>
/// <returns>List of related THTQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> TryFindByR1ROOM(string R1ROOM)
{
IReadOnlyList<THTQ> value;
if (Index_R1ROOM.Value.TryGetValue(R1ROOM, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find THTQ by R2ROOM field
/// </summary>
/// <param name="R2ROOM">R2ROOM value used to find THTQ</param>
/// <returns>List of related THTQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> FindByR2ROOM(string R2ROOM)
{
return Index_R2ROOM.Value[R2ROOM];
}
/// <summary>
/// Attempt to find THTQ by R2ROOM field
/// </summary>
/// <param name="R2ROOM">R2ROOM value used to find THTQ</param>
/// <param name="Value">List of related THTQ entities</param>
/// <returns>True if the list of related THTQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByR2ROOM(string R2ROOM, out IReadOnlyList<THTQ> Value)
{
return Index_R2ROOM.Value.TryGetValue(R2ROOM, out Value);
}
/// <summary>
/// Attempt to find THTQ by R2ROOM field
/// </summary>
/// <param name="R2ROOM">R2ROOM value used to find THTQ</param>
/// <returns>List of related THTQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> TryFindByR2ROOM(string R2ROOM)
{
IReadOnlyList<THTQ> value;
if (Index_R2ROOM.Value.TryGetValue(R2ROOM, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find THTQ by SUBJ field
/// </summary>
/// <param name="SUBJ">SUBJ value used to find THTQ</param>
/// <returns>List of related THTQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> FindBySUBJ(string SUBJ)
{
return Index_SUBJ.Value[SUBJ];
}
/// <summary>
/// Attempt to find THTQ by SUBJ field
/// </summary>
/// <param name="SUBJ">SUBJ value used to find THTQ</param>
/// <param name="Value">List of related THTQ entities</param>
/// <returns>True if the list of related THTQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySUBJ(string SUBJ, out IReadOnlyList<THTQ> Value)
{
return Index_SUBJ.Value.TryGetValue(SUBJ, out Value);
}
/// <summary>
/// Attempt to find THTQ by SUBJ field
/// </summary>
/// <param name="SUBJ">SUBJ value used to find THTQ</param>
/// <returns>List of related THTQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> TryFindBySUBJ(string SUBJ)
{
IReadOnlyList<THTQ> value;
if (Index_SUBJ.Value.TryGetValue(SUBJ, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find THTQ by T1TEACH field
/// </summary>
/// <param name="T1TEACH">T1TEACH value used to find THTQ</param>
/// <returns>List of related THTQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> FindByT1TEACH(string T1TEACH)
{
return Index_T1TEACH.Value[T1TEACH];
}
/// <summary>
/// Attempt to find THTQ by T1TEACH field
/// </summary>
/// <param name="T1TEACH">T1TEACH value used to find THTQ</param>
/// <param name="Value">List of related THTQ entities</param>
/// <returns>True if the list of related THTQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByT1TEACH(string T1TEACH, out IReadOnlyList<THTQ> Value)
{
return Index_T1TEACH.Value.TryGetValue(T1TEACH, out Value);
}
/// <summary>
/// Attempt to find THTQ by T1TEACH field
/// </summary>
/// <param name="T1TEACH">T1TEACH value used to find THTQ</param>
/// <returns>List of related THTQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> TryFindByT1TEACH(string T1TEACH)
{
IReadOnlyList<THTQ> value;
if (Index_T1TEACH.Value.TryGetValue(T1TEACH, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find THTQ by T2TEACH field
/// </summary>
/// <param name="T2TEACH">T2TEACH value used to find THTQ</param>
/// <returns>List of related THTQ entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> FindByT2TEACH(string T2TEACH)
{
return Index_T2TEACH.Value[T2TEACH];
}
/// <summary>
/// Attempt to find THTQ by T2TEACH field
/// </summary>
/// <param name="T2TEACH">T2TEACH value used to find THTQ</param>
/// <param name="Value">List of related THTQ entities</param>
/// <returns>True if the list of related THTQ entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByT2TEACH(string T2TEACH, out IReadOnlyList<THTQ> Value)
{
return Index_T2TEACH.Value.TryGetValue(T2TEACH, out Value);
}
/// <summary>
/// Attempt to find THTQ by T2TEACH field
/// </summary>
/// <param name="T2TEACH">T2TEACH value used to find THTQ</param>
/// <returns>List of related THTQ entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<THTQ> TryFindByT2TEACH(string T2TEACH)
{
IReadOnlyList<THTQ> value;
if (Index_T2TEACH.Value.TryGetValue(T2TEACH, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find THTQ by TID field
/// </summary>
/// <param name="TID">TID value used to find THTQ</param>
/// <returns>Related THTQ entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public THTQ FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find THTQ by TID field
/// </summary>
/// <param name="TID">TID value used to find THTQ</param>
/// <param name="Value">Related THTQ entity</param>
/// <returns>True if the related THTQ entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out THTQ Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find THTQ by TID field
/// </summary>
/// <param name="TID">TID value used to find THTQ</param>
/// <returns>Related THTQ entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public THTQ TryFindByTID(int TID)
{
THTQ value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a THTQ table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[THTQ](
[TID] int IDENTITY NOT NULL,
[QKEY] varchar(8) NOT NULL,
[GKEY] varchar(8) NULL,
[SUBJ] varchar(5) NULL,
[CLASS] smallint NULL,
[OCCUR] smallint NULL,
[FREQ] smallint NULL,
[ROW_LABEL] varchar(6) NULL,
[TIED] smallint NULL,
[IDENT] int NULL,
[CLASS_SIZE] smallint NULL,
[T1TEACH] varchar(4) NULL,
[T2TEACH] varchar(4) NULL,
[R1ROOM] varchar(4) NULL,
[R2ROOM] varchar(4) NULL,
[RESOURCES01] varchar(4) NULL,
[RESOURCES02] varchar(4) NULL,
[RESOURCES03] varchar(4) NULL,
[RESOURCES04] varchar(4) NULL,
[RESOURCES05] varchar(4) NULL,
[RESOURCES06] varchar(4) NULL,
[RESOURCES07] varchar(4) NULL,
[RESOURCES08] varchar(4) NULL,
[RESOURCES09] varchar(4) NULL,
[EXTRA_TEACH] varchar(4) NULL,
[EXTRA_ROOM] varchar(4) NULL,
[QROW] smallint NULL,
[QCOL] smallint NULL,
[GROW] smallint NULL,
[GCOL] smallint NULL,
[LINK] smallint NULL,
[COMPOSITE] smallint NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [THTQ_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE NONCLUSTERED INDEX [THTQ_Index_EXTRA_ROOM] ON [dbo].[THTQ]
(
[EXTRA_ROOM] ASC
);
CREATE NONCLUSTERED INDEX [THTQ_Index_EXTRA_TEACH] ON [dbo].[THTQ]
(
[EXTRA_TEACH] ASC
);
CREATE NONCLUSTERED INDEX [THTQ_Index_GKEY] ON [dbo].[THTQ]
(
[GKEY] ASC
);
CREATE NONCLUSTERED INDEX [THTQ_Index_IDENT] ON [dbo].[THTQ]
(
[IDENT] ASC
);
CREATE NONCLUSTERED INDEX [THTQ_Index_LW_DATE] ON [dbo].[THTQ]
(
[LW_DATE] ASC
);
CREATE CLUSTERED INDEX [THTQ_Index_QKEY] ON [dbo].[THTQ]
(
[QKEY] ASC
);
CREATE NONCLUSTERED INDEX [THTQ_Index_R1ROOM] ON [dbo].[THTQ]
(
[R1ROOM] ASC
);
CREATE NONCLUSTERED INDEX [THTQ_Index_R2ROOM] ON [dbo].[THTQ]
(
[R2ROOM] ASC
);
CREATE NONCLUSTERED INDEX [THTQ_Index_SUBJ] ON [dbo].[THTQ]
(
[SUBJ] ASC
);
CREATE NONCLUSTERED INDEX [THTQ_Index_T1TEACH] ON [dbo].[THTQ]
(
[T1TEACH] ASC
);
CREATE NONCLUSTERED INDEX [THTQ_Index_T2TEACH] ON [dbo].[THTQ]
(
[T2TEACH] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_EXTRA_ROOM')
ALTER INDEX [THTQ_Index_EXTRA_ROOM] ON [dbo].[THTQ] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_EXTRA_TEACH')
ALTER INDEX [THTQ_Index_EXTRA_TEACH] ON [dbo].[THTQ] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_GKEY')
ALTER INDEX [THTQ_Index_GKEY] ON [dbo].[THTQ] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_IDENT')
ALTER INDEX [THTQ_Index_IDENT] ON [dbo].[THTQ] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_LW_DATE')
ALTER INDEX [THTQ_Index_LW_DATE] ON [dbo].[THTQ] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_R1ROOM')
ALTER INDEX [THTQ_Index_R1ROOM] ON [dbo].[THTQ] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_R2ROOM')
ALTER INDEX [THTQ_Index_R2ROOM] ON [dbo].[THTQ] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_SUBJ')
ALTER INDEX [THTQ_Index_SUBJ] ON [dbo].[THTQ] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_T1TEACH')
ALTER INDEX [THTQ_Index_T1TEACH] ON [dbo].[THTQ] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_T2TEACH')
ALTER INDEX [THTQ_Index_T2TEACH] ON [dbo].[THTQ] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_TID')
ALTER INDEX [THTQ_Index_TID] ON [dbo].[THTQ] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_EXTRA_ROOM')
ALTER INDEX [THTQ_Index_EXTRA_ROOM] ON [dbo].[THTQ] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_EXTRA_TEACH')
ALTER INDEX [THTQ_Index_EXTRA_TEACH] ON [dbo].[THTQ] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_GKEY')
ALTER INDEX [THTQ_Index_GKEY] ON [dbo].[THTQ] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_IDENT')
ALTER INDEX [THTQ_Index_IDENT] ON [dbo].[THTQ] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_LW_DATE')
ALTER INDEX [THTQ_Index_LW_DATE] ON [dbo].[THTQ] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_R1ROOM')
ALTER INDEX [THTQ_Index_R1ROOM] ON [dbo].[THTQ] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_R2ROOM')
ALTER INDEX [THTQ_Index_R2ROOM] ON [dbo].[THTQ] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_SUBJ')
ALTER INDEX [THTQ_Index_SUBJ] ON [dbo].[THTQ] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_T1TEACH')
ALTER INDEX [THTQ_Index_T1TEACH] ON [dbo].[THTQ] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_T2TEACH')
ALTER INDEX [THTQ_Index_T2TEACH] ON [dbo].[THTQ] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[THTQ]') AND name = N'THTQ_Index_TID')
ALTER INDEX [THTQ_Index_TID] ON [dbo].[THTQ] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="THTQ"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="THTQ"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<THTQ> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[THTQ] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the THTQ data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the THTQ data set</returns>
public override EduHubDataSetDataReader<THTQ> GetDataSetDataReader()
{
return new THTQDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the THTQ data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the THTQ data set</returns>
public override EduHubDataSetDataReader<THTQ> GetDataSetDataReader(List<THTQ> Entities)
{
return new THTQDataReader(new EduHubDataSetLoadedReader<THTQ>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class THTQDataReader : EduHubDataSetDataReader<THTQ>
{
public THTQDataReader(IEduHubDataSetReader<THTQ> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 35; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // QKEY
return Current.QKEY;
case 2: // GKEY
return Current.GKEY;
case 3: // SUBJ
return Current.SUBJ;
case 4: // CLASS
return Current.CLASS;
case 5: // OCCUR
return Current.OCCUR;
case 6: // FREQ
return Current.FREQ;
case 7: // ROW_LABEL
return Current.ROW_LABEL;
case 8: // TIED
return Current.TIED;
case 9: // IDENT
return Current.IDENT;
case 10: // CLASS_SIZE
return Current.CLASS_SIZE;
case 11: // T1TEACH
return Current.T1TEACH;
case 12: // T2TEACH
return Current.T2TEACH;
case 13: // R1ROOM
return Current.R1ROOM;
case 14: // R2ROOM
return Current.R2ROOM;
case 15: // RESOURCES01
return Current.RESOURCES01;
case 16: // RESOURCES02
return Current.RESOURCES02;
case 17: // RESOURCES03
return Current.RESOURCES03;
case 18: // RESOURCES04
return Current.RESOURCES04;
case 19: // RESOURCES05
return Current.RESOURCES05;
case 20: // RESOURCES06
return Current.RESOURCES06;
case 21: // RESOURCES07
return Current.RESOURCES07;
case 22: // RESOURCES08
return Current.RESOURCES08;
case 23: // RESOURCES09
return Current.RESOURCES09;
case 24: // EXTRA_TEACH
return Current.EXTRA_TEACH;
case 25: // EXTRA_ROOM
return Current.EXTRA_ROOM;
case 26: // QROW
return Current.QROW;
case 27: // QCOL
return Current.QCOL;
case 28: // GROW
return Current.GROW;
case 29: // GCOL
return Current.GCOL;
case 30: // LINK
return Current.LINK;
case 31: // COMPOSITE
return Current.COMPOSITE;
case 32: // LW_DATE
return Current.LW_DATE;
case 33: // LW_TIME
return Current.LW_TIME;
case 34: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // GKEY
return Current.GKEY == null;
case 3: // SUBJ
return Current.SUBJ == null;
case 4: // CLASS
return Current.CLASS == null;
case 5: // OCCUR
return Current.OCCUR == null;
case 6: // FREQ
return Current.FREQ == null;
case 7: // ROW_LABEL
return Current.ROW_LABEL == null;
case 8: // TIED
return Current.TIED == null;
case 9: // IDENT
return Current.IDENT == null;
case 10: // CLASS_SIZE
return Current.CLASS_SIZE == null;
case 11: // T1TEACH
return Current.T1TEACH == null;
case 12: // T2TEACH
return Current.T2TEACH == null;
case 13: // R1ROOM
return Current.R1ROOM == null;
case 14: // R2ROOM
return Current.R2ROOM == null;
case 15: // RESOURCES01
return Current.RESOURCES01 == null;
case 16: // RESOURCES02
return Current.RESOURCES02 == null;
case 17: // RESOURCES03
return Current.RESOURCES03 == null;
case 18: // RESOURCES04
return Current.RESOURCES04 == null;
case 19: // RESOURCES05
return Current.RESOURCES05 == null;
case 20: // RESOURCES06
return Current.RESOURCES06 == null;
case 21: // RESOURCES07
return Current.RESOURCES07 == null;
case 22: // RESOURCES08
return Current.RESOURCES08 == null;
case 23: // RESOURCES09
return Current.RESOURCES09 == null;
case 24: // EXTRA_TEACH
return Current.EXTRA_TEACH == null;
case 25: // EXTRA_ROOM
return Current.EXTRA_ROOM == null;
case 26: // QROW
return Current.QROW == null;
case 27: // QCOL
return Current.QCOL == null;
case 28: // GROW
return Current.GROW == null;
case 29: // GCOL
return Current.GCOL == null;
case 30: // LINK
return Current.LINK == null;
case 31: // COMPOSITE
return Current.COMPOSITE == null;
case 32: // LW_DATE
return Current.LW_DATE == null;
case 33: // LW_TIME
return Current.LW_TIME == null;
case 34: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // QKEY
return "QKEY";
case 2: // GKEY
return "GKEY";
case 3: // SUBJ
return "SUBJ";
case 4: // CLASS
return "CLASS";
case 5: // OCCUR
return "OCCUR";
case 6: // FREQ
return "FREQ";
case 7: // ROW_LABEL
return "ROW_LABEL";
case 8: // TIED
return "TIED";
case 9: // IDENT
return "IDENT";
case 10: // CLASS_SIZE
return "CLASS_SIZE";
case 11: // T1TEACH
return "T1TEACH";
case 12: // T2TEACH
return "T2TEACH";
case 13: // R1ROOM
return "R1ROOM";
case 14: // R2ROOM
return "R2ROOM";
case 15: // RESOURCES01
return "RESOURCES01";
case 16: // RESOURCES02
return "RESOURCES02";
case 17: // RESOURCES03
return "RESOURCES03";
case 18: // RESOURCES04
return "RESOURCES04";
case 19: // RESOURCES05
return "RESOURCES05";
case 20: // RESOURCES06
return "RESOURCES06";
case 21: // RESOURCES07
return "RESOURCES07";
case 22: // RESOURCES08
return "RESOURCES08";
case 23: // RESOURCES09
return "RESOURCES09";
case 24: // EXTRA_TEACH
return "EXTRA_TEACH";
case 25: // EXTRA_ROOM
return "EXTRA_ROOM";
case 26: // QROW
return "QROW";
case 27: // QCOL
return "QCOL";
case 28: // GROW
return "GROW";
case 29: // GCOL
return "GCOL";
case 30: // LINK
return "LINK";
case 31: // COMPOSITE
return "COMPOSITE";
case 32: // LW_DATE
return "LW_DATE";
case 33: // LW_TIME
return "LW_TIME";
case 34: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "QKEY":
return 1;
case "GKEY":
return 2;
case "SUBJ":
return 3;
case "CLASS":
return 4;
case "OCCUR":
return 5;
case "FREQ":
return 6;
case "ROW_LABEL":
return 7;
case "TIED":
return 8;
case "IDENT":
return 9;
case "CLASS_SIZE":
return 10;
case "T1TEACH":
return 11;
case "T2TEACH":
return 12;
case "R1ROOM":
return 13;
case "R2ROOM":
return 14;
case "RESOURCES01":
return 15;
case "RESOURCES02":
return 16;
case "RESOURCES03":
return 17;
case "RESOURCES04":
return 18;
case "RESOURCES05":
return 19;
case "RESOURCES06":
return 20;
case "RESOURCES07":
return 21;
case "RESOURCES08":
return 22;
case "RESOURCES09":
return 23;
case "EXTRA_TEACH":
return 24;
case "EXTRA_ROOM":
return 25;
case "QROW":
return 26;
case "QCOL":
return 27;
case "GROW":
return 28;
case "GCOL":
return 29;
case "LINK":
return 30;
case "COMPOSITE":
return 31;
case "LW_DATE":
return 32;
case "LW_TIME":
return 33;
case "LW_USER":
return 34;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BlendVariableDouble()
{
var test = new SimpleTernaryOpTest__BlendVariableDouble();
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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__BlendVariableDouble
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int Op2ElementCount = VectorSize / sizeof(Double);
private const int Op3ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Double[] _data3 = new Double[Op3ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private static Vector128<Double> _clsVar3;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private Vector128<Double> _fld3;
private SimpleTernaryOpTest__DataTable<Double, Double, Double, Double> _dataTable;
static SimpleTernaryOpTest__BlendVariableDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (double)(((i % 2) == 0) ? -0.0 : 1.0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar3), ref Unsafe.As<Double, byte>(ref _data3[0]), VectorSize);
}
public SimpleTernaryOpTest__BlendVariableDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (double)(((i % 2) == 0) ? -0.0 : 1.0); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld3), ref Unsafe.As<Double, byte>(ref _data3[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (double)(((i % 2) == 0) ? -0.0 : 1.0); }
_dataTable = new SimpleTernaryOpTest__DataTable<Double, Double, Double, Double>(_data1, _data2, _data3, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.BlendVariable(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.BlendVariable(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.BlendVariable(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.BlendVariable), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.BlendVariable(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var secondOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var thirdOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArray3Ptr);
var result = Sse41.BlendVariable(firstOp, secondOp, thirdOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, secondOp, thirdOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var secondOp = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var thirdOp = Sse2.LoadVector128((Double*)(_dataTable.inArray3Ptr));
var result = Sse41.BlendVariable(firstOp, secondOp, thirdOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, secondOp, thirdOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var secondOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var thirdOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray3Ptr));
var result = Sse41.BlendVariable(firstOp, secondOp, thirdOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, secondOp, thirdOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleTernaryOpTest__BlendVariableDouble();
var result = Sse41.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> firstOp, Vector128<Double> secondOp, Vector128<Double> thirdOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), firstOp);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), secondOp);
Unsafe.Write(Unsafe.AsPointer(ref inArray3[0]), thirdOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* firstOp, void* secondOp, void* thirdOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] inArray3 = new Double[Op3ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(thirdOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] secondOp, Double[] thirdOp, Double[] result, [CallerMemberName] string method = "")
{
if (((BitConverter.DoubleToInt64Bits(thirdOp[0]) >> 63) & 1) == 1 ? BitConverter.DoubleToInt64Bits(secondOp[0]) != BitConverter.DoubleToInt64Bits(result[0]) : BitConverter.DoubleToInt64Bits(firstOp[0]) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (((BitConverter.DoubleToInt64Bits(thirdOp[i]) >> 63) & 1) == 1 ? BitConverter.DoubleToInt64Bits(secondOp[i]) != BitConverter.DoubleToInt64Bits(result[i]) : BitConverter.DoubleToInt64Bits(firstOp[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.BlendVariable)}<Double>(Vector128<Double>, Vector128<Double>, Vector128<Double>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" secondOp: ({string.Join(", ", secondOp)})");
Console.WriteLine($" thirdOp: ({string.Join(", ", thirdOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using Funq;
using NServiceKit.ServiceHost;
namespace NServiceKit.ServiceInterface.Testing
{
/// <summary>A mock HTTP request.</summary>
public class MockHttpRequest : IHttpRequest
{
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Testing.MockHttpRequest class.</summary>
public MockHttpRequest()
{
this.FormData = new NameValueCollection();
this.Headers = new NameValueCollection();
this.QueryString = new NameValueCollection();
this.Cookies = new Dictionary<string, Cookie>();
this.Items = new Dictionary<string, object>();
this.Container = new Container();
}
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Testing.MockHttpRequest class.</summary>
///
/// <param name="operationName">The name of the operation.</param>
/// <param name="httpMethod"> The HTTP method.</param>
/// <param name="contentType"> The type of the content.</param>
/// <param name="pathInfo"> Information describing the path.</param>
/// <param name="queryString"> The query string.</param>
/// <param name="inputStream"> The input stream.</param>
/// <param name="formData"> Information describing the form.</param>
public MockHttpRequest(string operationName, string httpMethod,
string contentType, string pathInfo,
NameValueCollection queryString, Stream inputStream, NameValueCollection formData)
: this()
{
this.OperationName = operationName;
this.HttpMethod = httpMethod;
this.ContentType = contentType;
this.ResponseContentType = contentType;
this.PathInfo = pathInfo;
this.InputStream = inputStream;
this.QueryString = queryString;
this.FormData = formData ?? new NameValueCollection();
}
/// <summary>The underlying ASP.NET or HttpListener HttpRequest.</summary>
///
/// <value>The original request.</value>
public object OriginalRequest
{
get { return null; }
}
/// <summary>Try resolve.</summary>
///
/// <typeparam name="T">Generic type parameter.</typeparam>
///
/// <returns>A T.</returns>
public T TryResolve<T>()
{
return Container.TryResolve<T>();
}
/// <summary>Gets or sets the container.</summary>
///
/// <value>The container.</value>
public Container Container { get; set; }
/// <summary>The name of the service being called (e.g. Request DTO Name)</summary>
///
/// <value>The name of the operation.</value>
public string OperationName { get; set; }
/// <summary>The request ContentType.</summary>
///
/// <value>The type of the content.</value>
public string ContentType { get; set; }
/// <summary>Gets or sets the HTTP method.</summary>
///
/// <value>The HTTP method.</value>
public string HttpMethod { get; set; }
/// <summary>Gets or sets the user agent.</summary>
///
/// <value>The user agent.</value>
public string UserAgent { get; set; }
/// <summary>Gets or sets a value indicating whether this object is local.</summary>
///
/// <value>true if this object is local, false if not.</value>
public bool IsLocal { get; set; }
/// <summary>Gets or sets the cookies.</summary>
///
/// <value>The cookies.</value>
public IDictionary<string, Cookie> Cookies { get; set; }
private string responseContentType;
/// <summary>The expected Response ContentType for this request.</summary>
///
/// <value>The type of the response content.</value>
public string ResponseContentType
{
get { return responseContentType ?? this.ContentType; }
set { responseContentType = value; }
}
/// <summary>Gets or sets the headers.</summary>
///
/// <value>The headers.</value>
public NameValueCollection Headers { get; set; }
/// <summary>Gets or sets the query string.</summary>
///
/// <value>The query string.</value>
public NameValueCollection QueryString { get; set; }
/// <summary>Gets or sets information describing the form.</summary>
///
/// <value>Information describing the form.</value>
public NameValueCollection FormData { get; set; }
/// <summary>Buffer the Request InputStream so it can be re-read.</summary>
///
/// <value>true if use buffered stream, false if not.</value>
public bool UseBufferedStream { get; set; }
/// <summary>Attach any data to this request that all filters and services can access.</summary>
///
/// <value>The items.</value>
public Dictionary<string, object> Items
{
get;
private set;
}
private string rawBody;
/// <summary>The entire string contents of Request.InputStream.</summary>
///
/// <returns>The raw body.</returns>
public string GetRawBody()
{
if (rawBody != null) return rawBody;
if (InputStream == null) return null;
//Keep the stream alive in-case it needs to be read twice (i.e. ContentLength)
rawBody = new StreamReader(InputStream).ReadToEnd();
InputStream.Position = 0;
return rawBody;
}
/// <summary>Gets or sets URL of the raw.</summary>
///
/// <value>The raw URL.</value>
public string RawUrl { get; set; }
/// <summary>Gets or sets URI of the absolute.</summary>
///
/// <value>The absolute URI.</value>
public string AbsoluteUri
{
get { return "http://localhost" + this.PathInfo; }
}
/// <summary>The Remote Ip as reported by Request.UserHostAddress.</summary>
///
/// <value>The user host address.</value>
public string UserHostAddress { get; set; }
/// <summary>The Remote Ip as reported by X-Forwarded-For, X-Real-IP or Request.UserHostAddress.</summary>
///
/// <value>The remote IP.</value>
public string RemoteIp { get; set; }
/// <summary>The value of the X-Forwarded-For header, null if null or empty.</summary>
///
/// <value>The x coordinate forwarded for.</value>
public string XForwardedFor { get; set; }
/// <summary>The value of the X-Real-IP header, null if null or empty.</summary>
///
/// <value>The x coordinate real IP.</value>
public string XRealIp { get; set; }
/// <summary>e.g. is https or not.</summary>
///
/// <value>true if this object is secure connection, false if not.</value>
public bool IsSecureConnection { get; set; }
/// <summary>Gets or sets a list of types of the accepts.</summary>
///
/// <value>A list of types of the accepts.</value>
public string[] AcceptTypes { get; set; }
/// <summary>Gets or sets information describing the path.</summary>
///
/// <value>Information describing the path.</value>
public string PathInfo { get; set; }
/// <summary>Gets or sets the input stream.</summary>
///
/// <value>The input stream.</value>
public Stream InputStream { get; set; }
/// <summary>Gets the length of the content.</summary>
///
/// <value>The length of the content.</value>
public long ContentLength
{
get
{
var body = GetRawBody();
return body != null ? body.Length : 0;
}
}
/// <summary>Access to the multi-part/formdata files posted on this request.</summary>
///
/// <value>The files.</value>
public IFile[] Files { get; set; }
/// <summary>Gets or sets the full pathname of the application file.</summary>
///
/// <value>The full pathname of the application file.</value>
public string ApplicationFilePath { get; set; }
/// <summary>Adds session cookies.</summary>
public void AddSessionCookies()
{
var permSessionId = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
this.Cookies[SessionFeature.PermanentSessionId] = new Cookie(SessionFeature.PermanentSessionId, permSessionId);
var sessionId = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
this.Cookies[SessionFeature.SessionId] = new Cookie(SessionFeature.SessionId, sessionId);
}
/// <summary>The value of the Referrer, null if not available.</summary>
///
/// <value>The URL referrer.</value>
public Uri UrlReferrer { get { return null; } }
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Reflection;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Aurora.Framework;
using Aurora.Framework.Capabilities;
using Aurora.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
namespace Aurora.Modules.Gods
{
public class GodsModule : INonSharedRegionModule, IGodsModule
{
/// <summary>
/// Special UUID for actions that apply to all agents
/// </summary>
private static readonly UUID ALL_AGENTS = new UUID("44e87126-e794-4ded-05b3-7c42da3d5cdb");
protected IDialogModule m_dialogModule;
protected IScene m_scene;
public bool IsSharedModule
{
get { return false; }
}
#region IGodsModule Members
public void RequestGodlikePowers(
UUID agentID, UUID sessionID, UUID token, bool godLike, IClientAPI controllingClient)
{
IScenePresence sp = m_scene.GetScenePresence(agentID);
if (sp != null)
{
if (godLike == false)
{
//Unconditionally remove god levels
sp.GodLevel = 0;
sp.ControllingClient.SendAdminResponse(token, (uint) sp.GodLevel);
return;
}
// First check that this is the sim owner
if (m_scene.Permissions.IsAdministrator(sp.UUID))
{
sp.GodLevel = sp.UserLevel;
if (sp.GodLevel == 0)
sp.GodLevel = 250;
MainConsole.Instance.Info("[GODS]: God level set for " + sp.Name + ", level " + sp.GodLevel.ToString());
sp.ControllingClient.SendAdminResponse(token, (uint) sp.GodLevel);
}
else
{
if (m_dialogModule != null)
m_dialogModule.SendAlertToUser(agentID,
"Request for god powers denied. This request has been logged.");
MainConsole.Instance.Info("[GODS]: God powers requested by " + sp.Name + ", user is not allowed to have god powers");
}
}
}
public void KickUser(UUID godID, UUID sessionID, UUID agentID, uint kickflags, string reason)
{
UUID kickUserID = ALL_AGENTS;
IScenePresence sp = m_scene.GetScenePresence(agentID);
if (sp != null || agentID == kickUserID)
{
if (m_scene.Permissions.IsGod(godID))
{
if (kickflags == 0)
{
if (agentID == kickUserID)
{
m_scene.ForEachClient(
delegate(IClientAPI controller)
{
if (controller.AgentId != godID)
controller.Kick(reason);
}
);
//This does modify this list, but we make a copy of it
foreach (IScenePresence p in m_scene.GetScenePresences())
{
if (p.UUID != godID)
{
IEntityTransferModule transferModule =
m_scene.RequestModuleInterface<IEntityTransferModule>();
if (transferModule != null)
transferModule.IncomingCloseAgent(m_scene, p.UUID);
}
}
}
else
{
IEntityTransferModule transferModule =
m_scene.RequestModuleInterface<IEntityTransferModule>();
if (transferModule != null)
transferModule.IncomingCloseAgent(m_scene, sp.UUID);
}
}
else if (kickflags == 1)
{
sp.Frozen = true;
m_dialogModule.SendAlertToUser(agentID, reason);
m_dialogModule.SendAlertToUser(godID, "User Frozen");
}
else if (kickflags == 2)
{
sp.Frozen = false;
m_dialogModule.SendAlertToUser(agentID, reason);
m_dialogModule.SendAlertToUser(godID, "User Unfrozen");
}
}
else
{
m_dialogModule.SendAlertToUser(godID, "Kick request denied");
}
}
}
#endregion
#region INonSharedRegionModule Members
public void Initialise(IConfigSource source)
{
}
public void AddRegion(IScene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IGodsModule>(this);
m_scene.EventManager.OnNewClient += SubscribeToClientEvents;
m_scene.EventManager.OnClosingClient += UnsubscribeFromClientEvents;
m_scene.EventManager.OnRegisterCaps += RegisterCaps;
}
public void RemoveRegion(IScene scene)
{
m_scene.UnregisterModuleInterface<IGodsModule>(this);
m_scene.EventManager.OnNewClient -= SubscribeToClientEvents;
m_scene.EventManager.OnClosingClient -= UnsubscribeFromClientEvents;
m_scene.EventManager.OnRegisterCaps -= RegisterCaps;
}
public void RegionLoaded(IScene scene)
{
m_dialogModule = m_scene.RequestModuleInterface<IDialogModule>();
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Close()
{
}
public string Name
{
get { return "Gods Module"; }
}
#endregion
public void PostInitialise()
{
}
public void SubscribeToClientEvents(IClientAPI client)
{
client.OnGodKickUser += KickUser;
client.OnRequestGodlikePowers += RequestGodlikePowers;
}
public void UnsubscribeFromClientEvents(IClientAPI client)
{
client.OnGodKickUser -= KickUser;
client.OnRequestGodlikePowers -= RequestGodlikePowers;
}
public OSDMap RegisterCaps(UUID agentID, IHttpServer server)
{
OSDMap retVal = new OSDMap();
retVal["UntrustedSimulatorMessage"] = CapsUtil.CreateCAPS("UntrustedSimulatorMessage", "");
#if (!ISWIN)
server.AddStreamHandler(new RestHTTPHandler("POST", retVal["UntrustedSimulatorMessage"],
delegate(Hashtable m_dhttpMethod)
{
return UntrustedSimulatorMessage(agentID, m_dhttpMethod);
}));
#else
server.AddStreamHandler(new RestHTTPHandler("POST", retVal["UntrustedSimulatorMessage"],
m_dhttpMethod =>
UntrustedSimulatorMessage(agentID, m_dhttpMethod)));
#endif
return retVal;
}
private Hashtable UntrustedSimulatorMessage(UUID AgentID, Hashtable mDhttpMethod)
{
OSDMap rm = (OSDMap) OSDParser.DeserializeLLSDXml((string) mDhttpMethod["requestbody"]);
if (rm["message"] == "GodKickUser")
{
OSDArray innerArray = ((OSDArray) ((OSDMap) rm["body"])["UserInfo"]);
OSDMap innerMap = (OSDMap) innerArray[0];
UUID toKick = innerMap["AgentID"].AsUUID();
UUID sessionID = innerMap["GodSessionID"].AsUUID();
string reason = innerMap["Reason"].AsString();
uint kickFlags = innerMap["KickFlags"].AsUInteger();
KickUser(AgentID, sessionID, toKick, kickFlags, reason);
}
//Send back data
Hashtable responsedata = new Hashtable();
responsedata["int_response_code"] = 200; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "";
return responsedata;
}
/// <summary>
/// Kicks User specified from the simulator. This logs them off of the grid
/// If the client gets the UUID: 44e87126e7944ded05b37c42da3d5cdb it assumes
/// that you're kicking it even if the avatar's UUID isn't the UUID that the
/// agent is assigned
/// </summary>
/// <param name = "godID">The person doing the kicking</param>
/// <param name = "sessionID">The session of the person doing the kicking</param>
/// <param name = "agentID">the person that is being kicked</param>
/// <param name = "kickflags">Tells what to do to the user</param>
/// <param name = "reason">The message to send to the user after it's been turned into a field</param>
public void KickUser(UUID godID, UUID sessionID, UUID agentID, uint kickflags, byte[] reason)
{
KickUser(godID, sessionID, agentID, kickflags, Utils.BytesToString(reason));
}
}
}
| |
#region Using
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
using TribalWars.Controls;
using TribalWars.Maps.Drawing.Displays;
using TribalWars.Maps.Manipulators;
using TribalWars.Maps.Manipulators.EventArg;
using TribalWars.Maps.Manipulators.Implementations;
using TribalWars.Maps.Manipulators.Managers;
using TribalWars.Tools;
using TribalWars.Villages;
using TribalWars.Worlds;
#endregion
namespace TribalWars.Maps.Polygons
{
/// <summary>
/// Allows the user to draw polygons on the map
/// </summary>
public class PolygonDrawerManipulator : ManipulatorBase
{
#region Constants
private const int MinDistanceBetweenPoints = 50;
#endregion
#region Fields
private readonly Dictionary<Color, Tuple<Pen, Brush>> _pens;
private readonly Font _font;
private readonly DefaultManipulatorManager _parent;
private int _nextId = 1;
private Polygon _activePolygon;
private List<Polygon> _collection = new List<Polygon>();
private Point _lastAddedMapLocation;
private Polygon _currentSelectedPolygon;
#endregion
#region Properties
/// <summary>
/// Gets the currently selected polygon
/// </summary>
public Polygon ActivePolygon
{
get { return _activePolygon; }
private set
{
_activePolygon = value;
if (value == null)
{
_parent.RemoveFullControlManipulator();
}
}
}
/// <summary>
/// Gets all defined polygons
/// </summary>
public List<Polygon> Polygons
{
get { return _collection; }
}
#endregion
#region Constructors
public PolygonDrawerManipulator(Map map, DefaultManipulatorManager parent)
: base(map)
{
_parent = parent;
_pens = new Dictionary<Color, Tuple<Pen, Brush>>();
_font = new Font("Verdana", 12, FontStyle.Bold);
}
#endregion
#region Events
/// <summary>
/// Paints the polygons
/// </summary>
public override void Paint(MapPaintEventArgs e, bool isActiveManipulator)
{
if (Polygons != null)
{
foreach (Polygon poly in Polygons)
{
bool active = poly == ActivePolygon && isActiveManipulator;
if (poly.List.Count > 1 && poly.Visible)
{
Pen pen = GetPen(poly.LineColor);
Brush brush = GetBrush(poly.LineColor);
var firstP = new Point();
var p = new Point();
int x = -1, y = -1;
foreach (Point gameP in poly.List)
{
p = World.Default.Map.Display.GetMapLocation(gameP);
if (x != -1 || y != -1)
{
e.Graphics.DrawLine(pen, x, y, p.X, p.Y);
}
else
{
firstP = p;
}
if (active)
{
e.Graphics.FillRectangle(brush, new Rectangle(p.X - 3, p.Y - 3, 7, 7));
}
x = p.X;
y = p.Y;
}
if (!poly.Drawing)
{
e.Graphics.DrawLine(pen, firstP, p);
if (_map.Display.AllowText)
{
SizeF size = e.Graphics.MeasureString(poly.Name, _font);
p.Offset(5, 5);
e.Graphics.DrawEllipse(pen, p.X, p.Y, size.Width, size.Height);
e.Graphics.DrawString(poly.Name, _font, brush, new Point(p.X, p.Y));
}
}
}
}
}
}
/// <summary>
/// Start creation of a new polygon
/// </summary>
protected internal override bool MouseDownCore(MapMouseEventArgs e)
{
if (e.MouseEventArgs.Button == MouseButtons.Left)
{
if (_activePolygon == null || !_activePolygon.Drawing)
{
StartNewPolygon(e.MouseEventArgs.Location);
return true;
}
}
return false;
}
/// <summary>
/// Stop polygon creation.
/// </summary>
protected internal override bool MouseUpCore(MapMouseEventArgs e)
{
if (e.MouseEventArgs.Button == MouseButtons.Left)
{
if (_activePolygon != null && _activePolygon.Drawing)
{
if (_activePolygon.List.Count > 2)
{
// Polygon completed
_activePolygon.Stop(e.MouseEventArgs.Location);
_nextId++;
DeleteIfEmpty(_activePolygon);
}
else
{
// Too small area to be a polygon
// try to select an existing one instead
Delete(_activePolygon);
Select(e.MouseEventArgs.Location);
}
}
return true;
}
else if (e.MouseEventArgs.Button == MouseButtons.Right)
{
Select(e.MouseEventArgs.Location);
return true;
}
return false;
}
/// <summary>
/// Add points to the polygon
/// </summary>
protected internal override bool MouseMoveCore(MapMouseMoveEventArgs e)
{
if (e.MouseEventArgs.Button == MouseButtons.Left)
{
Point currentMap = e.MouseEventArgs.Location;
if (Control.ModifierKeys.HasFlag(Keys.Control))
{
currentMap.X = _lastAddedMapLocation.X;
}
if (Control.ModifierKeys.HasFlag(Keys.Shift))
{
currentMap.Y = _lastAddedMapLocation.Y;
}
if (_activePolygon != null && _activePolygon.Drawing && CanAddPointToPolygon(_lastAddedMapLocation, currentMap))
{
// Add extra point to the polygon
_activePolygon.Add(currentMap);
_lastAddedMapLocation = currentMap;
return true;
}
}
return false;
}
/// <summary>
/// Handles keypresses on the map
/// </summary>
protected internal override bool OnKeyDownCore(MapKeyEventArgs e)
{
if (ActivePolygon != null)
{
if (e.KeyEventArgs.KeyCode == Keys.Delete)
{
Delete(ActivePolygon);
return true;
}
if (!ActivePolygon.Drawing)
{
var polygonMove = new KeyboardInputToMovementConverter(e.KeyEventArgs.KeyData, 1, 5).GetKeyMove();
if (polygonMove.HasValue)
{
ActivePolygon.Move(polygonMove.Value);
return true;
}
}
}
return false;
}
#endregion
#region Public Methods
public override IContextMenu GetContextMenu(Point location, Village village)
{
Debug.Assert(ActivePolygon != null);
return new PolygonContextMenu(this);
}
/// <summary>
/// Deletes all polygons
/// </summary>
public void Clear()
{
_collection = new List<Polygon>();
ActivePolygon = null;
_nextId = 1;
_map.Invalidate(false);
}
/// <summary>
/// Hides/Shows the polygons
/// </summary>
public void ToggleVisibility(bool visible)
{
if (_collection.Count > 0)
{
foreach (Polygon poly in _collection)
{
poly.Visible = visible;
}
_map.Invalidate(false);
}
}
/// <summary>
/// Toggles the visibility of the active polygon
/// </summary>
public void ToggleVisibility()
{
if (ActivePolygon != null)
{
ActivePolygon.Visible = !ActivePolygon.Visible;
_map.Invalidate(false);
}
}
/// <summary>
/// Deletes the active polygon
/// </summary>
public void Delete()
{
Delete(ActivePolygon);
}
/// <summary>
/// Deletes a polygon
/// </summary>
public void Delete(Polygon poly)
{
if (poly != null)
{
Polygons.Remove(poly);
if (poly == ActivePolygon)
{
ActivePolygon = null;
}
_map.Invalidate(false);
}
}
/// <summary>
/// Dispose resources
/// </summary>
public override void Dispose()
{
foreach (KeyValuePair<Color, Tuple<Pen, Brush>> penAndBrush in _pens)
{
penAndBrush.Value.Item1.Dispose();
penAndBrush.Value.Item2.Dispose();
}
_font.Dispose();
}
#endregion
#region Persistence
/// <summary>
/// Saves state to stream
/// </summary>
protected internal override void WriteXmlCore(XmlWriter w)
{
if (Polygons.Count > 0)
{
w.WriteStartElement("BBCodeManipulator");
foreach (Polygon poly in Polygons)
{
w.WriteStartElement("Polygon");
w.WriteAttributeString("ID", poly.Name);
w.WriteAttributeString("Visible", poly.Visible.ToString());
w.WriteAttributeString("Color", XmlHelper.SetColor(poly.LineColor));
w.WriteAttributeString("Group", poly.Group);
foreach (Point p in poly.List)
{
w.WriteStartElement("Point");
w.WriteAttributeString("X", p.X.ToString(CultureInfo.InvariantCulture));
w.WriteAttributeString("Y", p.Y.ToString(CultureInfo.InvariantCulture));
w.WriteEndElement();
}
w.WriteEndElement();
}
w.WriteEndElement();
}
}
/// <summary>
/// Loads state from stream
/// </summary>
protected internal override void ReadXmlCore(XmlReader r)
{
if (r.IsStartElement("BBCodeManipulator") && !r.IsEmptyElement)
{
r.ReadStartElement();
while (r.IsStartElement("Polygon"))
{
string id = r.GetAttribute("ID");
bool visible = Convert.ToBoolean(r.GetAttribute("Visible"));
Color color = XmlHelper.GetColor(r.GetAttribute("Color"), Color.White);
string group = r.GetAttribute("Group");
var points = new List<Point>();
r.ReadStartElement();
while (r.IsStartElement("Point"))
{
int x = Convert.ToInt32(r.GetAttribute("X"));
int y = Convert.ToInt32(r.GetAttribute("Y"));
points.Add(new Point(x, y));
r.Read();
}
var poly = new Polygon(id, visible, color, group, points);
Polygons.Add(poly);
r.ReadEndElement();
}
r.ReadEndElement();
}
}
/// <summary>
/// Cleanup anything when switching worlds or settings
/// </summary>
protected internal override void CleanUp()
{
Clear();
}
#endregion
#region Private Implementation
/// <summary>
/// Polygon started
/// </summary>
private void StartNewPolygon(Point loc)
{
_lastAddedMapLocation = loc;
_activePolygon = new Polygon(string.Format(ControlsRes.PolygonDrawerManipulator_NewClusterName, _nextId.ToString(CultureInfo.InvariantCulture)), _lastAddedMapLocation);
_collection.Add(_activePolygon);
_parent.SetFullControlManipulator(this);
}
/// <summary>
/// If the polygon has no villages, we will not add it to the collection
/// </summary>
private void DeleteIfEmpty(Polygon polygon)
{
if (!polygon.GetVillages().Any())
{
Delete(polygon);
}
}
/// <summary>
/// Returns the first polygon that contains the point.
/// Cycle when there are multiple in the location.
/// </summary>
private Polygon GetSelectedPolygon(Point loc)
{
var polys = (from poly in _collection
where poly.IsHitIn(loc) && poly.Visible
select poly).ToArray();
if (!polys.Any())
{
_currentSelectedPolygon = null;
}
else if (polys.Count() == 1)
{
_currentSelectedPolygon = polys.Single();
}
else
{
if (_currentSelectedPolygon == null || !polys.Contains(_currentSelectedPolygon) || polys.Last() == _currentSelectedPolygon)
{
_currentSelectedPolygon = polys.First();
}
else
{
_currentSelectedPolygon = polys.SkipWhile((Polygon poly) => !poly.Equals(_currentSelectedPolygon)).Take(2).Last();
}
}
return _currentSelectedPolygon;
}
/// <summary>
/// Set the active polygon
/// </summary>
private void Select(Point loc)
{
_activePolygon = GetSelectedPolygon(loc);
if (_activePolygon == null)
{
_parent.RemoveFullControlManipulator();
}
else
{
_parent.SetFullControlManipulator(this);
}
}
/// <summary>
/// Returns false if the point is not to be added to the collection
/// </summary>
private bool CanAddPointToPolygon(Point lastMap, Point currentMap)
{
if (World.Default.Map.Display.Type == DisplayTypes.Icon)
{
Point lastGame = World.Default.Map.Display.GetGameLocation(lastMap);
Point currentGame = World.Default.Map.Display.GetGameLocation(currentMap);
return lastGame != currentGame;
}
else
{
Debug.Assert(World.Default.Map.Display.Type == DisplayTypes.Shape);
double distance = Math.Sqrt(Math.Pow(currentMap.X - lastMap.X, 2) + Math.Pow(currentMap.Y - lastMap.Y, 2));
return distance > MinDistanceBetweenPoints;
}
}
#endregion
#region Pens & Brushes
private Pen GetPen(Color color)
{
CacheIfNotExists(color);
return _pens[color].Item1;
}
private Brush GetBrush(Color color)
{
CacheIfNotExists(color);
return _pens[color].Item2;
}
private void CacheIfNotExists(Color color)
{
if (!_pens.ContainsKey(color))
{
var pen = new Pen(color);
var brush = new SolidBrush(color);
_pens.Add(color, new Tuple<Pen, Brush>(pen, brush));
}
}
#endregion
}
}
| |
//
// Mono.Data.TdsTypes.TdsBinary
//
// Author:
// Tim Coleman ([email protected])
//
// (C) Copyright Tim Coleman, 2002
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Mono.Data.TdsClient;
using System;
using System.Data.SqlTypes;
using System.Globalization;
namespace Mono.Data.TdsTypes {
public struct TdsBinary : INullable, IComparable
{
#region Fields
byte[] value;
private bool notNull;
public static readonly TdsBinary Null;
#endregion
#region Constructors
public TdsBinary (byte[] value)
{
this.value = value;
notNull = true;
}
#endregion
#region Properties
public bool IsNull {
get { return !notNull; }
}
public byte this[int index] {
get {
if (this.IsNull)
throw new TdsNullValueException ("The property contains Null.");
else if (index >= this.Length)
throw new TdsNullValueException ("The index parameter indicates a position beyond the length of the byte array.");
else
return value [index];
}
}
public int Length {
get {
if (this.IsNull)
throw new TdsNullValueException ("The property contains Null.");
else
return value.Length;
}
}
public byte[] Value
{
get {
if (this.IsNull)
throw new TdsNullValueException ("The property contains Null.");
else
return value;
}
}
#endregion
#region Methods
[MonoTODO]
public int CompareTo (object value)
{
throw new NotImplementedException ();
}
public static TdsBinary Concat (TdsBinary x, TdsBinary y)
{
return (x + y);
}
public override bool Equals (object value)
{
if (!(value is TdsBinary))
return false;
else
return (bool) (this == (TdsBinary)value);
}
public static TdsBoolean Equals (TdsBinary x, TdsBinary y)
{
return (x == y);
}
[MonoTODO]
public override int GetHashCode ()
{
throw new NotImplementedException ();
}
#endregion
#region Operators
public static TdsBoolean GreaterThan (TdsBinary x, TdsBinary y)
{
return (x > y);
}
public static TdsBoolean GreaterThanOrEqual (TdsBinary x, TdsBinary y)
{
return (x >= y);
}
public static TdsBoolean LessThan (TdsBinary x, TdsBinary y)
{
return (x < y);
}
public static TdsBoolean LessThanOrEqual (TdsBinary x, TdsBinary y)
{
return (x <= y);
}
public static TdsBoolean NotEquals (TdsBinary x, TdsBinary y)
{
return (x != y);
}
public TdsGuid ToTdsGuid ()
{
return new TdsGuid (value);
}
public override string ToString ()
{
if (IsNull)
return "null";
return String.Format ("TdsBinary ({0})", Length);
}
#endregion
#region Operators
[MonoTODO]
public static TdsBinary operator + (TdsBinary x, TdsBinary y)
{
throw new NotImplementedException ();
}
[MonoTODO]
public static TdsBoolean operator == (TdsBinary x, TdsBinary y)
{
if (x.IsNull || y.IsNull)
return TdsBoolean.Null;
else
throw new NotImplementedException ();
}
[MonoTODO]
public static TdsBoolean operator > (TdsBinary x, TdsBinary y)
{
if (x.IsNull || y.IsNull)
return TdsBoolean.Null;
else
throw new NotImplementedException ();
}
[MonoTODO]
public static TdsBoolean operator >= (TdsBinary x, TdsBinary y)
{
if (x.IsNull || y.IsNull)
return TdsBoolean.Null;
else
throw new NotImplementedException ();
}
[MonoTODO]
public static TdsBoolean operator != (TdsBinary x, TdsBinary y)
{
if (x.IsNull || y.IsNull)
return TdsBoolean.Null;
else
throw new NotImplementedException ();
}
[MonoTODO]
public static TdsBoolean operator < (TdsBinary x, TdsBinary y)
{
if (x.IsNull || y.IsNull)
return TdsBoolean.Null;
else
throw new NotImplementedException ();
}
[MonoTODO]
public static TdsBoolean operator <= (TdsBinary x, TdsBinary y)
{
if (x.IsNull || y.IsNull)
return TdsBoolean.Null;
else
throw new NotImplementedException ();
}
public static explicit operator byte[] (TdsBinary x)
{
return x.Value;
}
[MonoTODO]
public static explicit operator TdsBinary (TdsGuid x)
{
throw new NotImplementedException ();
}
public static implicit operator TdsBinary (byte[] x)
{
return new TdsBinary (x);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
using DiffLib;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SolidWorks.Interop.swpublished;
using Weingartner.ReactiveCompositeCollections;
using Weingartner.WeinCad.Interfaces;
using Weingartner.WeinCad.Interfaces.Monads;
using Weingartner.WeinCad.Interfaces.Reflection;
using Weingartner.WeinCad.Interfaces.ViewModels.EditorView;
using Unit = System.Reactive.Unit;
namespace SolidworksAddinFramework
{
/// <summary>
/// Base class for all property manager pages. See sample for more info
/// </summary>
/// <typeparam name="TMacroFeature">The type of the macro feature this page is designed for</typeparam>
[ComVisible(false)]
public abstract class PropertyManagerPageBase : ReactiveObject, IPropertyManagerPage2Handler9, IEditor, IDisposable
{
public readonly ISldWorks SwApp;
private readonly string _Name;
private readonly IEnumerable<swPropertyManagerPageOptions_e> _OptionsE;
private readonly CompositeDisposable _Disposable = new CompositeDisposable();
private IDisposable _Deselect;
/// <summary>
/// We default to true so that in the absense of any explicit validation
/// the accept button on the property manager page is always on
/// </summary>
bool _IsValid = true;
public bool IsValid
{
get { return _IsValid; }
set { this.RaiseAndSetIfChanged(ref _IsValid, value); }
}
protected BehaviorSubject<Unit> ValidationSubject = new BehaviorSubject<Unit>(Unit.Default);
protected PropertyManagerPageBase(string name, IEnumerable<swPropertyManagerPageOptions_e> optionsE, IModelDoc2 modelDoc)
{
SwApp = SwAddinBase.Active.SwApp;
ModelDoc = modelDoc;
_Name = name;
_OptionsE = optionsE;
}
private readonly Subject<Unit> _ShowSubject = new Subject<Unit>();
public IObservable<Unit> ShowObservable => _ShowSubject.AsObservable();
/// <summary>
/// Creates a new SolidWorks property manager page, adds controls, and shows the page.
/// </summary>
public virtual void Show()
{
var options = _OptionsE.Aggregate(0, (acc, v) => (int)v | acc);
var errors = 0;
_PropertyManagerPage2Handler9Wrapper = new PropertyManagerPage2Handler9Wrapper(this);
var propertyManagerPage = SwApp.CreatePropertyManagerPage(_Name, options,
_PropertyManagerPage2Handler9Wrapper, ref errors);
if (errors != (int)swPropertyManagerPageStatus_e.swPropertyManagerPage_Okay)
{
throw new Exception("Unable to Create PMP");
}
Page = (IPropertyManagerPage2)propertyManagerPage;
var selectionMgr = (ISelectionMgr)ModelDoc.SelectionManager;
_Deselect = selectionMgr.DeselectAllUndoable();
AddControls();
Page.Show();
// Force validation of the page
ValidationSubject.OnNext(Unit.Default);
var d = this.WhenAnyValue(p => p.IsValid)
.Subscribe(isValid => Page.EnableButton((int)swPropertyManagerPageButtons_e.swPropertyManagerPageButton_Ok, isValid));
DisposeOnClose(d);
AddSelections();
_ShowSubject.OnNext(Unit.Default);
}
protected void DisposeOnClose(IDisposable disposable)
{
_Disposable.Add(disposable);
}
protected abstract void AddSelections();
private void AddControls()
{
_Disposable.Add(AddControlsImpl().ToCompositeDisposable());
}
/// <summary>
/// Implement this method to add all controls to the page. See sample for more info
/// </summary>
/// <returns></returns>
protected abstract IEnumerable<IDisposable> AddControlsImpl();
/// <summary>
/// The instance of the real solid works property manager page. You will still have to call some
/// methods on this. Not all magic is done automatically.
/// </summary>
public IPropertyManagerPage2 Page { get; private set; }
private readonly Subject<Unit> _AfterActivation = new Subject<Unit>();
public IObservable<Unit> AfterActivationObs => _AfterActivation.AsObservable();
public virtual void AfterActivation()
{
_AfterActivation.OnNext(Unit.Default);
}
public void OnClose(int reason)
{
OnClose((swPropertyManagerPageCloseReasons_e) reason);
}
protected readonly TaskCompletionSource<bool> _CloseTaskSource = new TaskCompletionSource<bool>();
public Task<bool> Closed => _CloseTaskSource.Task;
public void AfterClose()
{
Page = null;
}
public virtual bool OnHelp()
{
return true;
}
public virtual bool OnPreviousPage()
{
return true;
}
public virtual bool OnNextPage()
{
return true;
}
public virtual bool OnPreview()
{
return true;
}
public virtual void OnWhatsNew()
{
}
public virtual void OnUndo()
{
}
public virtual void OnRedo()
{
}
public virtual bool OnTabClicked(int id)
{
return true;
}
public virtual void OnGroupExpand(int id, bool expanded)
{
}
public virtual void OnGroupCheck(int id, bool Checked)
{
}
#region checkbox
private readonly Subject<Tuple<int, bool>> _CheckBoxChanged = new Subject<Tuple<int, bool>>();
public virtual void OnCheckboxCheck(int id, bool @checked)
{
_CheckBoxChanged.OnNext(Tuple.Create(id,@checked));
}
public IObservable<bool> CheckBoxChangedObservable(int id) => _CheckBoxChanged
.Where(t=>t.Item1==id).Select(t=>t.Item2);
#endregion
private readonly Subject<int> _OptionChecked = new Subject<int>();
public virtual void OnOptionCheck(int id)
{
_OptionChecked.OnNext(id);
}
public IObservable<int> OptionCheckedObservable(int id) => _OptionChecked.DistinctUntilChanged().Where(i => i == id);
private readonly Subject<int> _ButtonPressed = new Subject<int>();
public IObservable<int> ButtonPressedObservable(int id) => _ButtonPressed.Where(i => i == id);
public virtual void OnButtonPress(int id)
{
_ButtonPressed.OnNext(id);
}
#region textbox
public virtual void OnTextboxChanged(int id, string text)
{
_TextBoxChanged.OnNext(Tuple.Create(id,text));
}
private readonly Subject<Tuple<int, string>> _TextBoxChanged = new Subject<Tuple<int, string>>();
public IObservable<string> TextBoxChangedObservable(int id) => _TextBoxChanged
.Where(t=>t.Item1==id).Select(t=>t.Item2);
#endregion
#region numberbox
private readonly Subject<Tuple<int, double>> _NumberBoxChanged = new Subject<Tuple<int, double>>();
public IObservable<double> NumberBoxChangedObservable(int id) => _NumberBoxChanged
.Where(t=>t.Item1==id).Select(t=>t.Item2);
public virtual void OnNumberboxChanged(int id, double value)
{
_NumberBoxChanged.OnNext(Tuple.Create(id,value));
}
#endregion
#region combobox
public virtual void OnComboboxEditChanged(int id, string text)
{
}
private readonly Subject<Tuple<int, int>> _ComboBoxSelectionSubject = new Subject<Tuple<int, int>>();
public virtual void OnComboboxSelectionChanged(int id, int item)
{
_ComboBoxSelectionSubject.OnNext(Tuple.Create(id,item));
}
public IObservable<int> ComboBoxSelectionObservable(int id) => _ComboBoxSelectionSubject
.Where(i => i.Item1 == id).Select(t => t.Item2);
#endregion
#region listbox
private readonly Subject<Tuple<int, int>> _ListBoxSelectionSubject = new Subject<Tuple<int, int>>();
private int _NextId = 0;
public virtual void OnListboxSelectionChanged(int id, int item)
{
_ListBoxSelectionSubject.OnNext(Tuple.Create(id,item));
}
public IObservable<int> ListBoxSelectionObservable(int id) => _ListBoxSelectionSubject
.Where(i => i.Item1 == id).Select(t => t.Item2);
public virtual void OnListboxRMBUp(int id, int posX, int posY)
{
}
#endregion
private readonly Subject<int> _SelectionBoxFocusChangedSubject = new Subject<int>();
public IObservable<Unit> SelectionBoxFocusChangedObservable(int id) => _SelectionBoxFocusChangedSubject.Where(i => id == i).Select(_=>Unit.Default);
public void OnSelectionboxFocusChanged(int id)
{
_SelectionBoxFocusChangedSubject.OnNext(id);
}
#region selection changed observables
private readonly Subject<int> _SelectionChangedSubject = new Subject<int>();
private PropertyManagerPage2Handler9Wrapper _PropertyManagerPage2Handler9Wrapper;
private IObservable<Unit> SelectionChangedObservable(int id) => _SelectionChangedSubject.Where(i => id == i).Select(_=>Unit.Default);
protected IModelDoc2 ModelDoc { get; }
#endregion
public virtual void OnSelectionboxListChanged(int id, int count)
{
_SelectionChangedSubject.OnNext(id);
}
public virtual void OnSelectionboxCalloutCreated(int id)
{
}
public virtual void OnSelectionboxCalloutDestroyed(int id)
{
}
public bool OnSubmitSelection(int id, object selection, int selType, ref string itemText)
{
return OnSubmitSelection(id, selection, (swSelectType_e) selType, ref itemText );
}
protected virtual bool OnSubmitSelection(int id, object selection, swSelectType_e selType, ref string itemText)
{
return true;
}
public virtual int OnActiveXControlCreated(int id, bool status)
{
return -1;
}
private readonly Subject<Tuple<int, double>> _SliderPositionChangedSubject = new Subject<Tuple<int, double>>();
private IObservable<int> SliderPositionChangedObservable(int id) =>
_SliderPositionChangedSubject
.Where(p => id == p.Item1)
.Select(p => (int)p.Item2);
public virtual void OnSliderPositionChanged(int id, double value)
{
_SliderPositionChangedSubject.OnNext(Tuple.Create(id, value));
}
public virtual void OnSliderTrackingCompleted(int id, double value)
{
_SliderPositionChangedSubject.OnNext(Tuple.Create(id, value));
}
public virtual bool OnKeystroke(int wparam, int message, int lparam, int id)
{
return true;
}
public virtual void OnPopupMenuItem(int id)
{
}
public virtual void OnPopupMenuItemUpdate(int id, ref int retval)
{
}
private readonly Subject<int> _GainedFocusSubject = new Subject<int>();
protected IObservable<int> GainedFocusObservable(int id) => _GainedFocusSubject.Where(i => i == id);
public virtual void OnGainedFocus(int id)
{
_GainedFocusSubject.OnNext(id);
}
private readonly Subject<int> _LostFocusSubject = new Subject<int>();
private IObservable<int> LostFocusObservable(int id) => _LostFocusSubject.Where(i => i == id).AsObservable();
public virtual void OnLostFocus(int id)
{
_LostFocusSubject.OnNext(id);
}
public virtual int OnWindowFromHandleControlCreated(int id, bool status)
{
return 0;
}
public virtual void OnNumberBoxTrackingCompleted(int id, double value)
{
}
protected IDisposable CreateListBox(IPropertyManagerPageGroup @group, string caption, string tip, Func<int> get, Action<int> set, Action<IPropertyManagerPageListbox> config)
{
var id = NextId();
var list = PropertyManagerGroupExtensions.CreateListBox(@group, id, caption, tip);
config(list);
list.CurrentSelection = (short) get();
var d = ListBoxSelectionObservable(id).Subscribe(set);
return ControlHolder.Create(@group, list, d);
}
protected IDisposable CreateComboBox<TEnum, TModel>(
IPropertyManagerPageGroup @group,
string caption,
string tip,
Func<TEnum, string> itemToStringFn,
TModel model,
Expression<Func<TModel, TEnum>> selectedItemExpression,
Action<IPropertyManagerPageCombobox> config = null)
{
var items = Enum.GetValues(typeof (TEnum))
.CastArray<TEnum>()
.ToCompositeList();
return CreateComboBox(group,
caption,
tip,
items,
EqualityComparer<TEnum>.Default,
itemToStringFn,
model,
selectedItemExpression,
config);
}
protected IDisposable CreateComboBox<T, TModel>(
IPropertyManagerPageGroup @group,
string caption,
string tip,
ICompositeList<T> items,
IEqualityComparer<T> itemEqualityComparer,
Func<T, string> itemToStringFn,
TModel model,
Expression<Func<TModel, T>> selectedItemExpression,
Action<IPropertyManagerPageCombobox> config = null)
{
var id = NextId();
var comboBox = @group.CreateComboBox(id, caption, tip);
config?.Invoke(comboBox);
// Sync source collection with SW ComboBox collection
Action<short, T> insert = (index, element) =>
{
var insertIndex = comboBox.InsertItem(index, itemToStringFn(element));
Debug.Assert(insertIndex != -1, "Item couldn't be inserted");
};
Action<short> delete = index =>
{
var deleteIndex = comboBox.DeleteItem(index);
Debug.Assert(deleteIndex != -1, "Item couldn't be deleted");
};
var swComboBoxUpdated = new Subject<Unit>();
var d0 = AfterActivationObs
.Select(_ => items.ChangesObservable(itemEqualityComparer))
.Switch()
.Subscribe(changes =>
{
short index = 0;
foreach (var change in changes)
{
switch (change.Operation)
{
case DiffOperation.Match:
break;
case DiffOperation.Insert:
insert(index++, change.ElementFromCollection2.Value);
break;
case DiffOperation.Delete:
delete(index);
break;
case DiffOperation.Replace:
delete(index);
insert(index++, change.ElementFromCollection2.Value);
break;
case DiffOperation.Modify:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
swComboBoxUpdated.OnNext(Unit.Default);
});
// Sync source to SW selection
var d1 = swComboBoxUpdated
.Select(_ => model.WhenAnyValue(selectedItemExpression))
.Switch()
.Select(selectedItem => items
.Items
.Select(list => (short)list.IndexOf(selectedItem))
)
.Switch()
.AssignTo(comboBox, box => box.CurrentSelection);
// Sync SW to source selection
var selectedItemProxy = selectedItemExpression.GetProxy(model);
var d2 = ComboBoxSelectionObservable(id)
.Select(index => items
.Items
.Select(list => list[index])
)
.Switch()
.AssignTo(selectedItemProxy, p=> p.Value);
return ControlHolder.Create(@group, comboBox, d0, d1, d2, swComboBoxUpdated);
}
protected IDisposable CreateTextBox(IPropertyManagerPageGroup @group, string caption, string tip, Func<string> get, Action<string> set)
{
var id = NextId();
var text = PropertyManagerGroupExtensions.CreateTextBox(@group, id, caption, tip);
text.Text = get();
var d = TextBoxChangedObservable(id).Subscribe(set);
return ControlHolder.Create(@group, text, d);
}
public static Func<T, IDisposable> Disposify<T>(Action<T> a)
{
return t =>
{
a(t);
return Disposable.Empty;
};
}
/// <summary>
/// ReactiveUI version of CreateNumberBox
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="group"></param>
/// <param name="tip"></param>
/// <param name="caption"></param>
/// <param name="source"></param>
/// <param name="selector"></param>
/// <param name="config"></param>
/// <param name="gainedFocusObserver"></param>
/// <param name="lostFocusObserver"></param>
/// <returns></returns>
protected IDisposable CreateNumberBox<T>(IPropertyManagerPageGroup @group,
string tip,
string caption,
T source,
Expression<Func<T, double>> selector,
Func<IPropertyManagerPageNumberbox, IDisposable> config = null,
IObserver<Unit> gainedFocusObserver = null,
IObserver<Unit> lostFocusObserver = null)
{
var id = NextId();
var box = @group.CreateNumberBox(id, caption, tip);
var d = new CompositeDisposable();
if (gainedFocusObserver != null)
{
GainedFocusObservable(id)
.Ignore()
.Subscribe(gainedFocusObserver)
.DisposeWith(d);
}
if (lostFocusObserver != null)
{
LostFocusObservable(id)
.Ignore()
.Subscribe(lostFocusObserver)
.DisposeWith(d);
}
InitControl(@group, box, config, c => c.Value, NumberBoxChangedObservable(id), source, selector)
.DisposeWith(d);
return d;
}
protected IDisposable CreateCheckBox<T>(IPropertyManagerPageGroup @group,
string tip,
string caption,
T source,
Expression<Func<T, bool>> selector,
Func<IPropertyManagerPageCheckbox, IDisposable> config = null,
bool enable = true)
{
var id = NextId();
var box = @group.CreateCheckBox(id, caption, tip);
return InitControl(@group, box, config, c => c.Checked, CheckBoxChangedObservable(id), source, selector);
}
private static IDisposable InitControl<T, TContrl, TCtrlProp, TDataProp>(
IPropertyManagerPageGroup @group,
TContrl control,
Func<TContrl, IDisposable> controlConfig,
Expression<Func<TContrl, TCtrlProp>> ctrlPropSelector,
IObservable<TCtrlProp> ctrlPropChangeObservable,
T propParent,
Expression<Func<T, TDataProp>> propSelector,
Func<TCtrlProp, TDataProp> controlToDataConversion ,
Func<TDataProp, TCtrlProp> dataToControlConversion)
{
var proxy = propSelector.GetProxy(propParent);
var ctrlProxy = ctrlPropSelector.GetProxy(control);
var d5 = controlConfig?.Invoke(control);
var d2 = propParent
.WhenAnyValue(propSelector)
.Select(dataToControlConversion)
.Subscribe(v => ctrlProxy.Value = v);
var d1 = ctrlPropChangeObservable
.Select(controlToDataConversion)
.Subscribe(v => proxy.Value = v);
return ControlHolder.Create(@group, control, d1, d2, d5);
}
private static IDisposable InitControl<T, TContrl, TProp>(
IPropertyManagerPageGroup @group,
TContrl control,
Func<TContrl, IDisposable> controlConfig,
Expression<Func<TContrl, TProp>> ctrlPropSelector,
IObservable<TProp> ctrlPropChangeObservable,
T propParent,
Expression<Func<T, TProp>> propSelector)
{
return InitControl(@group, control, controlConfig, ctrlPropSelector, ctrlPropChangeObservable, propParent, propSelector, x => x, x => x);
}
public IDisposable CreateLabel(IPropertyManagerPageGroup @group, string tip, string caption = null, Func<IPropertyManagerPageLabel, IDisposable> config = null)
{
caption = caption ?? tip;
return CreateLabel(@group, tip, Observable.Return(caption), config);
}
private IDisposable CreateLabel(IPropertyManagerPageGroup @group, string tip, IObservable<string> captionObs, Func<IPropertyManagerPageLabel, IDisposable> config)
{
var id = NextId();
var box = @group.CreateLabel(id, String.Empty, tip);
var d1 = config?.Invoke(box) ?? Disposable.Empty;
var d0 = captionObs.Subscribe(caption => box.Caption = caption);
return ControlHolder.Create(@group, box, d0, d1);
}
/// <summary>
/// Creates an options group
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TOption"></typeparam>
/// <param name="pageGroup">The page group the options group belongs to</param>
/// <param name="source">The model object</param>
/// <param name="selector">The binding selector for the property on the model</param>
/// <param name="builder">A callback which is passed the options group object. You can add options here. </param>
/// <returns></returns>
protected IDisposable CreateOptionGroup<T,TOption>
(IPropertyManagerPageGroup pageGroup,T source, Expression<Func<T, TOption>> selector, Action<OptionGroup<T, TOption>> builder)
{
var optionGroup = new OptionGroup<T, TOption>(this, pageGroup, source, selector);
builder(optionGroup);
return optionGroup;
}
protected IDisposable CreateSelectionBox<TModel>(
IPropertyManagerPageGroup @group,
string tip,
string caption,
swSelectType_e selectType,
TModel model,
Expression<Func<TModel, SelectionData>> propertyExpr,
Action<IPropertyManagerPageSelectionbox> config)
{
return CreateSelectionBox(@group, tip, caption, new[] { selectType}, model, propertyExpr, config, () => { });
}
protected IDisposable CreateSelectionBox<TModel>(
IPropertyManagerPageGroup @group,
string tip,
string caption,
swSelectType_e[] selectType,
TModel model,
Expression<Func<TModel, SelectionData>> propertyExpr,
Action<IPropertyManagerPageSelectionbox> config)
{
return CreateSelectionBox(@group, tip, caption, selectType, model, propertyExpr, config, () => { });
}
protected IDisposable CreateSelectionBox<TModel>
(
IPropertyManagerPageGroup @group,
string tip,
string caption,
swSelectType_e selectType,
TModel model,
Expression<Func<TModel, SelectionData>> propertyExpr,
Action<IPropertyManagerPageSelectionbox> config,
Action onFocus)
{
return CreateSelectionBox(@group, tip, caption, new[] {selectType}, model, propertyExpr, config, onFocus);
}
protected IDisposable CreateSelectionBox<TModel>(
IPropertyManagerPageGroup @group,
string tip,
string caption,
swSelectType_e[] selectType,
TModel model,
Expression<Func<TModel, SelectionData>> propertyExpr,
Action<IPropertyManagerPageSelectionbox> config,
Action onFocus)
{
var d = new CompositeDisposable();
var id = NextId();
var box = @group.CreateSelectionBox(id, caption, tip);
config(box);
box.SetSelectionFilters(selectType);
SelectionBoxFocusChangedObservable(id)
.Subscribe(_ => onFocus())
.DisposeWith(d);
var canSetSelectionSubject = new BehaviorSubject<bool>(true).DisposeWith(d);
Func<IDisposable> startTransaction = () =>
{
canSetSelectionSubject.OnNext(false);
return Disposable.Create(() => canSetSelectionSubject.OnNext(true));
};
BindFromSource(model, propertyExpr, startTransaction)
.DisposeWith(d);
var inTransactionObservable = canSetSelectionSubject.AsObservable();
BindFromTarget(selectType, model, propertyExpr, id, inTransactionObservable, box)
.DisposeWith(d);
return ControlHolder.Create(@group, box, d);
}
private IDisposable BindFromSource<TModel>(TModel model, Expression<Func<TModel, SelectionData>> propertyExpr, Func<IDisposable> startTransaction)
{
return model.WhenAnyValue(propertyExpr)
.Buffer(2, 1)
.Where(b => b.Count == 2)
.Select(b =>
{
var previous = b[0].ObjectIds.ToList();
var current = b[1].ObjectIds.ToList();
var sections = Diff.CalculateSections(previous, current);
var alignedElements = Diff
.AlignElements(previous, current, sections,
new BasicInsertDeleteDiffElementAligner<SelectionData.ObjectId>())
.ToList();
var oldObjectIds = alignedElements
.Where(e => e.Operation == DiffOperation.Delete || e.Operation == DiffOperation.Replace)
.Select(e => e.ElementFromCollection1.Value);
var newObjectIds = alignedElements
.Where(e => e.Operation == DiffOperation.Insert || e.Operation == DiffOperation.Replace)
.Select(e => e.ElementFromCollection2.Value);
return new { oldSelectionData = b[0], oldObjectIds, newSelectionData = b[1], newObjectIds };
})
.Subscribe(o =>
{
using (startTransaction())
{
ModelDoc.ClearSelection(o.oldSelectionData.WithObjectIds(o.oldObjectIds));
ModelDoc.AddSelection(o.newSelectionData.WithObjectIds(o.newObjectIds));
}
});
}
private IDisposable BindFromTarget<TModel>(swSelectType_e[] selectType, TModel model, Expression<Func<TModel, SelectionData>> propertyExpr, int id, IObservable<bool> inTransactionObservable, IPropertyManagerPageSelectionbox box)
{
return SelectionChangedObservable(id)
.CombineLatest(inTransactionObservable, (_, canSetSelection) => canSetSelection)
.Where(v => v)
.Subscribe(_ => SetSelection(box, selectType, model, propertyExpr));
}
private void SetSelection<TModel>(IPropertyManagerPageSelectionbox box, swSelectType_e[] selectType, TModel model, Expression<Func<TModel, SelectionData>> propertyExpr)
{
var selectionManager = (ISelectionMgr) ModelDoc.SelectionManager;
var selectedItems = selectionManager.GetSelectedObjects((type, mark) => selectType.Any(st => type == st) && box.Mark == mark);
var expressionChain = ReactiveUI.Reflection.Rewrite(propertyExpr.Body).GetExpressionChain().ToList();
var newSelection = Create(selectedItems, box.Mark, ModelDoc);
ReactiveUI.Reflection.TrySetValueToPropertyChain<SelectionData>(model, expressionChain, newSelection);
}
protected IDisposable CreateButton(IPropertyManagerPageGroup @group, string tip, string caption, Action onClick, Func<IPropertyManagerPageButton, IDisposable> config = null)
{
var id = NextId();
var box = PropertyManagerGroupExtensions.CreateButton(@group, id, caption, tip);
var d0 = ButtonPressedObservable(id).Subscribe(_ => onClick());
return ControlHolder.Create(@group, box, d0,config?.Invoke(box) ?? Disposable.Empty);
}
protected IDisposable CreateSlider<T, TProp>(
IPropertyManagerPageGroup @group,
string tip,
string caption,
T source,
Expression<Func<T, TProp>> selector,
Func<IPropertyManagerPageSlider, IDisposable> config,
Func<int, TProp> controlToDataConversion,
Func<TProp, int> dataToControlConversion)
{
var id = NextId();
var control = group.CreateSlider(id, caption, tip);
return InitControl(group, control, config, c => c.Position, SliderPositionChangedObservable(id), source, selector, controlToDataConversion, dataToControlConversion);
}
protected IDisposable SetupControlEnabling(IPropertyManagerPageControl control, IObservable<bool> enabledObservable)
{
return AfterActivationObs
.Select(_ => enabledObservable)
.Switch()
.Subscribe(v => control.Enabled = v);
}
public int NextId()
{
_NextId++;
return _NextId;
}
public void Dispose()
{
Page?.Close(true);
}
protected static void ConfigAngleNumberBox(IPropertyManagerPageNumberbox config)
{
config.SetRange2((int) swNumberboxUnitType_e.swNumberBox_Angle, -10, 10, true, 0.005, 0.010, 0.001);
config.DisplayedUnit = (int) swAngleUnit_e.swDEGREES;
}
public IDisposable CreatePMPControlFromForm(IPropertyManagerPageGroup @group,
Form host,
Action<IPropertyManagerPageWindowFromHandle> config = null) => CreatePMPControlFromForm
(@group,
host,
c =>
{
config?.Invoke(c);
return Disposable.Empty;
});
public IDisposable CreatePMPControlFromForm(IPropertyManagerPageGroup @group, Form host, Func<IPropertyManagerPageWindowFromHandle, IDisposable> config = null)
{
host.Dock = DockStyle.Fill;
host.TopLevel = false;
short controlType = (short) swPropertyManagerPageControlType_e.swControlType_WindowFromHandle;
short align = 0;
var options = (int) swAddControlOptions_e.swControlOptions_Enabled |
(int) swAddControlOptions_e.swControlOptions_Visible;
var dotnet3 =
(IPropertyManagerPageWindowFromHandle)
@group.AddControl2
(NextId(), controlType, "", align, options, "");
dotnet3.SetWindowHandlex64(host.Handle.ToInt64());
var d = config?.Invoke(dotnet3) ?? Disposable.Empty;
//wrapper.SizeChanged += (sender, args) => host.Size = wrapper.Size;
return new ControlHolder(@group, dotnet3, d);
}
/// <summary>
/// Creates a simple label that when the option is some it becomes
/// visibile and displays the text in red.
/// </summary>
/// <param name="group"></param>
/// <param name="errorObservable"></param>
/// <returns></returns>
protected IDisposable CreateErrorLabel(IPropertyManagerPageGroup @group, IObservable<LanguageExt.Option<string>> errorObservable)
{
return CreateLabel(@group, "", "",
label =>
{
var ctrl = (IPropertyManagerPageControl) label;
ctrl.TextColor = ColorTranslator.ToWin32(Color.Red);
return errorObservable.Subscribe
(errorOpt =>
{
errorOpt.Match
(text =>
{
label.Caption = text;
ctrl.Visible = true;
},
() =>
{
ctrl.Visible = false;
});
});
});
}
[Reactive]
public bool IsEditing { get; private set; }
public async Task<bool> Edit()
{
try
{
IsEditing = true;
Show();
return await Closed;
}
finally
{
IsEditing = false;
}
}
protected virtual void OnClose(swPropertyManagerPageCloseReasons_e reason)
{
_Disposable.Dispose();
switch (reason)
{
case swPropertyManagerPageCloseReasons_e.swPropertyManagerPageClose_Cancel:
case swPropertyManagerPageCloseReasons_e.swPropertyManagerPageClose_UnknownReason:
case swPropertyManagerPageCloseReasons_e.swPropertyManagerPageClose_UserEscape:
OnCancel();
_CloseTaskSource.SetResult(false);
break;
case swPropertyManagerPageCloseReasons_e.swPropertyManagerPageClose_Okay:
case swPropertyManagerPageCloseReasons_e.swPropertyManagerPageClose_Apply:
case swPropertyManagerPageCloseReasons_e.swPropertyManagerPageClose_Closed: // renders as green tick, so I guess it means "save"
case swPropertyManagerPageCloseReasons_e.swPropertyManagerPageClose_ParentClosed: // don't know what this is, maybe it applies to `swPropertyManagerPageOptions_e .swPropertyManagerOptions_MultiplePages`
default:
OnCommit();
_CloseTaskSource.SetResult(true);
break;
}
_Deselect.Dispose();
}
protected virtual void OnCommit()
{
}
protected virtual void OnCancel()
{
}
public static SelectionData Create(IEnumerable<object> objects, int mark, IModelDoc2 doc)
{
var objectIds = objects
.Select(doc.GetPersistReference)
.Select(id => new SelectionData.ObjectId(id));
return new SelectionData(objectIds, mark);
}
}
#region control reference holding
/// <summary>
/// It is neccessary to keep reference to the property manager page controls. If you
/// lose the reference then the garbage collector may call the finalize method on the
/// control. The finalize method then will detach all callback or possibly remove
/// the control completely from the page.
///
/// This object just allows the control to be help along with another IDisposable
/// which will get disposed when the dispose method on this class is called.
/// </summary>
public class ControlHolder : IDisposable
{
private readonly List<object> _Objects = new List<object>();
private readonly IDisposable _Disposable = Disposable.Empty;
public ControlHolder(IPropertyManagerPageGroup pageGroup, object control, IDisposable disposable)
{
_Objects.Add(pageGroup);
_Objects.Add(control);
_Disposable = disposable;
}
public ControlHolder(IPropertyManagerPage2 object0 )
{
_Objects.Add(object0);
}
public void Dispose()
{
_Disposable.Dispose();
}
public static IDisposable Create(IPropertyManagerPageGroup @group, object control, params IDisposable[] d)
{
return new ControlHolder(group, control, d.ToCompositeDisposable());
}
public static IDisposable Create(IPropertyManagerPage2 page )
{
return new ControlHolder(page);
}
}
#endregion
public class OptionGroup<T,TOption> : IDisposable
{
private List<IPropertyManagerPageOption> _Options = new List<IPropertyManagerPageOption>();
IPropertyManagerPageGroup _PageGroup;
private CompositeDisposable _Disposable = new CompositeDisposable();
public void Dispose()
{
_Disposable.Dispose();
}
private PropertyManagerPageBase _Page;
private readonly T _Source;
private readonly Expression<Func<T,TOption>> _Selector;
public OptionGroup(PropertyManagerPageBase page, IPropertyManagerPageGroup pageGroup, T source, Expression<Func<T, TOption>> selector)
{
_Page = page;
_PageGroup = pageGroup;
_Source = source;
_Selector = selector;
}
public void CreateOption(
string caption,
TOption match)
{
var id = _Page.NextId();
var box = _PageGroup.CreateOption(id, caption, caption);
_Options.Add(box);
if (_Options.Count == 1)
box.Style = (int) swPropMgrPageOptionStyle_e.swPropMgrPageOptionStyle_FirstInGroup;
var proxy = _Selector.GetProxy(_Source);
var d2 = _Source
.WhenAnyValue(_Selector)
.Subscribe(v1 => box.Checked = v1.Equals(match));
var d1 = _Page.OptionCheckedObservable(id).Subscribe(v2 => proxy.Value = match);
var d = ControlHolder.Create(_PageGroup, box, d1, d2);
_Disposable.Add(d);
}
}
}
| |
//
// CustomPrintWidget.cs
//
// Author:
// Stephane Delcroix <[email protected]>
// Vincent Pomey <[email protected]>
//
// Copyright (C) 2008-2009 Novell, Inc.
// Copyright (C) 2008-2009 Stephane Delcroix
// Copyright (C) 2009 Vincent Pomey
//
// 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 Mono.Unix;
using Gtk;
namespace FSpot.Widgets
{
public class CustomPrintWidget : Table
{
public delegate void ChangedHandler (Gtk.Widget widget);
public enum FitMode {
Zoom,
Scaled,
Fill,
}
Gtk.Image preview_image;
CheckButton fullpage;
RadioButton ppp1, ppp2, ppp4, ppp9, ppp20, ppp30;
RadioButton zoom, fill, scaled;
CheckButton repeat, white_border, crop_marks, print_tags,
print_filename, print_date, print_time, print_comments;
Entry custom_text;
PrintOperation print_operation;
public event ChangedHandler Changed;
private void TriggerChanged (object sender, EventArgs e)
{
if (Changed != null)
Changed (this);
}
public bool CropMarks {
get { return crop_marks.Active; }
}
public string PrintLabelFormat {
get {
string label_format = "{0}";
if (print_tags.Active)
label_format += "\t{4}";
if (print_filename.Active)
label_format += "\t{1}";
if (print_date.Active)
label_format += "\t{2}";
if (print_time.Active)
label_format += " {3}";
if (print_comments.Active)
label_format += "\t{5}";
return label_format;
}
}
public string CustomText {
get { return custom_text.Text; }
}
public FitMode Fitmode {
get {
if (zoom.Active) return FitMode.Zoom;
else if (fill.Active) return FitMode.Fill;
else if (scaled.Active) return FitMode.Scaled;
else
throw new Exception ("Something is wrong on this GUI");
}
}
public int PhotosPerPage {
get {
if (ppp1.Active) return 1;
else if (ppp2.Active) return 2;
else if (ppp4.Active) return 4;
else if (ppp9.Active) return 9;
else if (ppp20.Active) return 20;
else if (ppp30.Active) return 30;
else
throw new Exception ("Something is wrong on this GUI");
}
}
public Gtk.Image PreviewImage {
get { return preview_image; }
}
public bool Repeat {
get { return repeat.Active; }
}
public bool UseFullPage {
get { return fullpage.Active; }
}
public bool WhiteBorders {
get { return white_border.Active; }
}
public CustomPrintWidget (PrintOperation print_operation) : base (2, 4, false)
{
this.print_operation = print_operation;
preview_image = new Gtk.Image ();
Attach (preview_image, 0, 2, 0, 1);
Frame page_frame = new Frame (Catalog.GetString ("Page Setup"));
VBox page_box = new VBox ();
Label current_settings = new Label ();
if (FSpot.Core.Global.PageSetup != null)
current_settings.Text = String.Format (Catalog.GetString ("Paper Size: {0} x {1} mm"),
Math.Round (print_operation.DefaultPageSetup.GetPaperWidth (Unit.Mm), 1),
Math.Round (print_operation.DefaultPageSetup.GetPaperHeight (Unit.Mm), 1));
else
current_settings.Text = String.Format (Catalog.GetString ("Paper Size: {0} x {1} mm"), "...", "...");
page_box.PackStart (current_settings, false, false, 0);
Button page_setup_btn = new Button (Catalog.GetString ("Set Page Size and Orientation"));
page_setup_btn.Clicked += delegate {
this.print_operation.DefaultPageSetup = Print.RunPageSetupDialog (null, print_operation.DefaultPageSetup, this.print_operation.PrintSettings);
current_settings.Text = String.Format (Catalog.GetString ("Paper Size: {0} x {1} mm"),
Math.Round (print_operation.DefaultPageSetup.GetPaperWidth (Unit.Mm), 1),
Math.Round (print_operation.DefaultPageSetup.GetPaperHeight (Unit.Mm), 1));
};
page_box.PackStart (page_setup_btn, false, false, 0);
page_frame.Add (page_box);
Attach (page_frame, 1, 2, 3, 4);
Frame ppp_frame = new Frame (Catalog.GetString ("Photos per page"));
Table ppp_tbl = new Table(2, 7, false);
ppp_tbl.Attach (ppp1 = new RadioButton ("1"), 0, 1, 1, 2);
ppp_tbl.Attach (ppp2 = new RadioButton (ppp1, "2"), 0, 1, 2, 3);
ppp_tbl.Attach (ppp4 = new RadioButton (ppp1, "2 x 2"), 0, 1, 3, 4);
ppp_tbl.Attach (ppp9 = new RadioButton (ppp1, "3 x 3"), 0, 1, 4, 5);
ppp_tbl.Attach (ppp20 = new RadioButton (ppp1, "4 x 5"), 0, 1, 5, 6);
ppp_tbl.Attach (ppp30 = new RadioButton (ppp1, "5 x 6"), 0, 1, 6, 7);
ppp_tbl.Attach (repeat = new CheckButton (Catalog.GetString ("Repeat")), 1, 2, 2, 3);
ppp_tbl.Attach (crop_marks = new CheckButton (Catalog.GetString ("Print cut marks")), 1, 2, 3, 4);
// crop_marks.Toggled += TriggerChanged;
ppp_frame.Child = ppp_tbl;
Attach (ppp_frame, 0, 1, 1, 2);
Frame layout_frame = new Frame (Catalog.GetString ("Photos layout"));
VBox layout_vbox = new VBox();
layout_vbox.PackStart (fullpage = new CheckButton (Catalog.GetString ("Full Page (no margin)")), false, false, 0);
HBox hb = new HBox ();
// Note for translators: "Zoom" is a Fit Mode
hb.PackStart (zoom = new RadioButton (Catalog.GetString ("Zoom")), false, false, 0);
hb.PackStart (fill = new RadioButton (zoom, Catalog.GetString ("Fill")), false, false, 0);
hb.PackStart (scaled = new RadioButton (zoom, Catalog.GetString ("Scaled")), false, false, 0);
zoom.Toggled += TriggerChanged;
fill.Toggled += TriggerChanged;
scaled.Toggled += TriggerChanged;
layout_vbox.PackStart (hb, false, false, 0);
layout_vbox.PackStart (white_border = new CheckButton (Catalog.GetString ("White borders")), false, false, 0);
white_border.Toggled += TriggerChanged;
layout_frame.Child = layout_vbox;
Attach (layout_frame, 1, 2, 1, 2);
Frame cmt_frame = new Frame (Catalog.GetString ("Custom Text"));
cmt_frame.Child = custom_text = new Entry ();
Attach (cmt_frame, 1, 2, 2, 3);
Frame detail_frame = new Frame (Catalog.GetString ("Photos infos"));
VBox detail_vbox = new VBox();
detail_vbox.PackStart (print_filename = new CheckButton (Catalog.GetString ("Print file name")), false, false, 0);
detail_vbox.PackStart (print_date = new CheckButton (Catalog.GetString ("Print photo date")), false, false, 0);
detail_vbox.PackStart (print_time = new CheckButton (Catalog.GetString ("Print photo time")), false, false, 0);
detail_vbox.PackStart (print_tags = new CheckButton (Catalog.GetString ("Print photo tags")), false, false, 0);
detail_vbox.PackStart (print_comments = new CheckButton (Catalog.GetString ("Print photo comment")), false, false, 0);
detail_frame.Child = detail_vbox;
Attach (detail_frame, 0, 1, 2, 4);
TriggerChanged (this, null);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using ToolKit.DirectoryServices.ActiveDirectory;
using Xunit;
namespace UnitTests.DirectoryServices.ActiveDirectory
{
[SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1600:ElementsMustBeDocumented",
Justification = "Test Suites do not need XML Documentation.")]
public class UserTests
{
[Fact]
public void AccountExpires_Should_ReturnExpectedResult()
{
// Arrange
var expected = DateTime.Parse("1893-04-11T23:47:16.8775807", null, DateTimeStyles.AdjustToUniversal);
var user = new User(InitializeProperties());
// Act
var actual = user.AccountExpires;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void AccountExpires_Should_ReturnsMaxDateTime_When_EmptyString()
{
// Arrange
var expected = DateTime.MaxValue;
var user = new User(UserAccountExpireEmpty());
// Act
var actual = user.AccountExpires;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void AccountExpires_Should_ReturnsMaxDateTime_When_InvalidNumber()
{
// Arrange
var expected = DateTime.MaxValue;
var user = new User(UserAccountExpireInvalid());
// Act
var actual = user.AccountExpires;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void BadPasswordCount_Should_ReturnExpectedResult()
{
// Arrange
var expected = 2;
var user = new User(InitializeProperties());
// Act
var actual = user.BadPasswordCount;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void BadPasswordTime_Should_ReturnExpectedResult()
{
// Arrange
var expected = DateTime.Parse("2015-10-05T11:00:51.0451845", null, DateTimeStyles.AdjustToUniversal);
var user = new User(InitializeProperties());
// Act
var actual = user.BadPasswordTime;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Category_Should_ReturnExpectedResult()
{
// Arrange
var expected = "CN=Person,CN=Schema,CN=Configuration,DC=company,DC=local";
var user = new User(InitializeProperties());
// Act
var actual = user.Category;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Changed_Should_ReturnExpectedResult()
{
// Arrange
var expected = new DateTime(2015, 10, 28, 3, 39, 34, DateTimeKind.Utc);
var user = new User(InitializeProperties());
// Act
var actual = user.Changed;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void City_Should_ReturnExpectedResult()
{
// Arrange
var expected = "Bethesda";
var user = new User(InitializeProperties());
// Act
var actual = user.City;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void CommonName_Should_ReturnExpectedResult()
{
// Arrange
var expected = "USER01";
var user = new User(InitializeProperties());
// Act
var actual = user.CommonName;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Company_Should_ReturnExpectedResult()
{
// Arrange
var expected = "Company";
var user = new User(InitializeProperties());
// Act
var actual = user.Company;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Country_Should_ReturnExpectedResult()
{
// Arrange
var expected = "Aruba";
var user = new User(InitializeProperties());
// Act
var actual = user.Country;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void CountryCode_Should_ReturnExpectedResult()
{
// Arrange
var expected = 553;
var user = new User(InitializeProperties());
// Act
var actual = user.CountryCode;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Created_Should_ReturnExpectedResult()
{
// Arrange
var expected = new DateTime(2015, 10, 5, 11, 0, 50, DateTimeKind.Utc);
var user = new User(InitializeProperties());
// Act
var actual = user.Created;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Ctor_Should_ReturnExpectedResult()
{
// Arrange
var obj = InitializeProperties();
// Act
var user = new User(obj);
// Assert
Assert.NotNull(user);
}
[Fact]
public void Ctor_Should_ThrowException_When_NonUserObject()
{
// Arrange
var obj = NotAUser();
// Act/Assert
Assert.Throws<ArgumentException>(() =>
{
_ = new User(obj);
});
}
[Fact]
public void Department_Should_ReturnExpectedResult()
{
// Arrange
var expected = "Accounting";
var user = new User(InitializeProperties());
// Act
var actual = user.Department;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Description_Should_ReturnExpectedResult()
{
// Arrange
var expected = "User For Stuff";
var user = new User(InitializeProperties());
// Act
var actual = user.Description;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Disabled_Should_ReturnExpectedResult()
{
// Arrange
var user = new User(InitializeProperties());
// Act
var actual = user.Disabled;
// Assert
Assert.False(actual);
}
[Fact]
public void Disabled_Should_ReturnTrue_When_UserIsDisabled()
{
// Arrange
var user = new User(DisabledUser());
// Act
var actual = user.Disabled;
// Assert
Assert.True(actual);
}
[Fact]
public void DisplayName_Should_ReturnExpectedResult()
{
// Arrange
var expected = "USER01";
var user = new User(InitializeProperties());
// Act
var actual = user.DisplayName;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void DistinguishedName_Should_ReturnExpectedResult()
{
// Arrange
var expected = "CN=USER01,CN=Users,DC=company,DC=local";
var user = new User(InitializeProperties());
// Act
var actual = user.DistinguishedName;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void EmailAddress_Should_ReturnExpectedResult()
{
// Arrange
var expected = "[email protected]";
var user = new User(InitializeProperties());
// Act
var actual = user.EmailAddress;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Fax_Should_ReturnExpectedResult()
{
// Arrange
var expected = "202-555-1212";
var user = new User(InitializeProperties());
// Act
var actual = user.Fax;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void FirstName_Should_ReturnExpectedResult()
{
// Arrange
var expected = "First";
var user = new User(InitializeProperties());
// Act
var actual = user.FirstName;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Groups_Should_ReturnExpectedResult()
{
// Arrange
var expected = new List<string>()
{
"CN=group1,CN=Users,DC=company,DC=local"
};
var user = new User(InitializeProperties());
// Act
var actual = user.Groups;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Guid_Should_ReturnExpectedResult()
{
// Arrange
var expected = Guid.Parse("cd29418b-45d7-4d55-952e-e4da717172af");
var user = new User(InitializeProperties());
// Act
var actual = user.Guid;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void HomeDirectory_Should_ReturnExpectedResult()
{
// Arrange
var expected = @"\\FS01\USER01";
var user = new User(InitializeProperties());
// Act
var actual = user.HomeDirectory;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void HomeDrive_Should_ReturnExpectedResult()
{
// Arrange
var expected = "H:";
var user = new User(InitializeProperties());
// Act
var actual = user.HomeDrive;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void HomePhone_Should_ReturnExpectedResult()
{
// Arrange
var expected = "202-555-1212";
var user = new User(InitializeProperties());
// Act
var actual = user.HomePhone;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void IpPhone_Should_ReturnExpectedResult()
{
// Arrange
var expected = "202-555-1212";
var user = new User(InitializeProperties());
// Act
var actual = user.IpPhone;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void IsAdministrativeAccount_Should_ReturnFalse_When_NotAdministrativeUser()
{
// Arrange
var user = new User(InitializeProperties());
// Act
var actual = user.IsAdministrativeAccount();
// Assert
Assert.False(actual);
}
[Fact]
public void IsAdministrativeAccount_Should_ReturnTrue_When_AdministrativeUser()
{
// Arrange
var user = new User(AdministrativeAccount());
// Act
var actual = user.IsAdministrativeAccount();
// Assert
Assert.True(actual);
}
[Fact]
public void IsApplicationAccount_Should_ReturnTrue_When_ApplicationAccount()
{
// Arrange
var user = new User(ApplicationAccount());
// Act
var actual = user.IsApplicationAccount();
// Assert
Assert.True(actual);
}
[Fact]
public void IsRegularAccount_Should_ReturnTrue_When_RegularAccount()
{
// Arrange
var user = new User(InitializeProperties());
// Act
var actual = user.IsRegularAccount();
// Assert
Assert.True(actual);
}
[Fact]
public void IsServiceAccount_Should_ReturnTrue_When_ServiceAccount()
{
// Arrange
var user = new User(ServiceAccount());
// Act
var actual = user.IsServiceAccount();
// Assert
Assert.True(actual);
}
[Fact]
public void LastLogoff_Should_ReturnExpectedResult()
{
// Arrange
var expected = DateTime.Parse("2015-10-29T00:24:10.5124008", null, DateTimeStyles.AdjustToUniversal);
var user = new User(InitializeProperties());
// Act
var actual = user.LastLogoff;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void LastLogon_Should_ReturnExpectedResult()
{
// Arrange
var expected = DateTime.Parse("2015-10-17T21:28:33.7228038", null, DateTimeStyles.AdjustToUniversal);
var user = new User(InitializeProperties());
// Act
var actual = user.LastLogon;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void LastLogonTimestamp_Should_ReturnExpectedResult()
{
// Arrange
var expected = DateTime.Parse("2015-10-27T22:28:54.7417734", null, DateTimeStyles.AdjustToUniversal);
var user = new User(InitializeProperties());
// Act
var actual = user.LastLogonTimestamp;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void LastName_Should_ReturnExpectedResult()
{
// Arrange
var expected = "Last";
var user = new User(InitializeProperties());
// Act
var actual = user.LastName;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void LogonCount_Should_ReturnExpectedResult()
{
// Arrange
var expected = 60;
var user = new User(InitializeProperties());
// Act
var actual = user.LogonCount;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void LogonScript_Should_ReturnExpectedResult()
{
// Arrange
var expected = @"\\FS01\Scripts\logon.bat";
var user = new User(InitializeProperties());
// Act
var actual = user.LogonScript;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Manager_Should_ReturnExpectedResult()
{
// Arrange
var expected = "CN=manager1,CN=Users,DC=company,DC=local";
var user = new User(InitializeProperties());
// Act
var actual = user.Manager;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void MiddleInitial_Should_ReturnExpectedResult()
{
// Arrange
var expected = "C";
var user = new User(InitializeProperties());
// Act
var actual = user.MiddleInitial;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void MobilePhone_Should_ReturnExpectedResult()
{
// Arrange
var expected = "202-555-1212";
var user = new User(InitializeProperties());
// Act
var actual = user.MobilePhone;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Modified_Should_ReturnExpectedResult()
{
// Arrange
var expected = new DateTime(2015, 10, 28, 3, 39, 34, DateTimeKind.Utc);
var user = new User(InitializeProperties());
// Act
var actual = user.Modified;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Name_Should_ReturnExpectedResult()
{
// Arrange
var expected = "USER01";
var user = new User(InitializeProperties());
// Act
var actual = user.Name;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Notes_Should_ReturnExpectedResult()
{
// Arrange
var expected = "A note about the user.";
var user = new User(InitializeProperties());
// Act
var actual = user.Notes;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Office_Should_ReturnExpectedResult()
{
// Arrange
var expected = "Ashburn";
var user = new User(InitializeProperties());
// Act
var actual = user.Office;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Pager_Should_ReturnExpectedResult()
{
// Arrange
var expected = "202-555-1212";
var user = new User(InitializeProperties());
// Act
var actual = user.Pager;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void PasswordLastSet_Should_ReturnExpectedResult()
{
// Arrange
var expected = DateTime.Parse("2015-10-05T11:00:51.0459354", null, DateTimeStyles.AdjustToUniversal);
var user = new User(InitializeProperties());
// Act
var actual = user.PasswordLastSet;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void PoBox_Should_ReturnExpectedResult()
{
// Arrange
var expected = "151515";
var user = new User(InitializeProperties());
// Act
var actual = user.PoBox;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void PostalCode_Should_ReturnExpectedResult()
{
// Arrange
var expected = "20016";
var user = new User(InitializeProperties());
// Act
var actual = user.PostalCode;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void PrimaryGroupId_Should_ReturnExpectedResult()
{
// Arrange
var expected = 515;
var user = new User(InitializeProperties());
// Act
var actual = user.PrimaryGroupId;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void ProfilePath_Should_ReturnExpectedResult()
{
// Arrange
var expected = @"\\FS01\Profiles\USER01";
var user = new User(InitializeProperties());
// Act
var actual = user.ProfilePath;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Province_Should_ReturnExpectedResult()
{
// Arrange
var expected = "Maine";
var user = new User(InitializeProperties());
// Act
var actual = user.Province;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Region_Should_ReturnExpectedResult()
{
// Arrange
var expected = "Aruba";
var user = new User(InitializeProperties());
// Act
var actual = user.Region;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void SamAccountName_Should_ReturnExpectedResult()
{
// Arrange
var expected = "USER01";
var user = new User(InitializeProperties());
// Act
var actual = user.SamAccountName;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Sid_Should_ReturnExpectedResult()
{
// Arrange
var expected = "S-1-5-21-1501611499-78517565-1004253924-2105";
var user = new User(InitializeProperties());
// Act
var actual = user.Sid;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void State_Should_ReturnExpectedResult()
{
// Arrange
var expected = "Maine";
var user = new User(InitializeProperties());
// Act
var actual = user.State;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void StreetAddress_Should_ReturnExpectedResult()
{
// Arrange
var expected = "123 Any Street";
var user = new User(InitializeProperties());
// Act
var actual = user.StreetAddress;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void TelephoneNumber_Should_ReturnExpectedResult()
{
// Arrange
var expected = "202-555-1212";
var user = new User(InitializeProperties());
// Act
var actual = user.TelephoneNumber;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Title_Should_ReturnExpectedResult()
{
// Arrange
var expected = "Software Engineer";
var user = new User(InitializeProperties());
// Act
var actual = user.Title;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UpdateSequenceNumberCreated_Should_ReturnExpectedResult()
{
// Arrange
var expected = 43640;
var user = new User(InitializeProperties());
// Act
var actual = user.UpdateSequenceNumberCreated;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UpdateSequenceNumberCurrent_Should_ReturnExpectedResult()
{
// Arrange
var expected = 129204;
var user = new User(InitializeProperties());
// Act
var actual = user.UpdateSequenceNumberCurrent;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UserAccountControl_Should_ReturnExpectedResult()
{
// Arrange
var expected = 4096;
var user = new User(InitializeProperties());
// Act
var actual = user.UserAccountControl;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UserPrincipalName_Should_ReturnExpectedResult()
{
// Arrange
var expected = "[email protected]";
var user = new User(InitializeProperties());
// Act
var actual = user.UserPrincipalName;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void WebSite_Should_ReturnExpectedResult()
{
// Arrange
var expected = "http://company.local/user01";
var user = new User(InitializeProperties());
// Act
var actual = user.WebSite;
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void Zip_Should_ReturnExpectedResult()
{
// Arrange
var expected = "20016";
var user = new User(InitializeProperties());
// Act
var actual = user.Zip;
// Assert
Assert.Equal(expected, actual);
}
private Dictionary<string, object> AdministrativeAccount()
{
var properties = InitializeProperties();
properties["samaccountname"] = "account-adm";
return properties;
}
private Dictionary<string, object> ApplicationAccount()
{
var properties = InitializeProperties();
properties["samaccountname"] = "account-app";
return properties;
}
private Dictionary<string, object> DisabledUser()
{
var properties = InitializeProperties();
properties["useraccountcontrol"] = 66050;
return properties;
}
private Dictionary<string, object> InitializeProperties()
{
return new Dictionary<string, object>()
{
{ "accountexpires", 92233720368775807 },
{ "badpwdcount", 2 },
{ "badpasswordtime", 130885164510451845 },
{ "objectcategory", "CN=Person,CN=Schema,CN=Configuration,DC=company,DC=local" },
{ "cn", "USER01" },
{ "useraccountcontrol", 4096 },
{ "c", "Aruba" },
{ "countrycode", 553 },
{ "whencreated", DateTime.Parse("10/5/2015 11:00:50", null, DateTimeStyles.AdjustToUniversal) },
{ "description", "User For Stuff" },
{ "displayname", "USER01" },
{ "distinguishedname", "CN=USER01,CN=Users,DC=company,DC=local" },
{ "userprincipalname", "[email protected]" },
{ "memberof", "CN=group1,CN=Users,DC=company,DC=local" },
{
"objectguid", new Byte[]
{
0x8B, 0x41, 0x29, 0xCD, 0xD7, 0x45, 0x55, 0x4D,
0x95, 0x2E, 0xE4, 0xDA, 0x71, 0x71, 0x72, 0xAF
}
},
{ "lastlogoff", 130905518505124008 },
{ "location", "Ashburn" },
{ "logoncount", 60 },
{ "manager", "CN=manager1,CN=Users,DC=company,DC=local" },
{ "whenchanged", DateTime.Parse("10/28/2015 3:39:34", null, DateTimeStyles.AdjustToUniversal) },
{ "name", "USER01" },
{ "department", "Accounting" },
{ "l", "Bethesda" },
{ "company", "Company" },
{ "pwdlastset", 130885164510459354 },
{ "primarygroupid", 515 },
{ "samaccountname", "USER01" },
{
"objectsid", new Byte[]
{
0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
0x15, 0x00, 0x00, 0x00, 0xEB, 0xC5, 0x80, 0x59,
0x3D, 0x15, 0xAE, 0x04, 0xE4, 0xB2, 0xDB, 0x3B,
0x39, 0x08, 0x00, 0x00
}
},
{ "usncreated", (Int64)43640 },
{ "usnchanged", (Int64)129204 },
{ "objectclass", new[] { "top", "person", "organizationalPerson", "user" } },
{ "mail", "[email protected]" },
{ "facsimiletelephonenumber", "202-555-1212" },
{ "givenname", "First" },
{ "homedirectory", @"\\FS01\USER01" },
{ "homedrive", "H:" },
{ "homephone", "202-555-1212" },
{ "ipphone", "202-555-1212" },
{ "lastlogon", 130895909137228038 },
{ "lastlogontimestamp", 130904585347417734 },
{ "sn", "Last" },
{ "scriptpath", @"\\FS01\Scripts\logon.bat" },
{ "initials", "C" },
{ "mobile", "202-555-1212" },
{ "info", "A note about the user." },
{ "physicaldeliveryofficename", "Ashburn" },
{ "pager", "202-555-1212" },
{ "postofficebox", 151515 },
{ "postalcode", 20016 },
{ "profilepath", @"\\FS01\Profiles\USER01" },
{ "st", "Maine" },
{ "streetaddress", "123 Any Street" },
{ "telephonenumber", "202-555-1212" },
{ "title", "Software Engineer" },
{ "wwwhomepage", "http://company.local/user01" }
};
}
private Dictionary<string, object> NotAUser()
{
var properties = InitializeProperties();
properties["objectclass"] = new[] { "top", "group" };
return properties;
}
private Dictionary<string, object> ServiceAccount()
{
var properties = InitializeProperties();
properties["samaccountname"] = "account-svc";
return properties;
}
private Dictionary<string, object> UserAccountExpireEmpty()
{
var properties = InitializeProperties();
properties["accountexpires"] = String.Empty;
return properties;
}
private Dictionary<string, object> UserAccountExpireInvalid()
{
var properties = InitializeProperties();
properties["accountexpires"] = -1;
return properties;
}
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Testing.TimeZones;
using NodaTime.Text;
using NodaTime.TimeZones;
using NUnit.Framework;
namespace NodaTime.Test
{
/// <summary>
/// Tests for aspects of DateTimeZone to do with converting from LocalDateTime and
/// LocalDate to ZonedDateTime.
/// </summary>
// TODO: Fix all tests to use SingleTransitionZone.
public partial class DateTimeZoneTest
{
// Sample time zones for DateTimeZone.AtStartOfDay etc. I didn't want to only test midnight transitions.
private static readonly DateTimeZone LosAngeles = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
private static readonly DateTimeZone NewZealand = DateTimeZoneProviders.Tzdb["Pacific/Auckland"];
private static readonly DateTimeZone Paris = DateTimeZoneProviders.Tzdb["Europe/Paris"];
private static readonly DateTimeZone NewYork = DateTimeZoneProviders.Tzdb["America/New_York"];
private static readonly DateTimeZone Pacific = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
/// <summary>
/// Local midnight at the start of the transition (June 1st) becomes 1am.
/// </summary>
private static readonly DateTimeZone TransitionForwardAtMidnightZone =
new SingleTransitionDateTimeZone(Instant.FromUtc(2000, 6, 1, 2, 0), Offset.FromHours(-2), Offset.FromHours(-1));
/// <summary>
/// Local 1am at the start of the transition (June 1st) becomes midnight.
/// </summary>
private static readonly DateTimeZone TransitionBackwardToMidnightZone =
new SingleTransitionDateTimeZone(Instant.FromUtc(2000, 6, 1, 3, 0), Offset.FromHours(-2), Offset.FromHours(-3));
/// <summary>
/// Local 11.20pm at the start of the transition (May 30th) becomes 12.20am of June 1st.
/// </summary>
private static readonly DateTimeZone TransitionForwardBeforeMidnightZone =
new SingleTransitionDateTimeZone(Instant.FromUtc(2000, 6, 1, 1, 20), Offset.FromHours(-2), Offset.FromHours(-1));
/// <summary>
/// Local 12.20am at the start of the transition (June 1st) becomes 11.20pm of the previous day.
/// </summary>
private static readonly DateTimeZone TransitionBackwardAfterMidnightZone =
new SingleTransitionDateTimeZone(Instant.FromUtc(2000, 6, 1, 2, 20), Offset.FromHours(-2), Offset.FromHours(-3));
private static readonly LocalDate TransitionDate = new LocalDate(2000, 6, 1);
[Test]
public void AmbiguousStartOfDay_TransitionAtMidnight()
{
// Occurrence before transition
var expected = new ZonedDateTime(new LocalDateTime(2000, 6, 1, 0, 0).WithOffset(Offset.FromHours(-2)),
TransitionBackwardToMidnightZone);
var actual = TransitionBackwardToMidnightZone.AtStartOfDay(TransitionDate);
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected, TransitionDate.AtStartOfDayInZone(TransitionBackwardToMidnightZone));
}
[Test]
public void AmbiguousStartOfDay_TransitionAfterMidnight()
{
// Occurrence before transition
var expected = new ZonedDateTime(new LocalDateTime(2000, 6, 1, 0, 0).WithOffset(Offset.FromHours(-2)),
TransitionBackwardAfterMidnightZone);
var actual = TransitionBackwardAfterMidnightZone.AtStartOfDay(TransitionDate);
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected, TransitionDate.AtStartOfDayInZone(TransitionBackwardAfterMidnightZone));
}
[Test]
public void SkippedStartOfDay_TransitionAtMidnight()
{
// 1am because of the skip
var expected = new ZonedDateTime(new LocalDateTime(2000, 6, 1, 1, 0).WithOffset(Offset.FromHours(-1)),
TransitionForwardAtMidnightZone);
var actual = TransitionForwardAtMidnightZone.AtStartOfDay(TransitionDate);
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected, TransitionDate.AtStartOfDayInZone(TransitionForwardAtMidnightZone));
}
[Test]
public void SkippedStartOfDay_TransitionBeforeMidnight()
{
// 12.20am because of the skip
var expected = new ZonedDateTime(new LocalDateTime(2000, 6, 1, 0, 20).WithOffset(Offset.FromHours(-1)),
TransitionForwardBeforeMidnightZone);
var actual = TransitionForwardBeforeMidnightZone.AtStartOfDay(TransitionDate);
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected, TransitionDate.AtStartOfDayInZone(TransitionForwardBeforeMidnightZone));
}
[Test]
public void UnambiguousStartOfDay()
{
// Just a simple midnight in March.
var expected = new ZonedDateTime(new LocalDateTime(2000, 3, 1, 0, 0).WithOffset(Offset.FromHours(-2)),
TransitionForwardAtMidnightZone);
var actual = TransitionForwardAtMidnightZone.AtStartOfDay(new LocalDate(2000, 3, 1));
Assert.AreEqual(expected, actual);
Assert.AreEqual(expected, new LocalDate(2000, 3, 1).AtStartOfDayInZone(TransitionForwardAtMidnightZone));
}
private static void AssertImpossible(LocalDateTime localTime, DateTimeZone zone)
{
var mapping = zone.MapLocal(localTime);
Assert.AreEqual(0, mapping.Count);
var e = Assert.Throws<SkippedTimeException>(() => mapping.Single());
Assert.AreEqual(localTime, e.LocalDateTime);
Assert.AreEqual(zone, e.Zone);
e = Assert.Throws<SkippedTimeException>(() => mapping.First());
Assert.AreEqual(localTime, e.LocalDateTime);
Assert.AreEqual(zone, e.Zone);
e = Assert.Throws<SkippedTimeException>(() => mapping.Last());
Assert.AreEqual(localTime, e.LocalDateTime);
Assert.AreEqual(zone, e.Zone);
}
private static void AssertAmbiguous(LocalDateTime localTime, DateTimeZone zone)
{
ZonedDateTime earlier = zone.MapLocal(localTime).First();
ZonedDateTime later = zone.MapLocal(localTime).Last();
Assert.AreEqual(localTime, earlier.LocalDateTime);
Assert.AreEqual(localTime, later.LocalDateTime);
Assert.That(earlier.ToInstant(), Is.LessThan(later.ToInstant()));
var mapping = zone.MapLocal(localTime);
Assert.AreEqual(2, mapping.Count);
var e = Assert.Throws<AmbiguousTimeException>(() => mapping.Single());
Assert.AreEqual(localTime, e.LocalDateTime);
Assert.AreEqual(zone, e.Zone);
Assert.AreEqual(earlier, e.EarlierMapping);
Assert.AreEqual(later, e.LaterMapping);
Assert.AreEqual(earlier, mapping.First());
Assert.AreEqual(later, mapping.Last());
}
private static void AssertOffset(int expectedHours, LocalDateTime localTime, DateTimeZone zone)
{
var mapping = zone.MapLocal(localTime);
Assert.AreEqual(1, mapping.Count);
var zoned = mapping.Single();
Assert.AreEqual(zoned, mapping.First());
Assert.AreEqual(zoned, mapping.Last());
int actualHours = zoned.Offset.Milliseconds / NodaConstants.MillisecondsPerHour;
Assert.AreEqual(expectedHours, actualHours);
}
// Los Angeles goes from -7 to -8 on November 7th 2010 at 2am wall time
[Test]
public void GetOffsetFromLocal_LosAngelesFallTransition()
{
var before = new LocalDateTime(2010, 11, 7, 0, 30);
var atTransition = new LocalDateTime(2010, 11, 7, 1, 0);
var ambiguous = new LocalDateTime(2010, 11, 7, 1, 30);
var after = new LocalDateTime(2010, 11, 7, 2, 30);
AssertOffset(-7, before, LosAngeles);
AssertAmbiguous(atTransition, LosAngeles);
AssertAmbiguous(ambiguous, LosAngeles);
AssertOffset(-8, after, LosAngeles);
}
[Test]
public void GetOffsetFromLocal_LosAngelesSpringTransition()
{
var before = new LocalDateTime(2010, 3, 14, 1, 30);
var impossible = new LocalDateTime(2010, 3, 14, 2, 30);
var atTransition = new LocalDateTime(2010, 3, 14, 3, 0);
var after = new LocalDateTime(2010, 3, 14, 3, 30);
AssertOffset(-8, before, LosAngeles);
AssertImpossible(impossible, LosAngeles);
AssertOffset(-7, atTransition, LosAngeles);
AssertOffset(-7, after, LosAngeles);
}
// New Zealand goes from +13 to +12 on April 4th 2010 at 3am wall time
[Test]
public void GetOffsetFromLocal_NewZealandFallTransition()
{
var before = new LocalDateTime(2010, 4, 4, 1, 30);
var atTransition = new LocalDateTime(2010, 4, 4, 2, 0);
var ambiguous = new LocalDateTime(2010, 4, 4, 2, 30);
var after = new LocalDateTime(2010, 4, 4, 3, 30);
AssertOffset(+13, before, NewZealand);
AssertAmbiguous(atTransition, NewZealand);
AssertAmbiguous(ambiguous, NewZealand);
AssertOffset(+12, after, NewZealand);
}
// New Zealand goes from +12 to +13 on September 26th 2010 at 2am wall time
[Test]
public void GetOffsetFromLocal_NewZealandSpringTransition()
{
var before = new LocalDateTime(2010, 9, 26, 1, 30);
var impossible = new LocalDateTime(2010, 9, 26, 2, 30);
var atTransition = new LocalDateTime(2010, 9, 26, 3, 0);
var after = new LocalDateTime(2010, 9, 26, 3, 30);
AssertOffset(+12, before, NewZealand);
AssertImpossible(impossible, NewZealand);
AssertOffset(+13, atTransition, NewZealand);
AssertOffset(+13, after, NewZealand);
}
// Paris goes from +1 to +2 on March 28th 2010 at 2am wall time
[Test]
public void GetOffsetFromLocal_ParisFallTransition()
{
var before = new LocalDateTime(2010, 10, 31, 1, 30);
var atTransition = new LocalDateTime(2010, 10, 31, 2, 0);
var ambiguous = new LocalDateTime(2010, 10, 31, 2, 30);
var after = new LocalDateTime(2010, 10, 31, 3, 30);
AssertOffset(2, before, Paris);
AssertAmbiguous(ambiguous, Paris);
AssertAmbiguous(atTransition, Paris);
AssertOffset(1, after, Paris);
}
[Test]
public void GetOffsetFromLocal_ParisSpringTransition()
{
var before = new LocalDateTime(2010, 3, 28, 1, 30);
var impossible = new LocalDateTime(2010, 3, 28, 2, 30);
var atTransition = new LocalDateTime(2010, 3, 28, 3, 0);
var after = new LocalDateTime(2010, 3, 28, 3, 30);
AssertOffset(1, before, Paris);
AssertImpossible(impossible, Paris);
AssertOffset(2, atTransition, Paris);
AssertOffset(2, after, Paris);
}
[Test]
public void MapLocalDateTime_UnambiguousDateReturnsUnambiguousMapping()
{
//2011-11-09 01:30:00 - not ambiguous in America/New York timezone
var unambigiousTime = new LocalDateTime(2011, 11, 9, 1, 30);
var mapping = NewYork.MapLocal(unambigiousTime);
Assert.AreEqual(1, mapping.Count);
}
[Test]
public void MapLocalDateTime_AmbiguousDateReturnsAmbigousMapping()
{
//2011-11-06 01:30:00 - falls during DST - EST conversion in America/New York timezone
var ambiguousTime = new LocalDateTime(2011, 11, 6, 1, 30);
var mapping = NewYork.MapLocal(ambiguousTime);
Assert.AreEqual(2, mapping.Count);
}
[Test]
public void MapLocalDateTime_SkippedDateReturnsSkippedMapping()
{
//2011-03-13 02:30:00 - falls during EST - DST conversion in America/New York timezone
var skippedTime = new LocalDateTime(2011, 3, 13, 2, 30);
var mapping = NewYork.MapLocal(skippedTime);
Assert.AreEqual(0, mapping.Count);
}
// Some zones skipped dates by changing from UTC-lots to UTC+lots. For example, Samoa (Pacific/Apia)
// skipped December 30th 2011, going from 23:59:59 December 29th local time UTC-10
// to 00:00:00 December 31st local time UTC+14
[Test]
[TestCase("Pacific/Apia", "2011-12-30")]
[TestCase("Pacific/Enderbury", "1994-12-31")]
[TestCase("Pacific/Kiritimati", "1994-12-31")]
[TestCase("Pacific/Kwajalein", "1993-08-21")]
public void AtStartOfDay_DayDoesntExist(string zoneId, string localDate)
{
LocalDate badDate = LocalDatePattern.Iso.Parse(localDate).Value;
DateTimeZone zone = DateTimeZoneProviders.Tzdb[zoneId];
var exception = Assert.Throws<SkippedTimeException>(() => zone.AtStartOfDay(badDate));
Assert.AreEqual(badDate + LocalTime.Midnight, exception.LocalDateTime);
}
[Test]
public void AtStrictly_InWinter()
{
var when = Pacific.AtStrictly(new LocalDateTime(2009, 12, 22, 21, 39, 30));
Assert.AreEqual(2009, when.Year);
Assert.AreEqual(12, when.Month);
Assert.AreEqual(22, when.Day);
Assert.AreEqual(IsoDayOfWeek.Tuesday, when.DayOfWeek);
Assert.AreEqual(21, when.Hour);
Assert.AreEqual(39, when.Minute);
Assert.AreEqual(30, when.Second);
Assert.AreEqual(Offset.FromHours(-8), when.Offset);
}
[Test]
public void AtStrictly_InSummer()
{
var when = Pacific.AtStrictly(new LocalDateTime(2009, 6, 22, 21, 39, 30));
Assert.AreEqual(2009, when.Year);
Assert.AreEqual(6, when.Month);
Assert.AreEqual(22, when.Day);
Assert.AreEqual(21, when.Hour);
Assert.AreEqual(39, when.Minute);
Assert.AreEqual(30, when.Second);
Assert.AreEqual(Offset.FromHours(-7), when.Offset);
}
/// <summary>
/// Pacific time changed from -7 to -8 at 2am wall time on November 2nd 2009,
/// so 2am became 1am.
/// </summary>
[Test]
public void AtStrictly_ThrowsWhenAmbiguous()
{
Assert.Throws<AmbiguousTimeException>(() => Pacific.AtStrictly(new LocalDateTime(2009, 11, 1, 1, 30, 0)));
}
/// <summary>
/// Pacific time changed from -8 to -7 at 2am wall time on March 8th 2009,
/// so 2am became 3am. This means that 2.30am doesn't exist on that day.
/// </summary>
[Test]
public void AtStrictly_ThrowsWhenSkipped()
{
Assert.Throws<SkippedTimeException>(() => Pacific.AtStrictly(new LocalDateTime(2009, 3, 8, 2, 30, 0)));
}
/// <summary>
/// Pacific time changed from -7 to -8 at 2am wall time on November 2nd 2009,
/// so 2am became 1am. We'll return the earlier result, i.e. with the offset of -7
/// </summary>
[Test]
public void AtLeniently_AmbiguousTime_ReturnsEarlierMapping()
{
var local = new LocalDateTime(2009, 11, 1, 1, 30, 0);
var zoned = Pacific.AtLeniently(local);
Assert.AreEqual(local, zoned.LocalDateTime);
Assert.AreEqual(Offset.FromHours(-7), zoned.Offset);
}
/// <summary>
/// Pacific time changed from -8 to -7 at 2am wall time on March 8th 2009,
/// so 2am became 3am. This means that 2:30am doesn't exist on that day.
/// We'll return 3:30am, the forward-shifted value.
/// </summary>
[Test]
public void AtLeniently_ReturnsForwardShiftedValue()
{
var local = new LocalDateTime(2009, 3, 8, 2, 30, 0);
var zoned = Pacific.AtLeniently(local);
Assert.AreEqual(new LocalDateTime(2009, 3, 8, 3, 30, 0), zoned.LocalDateTime);
Assert.AreEqual(Offset.FromHours(-7), zoned.Offset);
}
[Test]
public void ResolveLocal()
{
// Don't need much for this - it only delegates.
var ambiguous = new LocalDateTime(2009, 11, 1, 1, 30, 0);
var skipped = new LocalDateTime(2009, 3, 8, 2, 30, 0);
Assert.AreEqual(Pacific.AtLeniently(ambiguous), Pacific.ResolveLocal(ambiguous, Resolvers.LenientResolver));
Assert.AreEqual(Pacific.AtLeniently(skipped), Pacific.ResolveLocal(skipped, Resolvers.LenientResolver));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Almanac.Model;
using Almanac.Model.Abstractions;
using Almanac.Serialization.Abstractions;
using Almanac.Serialization.Protocol;
using Calendar = Almanac.Model.Calendar;
namespace Almanac.Serialization
{
public class CalendarSerializer : AbstractCalendarSerializer<Calendar, BclTimeZone, Event>
{
private static readonly Lazy<string> ProductIdentifier = new Lazy<string>(CreateProductIdentifier);
private static readonly Version SerializerVersion = new Version("2.0");
private static string CreateProductIdentifier()
{
var versionAttribute = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyVersionAttribute>();
var version = versionAttribute?.Version ?? "unknown version";
return $"-//Almanac//{version}//EN";
}
protected override Component SerializeCalendar(Calendar calendar)
{
var component = new Component(ComponentName.Calendar);
component.AddProperty(new Property(PropertyName.ProductIdentifier) {Value = ProductIdentifier.Value});
component.AddProperty(new Property(PropertyName.Version) {Value = "2.0"});
if (calendar.Method != null) {
component.AddProperty(new Property(PropertyName.Method) {Value = calendar.Method.Value});
}
var dates = calendar.Events.SelectMany(e => new[] {e.Start, e.End}).Where(d => d != null);
var timezones = dates.GroupBy(d => d.TimeZone).Select(g => new {
TimeZone = g.Key,
MinDate = g.Min(e => e.DateTime),
MaxDate = g.Max(e => e.DateTime)
});
foreach (var timezone in timezones) {
component.AddComponent(SerializeTimeZone(timezone.TimeZone, timezone.MinDate, timezone.MaxDate));
}
foreach (var @event in calendar.Events) {
component.AddComponent(SerializeEvent(@event));
}
// TODO Other calendar components
return component;
}
protected override Component SerializeTimeZone(BclTimeZone timezone, DateTime minDate, DateTime maxDate)
{
var component = new Component(ComponentName.TimeZone);
SerializeTimeZoneId(timezone, component);
SerializeTimeZoneLastUpdate(timezone, component);
SerializeTimeZoneUrl(timezone, component);
SerializeTimeZoneNonStandardProperties(timezone, component);
SerializeTimeZoneIanaProperties(timezone, component);
SerializeTimeZoneObservanceRules(timezone, component, minDate, maxDate);
return component;
}
protected virtual void SerializeTimeZoneId(BclTimeZone timezone, Component component)
{
if (String.IsNullOrWhiteSpace(timezone.Id)) {
throw new ArgumentException("The time zone identifier is required.");
}
component.AddProperty(new Property(PropertyName.TimeZoneId) {Value = timezone.Id});
}
protected virtual void SerializeTimeZoneLastUpdate(BclTimeZone timezone, Component component) {}
protected virtual void SerializeTimeZoneUrl(BclTimeZone timezone, Component component) {}
protected virtual void SerializeTimeZoneObservanceRules(BclTimeZone timezone, Component component, DateTime minDate, DateTime maxDate)
{
if (timezone.Info.SupportsDaylightSavingTime) {
foreach (var observanceComponent in SerializeAdjustmentRules(timezone.Info, minDate, maxDate)) {
component.AddComponent(observanceComponent);
}
} else {
component.AddComponent(new Component(ComponentName.TimeZoneStandard) {
// TODO
});
}
}
protected virtual void SerializeTimeZoneNonStandardProperties(BclTimeZone timezone, Component component) {}
protected virtual void SerializeTimeZoneIanaProperties(BclTimeZone timezone, Component component) {}
// TODO: Cleanup code
private static IEnumerable<Component> SerializeAdjustmentRules(TimeZoneInfo timezone, DateTime earliest, DateTime latest)
{
var rules = timezone.GetAdjustmentRules().Where(ar => ar.DateEnd > earliest && ar.DateStart < latest).OrderBy(ar => ar.DateStart).ToArray();
foreach (var rule in rules) {
// Standard Time
var standardTimeComponent = new Component(ComponentName.TimeZoneStandard);
var standardTimeStart = CalculateFirstOnset(rule.DaylightTransitionEnd, rule.DateStart);
standardTimeComponent.AddProperty(new Property(PropertyName.DateTimeStart) {Value = FormatDateTime(standardTimeStart)});
var standardTimeRecurrenceRule = CreateRecurrenceRule(rule.DaylightTransitionEnd);
if (rule.DateEnd < DateTime.MaxValue.Date) {
var end = CalculateLastOnset(rule.DaylightTransitionEnd, rule.DateEnd);
if (end > standardTimeStart) {
standardTimeRecurrenceRule += ";UNTIL=" + end.ToUniversalTime();
} else {
// TODO: single occurence
}
}
standardTimeComponent.AddProperty(new Property(PropertyName.RecurrenceRule) {Value = standardTimeRecurrenceRule});
var standardTimeOffsetFrom = timezone.BaseUtcOffset + rule.DaylightDelta;
standardTimeComponent.AddProperty(new Property(PropertyName.TimeZoneOffsetFrom) {Value = FormatOffset(standardTimeOffsetFrom)});
var standardTimeOffsetTo = timezone.BaseUtcOffset;
standardTimeComponent.AddProperty(new Property(PropertyName.TimeZoneOffsetTo) {Value = FormatOffset(standardTimeOffsetTo)});
yield return standardTimeComponent;
var daylightTimeComponent = new Component(ComponentName.TimeZoneDaylight);
var daylightTimeStart = CalculateFirstOnset(rule.DaylightTransitionStart, rule.DateStart);
daylightTimeComponent.AddProperty(new Property(PropertyName.DateTimeStart) {Value = FormatDateTime(daylightTimeStart)});
var daylightTimeRecurrenceRule = CreateRecurrenceRule(rule.DaylightTransitionStart);
if (rule.DateEnd < DateTime.MaxValue.Date) {
var end = CalculateLastOnset(rule.DaylightTransitionStart, rule.DateEnd);
if (end > daylightTimeStart) {
daylightTimeRecurrenceRule += ";UNTIL=" + end.ToUniversalTime();
} else {
// TODO: single occurence
}
}
daylightTimeComponent.AddProperty(new Property(PropertyName.RecurrenceRule) {Value = daylightTimeRecurrenceRule});
var daylightTimeOffsetFrom = timezone.BaseUtcOffset;
daylightTimeComponent.AddProperty(new Property(PropertyName.TimeZoneOffsetFrom) {Value = FormatOffset(daylightTimeOffsetFrom)});
var daylightTimeOffsetTo = timezone.BaseUtcOffset + rule.DaylightDelta;
daylightTimeComponent.AddProperty(new Property(PropertyName.TimeZoneOffsetTo) {Value = FormatOffset(daylightTimeOffsetTo)});
yield return daylightTimeComponent;
}
}
private static string CreateRecurrenceRule(TimeZoneInfo.TransitionTime transitionTime)
{
if (transitionTime.IsFixedDateRule) {
return $"FREQ=YEARLY;BYDAY={transitionTime.Day};BYMONTH={transitionTime.Month}";
}
var byDay = transitionTime.Week == 5 ? "-1" : $"{transitionTime.Week}";
var days = new[] {"SU", "MO", "TU", "WE", "TH", "SA"};
return $"FREQ=YEARLY;BYDAY={byDay}{days[(int) transitionTime.DayOfWeek]};BYMONTH={transitionTime.Month}";
}
private static DateTime CalculateFirstOnset(TimeZoneInfo.TransitionTime transition, DateTime start)
{
var onset = CalculateTransitionDate(transition, start.Year);
if (onset < start) {
onset = CalculateTransitionDate(transition, start.Year + 1);
}
return onset;
}
private static DateTime CalculateLastOnset(TimeZoneInfo.TransitionTime transition, DateTime end)
{
var onset = CalculateTransitionDate(transition, end.Year);
if (onset > end) {
onset = CalculateTransitionDate(transition, end.Year - 1);
}
return onset;
}
private static DateTime CalculateTransitionDate(TimeZoneInfo.TransitionTime transition, int year)
{
if (transition.IsFixedDateRule) {
return new DateTime(year, transition.Month, transition.Day).Add(transition.TimeOfDay.TimeOfDay);
}
return CalculateFloatingTransitionDate(transition, year);
}
private static DateTime CalculateFloatingTransitionDate(TimeZoneInfo.TransitionTime transition, int year)
{
var calendar = CultureInfo.InvariantCulture.Calendar;
var dayOfWeekOnFirstOfMonth = (int) calendar.GetDayOfWeek(new DateTime(year, transition.Month, 1));
var dayOfWeekOnTransition = (int) transition.DayOfWeek;
var effectiveDay = (dayOfWeekOnFirstOfMonth > dayOfWeekOnTransition) ? 1 + (dayOfWeekOnTransition + 7 - dayOfWeekOnFirstOfMonth) : 1 + (dayOfWeekOnTransition - dayOfWeekOnFirstOfMonth);
effectiveDay += (transition.Week - 1) * 7;
if (effectiveDay > calendar.GetDaysInMonth(year, transition.Month)) {
effectiveDay -= 7;
}
return new DateTime(year, transition.Month, effectiveDay).Add(transition.TimeOfDay.TimeOfDay);
}
private static string FormatOffset(TimeSpan timespan)
{
var sign = timespan < TimeSpan.Zero ? "-" : "+";
return $"{sign}{timespan.ToString("hhmm")}";
}
protected override Component SerializeEvent(Event @event)
{
var component = new Component(ComponentName.Event);
SerializeEventDateTimeStamp(@event, component);
SerializeEventId(@event, component);
SerializeEventStart(@event, component);
SerializeEventClassification(@event, component);
SerializeEventCreationDate(@event, component);
SerializeEventDescription(@event, component);
SerializeEventGeo(@event, component);
SerializeEventLastUpdate(@event, component);
SerializeEventLocation(@event, component);
SerializeEventOrganizer(@event, component);
SerializeEventPriority(@event, component);
SerializeEventSequence(@event, component);
SerializeEventStatus(@event, component);
SerializeEventSummary(@event, component);
SerializeEventTransparency(@event, component);
SerializeEventUrl(@event, component);
SerializeEventRecurrenceId(@event, component);
SerializeEventRecurrenceRule(@event, component);
SerializeEventEnd(@event, component);
SerializeEventDuration(@event, component);
SerializeEventAttachments(@event, component);
SerializeEventAttendees(@event, component);
SerializeEventCategories(@event, component);
SerializeEventComments(@event, component);
SerializeEventContacts(@event, component);
SerializeEventExceptionDates(@event, component);
SerializeEventRequestStatus(@event, component);
SerializeEventRelatedTo(@event, component);
SerializeEventResources(@event, component);
SerializeEventRecurrenceDateTimes(@event, component);
SerializeEventNonStandardProperties(@event, component);
SerializeEventIanaProperties(@event, component);
return component;
}
protected virtual void SerializeEventDateTimeStamp(Event @event, Component component)
{
var property = CreateUtcDateTimeProperty(PropertyName.DateTimeStamp, DateTime.UtcNow);
component.AddProperty(property);
}
protected virtual void SerializeEventId(Event @event, Component component)
{
if (String.IsNullOrWhiteSpace(@event.Id)) {
throw new ArgumentException("The event identifier is a required property.");
}
var property = new Property(PropertyName.UniqueIdentifier) {Value = @event.Id};
component.AddProperty(property);
}
protected virtual void SerializeEventStart(Event @event, Component component)
{
if (@event.Start == null) {
throw new ArgumentException("The event start date-time is required.");
}
var property = CreateDateTimeProperty(PropertyName.DateTimeStart, @event.Start);
component.AddProperty(property);
}
protected virtual void SerializeEventClassification(Event @event, Component component)
{
if (@event.Classification != null) {
var property = new Property(PropertyName.Classification) {Value = @event.Classification.Value};
component.AddProperty(property);
}
}
protected virtual void SerializeEventCreationDate(Event @event, Component component)
{
var property = CreateDateTimeProperty(PropertyName.Created, @event.CreatedAt);
component.AddProperty(property);
}
protected virtual void SerializeEventDescription(Event @event, Component component)
{
if (@event.Description != null) {
var property = SerializeLocalizedString(PropertyName.Description, @event.Description);
component.AddProperty(property);
}
}
protected virtual void SerializeEventGeo(Event @event, Component component)
{
if (@event.Geo != null) {
var property = new Property(PropertyName.Geo) {
Value = String.Format(CultureInfo.InvariantCulture, "{0};{1}", @event.Geo.Latitude, @event.Geo.Longitude)
};
component.AddProperty(property);
}
}
protected virtual void SerializeEventLastUpdate(Event @event, Component component)
{
var property = CreateUtcDateTimeProperty(PropertyName.LastModified, @event.UpdatedAt);
component.AddProperty(property);
}
protected virtual void SerializeEventLocation(Event @event, Component component)
{
if (@event.Location != null) {
var property = CreateLocalizedStringProperty(PropertyName.Location, @event.Location);
component.AddProperty(property);
}
}
protected virtual void SerializeEventOrganizer(Event @event, Component component)
{
if (@event.Organizer != null) {
var property = new Property(PropertyName.Organizer) {
Value = $"mailto:{@event.Organizer.Email}"
};
var parameter = new Parameter(ParameterName.CommonName) {
Quoted = true,
};
parameter.AddValue(@event.Organizer.Name.Text);
property.AddParameter(parameter);
component.AddProperty(property);
}
}
protected virtual void SerializeEventPriority(Event @event, Component component)
{
if (@event.Priority != null) {
var property = new Property(PropertyName.Priority) {
Value = @event.Priority.Value
};
component.AddProperty(property);
}
}
protected virtual void SerializeEventSequence(Event @event, Component component) {}
protected virtual void SerializeEventStatus(Event @event, Component component) {}
protected virtual void SerializeEventSummary(Event @event, Component component)
{
if (@event.Summary != null) {
var property = SerializeLocalizedString(PropertyName.Summary, @event.Summary);
component.AddProperty(property);
}
}
protected virtual void SerializeEventTransparency(Event @event, Component component) {}
protected virtual void SerializeEventUrl(Event @event, Component component) {}
protected virtual void SerializeEventRecurrenceId(Event @event, Component component) {}
protected virtual void SerializeEventRecurrenceRule(Event @event, Component component) {}
protected virtual void SerializeEventEnd(Event @event, Component component)
{
if (@event.End == null) {
throw new ArgumentException("The event end date-time is required.");
}
var property = CreateDateTimeProperty(PropertyName.DateTimeEnd, @event.End);
component.AddProperty(property);
}
protected virtual void SerializeEventDuration(Event @event, Component component)
{
// This serializer does not use duration, but uses DTEND instead.
}
protected virtual void SerializeEventAttachments(Event @event, Component component) {}
protected virtual void SerializeEventAttendees(Event @event, Component component)
{
foreach (var attendee in @event.Attendees) {
var property = new Property(PropertyName.Attendee) {
Value = $"mailto:{attendee.Email}"
};
if (!String.IsNullOrEmpty(attendee.Name?.Text)) {
property.AddParameter(new Parameter(ParameterName.CommonName, attendee.Name.Text) { Quoted = true });
if (attendee.Name.CultureInfo != null) {
property.AddParameter(new Parameter(ParameterName.Language, attendee.Name.CultureInfo.Name));
}
}
if (attendee.Type != null) {
property.AddParameter(new Parameter(ParameterName.CalendarUserType, attendee.Type.Value));
if (Equals(attendee.Type, AttendeeType.Resource) || Equals(attendee.Type, AttendeeType.Room)) {
property.AddParameter(new Parameter(ParameterName.ParticipationRole, AttendeeRole.NonParticipant.Value));
}
}
if (attendee.Role != null && !property.Parameters[ParameterName.ParticipationRole].Any()) {
property.AddParameter(new Parameter(ParameterName.ParticipationRole, attendee.Role.Value));
}
if (attendee.ParticipationStatus != null) {
property.AddParameter(new Parameter(ParameterName.ParticipationStatus, attendee.ParticipationStatus.Value));
}
property.AddParameter(new Parameter(ParameterName.RsvpExpectation, attendee.ResponseExpected.ToString().ToUpperInvariant()));
component.AddProperty(property);
}
}
protected virtual void SerializeEventCategories(Event @event, Component component) {}
protected virtual void SerializeEventComments(Event @event, Component component) {}
protected virtual void SerializeEventContacts(Event @event, Component component) {}
protected virtual void SerializeEventExceptionDates(Event @event, Component component) {}
protected virtual void SerializeEventRequestStatus(Event @event, Component component) {}
protected virtual void SerializeEventRelatedTo(Event @event, Component component) {}
protected virtual void SerializeEventResources(Event @event, Component component) {}
protected virtual void SerializeEventRecurrenceDateTimes(Event @event, Component component) {}
protected virtual void SerializeEventNonStandardProperties(Event @event, Component component) {}
protected virtual void SerializeEventIanaProperties(Event @event, Component component) {}
protected override Calendar DeserializeCalendarComponent(Component component)
{
if (component == null) {
throw new ArgumentNullException(nameof(component));
}
if (!String.Equals(component.Name, "VCALENDAR", StringComparison.OrdinalIgnoreCase)) {
throw new ArgumentException("Supplied component is not a Calendar component.", nameof(component));
}
var context = new SerializationContext();
var calendar = CreateCalendar();
DeserializeCalendarVersion(component, calendar);
DeserializeCalendarProductIdentifier(component, calendar);
DeserializeCalendarCalendarScale(component, calendar);
DeserializeCalendarMethod(component, calendar);
DeserializeCalendarNonStandardProperties(component, calendar);
DeserializeCalendarIanaProperties(component, calendar);
DeserializeCalendarTimeZones(component, calendar, context);
DeserializeCalendarEvents(component, calendar, context);
return calendar;
}
protected virtual Calendar CreateCalendar()
{
return new Calendar();
}
protected virtual void DeserializeCalendarVersion(Component component, Calendar calendar)
{
var property = component.Properties[PropertyName.Version].SingleOrDefault();
if (property == null) {
throw new ArgumentException("The version property is required.");
}
var match = Regex.Match(property.Value, "^(([0-9]\\.[0-9]);)?([0-9]\\.[0-9])$");
if (!match.Success) {
throw new ArgumentException("Invalid version specified.");
}
var maxVersion = new Version(match.Groups[3].Value);
var minVersion = match.Groups[2].Success
? new Version(match.Groups[2].Value)
: maxVersion;
if (maxVersion < SerializerVersion || minVersion > SerializerVersion) {
throw new NotSupportedException("This serializer only supports version 2.0.");
}
}
protected virtual void DeserializeCalendarProductIdentifier(Component component, Calendar calendar)
{
var property = component.Properties[PropertyName.ProductIdentifier].SingleOrDefault();
if (property == null) {
throw new ArgumentException("The product identifier is required.");
}
calendar.ProductIdentifier = property.Value;
}
protected virtual void DeserializeCalendarCalendarScale(Component component, Calendar calendar)
{
var property = component.Properties[PropertyName.CalendarScale].SingleOrDefault();
if (property != null) {
if (!String.Equals(property.Value, "GREGORIAN", StringComparison.OrdinalIgnoreCase)) {
throw new ArgumentException("This serializer only supports the Gregorian calendar scale.");
}
}
}
protected virtual void DeserializeCalendarMethod(Component component, Calendar calendar)
{
var property = component.Properties[PropertyName.Method].SingleOrDefault();
if (property != null) {
// TODO use registry?
calendar.Method = new Method {Value = property.Value};
}
}
protected virtual void DeserializeCalendarNonStandardProperties(Component component, Calendar calendar) {}
protected virtual void DeserializeCalendarIanaProperties(Component component, Calendar calendar) {}
protected virtual void DeserializeCalendarTimeZones(Component component, Calendar calendar, SerializationContext context)
{
foreach (var timezoneComponent in component.Components[ComponentName.TimeZone]) {
DeserializeTimeZoneComponent(timezoneComponent, calendar, context);
}
}
protected virtual void DeserializeCalendarEvents(Component component, Calendar calendar, SerializationContext context)
{
foreach (var eventComponent in component.Components[ComponentName.Event]) {
DeserializeEventComponent(eventComponent, calendar, context);
}
}
protected virtual void DeserializeTimeZoneComponent(Component component, Calendar calendar, SerializationContext context)
{
var idProperty = component.Properties[PropertyName.TimeZoneId].SingleOrDefault();
if (idProperty == null) {
throw new ArgumentException("The time zone identifier is a required property.");
}
var id = idProperty.Value;
try {
if (!context.TimeZones.ContainsKey(id)) {
var tzi = TimeZoneInfo.FindSystemTimeZoneById(id);
context.TimeZones[id] = new BclTimeZone(tzi);
}
} catch (TimeZoneNotFoundException) {
// TODO: Build custom time zone based on timezone components
}
}
private TimeZoneObservance DeserializeTimeZoneObservanceComponent(Component component)
{
var observance = new TimeZoneObservance();
var startProperty = component.Properties[PropertyName.DateTimeStart].SingleOrDefault();
if (startProperty == null) {
throw new ArgumentException("They date time start is a required time zone observance component property.");
}
observance.Start = DeserializeLocalDateTime(startProperty);
var offsetFromProperty = component.Properties[PropertyName.TimeZoneOffsetFrom].SingleOrDefault();
if (startProperty == null) {
throw new ArgumentException("They offset from is a required time zone observance component property.");
}
observance.OffsetFrom = DeserializeTimeSpan(offsetFromProperty);
var offsetToProperty = component.Properties[PropertyName.TimeZoneOffsetTo].SingleOrDefault();
if (startProperty == null) {
throw new ArgumentException("They offset from is a required time zone observance component property.");
}
observance.OffsetTo = DeserializeTimeSpan(offsetToProperty);
var recurrenceProperty = component.Properties[PropertyName.RecurrenceRule].FirstOrDefault();
if (recurrenceProperty != null) {
var parts = recurrenceProperty.Value.Split(';').ToDictionary(x => x.Split('=').First(), x => x.Split('=').Last(), StringComparer.OrdinalIgnoreCase);
if (parts.ContainsKey("BYDAY") && parts.ContainsKey("BYMONTH")) {
var month = Int32.Parse(parts["BYMONTH"]);
var week = Int32.Parse(parts["BYDAY"].Trim("MOTUWETHFRSASU".Distinct().ToArray()));
var weekdays = new Dictionary<string, DayOfWeek> {
{"MO", DayOfWeek.Monday},
{"TU", DayOfWeek.Tuesday},
{"WE", DayOfWeek.Wednesday},
{"TH", DayOfWeek.Thursday},
{"FR", DayOfWeek.Friday},
{"SA", DayOfWeek.Saturday},
{"SU", DayOfWeek.Sunday},
};
TimeZoneInfo.TransitionTime.CreateFloatingDateRule(new DateTime(observance.Start.TimeOfDay.Ticks), month, week < 0 ? (6 + week) : week, weekdays[parts["BYDAY"].Substring(parts["BYDAY"].Length - 2, 2)]);
}
}
var nameProperty = component.Properties[PropertyName.TimeZoneName].FirstOrDefault();
if (nameProperty != null) {
observance.Name = nameProperty.Value;
}
return observance;
}
private static TimeSpan DeserializeTimeSpan(Property property)
{
if (property.Value.StartsWith("-")) {
return TimeSpan.ParseExact(property.Value.Substring(1), "hhmm", CultureInfo.InvariantCulture, TimeSpanStyles.AssumeNegative);
}
if (property.Value.StartsWith("+")) {
return TimeSpan.ParseExact(property.Value.Substring(1), "hhmm", CultureInfo.InvariantCulture);
}
return TimeSpan.ParseExact(property.Value, "hhmm", CultureInfo.InvariantCulture);
}
private static DateTime DeserializeLocalDateTime(Property property)
{
var typeParameter = property.Parameters[ParameterName.ValueDataType].FirstOrDefault();
if (typeParameter != null) {
var type = typeParameter.Values.SingleOrDefault();
if (String.Equals("DATE", type)) {
return DateTime.ParseExact(property.Value, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
}
}
return DateTime.ParseExact(property.Value, "yyyyMMdd'T'HHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
}
private static DateTime DeserializeUtcDateTime(Property property)
{
var typeParameter = property.Parameters[ParameterName.ValueDataType].FirstOrDefault();
if (typeParameter != null) {
var type = typeParameter.Values.SingleOrDefault();
if (String.Equals("DATE", type)) {
return DateTime.ParseExact(property.Value, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
}
}
return DateTime.ParseExact(property.Value, "yyyyMMdd'T'HHmmss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
}
protected virtual void DeserializeEventComponent(Component component, Calendar calendar, SerializationContext context)
{
var @event = CreateEvent();
DeserializeEventDateTimeStamp(@event, component);
DeserializeEventId(@event, component);
DeserializeEventStart(@event, component, context);
DeserializeEventClassification(@event, component);
DeserializeEventCreationDate(@event, component);
DeserializeEventDescription(@event, component);
DeserializeEventGeo(@event, component);
DeserializeEventLastUpdate(@event, component);
DeserializeEventLocation(@event, component);
DeserializeEventOrganizer(@event, component);
DeserializeEventPriority(@event, component);
DeserializeEventSequence(@event, component);
DeserializeEventStatus(@event, component);
DeserializeEventSummary(@event, component);
DeserializeEventTransparency(@event, component);
DeserializeEventUrl(@event, component);
DeserializeEventRecurrenceId(@event, component);
DeserializeEventRecurrenceRule(@event, component);
DeserializeEventEnd(@event, component, context);
DeserializeEventDuration(@event, component);
DeserializeEventAttachments(@event, component);
DeserializeEventAttendees(@event, component);
DeserializeEventCategories(@event, component);
DeserializeEventComments(@event, component);
DeserializeEventContacts(@event, component);
DeserializeEventExceptionDates(@event, component);
DeserializeEventRequestStatus(@event, component);
DeserializeEventRelatedTo(@event, component);
DeserializeEventResources(@event, component);
DeserializeEventRecurrenceDateTimes(@event, component);
DeserializeEventNonStandardProperties(@event, component);
DeserializeEventIanaProperties(@event, component);
calendar.AddEvent(@event);
}
protected virtual Event CreateEvent()
{
return new Event();
}
protected virtual void DeserializeEventDateTimeStamp(Event @event, Component component)
{
var property = component.Properties[PropertyName.DateTimeStamp].SingleOrDefault();
if (property == null) {
throw new ArgumentException("The date-time stamp is a required event property.");
}
// Property is not used, only validated
}
protected virtual void DeserializeEventId(Event @event, Component component)
{
var property = component.Properties[PropertyName.UniqueIdentifier].SingleOrDefault();
if (property == null) {
throw new ArgumentException("The unique identifier is a required event property.");
}
@event.Id = property.Value;
}
protected virtual void DeserializeEventStart(Event @event, Component component, SerializationContext context)
{
var property = component.Properties[PropertyName.DateTimeStart].SingleOrDefault();
if (property == null) {
throw new ArgumentException("The date-time start is a required event property");
}
@event.Start = DeserializeZonedDateTime(property, context);
}
private static ZonedDateTime<BclTimeZone> DeserializeZonedDateTime(Property property, SerializationContext context)
{
var idParameter = property.Parameters[ParameterName.TimeZoneIdentifier].SingleOrDefault();
if (idParameter != null) {
return new ZonedDateTime<BclTimeZone>(context.TimeZones[idParameter.Values.Single()], DeserializeLocalDateTime(property));
}
return new ZonedDateTime<BclTimeZone>(BclTimeZone.Utc, DeserializeUtcDateTime(property));
}
protected virtual void DeserializeEventClassification(Event @event, Component component)
{
var property = component.Properties[PropertyName.Classification].SingleOrDefault();
if (property != null) {
@event.Classification = Classification.FromString(property.Value);
}
}
protected virtual void DeserializeEventCreationDate(Event @event, Component component)
{
var property = component.Properties[PropertyName.Created].SingleOrDefault();
if (property != null) {
@event.CreatedAt = DeserializeUtcDateTime(property);
}
}
protected virtual void DeserializeEventDescription(Event @event, Component component)
{
@event.Description = DeserializeLocalizedString(PropertyName.Description, component);
}
protected virtual void DeserializeEventGeo(Event @event, Component component) {}
protected virtual void DeserializeEventLastUpdate(Event @event, Component component)
{
var property = component.Properties[PropertyName.LastModified].SingleOrDefault();
if (property != null) {
@event.UpdatedAt = DeserializeUtcDateTime(property);
}
}
protected virtual void DeserializeEventLocation(Event @event, Component component)
{
@event.Location = DeserializeLocalizedString(PropertyName.Location, component);
}
protected virtual void DeserializeEventOrganizer(Event @event, Component component)
{
var property = component.Properties[PropertyName.Organizer].SingleOrDefault();
if (property != null) {
if (!property.Value.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException("Event organizer value must be of type cal-address.");
}
var organizer = new Organizer(property.Value.Substring(7));
var nameParameter = property.Parameters[ParameterName.CommonName].SingleOrDefault();
var name = nameParameter?.Values.SingleOrDefault();
if (!String.IsNullOrEmpty(name)) {
organizer.Name = new LocalizedString(name);
var languageParameter = property.Parameters[ParameterName.Language].SingleOrDefault();
var language = languageParameter?.Values.SingleOrDefault();
if (!String.IsNullOrEmpty(language)) {
organizer.Name.CultureInfo = new CultureInfo(language);
}
}
@event.Organizer = organizer;
}
}
protected virtual void DeserializeEventPriority(Event @event, Component component)
{
var property = component.Properties[PropertyName.Priority].SingleOrDefault();
if (property != null) {
@event.Priority = Priority.FromString(property.Value);
}
}
protected virtual void DeserializeEventSequence(Event @event, Component component) {}
protected virtual void DeserializeEventStatus(Event @event, Component component) {}
protected virtual void DeserializeEventSummary(Event @event, Component component)
{
@event.Summary = DeserializeLocalizedString(PropertyName.Summary, component);
}
protected virtual void DeserializeEventTransparency(Event @event, Component component) {}
protected virtual void DeserializeEventUrl(Event @event, Component component) {}
protected virtual void DeserializeEventRecurrenceId(Event @event, Component component) {}
protected virtual void DeserializeEventRecurrenceRule(Event @event, Component component) {}
protected virtual void DeserializeEventEnd(Event @event, Component component, SerializationContext context)
{
var property = component.Properties[PropertyName.DateTimeEnd].FirstOrDefault();
if (property != null) {
if (component.Properties[PropertyName.Duration].Any()) {
throw new ArgumentException("The event duration and date time end properties cannot appear both in an event component.");
}
@event.End = DeserializeZonedDateTime(property, context);
}
}
protected virtual void DeserializeEventDuration(Event @event, Component component)
{
var property = component.Properties[PropertyName.Duration].FirstOrDefault();
if (property != null) {
if (component.Properties[PropertyName.DateTimeEnd].Any()) {
throw new ArgumentException("The event duration and date time end properties cannot appear both in an event component.");
}
// TODO
throw new NotImplementedException();
}
}
protected virtual void DeserializeEventAttachments(Event @event, Component component) {}
protected virtual void DeserializeEventAttendees(Event @event, Component component)
{
var properties = component.Properties[PropertyName.Attendee];
foreach (var property in properties) {
if (!property.Value.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase)) {
throw new ArgumentException("Event attendees must be of type cal-address.");
}
var attendee = new Attendee(property.Value.Substring(7));
var nameProperty = property.Parameters[ParameterName.CommonName].SingleOrDefault();
var name = nameProperty?.Values.SingleOrDefault();
if (!String.IsNullOrEmpty(name)) {
attendee.Name = new LocalizedString(name);
var languageParameter = property.Parameters[ParameterName.Language].SingleOrDefault();
var language = languageParameter?.Values.SingleOrDefault();
if (!String.IsNullOrEmpty(language)) {
attendee.Name.CultureInfo = new CultureInfo(language);
}
}
var typeParameter = property.Parameters[ParameterName.CalendarUserType].SingleOrDefault();
var type = typeParameter?.Values.SingleOrDefault();
if (!String.IsNullOrEmpty(type)) {
attendee.Type = AttendeeType.FromString(type);
}
var roleParameter = property.Parameters[ParameterName.ParticipationRole].SingleOrDefault();
var role = roleParameter?.Values.SingleOrDefault();
if (!String.IsNullOrEmpty(role)) {
attendee.Role = AttendeeRole.FromString(role);
}
var participationStatusParameter = property.Parameters[ParameterName.ParticipationStatus].SingleOrDefault();
var participationStatus = participationStatusParameter?.Values.SingleOrDefault();
if (!String.IsNullOrEmpty(participationStatus)) {
attendee.ParticipationStatus = ParticipationStatus.FromString(participationStatus);
}
var responseExpectedParameter = property.Parameters[ParameterName.RsvpExpectation].SingleOrDefault();
var responseExpected = responseExpectedParameter?.Values.SingleOrDefault();
if (!String.IsNullOrEmpty(responseExpected)) {
bool expected;
if (Boolean.TryParse(responseExpected, out expected)) {
attendee.ResponseExpected = expected;
}
}
@event.AddAttendee(attendee);
}
}
protected virtual void DeserializeEventCategories(Event @event, Component component) {}
protected virtual void DeserializeEventComments(Event @event, Component component) {}
protected virtual void DeserializeEventContacts(Event @event, Component component) {}
protected virtual void DeserializeEventExceptionDates(Event @event, Component component) {}
protected virtual void DeserializeEventRequestStatus(Event @event, Component component) {}
protected virtual void DeserializeEventRelatedTo(Event @event, Component component) {}
protected virtual void DeserializeEventResources(Event @event, Component component) {}
protected virtual void DeserializeEventRecurrenceDateTimes(Event @event, Component component) {}
protected virtual void DeserializeEventNonStandardProperties(Event @event, Component component) {}
protected virtual void DeserializeEventIanaProperties(Event @event, Component component) {}
private static Property SerializeLocalizedString(string propertyName, LocalizedString localizedString)
{
var property = new Property(propertyName) {Value = localizedString.Text};
if (localizedString.CultureInfo != null) {
property.AddParameter(new Parameter(ParameterName.Language, localizedString.CultureInfo.Name));
}
return property;
}
private static LocalizedString DeserializeLocalizedString(string propertyName, Component component)
{
var property = component.Properties[propertyName].SingleOrDefault();
if (property != null) {
var languageParameter = property.Parameters[ParameterName.Language].SingleOrDefault();
if (languageParameter != null && languageParameter.Values.Count() == 1) {
return new LocalizedString(property.Value, new CultureInfo(languageParameter.Values.First()));
}
return new LocalizedString(property.Value);
}
return null;
}
}
public class SerializationContext : Calendar
{
internal IDictionary<string, BclTimeZone> TimeZones { get; } = new Dictionary<string, BclTimeZone>(StringComparer.OrdinalIgnoreCase);
}
internal class TimeZoneObservance
{
internal DateTime Start { get; set; }
internal DateTime? End { get; set; }
internal TimeSpan OffsetFrom { get; set; }
internal TimeSpan OffsetTo { get; set; }
internal string Name { get; set; }
internal TimeZoneInfo.TransitionTime TransitionTime { get; set; }
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Web;
namespace HtmlHelp.ChmDecoding
{
/// <summary>
/// The class <c>CHMBtree</c> implements methods/properties to decode the binary help index.
/// This class automatically creates an index arraylist for the current CHMFile instance.
/// It does not store the index internally !
/// </summary>
/// <remarks>The binary index can be found in the storage file $WWKeywordLinks/BTree</remarks>
internal sealed class CHMBtree : IDisposable
{
/// <summary>
/// Constant specifying the size of the string blocks
/// </summary>
private const int BLOCK_SIZE = 2048;
/// <summary>
/// Internal flag specifying if the object is going to be disposed
/// </summary>
private bool disposed = false;
/// <summary>
/// Internal member storing the binary file data
/// </summary>
private byte[] _binaryFileData = null;
/// <summary>
/// Internal member storing flags
/// </summary>
private int _flags = 0;
/// <summary>
/// Internal member storing the data format
/// </summary>
private byte[] _dataFormat = new byte[16];
/// <summary>
/// Internal member storing the index of the last listing block
/// </summary>
private int _indexOfLastListingBlock = 0;
/// <summary>
/// Internal member storing the index of the root block
/// </summary>
private int _indexOfRootBlock = 0;
/// <summary>
/// Internal member storing the number of blocks
/// </summary>
private int _numberOfBlocks = 0;
/// <summary>
/// Internal member storing the tree depth.
/// (1 if no index blocks, 2 one level of index blocks, ...)
/// </summary>
private int _treeDepth = 0;
/// <summary>
/// Internal member storing the number of keywords in the file
/// </summary>
private int _numberOfKeywords = 0;
/// <summary>
/// Internal member storing the codepage
/// </summary>
private int _codePage = 0;
/// <summary>
/// true if the index is from a CHI or CHM file, else CHW
/// </summary>
private bool _isCHI_CHM = true;
/// <summary>
/// Internal member storing the associated chmfile object
/// </summary>
private CHMFile _associatedFile = null;
/// <summary>
/// Internal flag specifying if we have to read listing or index blocks
/// </summary>
private bool _readListingBlocks = true;
/// <summary>
/// Internal member storing an indexlist of the current file.
/// </summary>
private ArrayList _indexList = new ArrayList();
/// <summary>
/// Constructor of the class
/// </summary>
/// <param name="binaryFileData">binary file data of the $WWKeywordLinks/BTree file</param>
/// <param name="associatedFile">associated chm file</param>
public CHMBtree(byte[] binaryFileData, CHMFile associatedFile)
{
if( associatedFile == null)
{
throw new ArgumentException("CHMBtree.ctor() - Associated CHMFile must not be null !", "associatedFile");
}
_binaryFileData = binaryFileData;
_associatedFile = associatedFile;
DecodeData();
// clear internal binary data after extraction
_binaryFileData = null;
}
/// <summary>
/// Decodes the binary file data and fills the internal properties
/// </summary>
/// <returns>true if succeeded</returns>
private bool DecodeData()
{
bool bRet = true;
MemoryStream memStream = new MemoryStream(_binaryFileData);
BinaryReader binReader = new BinaryReader(memStream);
int nCurOffset = 0;
int nTemp = 0;
// decode header
binReader.ReadChars(2); // 2chars signature (not important)
_flags = (int)binReader.ReadInt16(); // WORD flags
binReader.ReadInt16(); // size of blocks (always 2048)
_dataFormat = binReader.ReadBytes(16);
binReader.ReadInt32(); // unknown DWORD
_indexOfLastListingBlock = binReader.ReadInt32();
_indexOfRootBlock = binReader.ReadInt32();
binReader.ReadInt32(); // unknown DWORD
_numberOfBlocks = binReader.ReadInt32();
_treeDepth = binReader.ReadInt16();
_numberOfKeywords = binReader.ReadInt32();
_codePage = binReader.ReadInt32();
binReader.ReadInt32(); // lcid DWORD
nTemp = binReader.ReadInt32();
_isCHI_CHM = (nTemp==1);
binReader.ReadInt32(); // unknown DWORD
binReader.ReadInt32(); // unknown DWORD
binReader.ReadInt32(); // unknown DWORD
binReader.ReadInt32(); // unknown DWORD
// end of header decode
while( (memStream.Position < memStream.Length) && (bRet) )
{
nCurOffset = (int)memStream.Position;
byte [] dataBlock = binReader.ReadBytes(BLOCK_SIZE);
bRet &= DecodeBlock(dataBlock, ref nCurOffset, _treeDepth-1);
}
return bRet;
}
/// <summary>
/// Decodes a block of url-string data
/// </summary>
/// <param name="dataBlock">block of data</param>
/// <param name="nOffset">current file offset</param>
/// <param name="indexBlocks">number of index blocks</param>
/// <returns>true if succeeded</returns>
private bool DecodeBlock( byte[] dataBlock, ref int nOffset, int indexBlocks )
{
bool bRet = true;
int nblockOffset = nOffset;
MemoryStream memStream = new MemoryStream(dataBlock);
BinaryReader binReader = new BinaryReader(memStream);
int freeSpace = binReader.ReadInt16(); // length of freespace
int nrOfEntries = binReader.ReadInt16(); // number of entries
bool bListingEndReached = false;
//while( (memStream.Position < (memStream.Length-freeSpace)) && (bRet) )
//{
int nIndexOfPrevBlock = -1;
int nIndexOfNextBlock = -1;
int nIndexOfChildBlock = 0;
if(_readListingBlocks)
{
nIndexOfPrevBlock = binReader.ReadInt32(); // -1 if this is the header
nIndexOfNextBlock = binReader.ReadInt32(); // -1 if this is the last block
}
else
{
nIndexOfChildBlock = binReader.ReadInt32();
}
for(int nE = 0; nE < nrOfEntries; nE++)
{
if(_readListingBlocks)
{
bListingEndReached = (nIndexOfNextBlock==-1);
string keyWord = BinaryReaderHelp.ExtractUTF16String(ref binReader, 0, true, _associatedFile.TextEncoding);
bool isSeeAlsoKeyword = (binReader.ReadInt16()!=0);
int indent = binReader.ReadInt16(); // indent of entry
int nCharIndex = binReader.ReadInt32();
binReader.ReadInt32();
int numberOfPairs = binReader.ReadInt32();
int[] nTopics = new int[numberOfPairs];
string[] seeAlso = new string[numberOfPairs];
for(int i=0; i < numberOfPairs; i++)
{
if(isSeeAlsoKeyword)
{
seeAlso[i] = HttpUtility.HtmlDecode( BinaryReaderHelp.ExtractUTF16String(ref binReader, 0, true, _associatedFile.TextEncoding) );
}
else
{
nTopics[i] = binReader.ReadInt32();
}
}
binReader.ReadInt32(); // unknown
int nIndexOfThisEntry = binReader.ReadInt32();
IndexItem newItem = new IndexItem(_associatedFile, keyWord, isSeeAlsoKeyword, indent, nCharIndex, nIndexOfThisEntry, seeAlso, nTopics);
_indexList.Add(newItem);
}
else
{
string keyWord = BinaryReaderHelp.ExtractUTF16String(ref binReader, 0, true, _associatedFile.TextEncoding);
bool isSeeAlsoKeyword = (binReader.ReadInt16()!=0);
int indent = binReader.ReadInt16(); // indent of entry
int nCharIndex = binReader.ReadInt32();
binReader.ReadInt32();
int numberOfPairs = binReader.ReadInt32();
int[] nTopics = new int[numberOfPairs];
string[] seeAlso = new string[numberOfPairs];
for(int i=0; i < numberOfPairs; i++)
{
if(isSeeAlsoKeyword)
{
seeAlso[i] = BinaryReaderHelp.ExtractUTF16String(ref binReader, 0, true, _associatedFile.TextEncoding);
}
else
{
nTopics[i] = binReader.ReadInt32();
}
}
int nIndexChild = binReader.ReadInt32();
int nIndexOfThisEntry=-1;
IndexItem newItem = new IndexItem(_associatedFile, keyWord, isSeeAlsoKeyword, indent, nCharIndex, nIndexOfThisEntry, seeAlso, nTopics);
_indexList.Add(newItem);
}
}
//}
binReader.ReadBytes(freeSpace);
if( bListingEndReached )
_readListingBlocks = false;
return bRet;
}
/// <summary>
/// Gets the internal generated index list
/// </summary>
internal ArrayList IndexList
{
get { return _indexList; }
}
/// <summary>
/// Implement IDisposable.
/// </summary>
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </summary>
/// <param name="disposing">disposing flag</param>
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
// Dispose managed resources.
_binaryFileData = null;
}
}
disposed = true;
}
}
}
| |
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 WebAPIWT.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;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO.Ports;
using LibSystem;
using OSC.NET;
using LibOscilloscope;
using LibGui;
using Lib3DDraw;
using LibRoboteqController;
using LibHumanInputDevices;
using LibPicSensors;
using LibLvrGenericHid;
namespace RoboteqControllerTest
{
public partial class ControllerTestForm : Form
{
public Oscilloscope oscilloscope = null;
public LogitechRumblepad gamepad = null;
public ProximityModule _picpxmod = null;
private Hashtable measuredControls = new Hashtable();
public ControllerTestForm()
{
InitializeComponent();
compassTrackBar.Value = (int)compassBearing;
rpCloseButton.Enabled = false;
disconnectControllerButton.Enabled = false;
{
string[] ports = SerialPort.GetPortNames();
ArrayList alPorts = new ArrayList(ports);
this.comboBoxPort.Items.AddRange(ports);
this.comboBoxPortCsa.Items.AddRange(ports);
// a little hack to preset ports:
int pos = alPorts.IndexOf("COM1");
if (pos >= 0)
{
comboBoxPort.SelectedIndex = pos;
}
pos = alPorts.IndexOf("COM4");
if (pos >= 0)
{
comboBoxPortCsa.SelectedIndex = pos;
}
}
oscPortTextBox.Text = "9123";
oscStopButton.Enabled = false;
scaOscStopButton.Enabled = false;
DateTime t1 = DateTime.Now;
SettingsPersister.ReadOptions();
TimeSpan ts = DateTime.Now - t1;
Tracer.WriteLine("ReadOptions() took " + ts.Milliseconds + " ms");
Tracer.setInterface(statusBar, statusBar2, null); // mainProgressBar);
Tracer.WriteLine("GUI up");
periodicMaintenanceTimer = new System.Windows.Forms.Timer();
periodicMaintenanceTimer.Interval = 300;
periodicMaintenanceTimer.Tick += new EventHandler(periodicMaintenance);
periodicMaintenanceTimer.Start();
Tracer.WriteLine("OK: Maintenance ON");
//ensureOscilloscope();
initDashboard();
//create gamepad device.
//gamepad = new LogitechRumblepad(this, devicesTreeView);
//gamepad.leftJoystickVertMoved += new JoystickEventHandler(gamepad_leftJoystickMoved);
//gamepad.rightJoystickVertMoved += new JoystickEventHandler(gamepad_rightJoystickMoved);
//gamepad.btnChangedState += new ButtonEventHandler(gamepad_btnChangedState);
//create picpxmod device.
_picpxmod = new ProximityModule(this);
_picpxmod.HasReadFrame += pmFrameCompleteHandler;
picUsbVendorIdTextBox.Text = string.Format("0x{0:X}", _picpxmod.vendorId);
picUsbProductIdTextBox.Text = string.Format("0x{0:X}", _picpxmod.productId);
}
#region ensureOscilloscope()
private void ensureOscilloscope()
{
//// put Osc_DLL.dll in C:\Windows
if (oscilloscope == null)
{
string oscilloscopeIniFile = Project.startupPath + "..\\..\\LibOscilloscope\\Scope_Desk.ini";
oscilloscope = Oscilloscope.Create(oscilloscopeIniFile, null);
if (oscilloscope != null)
{
Tracer.Trace("loaded oscilloscope DLL");
oscilloscope.Show(); // appears in separate window
}
else
{
Tracer.Error("Couldn't load oscilloscope DLL");
Tracer.Error("Make sure " + oscilloscopeIniFile + " is in place");
Tracer.Error("Make sure C:\\WINDOWS\\Osc_DLL.dll is in place and registered with regsvr32");
}
}
}
#endregion // ensureOscilloscope()
#region initDashboard()
private void initDashboard()
{
rqMeasuredUserControlBatteryVoltage.valueName = "Main_Battery_Voltage";
measuredControls.Add(rqMeasuredUserControlBatteryVoltage.valueName, rqMeasuredUserControlBatteryVoltage);
rqMeasuredUserControlBatteryVoltage.minValue = 10.0d;
rqMeasuredUserControlBatteryVoltage.maxValue = 15.0d;
rqMeasuredUserControlInternalVoltage.valueName = "Internal_Voltage";
measuredControls.Add(rqMeasuredUserControlInternalVoltage.valueName, rqMeasuredUserControlInternalVoltage);
rqMeasuredUserControlInternalVoltage.minValue = 10.0d;
rqMeasuredUserControlInternalVoltage.maxValue = 15.0d;
rqMeasuredUserControlSpeedLeft.valueName = "Encoder_Speed_Left";
measuredControls.Add(rqMeasuredUserControlSpeedLeft.valueName, rqMeasuredUserControlSpeedLeft);
rqMeasuredUserControlSpeedLeft.minValue = -120;
rqMeasuredUserControlSpeedLeft.maxValue = 120;
rqMeasuredUserControlSpeedRight.valueName = "Encoder_Speed_Right";
measuredControls.Add(rqMeasuredUserControlSpeedRight.valueName, rqMeasuredUserControlSpeedRight);
rqMeasuredUserControlSpeedRight.minValue = -120;
rqMeasuredUserControlSpeedRight.maxValue = 120;
rqMeasuredUserControlCounterLeft.valueName = "Encoder_Absolute_Left";
measuredControls.Add(rqMeasuredUserControlCounterLeft.valueName, rqMeasuredUserControlCounterLeft);
rqMeasuredUserControlCounterLeft.maxValue = Double.NaN;
rqMeasuredUserControlCounterRight.valueName = "Encoder_Absolute_Right";
measuredControls.Add(rqMeasuredUserControlCounterRight.valueName, rqMeasuredUserControlCounterRight);
rqMeasuredUserControlCounterRight.maxValue = Double.NaN;
rqMeasuredUserControlPowerLeft.valueName = "Motor_Power_Left";
measuredControls.Add(rqMeasuredUserControlPowerLeft.valueName, rqMeasuredUserControlPowerLeft);
rqMeasuredUserControlPowerLeft.minValue = 0.0d;
rqMeasuredUserControlPowerLeft.maxValue = 120.0d;
rqMeasuredUserControlAmpsLeft.valueName = "Motor_Amps_Left";
measuredControls.Add(rqMeasuredUserControlAmpsLeft.valueName, rqMeasuredUserControlAmpsLeft);
rqMeasuredUserControlAmpsLeft.minValue = 0.0d;
rqMeasuredUserControlAmpsLeft.maxValue = 20.0d;
rqMeasuredUserControlPowerRight.valueName = "Motor_Power_Right";
measuredControls.Add(rqMeasuredUserControlPowerRight.valueName, rqMeasuredUserControlPowerRight);
rqMeasuredUserControlPowerRight.minValue = 0.0d;
rqMeasuredUserControlPowerRight.maxValue = 120.0d;
rqMeasuredUserControlAmpsRight.valueName = "Motor_Amps_Right";
measuredControls.Add(rqMeasuredUserControlAmpsRight.valueName, rqMeasuredUserControlAmpsRight);
rqMeasuredUserControlAmpsRight.minValue = 0.0d;
rqMeasuredUserControlAmpsRight.maxValue = 20.0d;
rqMeasuredUserControlTemperatureLeft.valueName = "Heatsink_Temperature_Left";
measuredControls.Add(rqMeasuredUserControlTemperatureLeft.valueName, rqMeasuredUserControlTemperatureLeft);
rqMeasuredUserControlTemperatureLeft.minValue = 10.0d;
rqMeasuredUserControlTemperatureLeft.maxValue = 90.0d;
rqMeasuredUserControlTemperatureRight.valueName = "Heatsink_Temperature_Right";
measuredControls.Add(rqMeasuredUserControlTemperatureRight.valueName, rqMeasuredUserControlTemperatureRight);
rqMeasuredUserControlTemperatureRight.minValue = 10.0d;
rqMeasuredUserControlTemperatureRight.maxValue = 90.0d;
rqMeasuredUserControlAnalogInput1.valueName = "Analog_Input_1";
measuredControls.Add(rqMeasuredUserControlAnalogInput1.valueName, rqMeasuredUserControlAnalogInput1);
rqMeasuredUserControlAnalogInput1.minValue = -120;
rqMeasuredUserControlAnalogInput1.maxValue = 120;
rqMeasuredUserControlAnalogInput2.valueName = "Analog_Input_2";
measuredControls.Add(rqMeasuredUserControlAnalogInput2.valueName, rqMeasuredUserControlAnalogInput2);
rqMeasuredUserControlAnalogInput2.minValue = -120;
rqMeasuredUserControlAnalogInput2.maxValue = 120;
rqMeasuredUserControlDigitalInputE.valueName = "Digital_Input_E";
measuredControls.Add(rqMeasuredUserControlDigitalInputE.valueName, rqMeasuredUserControlDigitalInputE);
rqMeasuredUserControlDigitalInputE.minValue = 0;
rqMeasuredUserControlDigitalInputE.maxValue = 1;
rqMeasuredUserControlDigitalInputF.valueName = "Digital_Input_F";
measuredControls.Add(rqMeasuredUserControlDigitalInputF.valueName, rqMeasuredUserControlDigitalInputF);
rqMeasuredUserControlDigitalInputF.minValue = 0;
rqMeasuredUserControlDigitalInputF.maxValue = 1;
rqMeasuredUserControlDigitalInputEmergencyStop.valueName = "Digital_Input_Emergency_Stop";
measuredControls.Add(rqMeasuredUserControlDigitalInputEmergencyStop.valueName, rqMeasuredUserControlDigitalInputEmergencyStop);
rqMeasuredUserControlDigitalInputEmergencyStop.minValue = 0;
rqMeasuredUserControlDigitalInputEmergencyStop.maxValue = 1;
// R/C mode measured values:
rqMeasuredUserControlCommand1.valueName = "Command1";
measuredControls.Add(rqMeasuredUserControlCommand1.valueName, rqMeasuredUserControlCommand1);
rqMeasuredUserControlCommand2.valueName = "Command2";
measuredControls.Add(rqMeasuredUserControlCommand2.valueName, rqMeasuredUserControlCommand2);
rqMeasuredUserControlValue1.valueName = "Value1";
measuredControls.Add(rqMeasuredUserControlValue1.valueName, rqMeasuredUserControlValue1);
rqMeasuredUserControlValue2.valueName = "Value2";
measuredControls.Add(rqMeasuredUserControlValue2.valueName, rqMeasuredUserControlValue2);
}
#endregion // initDashboard()
#region Periodic Maintenance related
private System.Windows.Forms.Timer periodicMaintenanceTimer = null;
public void periodicMaintenance(object obj, System.EventArgs args)
{
try
{
//Tracer.WriteLine("...maintenance ticker... " + DateTime.Now);
// oscilloscope.AddData(beam0, beam1, beam2);
Tracer.AllSync();
Application.DoEvents();
if (m_controller != null)
{
lock (m_controller)
{
syncMeasured();
if (m_controller.isGrabbed)
{
this.motorActivationGroupBox.Enabled = true;
stopMotorsButton.BackColor = Color.OrangeRed;
stopMotorsButton.Text = "S T O P";
}
else
{
this.motorActivationGroupBox.Enabled = false;
stopMotorsButton.BackColor = this.motorActivationGroupBox.BackColor;
stopMotorsButton.Text = m_controller.isMonitored ? "MONITORED" : "";
}
}
}
disconnectControllerButton.Enabled = (m_controller != null);
connectToControllerButton.Enabled = (m_controller == null);
}
catch(Exception exc)
{
Tracer.Error("Exception in periodicMaintenance: " + exc);
}
periodicMaintenanceTimer.Enabled = true;
}
private void syncMeasured()
{
foreach (string valueName in measuredControls.Keys)
{
RQMeasuredUserControl rqmc = (RQMeasuredUserControl)measuredControls[valueName];
if (m_controller.measuredValues.ContainsKey(valueName))
{
RQMeasuredValue rqmv = (RQMeasuredValue)m_controller.measuredValues[valueName];
rqmc.measured = rqmv;
}
}
}
#endregion // Periodic Maintenance related
private void statusBar_Click(object sender, EventArgs e)
{
Tracer.showLog();
}
#region Wiimote/Accelerator listener related
private static Thread m_oscListenerThread = null;
private bool oscStopNow = false;
private Hashtable wiiValuesControls = new Hashtable(); // of WiimoteValuesUserControl
private WiimoteValuesUserControl wiimoteValuesUserControl;
private void oscListenButton_Click(object sender, EventArgs e)
{
oscStopButton.Enabled = true;
oscListenButton.Enabled = false;
foreach (string addr in wiiValuesControls.Keys)
{
oscGroupBox.Controls.Remove((WiimoteValuesUserControl)wiiValuesControls[addr]);
}
wiiValuesControls.Clear();
m_oscListenerThread = new Thread(new ThreadStart(oscListenerLoop));
// see Entry.cs for how the current culture is set:
m_oscListenerThread.CurrentCulture = Thread.CurrentThread.CurrentCulture; //new CultureInfo("en-US", false);
m_oscListenerThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture; //new CultureInfo("en-US", false);
m_oscListenerThread.IsBackground = true; // terminate with the main process
m_oscListenerThread.Name = "WiimoteTestOSCListener";
m_oscListenerThread.Start();
}
private void oscListenerLoop()
{
OSCReceiver oscReceiver = null;
OSCMessage oscWiimoteData = null;
oscStopNow = false;
double[] beams = new double[200];
beams[0] = 0.0d;
beams[1] = 0.0d;
beams[2] = 0.0d;
double accel = 0.0d;
double accelBase = 0.0d;
double speed = 0.0d;
double dist = 0.0d;
double dT = 0.0d;
double par4 = 0.0d;
long currTick;
long prevTick;
currTick = prevTick = DateTime.Now.Ticks;
try
{
int oscPort = Convert.ToInt32(oscPortTextBox.Text);
oscReceiver = new OSCReceiver(oscPort);
oscReceiver.Connect();
Tracer.Trace("OSC connected and listening on port " + oscPort);
while (!oscStopNow && (oscWiimoteData = (OSCMessage)oscReceiver.Receive()) != null)
{
string addr = oscWiimoteData.Address;
if (wiiValuesControls.ContainsKey(addr))
{
wiimoteValuesUserControl = (WiimoteValuesUserControl)wiiValuesControls[addr];
}
else
{
this.Invoke(new MethodInvoker(createWiimoteValuesUserControl));
wiiValuesControls.Add(addr, wiimoteValuesUserControl);
}
wiimoteValuesUserControl.values = oscWiimoteData;
int i = 0;
switch (addr)
{
case "/accel-g":
currTick = DateTime.Now.Ticks;
dT = (double)(currTick - prevTick) / 10000000.0d; // sec
// string str = DateTime.Now.ToLongTimeString() + " OSC packet: " + oscWiimoteData.Address + " ";
foreach (object obj in oscWiimoteData.Values)
{
// str += obj.ToString() + " ";
if (i <= 2)
{
try
{
beams[i] = Convert.ToDouble((float)obj);
}
catch
{
beams[i] = 0.0d;
}
}
i++;
}
oscilloscope.AddData(beams[0], beams[1], beams[2]);
// Tracer.Trace(str.Trim());
prevTick = currTick;
break;
case "/wiimote-g":
currTick = DateTime.Now.Ticks;
dT = (double)(currTick - prevTick) / 10000000.0d; // sec
// string str = DateTime.Now.ToLongTimeString() + " OSC packet: " + oscWiimoteData.Address + " ";
foreach (object obj in oscWiimoteData.Values)
{
// str += obj.ToString() + " ";
if (i == 0)
{
try
{
beams[i] = Convert.ToDouble((float)obj);
}
catch
{
beams[i] = 0.0d;
}
accel = beams[i]; // m/c2
}
if (i == 4)
{
try
{
beams[i] = Convert.ToDouble((float)obj);
}
catch
{
beams[i] = 0.0d;
}
par4 = beams[i];
}
i++;
}
if (par4 > 0.0d)
{
accelBase = accel;
speed = 0.0d;
dist = 0.0d;
}
else
{
accel -= accelBase;
speed += accel * dT;
dist += speed * dT;
}
// oscilloscope.AddData(beams[0], beams[1], beams[2]);
oscilloscope.AddData(accel, speed * 100.0d, dist * 100.0d);
// Tracer.Trace(str.Trim());
prevTick = currTick;
break;
}
}
}
catch (Exception exc)
{
Tracer.Error(exc.ToString());
}
finally
{
if (oscReceiver != null)
{
oscReceiver.Close();
}
Tracer.Trace("OSC finished and closed");
}
}
private void createWiimoteValuesUserControl()
{
// must run in the form's thread
wiimoteValuesUserControl = new WiimoteValuesUserControl();
wiimoteValuesUserControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
wiimoteValuesUserControl.Location = new System.Drawing.Point(20, 25 * (wiiValuesControls.Count + 1));
wiimoteValuesUserControl.Size = new System.Drawing.Size(526, 30);
oscGroupBox.Controls.Add(wiimoteValuesUserControl);
}
private void oscStopButton_Click(object sender, EventArgs e)
{
oscStopNow = true;
Tracer.Trace("stopping OSC loop");
if (m_oscListenerThread != null)
{
Thread.Sleep(1000); // let the dialog close before we abort the thread
m_oscListenerThread.Abort();
m_oscListenerThread = null;
}
oscListenButton.Enabled = true;
oscStopButton.Enabled = false;
}
#endregion // Wiimote listener related
private ControllerRQAX2850 m_controller;
private void ensureController()
{
if (m_controller == null)
{
m_controller = new ControllerRQAX2850(comboBoxPort.Text);
m_controller.init();
}
}
private void disposeController()
{
if (m_controller != null)
{
lock (m_controller)
{
// Close the port
m_controller.Dispose();
m_controller = null;
}
}
foreach (Control cntrl in this.panel1.Controls)
{
if (cntrl.GetType() == typeof(RQMeasuredUserControl))
{
((RQMeasuredUserControl)cntrl).Cleanup();
}
}
this.motorActivationGroupBox.Enabled = false;
stopMotorsButton.BackColor = this.motorActivationGroupBox.BackColor;
stopMotorsButton.Text = "-";
}
private void connectToControllerButton_Click(object sender, EventArgs e)
{
// start monitoring serial line
ensureController();
}
private void grabButton_Click(object sender, EventArgs e)
{
// send TCCR to switch controller to Serial Mode
ensureController();
m_controller.GrabController();
stopMotorsButton_Click(null, null);
}
private void resetControllerButton_Click(object sender, EventArgs e)
{
// reset and possibly switch to R/C mode
ensureController();
m_controller.ResetController();
}
private void disconnectControllerButton_Click(object sender, EventArgs e)
{
// abandon controller, disconnect serial link
disposeController();
}
private void leftMotorPowerTrackBar_ValueChanged(object sender, EventArgs e)
{
int iVal = leftMotorPowerTrackBar.Value;
string cmdVal = String.Format("{0}{1:X02}", iVal >= 0 ? "A":"a", Math.Abs(iVal));
this.leftMotorPowerLabel.Text = String.Format("{0} == {1}", iVal, cmdVal);
if (m_controller != null && m_controller.isGrabbed)
{
m_controller.SetMotorPowerOrSpeedLeft(iVal);
}
}
private void stopLeftButton_Click(object sender, EventArgs e)
{
leftMotorPowerTrackBar.Value = 0;
}
private void rightMotorPowerTrackBar_ValueChanged(object sender, EventArgs e)
{
int iVal = rightMotorPowerTrackBar.Value;
string cmdVal = String.Format("{0}{1:X02}", iVal >= 0 ? "B" : "b", Math.Abs(iVal));
this.rightMotorPowerLabel.Text = String.Format("{0} == {1}", iVal, cmdVal);
if (m_controller != null && m_controller.isGrabbed)
{
m_controller.SetMotorPowerOrSpeedRight(iVal);
}
}
private void stopRightButton_Click(object sender, EventArgs e)
{
rightMotorPowerTrackBar.Value = 0;
}
private void stopMotorsButton_Click(object sender, EventArgs e)
{
leftMotorPowerTrackBar.Value = 0;
rightMotorPowerTrackBar.Value = 0;
}
private void rpOpenButton_Click(object sender, EventArgs e)
{
gamepad.init();
rpCloseButton.Enabled = true;
rpOpenButton.Enabled = false;
rpCloseButton2.Enabled = true;
rpOpenButton2.Enabled = false;
}
private void rpCloseButton_Click(object sender, EventArgs e)
{
gamepad.Close();
rpOpenButton.Enabled = true;
rpCloseButton.Enabled = false;
rpOpenButton2.Enabled = true;
rpCloseButton2.Enabled = false;
}
private void gamepad_leftJoystickMoved(Object sender, JoystickEventArgs args)
{
int pos = args.position;
int power = (32767 - pos) / 256 / (int)this.rpSensitivityNumericUpDown.Value;
//Tracer.Trace("left: " + pos);
leftVertTrackBar.Value = power;
leftMotorPowerTrackBar.Value = power;
}
private void gamepad_rightJoystickMoved(Object sender, JoystickEventArgs args)
{
int pos = args.position;
int power = (32767 - pos) / 256 / (int)this.rpSensitivityNumericUpDown.Value;
//Tracer.Trace("right: " + pos + " power: " + power);
rightVertTrackBar.Value = power;
rightMotorPowerTrackBar.Value = power;
}
void gamepad_btnChangedState(object sender, RPButtonsEventArgs args)
{
Tracer.Trace(args.ToString());
if (args.pressed)
{
switch (args.button)
{
case 2:
this.rpSensitivityNumericUpDown.Value++;
break;
case 4:
this.rpSensitivityNumericUpDown.Value--;
break;
}
}
}
private string m_csaPortName = "COM4";
private SerialPort m_csaPort = null;
private void ensureCsaPort()
{
if (m_csaPort == null)
{
m_csaPortName = comboBoxPortCsa.Text;
m_csaPort = new SerialPort(m_csaPortName, 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
// Attach a method to be called when there is data waiting in the port's buffer
m_csaPort.DataReceived += new SerialDataReceivedEventHandler(csaPort_DataReceived);
m_csaPort.ErrorReceived += new SerialErrorReceivedEventHandler(csaPort_ErrorReceived);
m_csaPort.NewLine = "\r";
m_csaPort.DtrEnable = true;
m_csaPort.Handshake = System.IO.Ports.Handshake.None;
m_csaPort.Encoding = Encoding.ASCII;
m_csaPort.RtsEnable = true;
// Open the port for communications
m_csaPort.Open();
m_csaPort.DiscardInBuffer();
}
}
void csaPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
Tracer.Error("csaPort_ErrorReceived: " + e.ToString());
}
private StringBuilder m_sb = new StringBuilder();
private int m_wCnt = 0; // watchdog "W" consecutive count to make sure we've grabbed the controller all right
private void csaPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
long timestamp = DateTime.Now.Ticks;
while (m_csaPort.BytesToRead > 0)
{
byte b = (byte)m_csaPort.ReadByte();
byte[] bb = new byte[1];
bb[0] = b;
Encoding enc = Encoding.ASCII;
string RxString = enc.GetString(bb);
if (RxString == "\r")
{
onStringReceived(m_sb.ToString(), timestamp);
m_sb.Remove(0, m_sb.Length);
}
else
{
m_wCnt = 0;
m_sb.Append(RxString);
}
}
// Show all the incoming data in the port's buffer
//Tracer.Trace(port.ReadExisting());
}
/// <summary>
/// hopefully not crippled string came in
/// </summary>
/// <param name="str"></param>
private void onStringReceived(string str, long timestamp)
{
try
{
interpretCsaString(str);
}
catch (Exception exc)
{
Tracer.Error(exc.ToString());
}
}
private void interpretCsaString(string str)
{
this.csaDataLabel.Text = str;
string[] tokens = str.Split(new char[] { ' ' });
int i = 0;
while (i < tokens.GetLength(0))
{
string token = tokens[i];
//Tracer.Trace(token); // + " " + tokens[i + 1] + " " + tokens[i + 2] + " " + tokens[i + 3]);
switch (token)
{
case "ACC":
interpretAccelerationData(Convert.ToDouble(tokens[i + 1]), Convert.ToDouble(tokens[i + 2]), Convert.ToDouble(tokens[i + 3]));
i += 3;
break;
case "HDG":
interpretCompassData(Convert.ToDouble(tokens[i + 1]));
i += 1;
break;
case "SON":
interpretSonarData(Convert.ToInt32(tokens[i + 1]), Convert.ToDouble(tokens[i + 2]));
i += 3;
break;
}
i++;
}
}
private const double GfCnv = 0.022d; // 0.022 puts 1G = 9.8
private void interpretAccelerationData(double accX, double accY, double accZ)
{
accX *= GfCnv;
accY *= GfCnv;
accZ *= GfCnv;
this.accelXLabel.Text = String.Format("{0}", accX);
this.accelYLabel.Text = String.Format("{0}", accY);
this.accelZLabel.Text = String.Format("{0}", accZ);
robotViewControl1.setAccelerometerData(accX, accY, accZ);
if (oscTransmitter != null)
{
OSCMessage oscAccelData = new OSCMessage("/accel-g");
oscAccelData.Append((float)(accX * 5.0d));
oscAccelData.Append((float)(accY * 5.0d));
oscAccelData.Append((float)(accZ * 5.0d));
oscTransmitter.Send(oscAccelData);
}
}
double lastHeading = -1;
private void interpretCompassData(double heading)
{
heading /= 10.0d;
this.compassDataLabel.Text = String.Format("{0}", heading);
if (lastHeading != heading)
{
compassBearing = heading;
this.compassViewControl1.CompassBearing = compassBearing;
lastHeading = heading;
}
}
private void interpretSonarData(int angleRaw, double distCm)
{
this.sonarBearingLabel.Text = String.Format("{0}", angleRaw);
this.sonarRangeCmLabel.Text = String.Format("{0}", distCm);
sonarViewControl1.setReading(angleRaw, 0.01d * distCm, DateTime.Now.Ticks);
}
private void csaOpenButton_Click(object sender, EventArgs e)
{
ensureCsaPort();
csaCloseButton.Enabled = true;
csaOpenButton.Enabled = false;
this.csaDataLabel.Text = "...waiting for serial data on " + m_csaPortName;
}
private void csaCloseButton_Click(object sender, EventArgs e)
{
csaOpenButton.Enabled = true;
csaCloseButton.Enabled = false;
m_csaPort.Close();
m_csaPort = null;
this.csaDataLabel.Text = "port " + m_csaPortName + " closed";
}
double compassBearing = 45.0d;
private void compassTrackBar_ValueChanged(object sender, EventArgs e)
{
compassBearing = (double)compassTrackBar.Value;
this.compassDataLabel.Text = String.Format("{0}", compassBearing);
this.compassViewControl1.CompassBearing = compassBearing;
}
private void testSonarLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Random random = new Random();
for(int angleRaw=150; angleRaw <= 1160 ;angleRaw+=50)
{
sonarViewControl1.setReading(angleRaw, 3.0d * random.NextDouble(), DateTime.Now.Ticks);
}
}
double m_accX = 1.0d;
double m_accY = 1.0d;
double m_accZ = 1.0d;
private void accelXTrackBar_ValueChanged(object sender, EventArgs e)
{
m_accX = accelXTrackBar.Value / 5.0d;
this.accelXLabel.Text = String.Format("{0}", m_accX);
robotViewControl1.setAccelerometerData(m_accX, m_accY, m_accZ);
}
private void accelYTrackBar_ValueChanged(object sender, EventArgs e)
{
m_accY = accelYTrackBar.Value / 5.0d;
this.accelYLabel.Text = String.Format("{0}", m_accY);
robotViewControl1.setAccelerometerData(m_accX, m_accY, m_accZ);
}
private void accelZTrackBar_ValueChanged(object sender, EventArgs e)
{
m_accZ = accelZTrackBar.Value / 5.0d;
this.accelZLabel.Text = String.Format("{0}", m_accZ);
robotViewControl1.setAccelerometerData(m_accX, m_accY, m_accZ);
}
private OSCTransmitter oscTransmitter = null;
private void scaOscButton_Click(object sender, EventArgs e)
{
scaOscStopButton.Enabled = true;
scaOscButton.Enabled = false;
ensureOscilloscope();
m_oscListenerThread = new Thread(new ThreadStart(oscListenerLoop));
// see Entry.cs for how the current culture is set:
m_oscListenerThread.CurrentCulture = Thread.CurrentThread.CurrentCulture; //new CultureInfo("en-US", false);
m_oscListenerThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture; //new CultureInfo("en-US", false);
m_oscListenerThread.IsBackground = true; // terminate with the main process
m_oscListenerThread.Name = "AccelTestOSCListener";
m_oscListenerThread.Start();
Thread.Sleep(3000); // let the oscilloscope start
int oscPort = Convert.ToInt32(oscPortTextBox.Text);
oscTransmitter = new OSCTransmitter("localhost", oscPort);
oscTransmitter.Connect();
Tracer.Trace("OSC connected and transmitting to port " + oscPort);
}
private void scaOscStopButton_Click(object sender, EventArgs e)
{
oscStopNow = true;
oscTransmitter.Close();
oscTransmitter = null;
Tracer.Trace("stopping OSC loop");
if (m_oscListenerThread != null)
{
Thread.Sleep(1000); // let the dialog close before we abort the thread
m_oscListenerThread.Abort();
m_oscListenerThread = null;
}
scaOscButton.Enabled = true;
scaOscStopButton.Enabled = false;
}
/// <summary>
/// Overrides WndProc to enable checking for and handling WM_DEVICECHANGE messages.
/// </summary>
///
/// <param name="m"> a Windows Message </param>
protected override void WndProc(ref Message m)
{
try
{
// The OnDeviceChange routine processes WM_DEVICECHANGE messages.
if (m.Msg == DeviceManagement.WM_DEVICECHANGE)
{
_picpxmod.OnDeviceChange(m);
}
// Let the base form process the message.
base.WndProc(ref m);
}
catch (Exception ex)
{
Tracer.Error(ex);
throw;
}
}
private void picUsbConnectButton_Click(object sender, EventArgs e)
{
_picpxmod.Open();
}
private void picUsbDisconnectButton_Click(object sender, EventArgs e)
{
_picpxmod.Close();
}
string locker = "";
private void pmServo1ScrollBar_ValueChanged(object sender, EventArgs e)
{
lock (locker)
{
int scrollValue = pmServo1ScrollBar.Value;
pmServo1NumericUpDown.Value = scrollValue;
_picpxmod.ServoPositionSet((int)pmServoNumberNumericUpDown.Value, (double)scrollValue);
}
}
private void pmServo1NumericUpDown_ValueChanged(object sender, EventArgs e)
{
lock (locker)
{
int scrollValue = (int)pmServo1NumericUpDown.Value;
//pmServo1ScrollBar.Value = scrollValue;
_picpxmod.ServoPositionSet((int)pmServoNumberNumericUpDown.Value, (double)scrollValue);
}
}
private void picUsbDataContinuousStartButton_Click(object sender, EventArgs e)
{
_picpxmod.DataContinuousStart();
}
private void picUsbDataContinuousStopButton_Click(object sender, EventArgs e)
{
_picpxmod.DataContinuousStop();
}
int rawAngle1_Min = int.MaxValue;
double angleDegrees1_Min = -120.0d;
int rawAngle1_Max = int.MinValue;
double angleDegrees1_Max = -5.0d;
int rawAngle2_Min = int.MaxValue;
double angleDegrees2_Min = 5.0d;
int rawAngle2_Max = int.MinValue;
double angleDegrees2_Max = 120.0d;
private int numRays1;
private int numRays2;
int angleRawStep1 = 0;
int angleRawStep2 = 0;
double angleDegreesStep1 = 0.0d;
double angleDegreesStep2 = 0.0d;
const int TEST_SAMPLES_COUNT = 100;
int inTestSamples = TEST_SAMPLES_COUNT;
SortedList<int, int> rawAngle1Values = new SortedList<int, int>();
SortedList<int, int> rawAngle2Values = new SortedList<int, int>();
// This will be called whenever the data is read from the board:
private void pmFrameCompleteHandler(object sender, AsyncInputFrameArgs aira)
{
long timestamp = DateTime.Now.Ticks;
Tracer.Trace("Async sonar frame arrived. " + DateTime.Now);
StringBuilder frameValue = new StringBuilder();
frameValue.AppendFormat("{0}\r\n", aira.dPos1Mks);
frameValue.AppendFormat("{0}\r\n", aira.dPos2Mks);
frameValue.AppendFormat("{0}\r\n", aira.dPing1DistanceMm);
frameValue.AppendFormat("{0}\r\n", aira.dPing2DistanceMm);
pmValuesTextBox.Text = frameValue.ToString();
int angleRaw1 = (int)aira.dPos1Mks;
double distCm1 = aira.dPing1DistanceMm / 10.0d;
int angleRaw2 = (int)aira.dPos2Mks;
double distCm2 = aira.dPing2DistanceMm / 10.0d;
if (inTestSamples > 0)
{
--inTestSamples;
// for a while just try figuring out what comes in - sweep angle ranges for both sides
if (inTestSamples > TEST_SAMPLES_COUNT - 10) // first few frames are garbled
{
return;
}
//rawAngle1_Min = int.MaxValue;
//rawAngle1_Max = int.MinValue;
//rawAngle2_Min = int.MaxValue;
//rawAngle2_Max = int.MinValue;
//inTestSamples = 200;
rawAngle1_Min = Math.Min(rawAngle1_Min, angleRaw1);
rawAngle1_Max = Math.Max(rawAngle1_Max, angleRaw1);
rawAngle2_Min = Math.Min(rawAngle2_Min, angleRaw2);
rawAngle2_Max = Math.Max(rawAngle2_Max, angleRaw2);
if (!rawAngle1Values.ContainsKey(angleRaw1))
{
rawAngle1Values.Add(angleRaw1, angleRaw1);
}
if (!rawAngle2Values.ContainsKey(angleRaw2))
{
rawAngle2Values.Add(angleRaw2, angleRaw2);
}
if (inTestSamples == 0) // last count
{
numRays1 = rawAngle1Values.Count;
numRays2 = rawAngle2Values.Count;
angleRawStep1 = (int)Math.Round((double)(rawAngle1_Max - rawAngle1_Min) / (double)numRays1);
angleRawStep2 = (int)Math.Round((double)(rawAngle2_Max - rawAngle2_Min) / (double)numRays2);
angleDegreesStep1 = (angleDegrees1_Max - angleDegrees1_Min) / numRays1;
angleDegreesStep2 = (angleDegrees2_Max - angleDegrees2_Min) / numRays2;
StringBuilder sBuf = new StringBuilder();
sBuf.Append("setReading(): numRays1=" + numRays1 + " angleRawStep1=" + angleRawStep1 + " rawAngle1_Min=" + rawAngle1_Min + " rawAngle1_Max=" + rawAngle1_Max + " angleDegreesStep1=" + angleDegreesStep1 + "\r\nsweep angles1 (us) : ");
for (int count = 0; count < rawAngle1Values.Count; count++)
{
// Display bytes as 2-character Hex strings.
sBuf.AppendFormat("{0} ", rawAngle1Values.ElementAt(count).Key);
}
sBuf.Append("\r\nsetReading(): numRays2=" + numRays2 + " angleRawStep2=" + angleRawStep2 + " rawAngle2_Min=" + rawAngle2_Min + " rawAngle2_Max=" + rawAngle2_Max + " angleDegreesStep2=" + angleDegreesStep2 + "\r\nsweep angles2 (us) : ");
for (int count = 0; count < rawAngle2Values.Count; count++)
{
// Display bytes as 2-character Hex strings.
sBuf.AppendFormat("{0} ", rawAngle2Values.ElementAt(count).Key);
}
Tracer.Trace(sBuf.ToString());
}
}
this.pmBearingLabel1.Text = String.Format("{0} us", angleRaw1);
this.pmRangeLabel1.Text = String.Format("{0} cm", distCm1);
pmSonarViewControl1.setReading(angleRaw1, 0.01d * distCm1, timestamp);
this.pmNraysLabel1.Text = String.Format("{0} rays", pmSonarViewControl1.NumNumbers);
this.pmBearingLabel2.Text = String.Format("{0} us", angleRaw2);
this.pmRangeLabel2.Text = String.Format("{0} cm", distCm2);
pmSonarViewControl2.setReading(angleRaw2, 0.01d * distCm2, timestamp);
this.pmNraysLabel2.Text = String.Format("{0} rays", pmSonarViewControl2.NumNumbers);
if (inTestSamples == 0)
{
this.pmBearingLabelComb.Text = String.Format("{0} us", angleRaw2);
this.pmRangeLabelComb.Text = String.Format("{0} cm", distCm2);
pmSonarViewControlComb.setReading(angleRawToSonarAngle(1, angleRaw1), 0.01d * distCm1, angleRawToSonarAngle(2, angleRaw2), 0.01d * distCm2, timestamp);
this.pmNraysLabelComb.Text = String.Format("{0} rays", pmSonarViewControlComb.NumNumbers);
if (angleRaw1 == rawAngle1_Min || angleRaw1 == rawAngle1_Max)
{
Tracer.Trace("Sweep Frame Ready");
SonarData p = pmSonarViewControlComb.sonarData;
foreach (int angle in p.angles.Keys)
{
RangeReading rr = p.getLatestReadingAt(angle);
double range = rr.rangeMeters * 1000.0d; // millimeters
//ranges.Add(range);
Tracer.Trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&& angle=" + angle + " range=" + range);
/*
* typical measurement:
* for dual radar:
angles: 26
Sweep Frame Ready
angle=883 range=2052
angle=982 range=2047
angle=1081 range=394
angle=1179 range=394
angle=1278 range=398
angle=1377 range=390
angle=1475 range=390
angle=1574 range=390
angle=1673 range=399
angle=1771 range=416
angle=1870 range=1972
angle=1969 range=2182
angle=2067 range=3802
angle=2166 range=245
angle=2265 range=241
angle=2364 range=224
angle=2462 range=211
angle=2561 range=202
angle=2660 range=202
angle=2758 range=135
angle=2857 range=135
angle=2956 range=135
angle=3054 range=228
angle=3153 range=254
angle=3252 range=248
angle=3350 range=244
* for single radar:
* PACKET READY -- angles: 26 packets: 1
angle=150 range=1440
angle=190 range=1450
angle=230 range=1450
angle=270 range=1450
angle=310 range=1460
angle=350 range=1540
angle=390 range=1540
angle=430 range=1700
angle=470 range=1700
angle=510 range=1740
angle=550 range=2260
angle=590 range=1100
angle=630 range=1100
angle=670 range=1090
angle=710 range=1100
angle=750 range=1090
angle=790 range=1090
angle=830 range=1090
angle=870 range=1090
angle=910 range=1700
angle=950 range=1710
angle=990 range=1730
angle=1030 range=1720
angle=1070 range=1710
angle=1110 range=3500
angle=1150 range=3500
*/
}
}
}
}
// =================================================================================================================
private int angleRawToSonarAngle(int channel, int rawAngle)
{
int ret = 0;
// these formulas are very dependent on the positioning of the servos/sonars and type of servos.
// for my particular robot servos are located upside down, the shaft facing the ground. EXI 227F are fast and dirt cheap, but the metal gears have generally short life compared to new hitec carbon gears.
// see CommLink::OnMeasurement() for the way the sonar data should look like, and how it will be converted to a 180 degrees sweep.
switch (channel)
{
case 1: // channel 1 is on the left
// ret = rawAngle
// ret = rawAngle1_Max + rawAngle2_Max + 99 - rawAngle; // Futaba S3003 left, upside down, and Hitec HS300 right, upside down
ret = rawAngle1_Max + rawAngle2_Max + 132 - rawAngle; // Two EXI 227F upside down
break;
case 2: // channel 2 is on the right
// ret = rawAngle2_Max - (rawAngle - rawAngle2_Min) + rawAngle1_Max + 99;
// ret = rawAngle;
ret = rawAngle1_Min + (rawAngle1_Max - rawAngle) - 99; // Two EXI 227F upside down
break;
}
return ret;
}
private void pmSetDefaultSweep()
{
double sweepStartPos1 = 2100.0d; // us
double sweepStartPos2 = 850.0d; // us
double sweepStep = 148; // these are not us
int sweepSteps = 13;
double sweepMax = 2100.0d;
double sweepMin = 850; // us
double sweepRate = 28; // must divide by 7, due to microprocessor servo pulse cycle interactions.
bool initialDirectionUp = false;
_picpxmod.ServoSweepParams(1, sweepMin, sweepMax, sweepStartPos1, sweepStep, initialDirectionUp, sweepRate);
_picpxmod.ServoSweepParams(2, sweepMin, sweepMax, sweepStartPos2, sweepStep, initialDirectionUp, sweepRate);
}
// =================================================================================================================
private void pmTestSonar1LinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Random random = new Random();
for (int angleRaw = 150; angleRaw <= 1160; angleRaw += 50)
{
pmSonarViewControl1.setReading(angleRaw, 3.0d * random.NextDouble(), DateTime.Now.Ticks);
}
}
private void pmTestSonar2LinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Random random = new Random();
for (int angleRaw = 150; angleRaw <= 1160; angleRaw += 50)
{
pmSonarViewControl2.setReading(angleRaw, 3.0d * random.NextDouble(), DateTime.Now.Ticks);
}
}
private void pmServoReadButton_Click(object sender, EventArgs e)
{
double dPosMks = _picpxmod.ServoPositionGet((int)pmServoNumberNumericUpDown.Value);
pmServoPositionTextBox.Text = "" + dPosMks;
}
private void pmPingReadButton_Click(object sender, EventArgs e)
{
double dPingDistanceMm = _picpxmod.PingDistanceGet((int)pmServoNumberNumericUpDown.Value);
pmPingDistanceTextBox.Text = "" + dPingDistanceMm;
}
private void picUsbServoSweepStartButton_Click(object sender, EventArgs e)
{
pmSonarViewControl1.Reset();
_picpxmod.ServoSweepEnable(true);
}
private void picUsbServoSweepStopButton_Click(object sender, EventArgs e)
{
_picpxmod.ServoSweepEnable(false);
}
private void pmSetServoSweepButton_Click(object sender, EventArgs e)
{
double sweepMin = double.Parse(pmSweepMinTextBox.Text);
double sweepMax = double.Parse(pmSweepMaxTextBox.Text);
double sweepStartPos = double.Parse(pmSweepStartTextBox.Text);
double sweepStep = double.Parse(pmSweepStepTextBox.Text);
bool initialDirectionUp = pmSweepDirectionUpCheckBox.Checked;
double sweepRate = double.Parse(pmSweepRateTextBox.Text);
_picpxmod.ServoSweepParams((int)pmServoNumberNumericUpDown.Value, sweepMin, sweepMax, sweepStartPos, sweepStep, initialDirectionUp, sweepRate);
}
private void pmSetDefaultSweepButton_Click(object sender, EventArgs e)
{
pmSetDefaultSweep();
}
private void pmFlipSonar1LinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
pmSonarViewControl1.flipped = !pmSonarViewControl1.flipped;
pmFlipSonar1LinkLabel.Text = pmSonarViewControl1.flipped ? "Unflip" : "Flip";
}
private void pmFlipSonar2LinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
pmSonarViewControl2.flipped = !pmSonarViewControl2.flipped;
pmFlipSonar2LinkLabel.Text = pmSonarViewControl2.flipped ? "Unflip" : "Flip";
}
private void pmSetSafePostureButton_Click(object sender, EventArgs e)
{
_picpxmod.SafePosture();
}
private void pmFlipSonarCombLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
pmSonarViewControlComb.flipped = !pmSonarViewControlComb.flipped;
pmFlipSonarCombLinkLabel.Text = pmSonarViewControlComb.flipped ? "Unflip" : "Flip";
}
private void pmTestSonarCombLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax
// .NET Compact Framework 1.0 has no support for Win32 NetMessageBufferSend API
#if !NETCF
// MONO 1.0 has no support for Win32 NetMessageBufferSend API
#if !MONO
// SSCLI 1.0 has no support for Win32 NetMessageBufferSend API
#if !SSCLI
// We don't want framework or platform specific code in the CLI version of Ctrip
#if !CLI_1_0
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using Ctrip.Log4.Util;
using Ctrip.Log4.Layout;
using Ctrip.Log4.Core;
namespace Ctrip.Log4.Appender
{
/// <summary>
/// Logs entries by sending network messages using the
/// <see cref="NetMessageBufferSend" /> native function.
/// </summary>
/// <remarks>
/// <para>
/// You can send messages only to names that are active
/// on the network. If you send the message to a user name,
/// that user must be logged on and running the Messenger
/// service to receive the message.
/// </para>
/// <para>
/// The receiver will get a top most window displaying the
/// messages one at a time, therefore this appender should
/// not be used to deliver a high volume of messages.
/// </para>
/// <para>
/// The following table lists some possible uses for this appender :
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Action</term>
/// <description>Property Value(s)</description>
/// </listheader>
/// <item>
/// <term>Send a message to a user account on the local machine</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Server"/> = <name of the local machine>
/// </para>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <user name>
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Send a message to a user account on a remote machine</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Server"/> = <name of the remote machine>
/// </para>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <user name>
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Send a message to a domain user account</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Server"/> = <name of a domain controller | uninitialized>
/// </para>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <user name>
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Send a message to all the names in a workgroup or domain</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <workgroup name | domain name>*
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Send a message from the local machine to a remote machine</term>
/// <description>
/// <para>
/// <see cref="NetSendAppender.Server"/> = <name of the local machine | uninitialized>
/// </para>
/// <para>
/// <see cref="NetSendAppender.Recipient"/> = <name of the remote machine>
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// <para>
/// <b>Note :</b> security restrictions apply for sending
/// network messages, see <see cref="NetMessageBufferSend" />
/// for more information.
/// </para>
/// </remarks>
/// <example>
/// <para>
/// An example configuration section to log information
/// using this appender from the local machine, named
/// LOCAL_PC, to machine OPERATOR_PC :
/// </para>
/// <code lang="XML" escaped="true">
/// <appender name="NetSendAppender_Operator" type="Ctrip.Log4.Appender.NetSendAppender">
/// <server value="LOCAL_PC" />
/// <recipient value="OPERATOR_PC" />
/// <layout type="Ctrip.Log4.Layout.PatternLayout" value="%-5p %c [%x] - %m%n" />
/// </appender>
/// </code>
/// </example>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class NetSendAppender : AppenderSkeleton
{
#region Member Variables
/// <summary>
/// The DNS or NetBIOS name of the server on which the function is to execute.
/// </summary>
private string m_server;
/// <summary>
/// The sender of the network message.
/// </summary>
private string m_sender;
/// <summary>
/// The message alias to which the message should be sent.
/// </summary>
private string m_recipient;
/// <summary>
/// The security context to use for privileged calls
/// </summary>
private SecurityContext m_securityContext;
#endregion
#region Constructors
/// <summary>
/// Initializes the appender.
/// </summary>
/// <remarks>
/// The default constructor initializes all fields to their default values.
/// </remarks>
public NetSendAppender()
{
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the sender of the message.
/// </summary>
/// <value>
/// The sender of the message.
/// </value>
/// <remarks>
/// If this property is not specified, the message is sent from the local computer.
/// </remarks>
public string Sender
{
get { return m_sender; }
set { m_sender = value; }
}
/// <summary>
/// Gets or sets the message alias to which the message should be sent.
/// </summary>
/// <value>
/// The recipient of the message.
/// </value>
/// <remarks>
/// This property should always be specified in order to send a message.
/// </remarks>
public string Recipient
{
get { return m_recipient; }
set { m_recipient = value; }
}
/// <summary>
/// Gets or sets the DNS or NetBIOS name of the remote server on which the function is to execute.
/// </summary>
/// <value>
/// DNS or NetBIOS name of the remote server on which the function is to execute.
/// </value>
/// <remarks>
/// <para>
/// For Windows NT 4.0 and earlier, the string should begin with \\.
/// </para>
/// <para>
/// If this property is not specified, the local computer is used.
/// </para>
/// </remarks>
public string Server
{
get { return m_server; }
set { m_server = value; }
}
/// <summary>
/// Gets or sets the <see cref="SecurityContext"/> used to call the NetSend method.
/// </summary>
/// <value>
/// The <see cref="SecurityContext"/> used to call the NetSend method.
/// </value>
/// <remarks>
/// <para>
/// Unless a <see cref="SecurityContext"/> specified here for this appender
/// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the
/// security context to use. The default behavior is to use the security context
/// of the current thread.
/// </para>
/// </remarks>
public SecurityContext SecurityContext
{
get { return m_securityContext; }
set { m_securityContext = value; }
}
#endregion
#region Implementation of IOptionHandler
/// <summary>
/// Initialize the appender based on the options set.
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// <para>
/// The appender will be ignored if no <see cref="Recipient" /> was specified.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">The required property <see cref="Recipient" /> was not specified.</exception>
public override void ActivateOptions()
{
base.ActivateOptions();
if (this.Recipient == null)
{
throw new ArgumentNullException("Recipient", "The required property 'Recipient' was not specified.");
}
if (m_securityContext == null)
{
m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
}
}
#endregion
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Sends the event using a network message.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
protected override void Append(LoggingEvent loggingEvent)
{
NativeError nativeError = null;
// Render the event in the callers security context
string renderedLoggingEvent = RenderLoggingEvent(loggingEvent);
using(m_securityContext.Impersonate(this))
{
// Send the message
int returnValue = NetMessageBufferSend(this.Server, this.Recipient, this.Sender, renderedLoggingEvent, renderedLoggingEvent.Length * Marshal.SystemDefaultCharSize);
// Log the error if the message could not be sent
if (returnValue != 0)
{
// Lookup the native error
nativeError = NativeError.GetError(returnValue);
}
}
if (nativeError != null)
{
// Handle the error over to the ErrorHandler
ErrorHandler.Error(nativeError.ToString() + " (Params: Server=" + this.Server + ", Recipient=" + this.Recipient + ", Sender=" + this.Sender + ")");
}
}
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion
#region Stubs For Native Function Calls
/// <summary>
/// Sends a buffer of information to a registered message alias.
/// </summary>
/// <param name="serverName">The DNS or NetBIOS name of the server on which the function is to execute.</param>
/// <param name="msgName">The message alias to which the message buffer should be sent</param>
/// <param name="fromName">The originator of the message.</param>
/// <param name="buffer">The message text.</param>
/// <param name="bufferSize">The length, in bytes, of the message text.</param>
/// <remarks>
/// <para>
/// The following restrictions apply for sending network messages:
/// </para>
/// <para>
/// <list type="table">
/// <listheader>
/// <term>Platform</term>
/// <description>Requirements</description>
/// </listheader>
/// <item>
/// <term>Windows NT</term>
/// <description>
/// <para>
/// No special group membership is required to send a network message.
/// </para>
/// <para>
/// Admin, Accounts, Print, or Server Operator group membership is required to
/// successfully send a network message on a remote server.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>Windows 2000 or later</term>
/// <description>
/// <para>
/// If you send a message on a domain controller that is running Active Directory,
/// access is allowed or denied based on the access control list (ACL) for the securable
/// object. The default ACL permits only Domain Admins and Account Operators to send a network message.
/// </para>
/// <para>
/// On a member server or workstation, only Administrators and Server Operators can send a network message.
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// <para>
/// For more information see <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netmgmt/netmgmt/security_requirements_for_the_network_management_functions.asp">Security Requirements for the Network Management Functions</a>.
/// </para>
/// </remarks>
/// <returns>
/// <para>
/// If the function succeeds, the return value is zero.
/// </para>
/// </returns>
[DllImport("netapi32.dll", SetLastError=true)]
protected static extern int NetMessageBufferSend(
[MarshalAs(UnmanagedType.LPWStr)] string serverName,
[MarshalAs(UnmanagedType.LPWStr)] string msgName,
[MarshalAs(UnmanagedType.LPWStr)] string fromName,
[MarshalAs(UnmanagedType.LPWStr)] string buffer,
int bufferSize);
#endregion
}
}
#endif // !CLI_1_0
#endif // !SSCLI
#endif // !MONO
#endif // !NETCF
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace RestOfUs.Api.WebApi.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// 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 Xunit;
namespace System.IO.Tests
{
public static class PathCombineTests
{
private static readonly char s_separator = Path.DirectorySeparatorChar;
public static IEnumerable<object[]> Combine_Basic_TestData()
{
yield return new object[] { new string[0] };
yield return new object[] { new string[] { "abc" } };
yield return new object[] { new string[] { "abc", "def" } };
yield return new object[] { new string[] { "abc", "def", "ghi", "jkl", "mno" } };
yield return new object[] { new string[] { "abc" + s_separator + "def", "def", "ghi", "jkl", "mno" } };
// All paths are empty
yield return new object[] { new string[] { "" } };
yield return new object[] { new string[] { "", "" } };
yield return new object[] { new string[] { "", "", "" } };
yield return new object[] { new string[] { "", "", "", "" } };
yield return new object[] { new string[] { "", "", "", "", "" } };
// Elements are all separated
yield return new object[] { new string[] { "abc" + s_separator, "def" + s_separator } };
yield return new object[] { new string[] { "abc" + s_separator, "def" + s_separator, "ghi" + s_separator } };
yield return new object[] { new string[] { "abc" + s_separator, "def" + s_separator, "ghi" + s_separator, "jkl" + s_separator } };
yield return new object[] { new string[] { "abc" + s_separator, "def" + s_separator, "ghi" + s_separator, "jkl" + s_separator, "mno" + s_separator } };
}
public static IEnumerable<string> Combine_CommonCases_Input_TestData()
{
// Any path is rooted (starts with \, \\, A:)
yield return s_separator + "abc";
yield return s_separator + s_separator + "abc";
// Any path is empty (skipped)
yield return "";
// Any path is single element
yield return "abc";
yield return "abc" + s_separator;
// Any path is multiple element
yield return Path.Combine("abc", Path.Combine("def", "ghi"));
}
public static IEnumerable<object[]> Combine_CommonCases_TestData()
{
foreach (string testPath in Combine_CommonCases_Input_TestData())
{
yield return new object[] { new string[] { testPath } };
yield return new object[] { new string[] { "abc", testPath } };
yield return new object[] { new string[] { testPath, "abc" } };
yield return new object[] { new string[] { "abc", "def", testPath } };
yield return new object[] { new string[] { "abc", testPath, "def" } };
yield return new object[] { new string[] { testPath, "abc", "def" } };
yield return new object[] { new string[] { "abc", "def", "ghi", testPath } };
yield return new object[] { new string[] { "abc", "def", testPath, "ghi" } };
yield return new object[] { new string[] { "abc", testPath, "def", "ghi" } };
yield return new object[] { new string[] { testPath, "abc", "def", "ghi" } };
yield return new object[] { new string[] { "abc", "def", "ghi", "jkl", testPath } };
yield return new object[] { new string[] { "abc", "def", "ghi", testPath, "jkl" } };
yield return new object[] { new string[] { "abc", "def", testPath, "ghi", "jkl" } };
yield return new object[] { new string[] { "abc", testPath, "def", "ghi", "jkl" } };
yield return new object[] { new string[] { testPath, "abc", "def", "ghi", "jkl" } };
}
}
[Theory]
[MemberData(nameof(Combine_Basic_TestData))]
[MemberData(nameof(Combine_CommonCases_TestData))]
public static void Combine(string[] paths)
{
string expected = string.Empty;
if (paths.Length > 0) expected = paths[0];
for (int i = 1; i < paths.Length; i++)
{
expected = Path.Combine(expected, paths[i]);
}
// Combine(string[])
Assert.Equal(expected, Path.Combine(paths));
// Verify special cases
switch (paths.Length)
{
case 2:
// Combine(string, string)
Assert.Equal(expected, Path.Combine(paths[0], paths[1]));
break;
case 3:
// Combine(string, string, string)
Assert.Equal(expected, Path.Combine(paths[0], paths[1], paths[2]));
break;
default:
// Nothing to do: everything else is pushed into an array
break;
}
}
[Fact]
public static void PathIsNull()
{
VerifyException<ArgumentNullException>(null);
}
[Fact]
public static void PathIsNullWihtoutRootedAfterArgumentNull()
{
//any path is null without rooted after (ANE)
CommonCasesException<ArgumentNullException>(null);
}
[Fact]
public static void ContainsInvalidCharWithoutRootedAfterArgumentNull()
{
//any path contains invalid character without rooted after (AE)
CommonCasesException<ArgumentException>("ab\0cd");
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public static void ContainsInvalidCharWithoutRootedAfterArgumentNull_Windows()
{
//any path contains invalid character without rooted after (AE)
CommonCasesException<ArgumentException>("ab\"cd");
CommonCasesException<ArgumentException>("ab\"cd");
CommonCasesException<ArgumentException>("ab<cd");
CommonCasesException<ArgumentException>("ab>cd");
CommonCasesException<ArgumentException>("ab|cd");
CommonCasesException<ArgumentException>("ab\bcd");
CommonCasesException<ArgumentException>("ab\0cd");
CommonCasesException<ArgumentException>("ab\tcd");
}
[Fact]
public static void ContainsInvalidCharWithRootedAfterArgumentNull()
{
//any path contains invalid character with rooted after (AE)
CommonCasesException<ArgumentException>("ab\0cd", s_separator + "abc");
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public static void ContainsInvalidCharWithRootedAfterArgumentNull_Windows()
{
//any path contains invalid character with rooted after (AE)
CommonCasesException<ArgumentException>("ab\"cd", s_separator + "abc");
CommonCasesException<ArgumentException>("ab<cd", s_separator + "abc");
CommonCasesException<ArgumentException>("ab>cd", s_separator + "abc");
CommonCasesException<ArgumentException>("ab|cd", s_separator + "abc");
CommonCasesException<ArgumentException>("ab\bcd", s_separator + "abc");
CommonCasesException<ArgumentException>("ab\tcd", s_separator + "abc");
}
private static void VerifyException<T>(string[] paths) where T : Exception
{
Assert.Throws<T>(() => Path.Combine(paths));
//verify passed as elements case
if (paths != null)
{
Assert.InRange(paths.Length, 1, 5);
Assert.Throws<T>(() =>
{
switch (paths.Length)
{
case 0:
Path.Combine();
break;
case 1:
Path.Combine(paths[0]);
break;
case 2:
Path.Combine(paths[0], paths[1]);
break;
case 3:
Path.Combine(paths[0], paths[1], paths[2]);
break;
case 4:
Path.Combine(paths[0], paths[1], paths[2], paths[3]);
break;
case 5:
Path.Combine(paths[0], paths[1], paths[2], paths[3], paths[4]);
break;
}
});
}
}
private static void CommonCasesException<T>(string testing) where T : Exception
{
VerifyException<T>(new string[] { testing });
VerifyException<T>(new string[] { "abc", testing });
VerifyException<T>(new string[] { testing, "abc" });
VerifyException<T>(new string[] { "abc", "def", testing });
VerifyException<T>(new string[] { "abc", testing, "def" });
VerifyException<T>(new string[] { testing, "abc", "def" });
VerifyException<T>(new string[] { "abc", "def", "ghi", testing });
VerifyException<T>(new string[] { "abc", "def", testing, "ghi" });
VerifyException<T>(new string[] { "abc", testing, "def", "ghi" });
VerifyException<T>(new string[] { testing, "abc", "def", "ghi" });
VerifyException<T>(new string[] { "abc", "def", "ghi", "jkl", testing });
VerifyException<T>(new string[] { "abc", "def", "ghi", testing, "jkl" });
VerifyException<T>(new string[] { "abc", "def", testing, "ghi", "jkl" });
VerifyException<T>(new string[] { "abc", testing, "def", "ghi", "jkl" });
VerifyException<T>(new string[] { testing, "abc", "def", "ghi", "jkl" });
}
private static void CommonCasesException<T>(string testing, string testing2) where T : Exception
{
VerifyException<T>(new string[] { testing, testing2 });
VerifyException<T>(new string[] { "abc", testing, testing2 });
VerifyException<T>(new string[] { testing, "abc", testing2 });
VerifyException<T>(new string[] { testing, testing2, "def" });
VerifyException<T>(new string[] { "abc", "def", testing, testing2 });
VerifyException<T>(new string[] { "abc", testing, "def", testing2 });
VerifyException<T>(new string[] { "abc", testing, testing2, "ghi" });
VerifyException<T>(new string[] { testing, "abc", "def", testing2 });
VerifyException<T>(new string[] { testing, "abc", testing2, "ghi" });
VerifyException<T>(new string[] { testing, testing2, "def", "ghi" });
VerifyException<T>(new string[] { "abc", "def", "ghi", testing, testing2 });
VerifyException<T>(new string[] { "abc", "def", testing, "ghi", testing2 });
VerifyException<T>(new string[] { "abc", "def", testing, testing2, "jkl" });
VerifyException<T>(new string[] { "abc", testing, "def", "ghi", testing2 });
VerifyException<T>(new string[] { "abc", testing, "def", testing2, "jkl" });
VerifyException<T>(new string[] { "abc", testing, testing2, "ghi", "jkl" });
VerifyException<T>(new string[] { testing, "abc", "def", "ghi", testing2 });
VerifyException<T>(new string[] { testing, "abc", "def", testing2, "jkl" });
VerifyException<T>(new string[] { testing, "abc", testing2, "ghi", "jkl" });
VerifyException<T>(new string[] { testing, testing2, "def", "ghi", "jkl" });
}
}
}
| |
// 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 CompareGreaterThanOrEqualSingle()
{
var test = new SimpleBinaryOpTest__CompareGreaterThanOrEqualSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.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 (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareGreaterThanOrEqualSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareGreaterThanOrEqualSingle testClass)
{
var result = Sse.CompareGreaterThanOrEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareGreaterThanOrEqualSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.CompareGreaterThanOrEqual(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareGreaterThanOrEqualSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleBinaryOpTest__CompareGreaterThanOrEqualSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse.CompareGreaterThanOrEqual(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse.CompareGreaterThanOrEqual(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse.CompareGreaterThanOrEqual(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThanOrEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThanOrEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThanOrEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse.CompareGreaterThanOrEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
{
var result = Sse.CompareGreaterThanOrEqual(
Sse.LoadVector128((Single*)(pClsVar1)),
Sse.LoadVector128((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareGreaterThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareGreaterThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareGreaterThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareGreaterThanOrEqualSingle();
var result = Sse.CompareGreaterThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareGreaterThanOrEqualSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
{
var result = Sse.CompareGreaterThanOrEqual(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse.CompareGreaterThanOrEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.CompareGreaterThanOrEqual(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse.CompareGreaterThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse.CompareGreaterThanOrEqual(
Sse.LoadVector128((Single*)(&test._fld1)),
Sse.LoadVector128((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != ((left[0] >= right[0]) ? -1 : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != ((left[i] >= right[i]) ? -1 : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareGreaterThanOrEqual)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using pol = Anycmd.Xacml.Policy;
using rtm = Anycmd.Xacml.Runtime;
namespace Anycmd.Xacml.ControlCenter.CustomControls
{
/// <summary>
/// Summary description for PolicySet.
/// </summary>
public class Obligations : BaseControl
{
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnRemove;
private System.Windows.Forms.Button btnUp;
private System.Windows.Forms.Button btnDown;
private pol.ObligationReadWriteCollection _obligations;
private System.Windows.Forms.ListBox lstObligations;
private System.Windows.Forms.GroupBox grpObligations;
private System.Windows.Forms.GroupBox grpObligation;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtId;
private System.Windows.Forms.ComboBox cmbEffect;
private System.Windows.Forms.GroupBox grpAssignment;
private System.Windows.Forms.ListBox lstAttributeAssignments;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtAttributeId;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtAttributeAssignemnt;
private int index = -1;
private int obligationIndex = -1;
private System.Windows.Forms.Button btnAttributeAssignmentsAdd;
private System.Windows.Forms.Button btnAttributeAssignmentsRemove;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
///
/// </summary>
/// <param name="obligations"></param>
public Obligations( pol.ObligationReadWriteCollection obligations )
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
LoadingData = true;
_obligations = obligations;
cmbEffect.Items.Add( pol.Effect.Deny );
cmbEffect.Items.Add( pol.Effect.Permit );
lstAttributeAssignments.DisplayMember = "AttributeId";
lstObligations.DisplayMember = "ObligationId";
foreach( pol.ObligationElementReadWrite obligation in obligations )
{
lstObligations.Items.Add( obligation );
}
if( obligations.Count != 0 )
{
lstObligations.SelectedIndex = 0;
}
LoadingData = false;
}
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.grpObligations = new System.Windows.Forms.GroupBox();
this.lstObligations = new System.Windows.Forms.ListBox();
this.btnDown = new System.Windows.Forms.Button();
this.btnUp = new System.Windows.Forms.Button();
this.btnRemove = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.grpObligation = new System.Windows.Forms.GroupBox();
this.grpAssignment = new System.Windows.Forms.GroupBox();
this.txtAttributeAssignemnt = new System.Windows.Forms.TextBox();
this.txtAttributeId = new System.Windows.Forms.TextBox();
this.lstAttributeAssignments = new System.Windows.Forms.ListBox();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.cmbEffect = new System.Windows.Forms.ComboBox();
this.txtId = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.btnAttributeAssignmentsAdd = new System.Windows.Forms.Button();
this.btnAttributeAssignmentsRemove = new System.Windows.Forms.Button();
this.grpObligations.SuspendLayout();
this.grpObligation.SuspendLayout();
this.grpAssignment.SuspendLayout();
this.SuspendLayout();
//
// grpObligations
//
this.grpObligations.Controls.Add(this.lstObligations);
this.grpObligations.Controls.Add(this.btnDown);
this.grpObligations.Controls.Add(this.btnUp);
this.grpObligations.Controls.Add(this.btnRemove);
this.grpObligations.Controls.Add(this.btnAdd);
this.grpObligations.Location = new System.Drawing.Point(8, 8);
this.grpObligations.Name = "grpObligations";
this.grpObligations.Size = new System.Drawing.Size(576, 160);
this.grpObligations.TabIndex = 2;
this.grpObligations.TabStop = false;
this.grpObligations.Text = "Obligations";
//
// lstObligations
//
this.lstObligations.Location = new System.Drawing.Point(8, 16);
this.lstObligations.Name = "lstObligations";
this.lstObligations.Size = new System.Drawing.Size(472, 134);
this.lstObligations.TabIndex = 5;
this.lstObligations.SelectedIndexChanged += new System.EventHandler(this.lstObligations_SelectedIndexChanged);
//
// btnDown
//
this.btnDown.Location = new System.Drawing.Point(488, 120);
this.btnDown.Name = "btnDown";
this.btnDown.TabIndex = 4;
this.btnDown.Text = "Down";
//
// btnUp
//
this.btnUp.Location = new System.Drawing.Point(488, 88);
this.btnUp.Name = "btnUp";
this.btnUp.TabIndex = 3;
this.btnUp.Text = "Up";
//
// btnRemove
//
this.btnRemove.Location = new System.Drawing.Point(488, 56);
this.btnRemove.Name = "btnRemove";
this.btnRemove.TabIndex = 2;
this.btnRemove.Text = "Remove";
this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click);
//
// btnAdd
//
this.btnAdd.Location = new System.Drawing.Point(488, 24);
this.btnAdd.Name = "btnAdd";
this.btnAdd.TabIndex = 1;
this.btnAdd.Text = "Add";
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// grpObligation
//
this.grpObligation.Controls.Add(this.grpAssignment);
this.grpObligation.Controls.Add(this.cmbEffect);
this.grpObligation.Controls.Add(this.txtId);
this.grpObligation.Controls.Add(this.label2);
this.grpObligation.Controls.Add(this.label1);
this.grpObligation.Location = new System.Drawing.Point(8, 176);
this.grpObligation.Name = "grpObligation";
this.grpObligation.Size = new System.Drawing.Size(576, 272);
this.grpObligation.TabIndex = 3;
this.grpObligation.TabStop = false;
this.grpObligation.Text = "Obligation";
//
// grpAssignment
//
this.grpAssignment.Controls.Add(this.btnAttributeAssignmentsRemove);
this.grpAssignment.Controls.Add(this.btnAttributeAssignmentsAdd);
this.grpAssignment.Controls.Add(this.txtAttributeAssignemnt);
this.grpAssignment.Controls.Add(this.txtAttributeId);
this.grpAssignment.Controls.Add(this.lstAttributeAssignments);
this.grpAssignment.Controls.Add(this.label3);
this.grpAssignment.Controls.Add(this.label4);
this.grpAssignment.Location = new System.Drawing.Point(8, 80);
this.grpAssignment.Name = "grpAssignment";
this.grpAssignment.Size = new System.Drawing.Size(560, 184);
this.grpAssignment.TabIndex = 5;
this.grpAssignment.TabStop = false;
this.grpAssignment.Text = "Attribute assignments";
//
// txtAttributeAssignemnt
//
this.txtAttributeAssignemnt.Location = new System.Drawing.Point(72, 136);
this.txtAttributeAssignemnt.Multiline = true;
this.txtAttributeAssignemnt.Name = "txtAttributeAssignemnt";
this.txtAttributeAssignemnt.Size = new System.Drawing.Size(480, 40);
this.txtAttributeAssignemnt.TabIndex = 6;
this.txtAttributeAssignemnt.Text = "";
//
// txtAttributeId
//
this.txtAttributeId.Location = new System.Drawing.Point(72, 104);
this.txtAttributeId.Name = "txtAttributeId";
this.txtAttributeId.Size = new System.Drawing.Size(480, 20);
this.txtAttributeId.TabIndex = 5;
this.txtAttributeId.Text = "";
//
// lstAttributeAssignments
//
this.lstAttributeAssignments.Location = new System.Drawing.Point(8, 24);
this.lstAttributeAssignments.Name = "lstAttributeAssignments";
this.lstAttributeAssignments.Size = new System.Drawing.Size(464, 69);
this.lstAttributeAssignments.TabIndex = 4;
this.lstAttributeAssignments.SelectedIndexChanged += new System.EventHandler(this.lstAttributeAssignments_SelectedIndexChanged);
//
// label3
//
this.label3.Location = new System.Drawing.Point(8, 104);
this.label3.Name = "label3";
this.label3.TabIndex = 1;
this.label3.Text = "Attribute id:";
//
// label4
//
this.label4.Location = new System.Drawing.Point(8, 136);
this.label4.Name = "label4";
this.label4.TabIndex = 1;
this.label4.Text = "Contents:";
//
// cmbEffect
//
this.cmbEffect.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbEffect.Location = new System.Drawing.Point(80, 48);
this.cmbEffect.Name = "cmbEffect";
this.cmbEffect.Size = new System.Drawing.Size(488, 21);
this.cmbEffect.TabIndex = 3;
this.cmbEffect.SelectedIndexChanged += cmbEffect_SelectedIndexChanged;
//
// txtId
//
this.txtId.Location = new System.Drawing.Point(80, 16);
this.txtId.Name = "txtId";
this.txtId.Size = new System.Drawing.Size(488, 20);
this.txtId.TabIndex = 2;
this.txtId.Text = "";
this.txtId.TextChanged += txtId_TextChanged;
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 48);
this.label2.Name = "label2";
this.label2.TabIndex = 1;
this.label2.Text = "Fullfill on:";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 16);
this.label1.Name = "label1";
this.label1.TabIndex = 0;
this.label1.Text = "Obligation id:";
//
// btnAttributeAssignmentsAdd
//
this.btnAttributeAssignmentsAdd.Location = new System.Drawing.Point(480, 24);
this.btnAttributeAssignmentsAdd.Name = "btnAttributeAssignmentsAdd";
this.btnAttributeAssignmentsAdd.Size = new System.Drawing.Size(72, 23);
this.btnAttributeAssignmentsAdd.TabIndex = 7;
this.btnAttributeAssignmentsAdd.Text = "Add";
this.btnAttributeAssignmentsAdd.Click += new System.EventHandler(this.btnAttributeAssignmentsAdd_Click);
//
// btnAttributeAssignmentsRemove
//
this.btnAttributeAssignmentsRemove.Location = new System.Drawing.Point(480, 56);
this.btnAttributeAssignmentsRemove.Name = "btnAttributeAssignmentsRemove";
this.btnAttributeAssignmentsRemove.Size = new System.Drawing.Size(72, 23);
this.btnAttributeAssignmentsRemove.TabIndex = 8;
this.btnAttributeAssignmentsRemove.Text = "Remove";
this.btnAttributeAssignmentsRemove.Click += new System.EventHandler(this.btnAttributeAssignmentsRemove_Click);
//
// Obligations
//
this.Controls.Add(this.grpObligation);
this.Controls.Add(this.grpObligations);
this.Name = "Obligations";
this.Size = new System.Drawing.Size(592, 456);
this.grpObligations.ResumeLayout(false);
this.grpObligation.ResumeLayout(false);
this.grpAssignment.ResumeLayout(false);
this.ResumeLayout(false);
}
private void txtId_TextChanged(object sender, EventArgs e)
{
base.TextBox_TextChanged(sender, e);
}
private void cmbEffect_SelectedIndexChanged(object sender, EventArgs e)
{
base.ComboBox_SelectedIndexChanged(sender, e);
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lstObligations_SelectedIndexChanged(object sender, System.EventArgs e)
{
if( index != -1 )
{
pol.AttributeAssignmentElementReadWrite attrAux = lstAttributeAssignments.Items[index] as pol.AttributeAssignmentElementReadWrite;
attrAux.AttributeId = txtAttributeId.Text;
attrAux.Value = txtAttributeAssignemnt.Text;
}
if( obligationIndex != -1 && obligationIndex != lstObligations.SelectedIndex )
{
pol.ObligationElementReadWrite obliAux = lstObligations.Items[obligationIndex] as pol.ObligationElementReadWrite;
obliAux.ObligationId = txtId.Text;
if( cmbEffect.Text.Equals( pol.Effect.Deny.ToString()) )
{
obliAux.FulfillOn = pol.Effect.Deny;
}
else if( cmbEffect.Text.Equals( pol.Effect.Permit.ToString()) )
{
obliAux.FulfillOn = pol.Effect.Permit;
}
lstObligations.Items.RemoveAt( obligationIndex );
lstObligations.Items.Insert( obligationIndex, obliAux );
}
obligationIndex = lstObligations.SelectedIndex;
pol.ObligationElementReadWrite obligation = lstObligations.SelectedItem as pol.ObligationElementReadWrite;
if(!LoadingData)
{
try
{
LoadingData = true;
if( obligation != null )
{
txtId.Text = obligation.ObligationId;
cmbEffect.SelectedIndex = cmbEffect.FindStringExact( obligation.FulfillOn.ToString() );
lstAttributeAssignments.Items.Clear();
foreach( pol.AttributeAssignmentElementReadWrite attr in obligation.AttributeAssignment )
{
lstAttributeAssignments.Items.Add( attr );
}
txtAttributeId.Text = string.Empty;
txtAttributeAssignemnt.Text = string.Empty;
}
index = -1;
}
finally
{
LoadingData = false;
}
}
else
{
obligationIndex = -1;
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lstAttributeAssignments_SelectedIndexChanged(object sender, System.EventArgs e)
{
if( index != -1 && index != lstAttributeAssignments.SelectedIndex )
{
pol.AttributeAssignmentElementReadWrite attrAux = lstAttributeAssignments.Items[index] as pol.AttributeAssignmentElementReadWrite;
attrAux.AttributeId = txtAttributeId.Text;
attrAux.Value = txtAttributeAssignemnt.Text;
lstAttributeAssignments.Items.RemoveAt( index );
lstAttributeAssignments.Items.Insert( index, attrAux );
}
pol.AttributeAssignmentElementReadWrite attr = lstAttributeAssignments.SelectedItem as pol.AttributeAssignmentElementReadWrite;
index = lstAttributeAssignments.SelectedIndex;
try
{
LoadingData = true;
if( attr != null )
{
txtAttributeId.Text = attr.AttributeId;
txtAttributeAssignemnt.Text = (string)attr.GetTypedValue( rtm.DataTypeDescriptor.String, 0 );
}
}
finally
{
LoadingData = false;
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAdd_Click(object sender, System.EventArgs e)
{
LoadingData = true;
txtId.Text = string.Empty;
lstAttributeAssignments.Items.Clear();
txtAttributeAssignemnt.Text = string.Empty;
txtAttributeId.Text = string.Empty;
index = -1;
obligationIndex = -1;
pol.ObligationElementReadWrite oObligation = new pol.ObligationElementReadWrite(null,Xacml.XacmlVersion.Version11);
lstObligations.Items.Add(oObligation);
_obligations.Add( oObligation );
LoadingData = false;
}
private void btnRemove_Click(object sender, System.EventArgs e)
{
index = -1;
obligationIndex = -1;
pol.ObligationElementReadWrite obligation = lstObligations.SelectedItem as pol.ObligationElementReadWrite;
try
{
LoadingData = true;
txtId.Text = string.Empty;
lstAttributeAssignments.Items.Clear();
txtAttributeAssignemnt.Text = string.Empty;
txtAttributeId.Text = string.Empty;
_obligations.RemoveAt(lstObligations.SelectedIndex);
lstObligations.Items.RemoveAt(lstObligations.SelectedIndex);
}
finally
{
LoadingData = false;
}
}
private void btnAttributeAssignmentsAdd_Click(object sender, System.EventArgs e)
{
pol.ObligationElementReadWrite obligation = lstObligations.SelectedItem as pol.ObligationElementReadWrite;
pol.AttributeAssignmentElementReadWrite oAtt = new pol.AttributeAssignmentElementReadWrite("TODO: Add AttributeId",Consts.Schema1.InternalDataTypes.XsdString,
string.Empty, obligation.SchemaVersion );
obligation.AttributeAssignment.Add( oAtt );
lstAttributeAssignments.Items.Add( oAtt );
}
private void btnAttributeAssignmentsRemove_Click(object sender, System.EventArgs e)
{
index = -1;
pol.ObligationElementReadWrite obligation = lstObligations.SelectedItem as pol.ObligationElementReadWrite;
pol.AttributeAssignmentElementReadWrite attribute = lstAttributeAssignments.SelectedItem as pol.AttributeAssignmentElementReadWrite;
try
{
LoadingData = true;
txtAttributeAssignemnt.Text = string.Empty;
txtAttributeId.Text = string.Empty;
obligation.AttributeAssignment.RemoveAt(lstAttributeAssignments.SelectedIndex);
lstAttributeAssignments.Items.RemoveAt(lstAttributeAssignments.SelectedIndex);
}
finally
{
LoadingData = false;
}
}
/// <summary>
/// Gets the ReadWriteObligationCollection
/// </summary>
public pol.ObligationReadWriteCollection ObligationsElement
{
get
{
if( index != -1 )
{
pol.AttributeAssignmentElementReadWrite attrAux = lstAttributeAssignments.Items[index] as pol.AttributeAssignmentElementReadWrite;
attrAux.AttributeId = txtAttributeId.Text;
attrAux.Value = txtAttributeAssignemnt.Text;
}
if( obligationIndex != -1 )
{
pol.ObligationElementReadWrite obliAux = lstObligations.Items[obligationIndex] as pol.ObligationElementReadWrite;
obliAux.ObligationId = txtId.Text;
if( cmbEffect.Text.Equals( pol.Effect.Deny.ToString()) )
{
obliAux.FulfillOn = pol.Effect.Deny;
}
else if( cmbEffect.Text.Equals( pol.Effect.Permit.ToString()) )
{
obliAux.FulfillOn = pol.Effect.Permit;
}
}
return _obligations;
}
}
}
}
| |
// 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.
//
using System.Diagnostics;
using System.Threading;
namespace System.Text
{
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.
_encoding = encoding;
}
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 (_encoding.CodePage == that._encoding.CodePage);
}
return (false);
}
public override int GetHashCode()
{
return _encoding.CodePage;
}
}
internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer
{
// Our variables
private char _cBestFit = '\0';
private int _iCount = -1;
private 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)
{
_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';
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// BccEmailArchive
/// </summary>
[DataContract]
public partial class BccEmailArchive : IEquatable<BccEmailArchive>, IValidatableObject
{
public BccEmailArchive()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="BccEmailArchive" /> class.
/// </summary>
/// <param name="AccountId">The account ID associated with the envelope..</param>
/// <param name="BccEmailArchiveId">BccEmailArchiveId.</param>
/// <param name="Created">Created.</param>
/// <param name="CreatedBy">CreatedBy.</param>
/// <param name="Email">Email.</param>
/// <param name="EmailNotificationId">EmailNotificationId.</param>
/// <param name="Modified">Modified.</param>
/// <param name="ModifiedBy">ModifiedBy.</param>
/// <param name="Status">Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later..</param>
/// <param name="Uri">Uri.</param>
public BccEmailArchive(string AccountId = default(string), string BccEmailArchiveId = default(string), string Created = default(string), UserInfo CreatedBy = default(UserInfo), string Email = default(string), string EmailNotificationId = default(string), string Modified = default(string), UserInfo ModifiedBy = default(UserInfo), string Status = default(string), string Uri = default(string))
{
this.AccountId = AccountId;
this.BccEmailArchiveId = BccEmailArchiveId;
this.Created = Created;
this.CreatedBy = CreatedBy;
this.Email = Email;
this.EmailNotificationId = EmailNotificationId;
this.Modified = Modified;
this.ModifiedBy = ModifiedBy;
this.Status = Status;
this.Uri = Uri;
}
/// <summary>
/// The account ID associated with the envelope.
/// </summary>
/// <value>The account ID associated with the envelope.</value>
[DataMember(Name="accountId", EmitDefaultValue=false)]
public string AccountId { get; set; }
/// <summary>
/// Gets or Sets BccEmailArchiveId
/// </summary>
[DataMember(Name="bccEmailArchiveId", EmitDefaultValue=false)]
public string BccEmailArchiveId { get; set; }
/// <summary>
/// Gets or Sets Created
/// </summary>
[DataMember(Name="created", EmitDefaultValue=false)]
public string Created { get; set; }
/// <summary>
/// Gets or Sets CreatedBy
/// </summary>
[DataMember(Name="createdBy", EmitDefaultValue=false)]
public UserInfo CreatedBy { get; set; }
/// <summary>
/// Gets or Sets Email
/// </summary>
[DataMember(Name="email", EmitDefaultValue=false)]
public string Email { get; set; }
/// <summary>
/// Gets or Sets EmailNotificationId
/// </summary>
[DataMember(Name="emailNotificationId", EmitDefaultValue=false)]
public string EmailNotificationId { get; set; }
/// <summary>
/// Gets or Sets Modified
/// </summary>
[DataMember(Name="modified", EmitDefaultValue=false)]
public string Modified { get; set; }
/// <summary>
/// Gets or Sets ModifiedBy
/// </summary>
[DataMember(Name="modifiedBy", EmitDefaultValue=false)]
public UserInfo ModifiedBy { get; set; }
/// <summary>
/// Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.
/// </summary>
/// <value>Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.</value>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets Uri
/// </summary>
[DataMember(Name="uri", EmitDefaultValue=false)]
public string Uri { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class BccEmailArchive {\n");
sb.Append(" AccountId: ").Append(AccountId).Append("\n");
sb.Append(" BccEmailArchiveId: ").Append(BccEmailArchiveId).Append("\n");
sb.Append(" Created: ").Append(Created).Append("\n");
sb.Append(" CreatedBy: ").Append(CreatedBy).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" EmailNotificationId: ").Append(EmailNotificationId).Append("\n");
sb.Append(" Modified: ").Append(Modified).Append("\n");
sb.Append(" ModifiedBy: ").Append(ModifiedBy).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" Uri: ").Append(Uri).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as BccEmailArchive);
}
/// <summary>
/// Returns true if BccEmailArchive instances are equal
/// </summary>
/// <param name="other">Instance of BccEmailArchive to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BccEmailArchive other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.AccountId == other.AccountId ||
this.AccountId != null &&
this.AccountId.Equals(other.AccountId)
) &&
(
this.BccEmailArchiveId == other.BccEmailArchiveId ||
this.BccEmailArchiveId != null &&
this.BccEmailArchiveId.Equals(other.BccEmailArchiveId)
) &&
(
this.Created == other.Created ||
this.Created != null &&
this.Created.Equals(other.Created)
) &&
(
this.CreatedBy == other.CreatedBy ||
this.CreatedBy != null &&
this.CreatedBy.Equals(other.CreatedBy)
) &&
(
this.Email == other.Email ||
this.Email != null &&
this.Email.Equals(other.Email)
) &&
(
this.EmailNotificationId == other.EmailNotificationId ||
this.EmailNotificationId != null &&
this.EmailNotificationId.Equals(other.EmailNotificationId)
) &&
(
this.Modified == other.Modified ||
this.Modified != null &&
this.Modified.Equals(other.Modified)
) &&
(
this.ModifiedBy == other.ModifiedBy ||
this.ModifiedBy != null &&
this.ModifiedBy.Equals(other.ModifiedBy)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.Uri == other.Uri ||
this.Uri != null &&
this.Uri.Equals(other.Uri)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.AccountId != null)
hash = hash * 59 + this.AccountId.GetHashCode();
if (this.BccEmailArchiveId != null)
hash = hash * 59 + this.BccEmailArchiveId.GetHashCode();
if (this.Created != null)
hash = hash * 59 + this.Created.GetHashCode();
if (this.CreatedBy != null)
hash = hash * 59 + this.CreatedBy.GetHashCode();
if (this.Email != null)
hash = hash * 59 + this.Email.GetHashCode();
if (this.EmailNotificationId != null)
hash = hash * 59 + this.EmailNotificationId.GetHashCode();
if (this.Modified != null)
hash = hash * 59 + this.Modified.GetHashCode();
if (this.ModifiedBy != null)
hash = hash * 59 + this.ModifiedBy.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.Uri != null)
hash = hash * 59 + this.Uri.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/***************************************************************************
* Gump.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : [email protected]
*
* $Id: Gump.cs 521 2010-06-17 07:11:43Z mark $
*
***************************************************************************/
/***************************************************************************
*
* 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.
*
***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Server;
using Server.Network;
namespace Server.Gumps
{
public class Gump
{
private List<GumpEntry> m_Entries;
private List<string> m_Strings;
internal int m_TextEntries, m_Switches;
private static int m_NextSerial = 1;
private int m_Serial;
private int m_TypeID;
private int m_X, m_Y;
private bool m_Dragable = true;
private bool m_Closable = true;
private bool m_Resizable = true;
private bool m_Disposable = true;
public static int GetTypeID( Type type )
{
return type.FullName.GetHashCode();
}
public Gump( int x, int y )
{
do
{
m_Serial = m_NextSerial++;
} while ( m_Serial == 0 ); // standard client apparently doesn't send a gump response packet if serial == 0
m_X = x;
m_Y = y;
m_TypeID = GetTypeID( this.GetType() );
m_Entries = new List<GumpEntry>();
m_Strings = new List<string>();
}
public void Invalidate()
{
//if ( m_Strings.Count > 0 )
// m_Strings.Clear();
}
public int TypeID
{
get
{
return m_TypeID;
}
}
public List<GumpEntry> Entries
{
get{ return m_Entries; }
}
public int Serial
{
get
{
return m_Serial;
}
set
{
if ( m_Serial != value )
{
m_Serial = value;
Invalidate();
}
}
}
public int X
{
get
{
return m_X;
}
set
{
if ( m_X != value )
{
m_X = value;
Invalidate();
}
}
}
public int Y
{
get
{
return m_Y;
}
set
{
if ( m_Y != value )
{
m_Y = value;
Invalidate();
}
}
}
public bool Disposable
{
get
{
return m_Disposable;
}
set
{
if ( m_Disposable != value )
{
m_Disposable = value;
Invalidate();
}
}
}
public bool Resizable
{
get
{
return m_Resizable;
}
set
{
if ( m_Resizable != value )
{
m_Resizable = value;
Invalidate();
}
}
}
public bool Dragable
{
get
{
return m_Dragable;
}
set
{
if ( m_Dragable != value )
{
m_Dragable = value;
Invalidate();
}
}
}
public bool Closable
{
get
{
return m_Closable;
}
set
{
if ( m_Closable != value )
{
m_Closable = value;
Invalidate();
}
}
}
public void AddPage( int page )
{
Add( new GumpPage( page ) );
}
public void AddAlphaRegion( int x, int y, int width, int height )
{
Add( new GumpAlphaRegion( x, y, width, height ) );
}
public void AddBackground( int x, int y, int width, int height, int gumpID )
{
Add( new GumpBackground( x, y, width, height, gumpID ) );
}
public void AddButton( int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type, int param )
{
Add( new GumpButton( x, y, normalID, pressedID, buttonID, type, param ) );
}
public void AddCheck( int x, int y, int inactiveID, int activeID, bool initialState, int switchID )
{
Add( new GumpCheck( x, y, inactiveID, activeID, initialState, switchID ) );
}
public void AddGroup( int group )
{
Add( new GumpGroup( group ) );
}
public void AddTooltip( int number )
{
Add( new GumpTooltip( number ) );
}
public void AddHtml( int x, int y, int width, int height, string text, bool background, bool scrollbar )
{
Add( new GumpHtml( x, y, width, height, text, background, scrollbar ) );
}
public void AddHtmlLocalized( int x, int y, int width, int height, int number, bool background, bool scrollbar )
{
Add( new GumpHtmlLocalized( x, y, width, height, number, background, scrollbar ) );
}
public void AddHtmlLocalized( int x, int y, int width, int height, int number, int color, bool background, bool scrollbar )
{
Add( new GumpHtmlLocalized( x, y, width, height, number, color, background, scrollbar ) );
}
public void AddHtmlLocalized( int x, int y, int width, int height, int number, string args, int color, bool background, bool scrollbar )
{
Add( new GumpHtmlLocalized( x, y, width, height, number, args, color, background, scrollbar ) );
}
public void AddImage( int x, int y, int gumpID )
{
Add( new GumpImage( x, y, gumpID ) );
}
public void AddImage( int x, int y, int gumpID, int hue )
{
Add( new GumpImage( x, y, gumpID, hue ) );
}
public void AddImageTiled( int x, int y, int width, int height, int gumpID )
{
Add( new GumpImageTiled( x, y, width, height, gumpID ) );
}
public void AddImageTiledButton( int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type, int param, int itemID, int hue, int width, int height )
{
Add( new GumpImageTileButton( x, y, normalID, pressedID, buttonID, type, param, itemID, hue, width, height ) );
}
public void AddImageTiledButton( int x, int y, int normalID, int pressedID, int buttonID, GumpButtonType type, int param, int itemID, int hue, int width, int height, int localizedTooltip )
{
Add( new GumpImageTileButton( x, y, normalID, pressedID, buttonID, type, param, itemID, hue, width, height, localizedTooltip ) );
}
public void AddItem( int x, int y, int itemID )
{
Add( new GumpItem( x, y, itemID ) );
}
public void AddItem( int x, int y, int itemID, int hue )
{
Add( new GumpItem( x, y, itemID, hue ) );
}
public void AddLabel( int x, int y, int hue, string text )
{
Add( new GumpLabel( x, y, hue, text ) );
}
public void AddLabelCropped( int x, int y, int width, int height, int hue, string text )
{
Add( new GumpLabelCropped( x, y, width, height, hue, text ) );
}
public void AddRadio( int x, int y, int inactiveID, int activeID, bool initialState, int switchID )
{
Add( new GumpRadio( x, y, inactiveID, activeID, initialState, switchID ) );
}
public void AddTextEntry( int x, int y, int width, int height, int hue, int entryID, string initialText )
{
Add( new GumpTextEntry( x, y, width, height, hue, entryID, initialText ) );
}
public void AddTextEntry( int x, int y, int width, int height, int hue, int entryID, string initialText, int size ) {
Add( new GumpTextEntryLimited( x, y, width, height, hue, entryID, initialText, size ) );
}
public void AddItemProperty(int serial)
{
Add(new GumpItemProperty(serial));
}
public void Add( GumpEntry g )
{
if ( g.Parent != this )
{
g.Parent = this;
}
else if ( !m_Entries.Contains( g ) )
{
Invalidate();
m_Entries.Add( g );
}
}
public void Remove( GumpEntry g )
{
Invalidate();
m_Entries.Remove( g );
g.Parent = null;
}
public int Intern( string value )
{
int indexOf = m_Strings.IndexOf( value );
if ( indexOf >= 0 )
{
return indexOf;
}
else
{
Invalidate();
m_Strings.Add( value );
return m_Strings.Count - 1;
}
}
public void SendTo( NetState state )
{
state.AddGump( this );
state.Send( Compile( state ) );
}
public static byte[] StringToBuffer( string str )
{
return Encoding.ASCII.GetBytes( str );
}
private static byte[] m_BeginLayout = StringToBuffer( "{ " );
private static byte[] m_EndLayout = StringToBuffer( " }" );
private static byte[] m_NoMove = StringToBuffer( "{ nomove }" );
private static byte[] m_NoClose = StringToBuffer( "{ noclose }" );
private static byte[] m_NoDispose = StringToBuffer( "{ nodispose }" );
private static byte[] m_NoResize = StringToBuffer( "{ noresize }" );
private Packet Compile()
{
return Compile( null );
}
private Packet Compile( NetState ns )
{
IGumpWriter disp;
if ( ns != null && ns.Unpack )
disp = new DisplayGumpPacked( this );
else
disp = new DisplayGumpFast( this );
if ( !m_Dragable )
disp.AppendLayout( m_NoMove );
if ( !m_Closable )
disp.AppendLayout( m_NoClose );
if ( !m_Disposable )
disp.AppendLayout( m_NoDispose );
if ( !m_Resizable )
disp.AppendLayout( m_NoResize );
int count = m_Entries.Count;
GumpEntry e;
for ( int i = 0; i < count; ++i )
{
e = m_Entries[i];
disp.AppendLayout( m_BeginLayout );
e.AppendTo( disp );
disp.AppendLayout( m_EndLayout );
}
disp.WriteStrings( m_Strings );
disp.Flush();
m_TextEntries = disp.TextEntries;
m_Switches = disp.Switches;
return disp as Packet;
}
public virtual void OnResponse( NetState sender, RelayInfo info )
{
}
public virtual void OnServerClose( NetState owner ) {
}
}
}
| |
using Codecov.Services.ContinuousIntegrationServers;
using FluentAssertions;
using Moq;
using Xunit;
namespace Codecov.Tests.Services.ContiniousIntegrationServers
{
public class JenkinsTests
{
[Fact]
public void Branch_Should_Be_Empty_String_When_Enviornment_Variable_Does_Not_Exist()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var jenkins = new Jenkins(ev.Object);
// When
var branch = jenkins.Branch;
// Then
branch.Should().BeEmpty();
}
[Theory]
[InlineData("ghprbSourceBranch", "123")]
[InlineData("GIT_BRANCH", "456")]
[InlineData("BRANCH_NAME", "789")]
public void Branch_Should_Be_Set_When_Enviornment_Variable_Exist(string key, string value)
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable(key)).Returns(value);
var jenkins = new Jenkins(ev.Object);
// When
var branch = jenkins.Branch;
// Then
branch.Should().Be(value);
}
[Fact]
public void Build_Should_Be_Empty_String_When_Environment_Variables_Do_Not_Exist()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var jenkins = new Jenkins(ev.Object);
// When
var build = jenkins.Build;
// Then
build.Should().BeEmpty();
}
[Fact]
public void Build_Should_Not_Be_Empty_String_When_Environment_Variable_Exists()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("BUILD_NUMBER")).Returns("111");
var jenkins = new Jenkins(ev.Object);
// When
var build = jenkins.Build;
// Then
build.Should().Be("111");
}
[Fact]
public void BuildUrl_Should_Be_Empty_String_When_Environment_Variables_Do_Not_Exist()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var jenkins = new Jenkins(ev.Object);
// When
var buildUrl = jenkins.BuildUrl;
// Then
buildUrl.Should().BeEmpty();
}
[Fact]
public void BuildUrl_Should_Not_Be_Empty_String_When_Environment_Variable_Exist()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("BUILD_URL")).Returns("https://jenkins.yourcompany.com/some-job/1");
var jenkins = new Jenkins(ev.Object);
// When
var buildUrl = jenkins.BuildUrl;
// Then
buildUrl.Should().Be("https://jenkins.yourcompany.com/some-job/1");
}
[Fact]
public void Commit_Should_Be_Empty_String_When_Environment_Variable_Does_Not_Exist()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var jenkins = new Jenkins(ev.Object);
// When
var commit = jenkins.Commit;
// Then
commit.Should().BeEmpty();
}
[Theory]
[InlineData("ghprbActualCommit", "123")]
[InlineData("GIT_COMMIT", "456")]
public void Commit_Should_Be_Set_When_Environment_Variable_Exists(string key, string pullId)
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable(key)).Returns(pullId);
var jenkins = new Jenkins(ev.Object);
// When
var commit = jenkins.Commit;
// Then
commit.Should().Be(pullId);
}
[Fact]
public void Detecter_Should_Be_False_When_Jenkins_Environment_Variable_Does_Not_Exist()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var jenkins = new Jenkins(ev.Object);
// When
var detecter = jenkins.Detecter;
// Then
detecter.Should().BeFalse();
}
[Fact]
public void Detecter_Should_Be_True_When_Jenkins_Environment_Variable_Exists()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("JENKINS_URL")).Returns("https://jenkins.yourcompany.com");
var jenkins = new Jenkins(ev.Object);
// When
var detecter = jenkins.Detecter;
// Then
detecter.Should().BeTrue();
}
[Fact]
public void Pr_Should_Be_Empty_String_When_Environment_Variable_Does_Not_Exist()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var jenkins = new Jenkins(ev.Object);
// When
var pr = jenkins.Pr;
// Then
pr.Should().BeEmpty();
}
[Theory]
[InlineData("ghprbPullId", "123")]
[InlineData("CHANGE_ID", "456")]
public void Pr_Should_Be_Set_When_Environment_Variable_Exists(string key, string pullId)
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable(key)).Returns(pullId);
var jenkins = new Jenkins(ev.Object);
// When
var pr = jenkins.Pr;
// Then
pr.Should().Be(pullId);
}
[Fact]
public void Service_Name_Should_Be_Set()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var jenkins = new Jenkins(ev.Object);
// When
var service = jenkins.Service;
// Then
service.Should().Be("jenkins");
}
}
}
| |
////////////////////////////////////////////////////////////////////////////
//
// This file is part of RTIMULibCS
//
// Copyright (c) 2015, richards-tech, LLC
//
// 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 Windows.Devices.I2c;
using Windows.Devices.Enumeration;
using System.Diagnostics;
namespace RTIMULibCS
{
public class RTHumidityHTS221
{
public string ErrorMessage = "";
public bool InitComplete { get { return this.mInitComplete; } }
private bool mInitComplete = false; // set true when init has completed
public bool HumidityValid { get { return this.mHumidityValid; } }
private bool mHumidityValid = false;
public bool TemperatureValid { get { return this.mTemperatureValid; } }
private bool mTemperatureValid = false;
private double mHumidity; // the current humidity
private double mTemperature; // the current temperature
private double mTemperature_m; // temperature calibration slope
private double mTemperature_c; // temperature calibration y intercept
private double mHumidity_m; // humidity calibration slope
private double mHumidity_c; // humidity calibration y intercept
// HTS221 I2C Slave Address
public const byte HTS221_ADDRESS = 0x5f;
public const byte HTS221_REG_ID = 0x0f;
public const byte HTS221_ID = 0xbc;
// Register map
public const byte HTS221_WHO_AM_I = 0x0f;
public const byte HTS221_AV_CONF = 0x10;
public const byte HTS221_CTRL1 = 0x20;
public const byte HTS221_CTRL2 = 0x21;
public const byte HTS221_CTRL3 = 0x22;
public const byte HTS221_STATUS = 0x27;
public const byte HTS221_HUMIDITY_OUT_L = 0x28;
public const byte HTS221_HUMIDITY_OUT_H = 0x29;
public const byte HTS221_TEMP_OUT_L = 0x2a;
public const byte HTS221_TEMP_OUT_H = 0x2b;
public const byte HTS221_H0_H_2 = 0x30;
public const byte HTS221_H1_H_2 = 0x31;
public const byte HTS221_T0_C_8 = 0x32;
public const byte HTS221_T1_C_8 = 0x33;
public const byte HTS221_T1_T0 = 0x35;
public const byte HTS221_H0_T0_OUT = 0x36;
public const byte HTS221_H1_T0_OUT = 0x3a;
public const byte HTS221_T0_OUT = 0x3c;
public const byte HTS221_T1_OUT = 0x3e;
private I2cDevice mHum;
public async void HumidityInit()
{
byte[] oneByte = new byte[1];
byte[] twoByte = new byte[2];
byte H0_H_2 = 0;
byte H1_H_2 = 0;
UInt16 T0_C_8 = 0;
UInt16 T1_C_8 = 0;
Int16 H0_T0_OUT = 0;
Int16 H1_T0_OUT = 0;
Int16 T0_OUT = 0;
Int16 T1_OUT = 0;
double H0, H1, T0, T1;
try {
string aqsFilter = I2cDevice.GetDeviceSelector("I2C1");
DeviceInformationCollection collection = await DeviceInformation.FindAllAsync(aqsFilter);
if (collection.Count == 0)
return;
I2cConnectionSettings settings0 = new I2cConnectionSettings(HTS221_ADDRESS);
settings0.BusSpeed = I2cBusSpeed.FastMode;
mHum = await I2cDevice.FromIdAsync(collection[0].Id, settings0);
} catch (Exception) {
ErrorMessage = "Failed to connect to HTS221";
if (Debugger.IsAttached) {
Debugger.Break();
}
return;
}
if (!RTI2C.Write(mHum, HTS221_CTRL1, 0x87)) {
ErrorMessage = "Failed to set HTS221 CTRL_REG_1";
return;
}
if (!RTI2C.Write(mHum, HTS221_AV_CONF, 0x1b)) {
ErrorMessage = "Failed to set HTS221 AV_CONF";
return;
}
// Get calibration data
if (!RTI2C.Read(mHum, HTS221_T1_T0 + 0x80, oneByte)) {
ErrorMessage = "Failed to read HTS221 T1_T0";
return;
}
byte temp0 = oneByte[0];
if (!RTI2C.Read(mHum, HTS221_T0_C_8 + 0x80, oneByte)) {
ErrorMessage = "Failed to read HTS221 T0_C_8";
return;
}
byte temp1 = oneByte[0];
T0_C_8 = (UInt16)((((UInt16)temp1 & 0x3) << 8) | (UInt16)temp0);
T0 = (double)T0_C_8 / 8.0;
if (!RTI2C.Read(mHum, HTS221_T1_C_8 + 0x80, oneByte)) {
ErrorMessage = "Failed to read HTS221 T1_C_8";
return;
}
temp0 = oneByte[0];
T1_C_8 = (UInt16)(((UInt16)(temp1 & 0xC) << 6) | (UInt16)temp0);
T1 = (double)T1_C_8 / 8.0;
if (!RTI2C.Read(mHum, HTS221_T0_OUT + 0x80, twoByte)) {
ErrorMessage = "Failed to read HTS221 T0_OUT";
return;
}
T0_OUT = (Int16)((((UInt16)twoByte[1]) << 8) | (UInt16)twoByte[0]);
if (!RTI2C.Read(mHum, HTS221_T1_OUT + 0x80, twoByte)) {
ErrorMessage = "Failed to read HTS221 T1_OUT";
return;
}
T1_OUT = (Int16)((((UInt16)twoByte[1]) << 8) | (UInt16)twoByte[0]);
if (!RTI2C.Read(mHum, HTS221_H0_H_2 + 0x80, oneByte)) {
ErrorMessage = "Failed to read HTS221 H0_H_2";
return;
}
H0_H_2 = oneByte[0];
H0 = (double)H0_H_2 / 2.0;
if (!RTI2C.Read(mHum, HTS221_H1_H_2 + 0x80, oneByte)) {
ErrorMessage = "Failed to read HTS221 H1_H_2";
return;
}
H1_H_2 = oneByte[0];
H1 = (double)H1_H_2 / 2.0;
if (!RTI2C.Read(mHum, HTS221_H0_T0_OUT + 0x80, twoByte)) {
ErrorMessage = "Failed to read HTS221 H0_T_OUT";
return;
}
H0_T0_OUT = (Int16)((((UInt16)twoByte[1]) << 8) | (UInt16)twoByte[0]);
if (!RTI2C.Read(mHum, HTS221_H1_T0_OUT + 0x80, twoByte)) {
ErrorMessage = "Failed to read HTS221 H1_T_OUT";
return;
}
H1_T0_OUT = (Int16)((((UInt16)twoByte[1]) << 8) | (UInt16)twoByte[0]);
mTemperature_m = (T1 - T0) / (T1_OUT - T0_OUT);
mTemperature_c = T0 - (mTemperature_m * T0_OUT);
mHumidity_m = (H1 - H0) / (H1_T0_OUT - H0_T0_OUT);
mHumidity_c = (H0) - (mHumidity_m * H0_T0_OUT);
mInitComplete = true;
ErrorMessage = "HTS221 init complete";
return;
}
public bool HumidityRead(ref RTIMUData data)
{
byte[] oneByte = new byte[1];
byte[] twoByte = new byte[2];
data.humidityValid = false;
data.temperatureValid = false;
data.temperature = 0;
data.humidity = 0;
if (!RTI2C.Read(mHum, HTS221_STATUS, oneByte)) {
ErrorMessage = "Failed to read HTS221 status";
return false;
}
if ((oneByte[0] & 2) == 2) {
if (!RTI2C.Read(mHum, HTS221_HUMIDITY_OUT_L + 0x80, twoByte)) {
ErrorMessage = "Failed to read HTS221 humidity";
return false;
}
mHumidity = (Int16)((((UInt16)twoByte[1]) << 8) | (UInt16)twoByte[0]);
mHumidity = mHumidity * mHumidity_m + mHumidity_c;
mHumidityValid = true;
}
if ((oneByte[0] & 1) == 1) {
if (!RTI2C.Read(mHum, HTS221_TEMP_OUT_L + 0x80, twoByte)) {
ErrorMessage = "Failed to read HTS221 temperature";
return false;
}
mTemperature = (Int16)((((UInt16)twoByte[1]) << 8) | (UInt16)twoByte[0]);
mTemperature = mTemperature * mTemperature_m + mTemperature_c;
mTemperatureValid = true;
}
data.humidityValid = mHumidityValid;
data.humidity = mHumidity;
data.temperatureValid = mTemperatureValid;
data.temperature = mTemperature;
return true;
}
}
}
| |
using System;
using NUnit.Framework;
using Raksha.Asn1;
using Raksha.Asn1.Pkcs;
using Raksha.Crypto;
using Raksha.Crypto.Digests;
using Raksha.Crypto.Generators;
using Raksha.Crypto.Parameters;
using Raksha.Security;
using Raksha.Utilities.Encoders;
using Raksha.Tests.Utilities;
namespace Raksha.Tests.Misc
{
/**
* test out the various PBE modes, making sure the JCE implementations
* are compatible woth the light weight ones.
*/
[TestFixture]
public class PbeTest
: SimpleTest
{
private class OpenSslTest
: SimpleTest
{
private char[] password;
private string baseAlgorithm;
private string algorithm;
private int keySize;
private int ivSize;
public OpenSslTest(
string baseAlgorithm,
string algorithm,
int keySize,
int ivSize)
{
this.password = algorithm.ToCharArray();
this.baseAlgorithm = baseAlgorithm;
this.algorithm = algorithm;
this.keySize = keySize;
this.ivSize = ivSize;
}
public override string Name
{
get { return "OpenSSLPBE"; }
}
public override void PerformTest()
{
byte[] salt = new byte[16];
int iCount = 100;
for (int i = 0; i != salt.Length; i++)
{
salt[i] = (byte)i;
}
PbeParametersGenerator pGen = new OpenSslPbeParametersGenerator();
pGen.Init(
PbeParametersGenerator.Pkcs5PasswordToBytes(password),
salt,
iCount);
ParametersWithIV parameters = (ParametersWithIV)
pGen.GenerateDerivedParameters(baseAlgorithm, keySize, ivSize);
KeyParameter encKey = (KeyParameter) parameters.Parameters;
IBufferedCipher c;
if (baseAlgorithm.Equals("RC4"))
{
c = CipherUtilities.GetCipher(baseAlgorithm);
c.Init(true, encKey);
}
else
{
c = CipherUtilities.GetCipher(baseAlgorithm + "/CBC/PKCS7Padding");
c.Init(true, parameters);
}
byte[] enc = c.DoFinal(salt);
c = CipherUtilities.GetCipher(algorithm);
// PBEKeySpec keySpec = new PBEKeySpec(password, salt, iCount);
// SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm);
//
// c.Init(false, fact.generateSecret(keySpec));
Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(
algorithm, salt, iCount);
ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(
algorithm, password, algParams);
c.Init(false, cipherParams);
byte[] dec = c.DoFinal(enc);
if (!AreEqual(salt, dec))
{
Fail("" + algorithm + "failed encryption/decryption test");
}
}
}
private class Pkcs12Test
: SimpleTest
{
private char[] password;
private string baseAlgorithm;
private string algorithm;
private IDigest digest;
private int keySize;
private int ivSize;
public Pkcs12Test(
string baseAlgorithm,
string algorithm,
IDigest digest,
int keySize,
int ivSize)
{
this.password = algorithm.ToCharArray();
this.baseAlgorithm = baseAlgorithm;
this.algorithm = algorithm;
this.digest = digest;
this.keySize = keySize;
this.ivSize = ivSize;
}
public override string Name
{
get { return "PKCS12PBE"; }
}
public override void PerformTest()
{
int iCount = 100;
byte[] salt = DigestUtilities.DoFinal(digest);
PbeParametersGenerator pGen = new Pkcs12ParametersGenerator(digest);
pGen.Init(
PbeParametersGenerator.Pkcs12PasswordToBytes(password),
salt,
iCount);
ParametersWithIV parameters = (ParametersWithIV)
pGen.GenerateDerivedParameters(baseAlgorithm, keySize, ivSize);
KeyParameter encKey = (KeyParameter) parameters.Parameters;
IBufferedCipher c;
if (baseAlgorithm.Equals("RC4"))
{
c = CipherUtilities.GetCipher(baseAlgorithm);
c.Init(true, encKey);
}
else
{
c = CipherUtilities.GetCipher(baseAlgorithm + "/CBC/PKCS7Padding");
c.Init(true, parameters);
}
byte[] enc = c.DoFinal(salt);
c = CipherUtilities.GetCipher(algorithm);
// PBEKeySpec keySpec = new PBEKeySpec(password, salt, iCount);
// SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm);
//
// c.Init(false, fact.generateSecret(keySpec));
Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(
algorithm, salt, iCount);
ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(
algorithm, password, algParams);
c.Init(false, cipherParams);
byte[] dec = c.DoFinal(enc);
if (!AreEqual(salt, dec))
{
Fail("" + algorithm + "failed encryption/decryption test");
}
// NB: We don't support retrieving parameters from cipher
// //
// // get the parameters
// //
// AlgorithmParameters param = c.getParameters();
// PBEParameterSpec spec = (PBEParameterSpec)param.getParameterSpec(PBEParameterSpec.class);
//
// if (!AreEqual(salt, spec.getSalt()))
// {
// Fail("" + algorithm + "failed salt test");
// }
//
// if (iCount != spec.getIterationCount())
// {
// Fail("" + algorithm + "failed count test");
// }
// NB: This section just repeats earlier test passing 'param' separately
// //
// // try using parameters
// //
// keySpec = new PBEKeySpec(password);
//
// c.Init(false, fact.generateSecret(keySpec), param);
//
// dec = c.DoFinal(enc);
//
// if (!AreEqual(salt, dec))
// {
// Fail("" + algorithm + "failed encryption/decryption test");
// }
}
}
private Pkcs12Test[] pkcs12Tests = {
new Pkcs12Test("DESede", "PBEWITHSHAAND3-KEYTRIPLEDES-CBC", new Sha1Digest(), 192, 64),
new Pkcs12Test("DESede", "PBEWITHSHAAND2-KEYTRIPLEDES-CBC", new Sha1Digest(), 128, 64),
new Pkcs12Test("RC4", "PBEWITHSHAAND128BITRC4", new Sha1Digest(), 128, 0),
new Pkcs12Test("RC4", "PBEWITHSHAAND40BITRC4", new Sha1Digest(), 40, 0),
new Pkcs12Test("RC2", "PBEWITHSHAAND128BITRC2-CBC", new Sha1Digest(), 128, 64),
new Pkcs12Test("RC2", "PBEWITHSHAAND40BITRC2-CBC", new Sha1Digest(), 40, 64),
new Pkcs12Test("AES", "PBEWithSHA1And128BitAES-CBC-BC", new Sha1Digest(), 128, 128),
new Pkcs12Test("AES", "PBEWithSHA1And192BitAES-CBC-BC", new Sha1Digest(), 192, 128),
new Pkcs12Test("AES", "PBEWithSHA1And256BitAES-CBC-BC", new Sha1Digest(), 256, 128),
new Pkcs12Test("AES", "PBEWithSHA256And128BitAES-CBC-BC", new Sha256Digest(), 128, 128),
new Pkcs12Test("AES", "PBEWithSHA256And192BitAES-CBC-BC", new Sha256Digest(), 192, 128),
new Pkcs12Test("AES", "PBEWithSHA256And256BitAES-CBC-BC", new Sha256Digest(), 256, 128)
};
private OpenSslTest[] openSSLTests = {
new OpenSslTest("AES", "PBEWITHMD5AND128BITAES-CBC-OPENSSL", 128, 128),
new OpenSslTest("AES", "PBEWITHMD5AND192BITAES-CBC-OPENSSL", 192, 128),
new OpenSslTest("AES", "PBEWITHMD5AND256BITAES-CBC-OPENSSL", 256, 128)
};
static byte[] message = Hex.Decode("4869205468657265");
private byte[] hMac1 = Hex.Decode("bcc42174ccb04f425d9a5c8c4a95d6fd7c372911");
private byte[] hMac2 = Hex.Decode("cb1d8bdb6aca9e3fa8980d6eb41ab28a7eb2cfd6");
// NB: These two makePbeCipher... methods are same in .NET
private IBufferedCipher makePbeCipherUsingParam(
string algorithm,
bool forEncryption,
char[] password,
byte[] salt,
int iterationCount)
{
// PBEKeySpec pbeSpec = new PBEKeySpec(password);
// SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm);
// PBEParameterSpec defParams = new PBEParameterSpec(salt, iterationCount);
Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(
algorithm, salt, iterationCount);
ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(
algorithm, password, algParams);
IBufferedCipher cipher = CipherUtilities.GetCipher(algorithm);
// cipher.Init(forEncryption, keyFact.generateSecret(pbeSpec), defParams);
cipher.Init(forEncryption, cipherParams);
return cipher;
}
// NB: These two makePbeCipher... methods are same in .NET
private IBufferedCipher makePbeCipherWithoutParam(
string algorithm,
bool forEncryption,
char[] password,
byte[] salt,
int iterationCount)
{
// PBEKeySpec pbeSpec = new PBEKeySpec(password, salt, iterationCount);
// SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm);
Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(
algorithm, salt, iterationCount);
ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(
algorithm, password, algParams);
IBufferedCipher cipher = CipherUtilities.GetCipher(algorithm);
// cipher.Init(forEncryption, keyFact.generateSecret(pbeSpec));
cipher.Init(forEncryption, cipherParams);
return cipher;
}
private void doTestPbeHMac(
string hmacName,
byte[] output)
{
ICipherParameters key = null;
byte[] outBytes;
IMac mac = null;
try
{
// SecretKeyFactory fact = SecretKeyFactory.getInstance(hmacName);
//
// key = fact.generateSecret(new PBEKeySpec("hello".ToCharArray()));
Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(
hmacName, new byte[20], 100);
key = PbeUtilities.GenerateCipherParameters(
hmacName, "hello".ToCharArray(), algParams);
mac = MacUtilities.GetMac(hmacName);
}
catch (Exception e)
{
Fail("Failed - exception " + e.ToString(), e);
}
try
{
// mac.Init(key, new PBEParameterSpec(new byte[20], 100));
mac.Init(key);
}
catch (Exception e)
{
Fail("Failed - exception " + e.ToString(), e);
}
mac.Reset();
mac.BlockUpdate(message, 0, message.Length);
// outBytes = mac.DoFinal();
outBytes = new byte[mac.GetMacSize()];
mac.DoFinal(outBytes, 0);
if (!AreEqual(outBytes, output))
{
Fail("Failed - expected "
+ Hex.ToHexString(output) + " got "
+ Hex.ToHexString(outBytes));
}
}
public override void PerformTest()
{
byte[] input = Hex.Decode("1234567890abcdefabcdef1234567890fedbca098765");
//
// DES
//
IBufferedCipher cEnc = CipherUtilities.GetCipher("DES/CBC/PKCS7Padding");
cEnc.Init(
true,
new ParametersWithIV(
new DesParameters(Hex.Decode("30e69252758e5346")),
Hex.Decode("7c1c1ab9c454a688")));
byte[] outBytes = cEnc.DoFinal(input);
char[] password = "password".ToCharArray();
IBufferedCipher cDec = makePbeCipherUsingParam(
"PBEWithSHA1AndDES",
false,
password,
Hex.Decode("7d60435f02e9e0ae"),
2048);
byte[] inBytes = cDec.DoFinal(outBytes);
if (!AreEqual(input, inBytes))
{
Fail("DES failed");
}
cDec = makePbeCipherWithoutParam(
"PBEWithSHA1AndDES",
false,
password,
Hex.Decode("7d60435f02e9e0ae"),
2048);
inBytes = cDec.DoFinal(outBytes);
if (!AreEqual(input, inBytes))
{
Fail("DES failed without param");
}
//
// DESede
//
cEnc = CipherUtilities.GetCipher("DESede/CBC/PKCS7Padding");
cEnc.Init(
true,
new ParametersWithIV(
new DesParameters(Hex.Decode("732f2d33c801732b7206756cbd44f9c1c103ddd97c7cbe8e")),
Hex.Decode("b07bf522c8d608b8")));
outBytes = cEnc.DoFinal(input);
cDec = makePbeCipherUsingParam(
"PBEWithSHAAnd3-KeyTripleDES-CBC",
false,
password,
Hex.Decode("7d60435f02e9e0ae"),
2048);
inBytes = cDec.DoFinal(outBytes);
if (!AreEqual(input, inBytes))
{
Fail("DESede failed");
}
//
// 40Bit RC2
//
cEnc = CipherUtilities.GetCipher("RC2/CBC/PKCS7Padding");
cEnc.Init(
true,
new ParametersWithIV(
new RC2Parameters(Hex.Decode("732f2d33c8")),
Hex.Decode("b07bf522c8d608b8")));
outBytes = cEnc.DoFinal(input);
cDec = makePbeCipherUsingParam(
"PBEWithSHAAnd40BitRC2-CBC",
false,
password,
Hex.Decode("7d60435f02e9e0ae"),
2048);
inBytes = cDec.DoFinal(outBytes);
if (!AreEqual(input, inBytes))
{
Fail("RC2 failed");
}
//
// 128bit RC4
//
cEnc = CipherUtilities.GetCipher("RC4");
cEnc.Init(
true,
ParameterUtilities.CreateKeyParameter("RC4", Hex.Decode("732f2d33c801732b7206756cbd44f9c1")));
outBytes = cEnc.DoFinal(input);
cDec = makePbeCipherUsingParam(
"PBEWithSHAAnd128BitRC4",
false,
password,
Hex.Decode("7d60435f02e9e0ae"),
2048);
inBytes = cDec.DoFinal(outBytes);
if (!AreEqual(input, inBytes))
{
Fail("RC4 failed");
}
cDec = makePbeCipherWithoutParam(
"PBEWithSHAAnd128BitRC4",
false,
password,
Hex.Decode("7d60435f02e9e0ae"),
2048);
inBytes = cDec.DoFinal(outBytes);
if (!AreEqual(input, inBytes))
{
Fail("RC4 failed without param");
}
for (int i = 0; i != pkcs12Tests.Length; i++)
{
pkcs12Tests[i].PerformTest();
}
for (int i = 0; i != openSSLTests.Length; i++)
{
openSSLTests[i].PerformTest();
}
doTestPbeHMac("PBEWithHMacSHA1", hMac1);
doTestPbeHMac("PBEWithHMacRIPEMD160", hMac2);
}
public override string Name
{
get { return "PbeTest"; }
}
public static void Main(
string[] args)
{
RunTest(new PbeTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Models.Editors;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Cms.Core.PublishedCache;
using Umbraco.Cms.Core.Routing;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.PropertyEditors
{
public class MultiUrlPickerValueEditor : DataValueEditor, IDataValueReference
{
private readonly IEntityService _entityService;
private readonly ILogger<MultiUrlPickerValueEditor> _logger;
private readonly IPublishedUrlProvider _publishedUrlProvider;
private readonly IPublishedSnapshotAccessor _publishedSnapshotAccessor;
public MultiUrlPickerValueEditor(
IEntityService entityService,
IPublishedSnapshotAccessor publishedSnapshotAccessor,
ILogger<MultiUrlPickerValueEditor> logger,
ILocalizedTextService localizedTextService,
IShortStringHelper shortStringHelper,
DataEditorAttribute attribute,
IPublishedUrlProvider publishedUrlProvider,
IJsonSerializer jsonSerializer,
IIOHelper ioHelper)
: base(localizedTextService, shortStringHelper, jsonSerializer, ioHelper, attribute)
{
_entityService = entityService ?? throw new ArgumentNullException(nameof(entityService));
_publishedSnapshotAccessor = publishedSnapshotAccessor ?? throw new ArgumentNullException(nameof(publishedSnapshotAccessor));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_publishedUrlProvider = publishedUrlProvider;
}
public override object ToEditor(IProperty property, string culture = null, string segment = null)
{
var value = property.GetValue(culture, segment)?.ToString();
if (string.IsNullOrEmpty(value))
{
return Enumerable.Empty<object>();
}
try
{
var links = JsonConvert.DeserializeObject<List<MultiUrlPickerValueEditor.LinkDto>>(value);
var documentLinks = links.FindAll(link => link.Udi != null && link.Udi.EntityType == Constants.UdiEntityType.Document);
var mediaLinks = links.FindAll(link => link.Udi != null && link.Udi.EntityType == Constants.UdiEntityType.Media);
var entities = new List<IEntitySlim>();
if (documentLinks.Count > 0)
{
entities.AddRange(
_entityService.GetAll(UmbracoObjectTypes.Document, documentLinks.Select(link => link.Udi.Guid).ToArray())
);
}
if (mediaLinks.Count > 0)
{
entities.AddRange(
_entityService.GetAll(UmbracoObjectTypes.Media, mediaLinks.Select(link => link.Udi.Guid).ToArray())
);
}
var result = new List<LinkDisplay>();
foreach (var dto in links)
{
GuidUdi udi = null;
var icon = "icon-link";
var published = true;
var trashed = false;
var url = dto.Url;
if (dto.Udi != null)
{
IUmbracoEntity entity = entities.Find(e => e.Key == dto.Udi.Guid);
if (entity == null)
{
continue;
}
var publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();
if (entity is IDocumentEntitySlim documentEntity)
{
icon = documentEntity.ContentTypeIcon;
published = culture == null ? documentEntity.Published : documentEntity.PublishedCultures.Contains(culture);
udi = new GuidUdi(Constants.UdiEntityType.Document, documentEntity.Key);
url = publishedSnapshot.Content.GetById(entity.Key)?.Url(_publishedUrlProvider) ?? "#";
trashed = documentEntity.Trashed;
}
else if(entity is IContentEntitySlim contentEntity)
{
icon = contentEntity.ContentTypeIcon;
published = !contentEntity.Trashed;
udi = new GuidUdi(Constants.UdiEntityType.Media, contentEntity.Key);
url = publishedSnapshot.Media.GetById(entity.Key)?.Url(_publishedUrlProvider) ?? "#";
trashed = contentEntity.Trashed;
}
else
{
// Not supported
continue;
}
}
result.Add(new LinkDisplay
{
Icon = icon,
Name = dto.Name,
Target = dto.Target,
Trashed = trashed,
Published = published,
QueryString = dto.QueryString,
Udi = udi,
Url = url ?? ""
});
}
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting links");
}
return base.ToEditor(property, culture, segment);
}
private static readonly JsonSerializerSettings LinkDisplayJsonSerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
public override object FromEditor(ContentPropertyData editorValue, object currentValue)
{
var value = editorValue.Value?.ToString();
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
try
{
return JsonConvert.SerializeObject(
from link in JsonConvert.DeserializeObject<List<LinkDisplay>>(value)
select new MultiUrlPickerValueEditor.LinkDto
{
Name = link.Name,
QueryString = link.QueryString,
Target = link.Target,
Udi = link.Udi,
Url = link.Udi == null ? link.Url : null, // only save the URL for external links
}, LinkDisplayJsonSerializerSettings
);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error saving links");
}
return base.FromEditor(editorValue, currentValue);
}
[DataContract]
public class LinkDto
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "target")]
public string Target { get; set; }
[DataMember(Name = "udi")]
public GuidUdi Udi { get; set; }
[DataMember(Name = "url")]
public string Url { get; set; }
[DataMember(Name = "queryString")]
public string QueryString { get; set; }
}
public IEnumerable<UmbracoEntityReference> GetReferences(object value)
{
var asString = value == null ? string.Empty : value is string str ? str : value.ToString();
if (string.IsNullOrEmpty(asString)) yield break;
var links = JsonConvert.DeserializeObject<List<LinkDto>>(asString);
foreach (var link in links)
{
if (link.Udi != null) // Links can be absolute links without a Udi
{
yield return new UmbracoEntityReference(link.Udi);
}
}
}
}
}
| |
using Avalonia.Threading;
using NBitcoin;
using ReactiveUI;
using Splat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading.Tasks;
using WalletWasabi.Crypto;
using WalletWasabi.Gui.Helpers;
using WalletWasabi.Gui.Models;
using WalletWasabi.Gui.Validation;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Models;
using WalletWasabi.Userfacing;
namespace WalletWasabi.Gui.Tabs
{
internal class SettingsViewModel : WasabiDocumentTabViewModel
{
private Network _network;
private string _torSocks5EndPoint;
private string _bitcoinP2pEndPoint;
private string _localBitcoinCoreDataDir;
private bool _autocopy;
private bool _customFee;
private bool _customChangeAddress;
private bool _useTor;
private bool _startLocalBitcoinCoreOnStartup;
private bool _stopLocalBitcoinCoreOnShutdown;
private bool _isModified;
private bool _terminateTorOnExit;
private string _somePrivacyLevel;
private string _finePrivacyLevel;
private string _strongPrivacyLevel;
private string _dustThreshold;
private string _pinBoxText;
private ObservableAsPropertyHelper<bool> _isPinSet;
private FeeDisplayFormat _selectedFeeDisplayFormat;
public SettingsViewModel() : base("Settings")
{
Global = Locator.Current.GetService<Global>();
this.ValidateProperty(x => x.SomePrivacyLevel, ValidateSomePrivacyLevel);
this.ValidateProperty(x => x.FinePrivacyLevel, ValidateFinePrivacyLevel);
this.ValidateProperty(x => x.StrongPrivacyLevel, ValidateStrongPrivacyLevel);
this.ValidateProperty(x => x.DustThreshold, ValidateDustThreshold);
this.ValidateProperty(x => x.TorSocks5EndPoint, ValidateTorSocks5EndPoint);
this.ValidateProperty(x => x.BitcoinP2pEndPoint, ValidateBitcoinP2pEndPoint);
Autocopy = Global.UiConfig.Autocopy;
CustomFee = Global.UiConfig.IsCustomFee;
CustomChangeAddress = Global.UiConfig.IsCustomChangeAddress;
var config = new Config(Global.Config.FilePath);
config.LoadOrCreateDefaultFile();
_network = config.Network;
_torSocks5EndPoint = config.TorSocks5EndPoint.ToString(-1);
UseTor = config.UseTor;
TerminateTorOnExit = config.TerminateTorOnExit;
StartLocalBitcoinCoreOnStartup = config.StartLocalBitcoinCoreOnStartup;
StopLocalBitcoinCoreOnShutdown = config.StopLocalBitcoinCoreOnShutdown;
_somePrivacyLevel = config.PrivacyLevelSome.ToString();
_finePrivacyLevel = config.PrivacyLevelFine.ToString();
_strongPrivacyLevel = config.PrivacyLevelStrong.ToString();
_dustThreshold = config.DustThreshold.ToString();
_bitcoinP2pEndPoint = config.GetP2PEndpoint().ToString(defaultPort: -1);
_localBitcoinCoreDataDir = config.LocalBitcoinCoreDataDir;
IsModified = !Global.Config.AreDeepEqual(config);
this.WhenAnyValue(
x => x.Network,
x => x.UseTor,
x => x.TerminateTorOnExit,
x => x.StartLocalBitcoinCoreOnStartup,
x => x.StopLocalBitcoinCoreOnShutdown)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(_ => Save());
this.WhenAnyValue(x => x.Autocopy)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(x => Global.UiConfig.Autocopy = x);
this.WhenAnyValue(x => x.CustomFee)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(x => Global.UiConfig.IsCustomFee = x);
this.WhenAnyValue(x => x.CustomChangeAddress)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(x => Global.UiConfig.IsCustomChangeAddress = x);
OpenConfigFileCommand = ReactiveCommand.CreateFromTask(OpenConfigFileAsync);
SetClearPinCommand = ReactiveCommand.Create(() =>
{
var pinBoxText = PinBoxText;
if (string.IsNullOrEmpty(pinBoxText))
{
NotificationHelpers.Error("Please provide a PIN.");
return;
}
var trimmedPinBoxText = pinBoxText?.Trim();
if (string.IsNullOrEmpty(trimmedPinBoxText)
|| trimmedPinBoxText.Any(x => !char.IsDigit(x)))
{
NotificationHelpers.Error("Invalid PIN.");
return;
}
if (trimmedPinBoxText.Length > 10)
{
NotificationHelpers.Error("PIN is too long.");
return;
}
var uiConfigPinHash = Global.UiConfig.LockScreenPinHash;
var enteredPinHash = HashHelpers.GenerateSha256Hash(trimmedPinBoxText);
if (IsPinSet)
{
if (uiConfigPinHash != enteredPinHash)
{
NotificationHelpers.Error("PIN is incorrect.");
PinBoxText = "";
return;
}
Global.UiConfig.LockScreenPinHash = "";
NotificationHelpers.Success("PIN was cleared.");
}
else
{
Global.UiConfig.LockScreenPinHash = enteredPinHash;
NotificationHelpers.Success("PIN was changed.");
}
PinBoxText = "";
});
TextBoxLostFocusCommand = ReactiveCommand.Create(Save);
Observable
.Merge(OpenConfigFileCommand.ThrownExceptions)
.Merge(SetClearPinCommand.ThrownExceptions)
.Merge(TextBoxLostFocusCommand.ThrownExceptions)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(ex => Logger.LogError(ex));
SelectedFeeDisplayFormat = Enum.IsDefined(typeof(FeeDisplayFormat), Global.UiConfig.FeeDisplayFormat)
? (FeeDisplayFormat)Global.UiConfig.FeeDisplayFormat
: FeeDisplayFormat.SatoshiPerByte;
this.WhenAnyValue(x => x.SelectedFeeDisplayFormat)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(x => Global.UiConfig.FeeDisplayFormat = (int)x);
}
private bool TabOpened { get; set; }
public bool IsPinSet => _isPinSet?.Value ?? false;
private Global Global { get; }
private object ConfigLock { get; } = new object();
public ReactiveCommand<Unit, Unit> OpenConfigFileCommand { get; }
public ReactiveCommand<Unit, Unit> SetClearPinCommand { get; }
public ReactiveCommand<Unit, Unit> TextBoxLostFocusCommand { get; }
public Version BitcoinCoreVersion => Constants.BitcoinCoreVersion;
public IEnumerable<Network> Networks => new[]
{
Network.Main,
Network.TestNet,
Network.RegTest
};
public Network Network
{
get => _network;
set => this.RaiseAndSetIfChanged(ref _network, value);
}
public string TorSocks5EndPoint
{
get => _torSocks5EndPoint;
set => this.RaiseAndSetIfChanged(ref _torSocks5EndPoint, value);
}
public string BitcoinP2pEndPoint
{
get => _bitcoinP2pEndPoint;
set => this.RaiseAndSetIfChanged(ref _bitcoinP2pEndPoint, value);
}
public string LocalBitcoinCoreDataDir
{
get => _localBitcoinCoreDataDir;
set => this.RaiseAndSetIfChanged(ref _localBitcoinCoreDataDir, value);
}
public bool IsModified
{
get => _isModified;
set => this.RaiseAndSetIfChanged(ref _isModified, value);
}
public bool Autocopy
{
get => _autocopy;
set => this.RaiseAndSetIfChanged(ref _autocopy, value);
}
public bool CustomFee
{
get => _customFee;
set => this.RaiseAndSetIfChanged(ref _customFee, value);
}
public bool CustomChangeAddress
{
get => _customChangeAddress;
set => this.RaiseAndSetIfChanged(ref _customChangeAddress, value);
}
public bool StartLocalBitcoinCoreOnStartup
{
get => _startLocalBitcoinCoreOnStartup;
set => this.RaiseAndSetIfChanged(ref _startLocalBitcoinCoreOnStartup, value);
}
public bool StopLocalBitcoinCoreOnShutdown
{
get => _stopLocalBitcoinCoreOnShutdown;
set => this.RaiseAndSetIfChanged(ref _stopLocalBitcoinCoreOnShutdown, value);
}
public bool UseTor
{
get => _useTor;
set => this.RaiseAndSetIfChanged(ref _useTor, value);
}
public bool TerminateTorOnExit
{
get => _terminateTorOnExit;
set => this.RaiseAndSetIfChanged(ref _terminateTorOnExit, value);
}
public string SomePrivacyLevel
{
get => _somePrivacyLevel;
set => this.RaiseAndSetIfChanged(ref _somePrivacyLevel, value);
}
public string FinePrivacyLevel
{
get => _finePrivacyLevel;
set => this.RaiseAndSetIfChanged(ref _finePrivacyLevel, value);
}
public string StrongPrivacyLevel
{
get => _strongPrivacyLevel;
set => this.RaiseAndSetIfChanged(ref _strongPrivacyLevel, value);
}
public string DustThreshold
{
get => _dustThreshold;
set => this.RaiseAndSetIfChanged(ref _dustThreshold, value);
}
public string PinBoxText
{
get => _pinBoxText;
set => this.RaiseAndSetIfChanged(ref _pinBoxText, value);
}
public IEnumerable<FeeDisplayFormat> FeeDisplayFormats => Enum.GetValues(typeof(FeeDisplayFormat)).Cast<FeeDisplayFormat>();
public FeeDisplayFormat SelectedFeeDisplayFormat
{
get => _selectedFeeDisplayFormat;
set => this.RaiseAndSetIfChanged(ref _selectedFeeDisplayFormat, value);
}
public override void OnOpen(CompositeDisposable disposables)
{
try
{
_isPinSet = Global.UiConfig
.WhenAnyValue(x => x.LockScreenPinHash, x => !string.IsNullOrWhiteSpace(x))
.ToProperty(this, x => x.IsPinSet, scheduler: RxApp.MainThreadScheduler)
.DisposeWith(disposables);
this.RaisePropertyChanged(nameof(IsPinSet)); // Fire now otherwise the button won't update for restart.
Global.UiConfig.WhenAnyValue(x => x.FeeDisplayFormat)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(x => SelectedFeeDisplayFormat = (FeeDisplayFormat)x)
.DisposeWith(disposables);
base.OnOpen(disposables);
}
finally
{
TabOpened = true;
}
}
public override bool OnClose()
{
TabOpened = false;
return base.OnClose();
}
private void Save()
{
// While the Tab is opening we are setting properties with loading and also LostFocus command called by Avalonia
// Those would trigger the Save function before we load the config.
if (!TabOpened)
{
return;
}
var network = Network;
if (network is null)
{
return;
}
if (Validations.Any)
{
return;
}
var config = new Config(Global.Config.FilePath);
Dispatcher.UIThread.PostLogException(() =>
{
lock (ConfigLock)
{
config.LoadFile();
if (Network == config.Network)
{
if (EndPointParser.TryParse(TorSocks5EndPoint, Constants.DefaultTorSocksPort, out EndPoint? torEp))
{
config.TorSocks5EndPoint = torEp;
}
if (EndPointParser.TryParse(BitcoinP2pEndPoint, network.DefaultPort, out EndPoint? p2pEp))
{
config.SetP2PEndpoint(p2pEp);
}
config.UseTor = UseTor;
config.TerminateTorOnExit = TerminateTorOnExit;
config.StartLocalBitcoinCoreOnStartup = StartLocalBitcoinCoreOnStartup;
config.StopLocalBitcoinCoreOnShutdown = StopLocalBitcoinCoreOnShutdown;
config.LocalBitcoinCoreDataDir = Guard.Correct(LocalBitcoinCoreDataDir);
config.DustThreshold = decimal.TryParse(DustThreshold, out var threshold) ? Money.Coins(threshold) : Config.DefaultDustThreshold;
config.PrivacyLevelSome = int.TryParse(SomePrivacyLevel, out int level) ? level : Config.DefaultPrivacyLevelSome;
config.PrivacyLevelStrong = int.TryParse(StrongPrivacyLevel, out level) ? level : Config.DefaultPrivacyLevelStrong;
config.PrivacyLevelFine = int.TryParse(FinePrivacyLevel, out level) ? level : Config.DefaultPrivacyLevelFine;
}
else
{
config.Network = Network;
BitcoinP2pEndPoint = config.GetP2PEndpoint().ToString(defaultPort: -1);
}
config.ToFile();
IsModified = !Global.Config.AreDeepEqual(config);
}
});
}
private async Task OpenConfigFileAsync()
{
await FileHelpers.OpenFileInTextEditorAsync(Global.Config.FilePath);
}
#region Validation
private void ValidateSomePrivacyLevel(IValidationErrors errors)
=> ValidatePrivacyLevel(errors, SomePrivacyLevel, whiteSpaceOk: true);
private void ValidateFinePrivacyLevel(IValidationErrors errors)
=> ValidatePrivacyLevel(errors, FinePrivacyLevel, whiteSpaceOk: true);
private void ValidateStrongPrivacyLevel(IValidationErrors errors)
=> ValidatePrivacyLevel(errors, StrongPrivacyLevel, whiteSpaceOk: true);
private void ValidateDustThreshold(IValidationErrors errors)
=> ValidateDustThreshold(errors, DustThreshold, whiteSpaceOk: true);
private void ValidateTorSocks5EndPoint(IValidationErrors errors)
=> ValidateEndPoint(errors, TorSocks5EndPoint, Constants.DefaultTorSocksPort, whiteSpaceOk: true);
private void ValidateBitcoinP2pEndPoint(IValidationErrors errors)
=> ValidateEndPoint(errors, BitcoinP2pEndPoint, Network.DefaultPort, whiteSpaceOk: true);
private void ValidatePrivacyLevel(IValidationErrors errors, string value, bool whiteSpaceOk)
{
if (!whiteSpaceOk || !string.IsNullOrWhiteSpace(value))
{
if (!uint.TryParse(value, out _))
{
errors.Add(ErrorSeverity.Error, "Invalid privacy level.");
}
}
}
private void ValidateDustThreshold(IValidationErrors errors, string dustThreshold, bool whiteSpaceOk)
{
if (!whiteSpaceOk || !string.IsNullOrWhiteSpace(dustThreshold))
{
if (!string.IsNullOrEmpty(dustThreshold) && dustThreshold.Contains(',', StringComparison.InvariantCultureIgnoreCase))
{
errors.Add(ErrorSeverity.Error, "Use decimal point instead of comma.");
}
if (!decimal.TryParse(dustThreshold, out var dust) || dust < 0)
{
errors.Add(ErrorSeverity.Error, "Invalid dust threshold.");
}
}
}
private void ValidateEndPoint(IValidationErrors errors, string endPoint, int defaultPort, bool whiteSpaceOk)
{
if (!whiteSpaceOk || !string.IsNullOrWhiteSpace(endPoint))
{
if (!EndPointParser.TryParse(endPoint, defaultPort, out _))
{
errors.Add(ErrorSeverity.Error, "Invalid endpoint.");
}
}
}
#endregion Validation
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Xml;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Individual node-specific silo configuration parameters.
/// </summary>
[Serializable]
public class NodeConfiguration : ITraceConfiguration, IStatisticsConfiguration
{
private readonly DateTime creationTimestamp;
private string siloName;
/// <summary>
/// The name of this silo.
/// </summary>
public string SiloName
{
get { return siloName; }
set
{
siloName = value;
ConfigUtilities.SetTraceFileName(this, siloName, creationTimestamp);
}
}
/// <summary>
/// The DNS host name of this silo.
/// This is a true host name, no IP address. It is NOT settable, equals Dns.GetHostName().
/// </summary>
public string DNSHostName { get; private set; }
/// <summary>
/// The host name or IP address of this silo.
/// This is a configurable IP address or Hostname.
/// </summary>
public string HostNameOrIPAddress { get; set; }
private IPAddress Address { get { return ClusterConfiguration.ResolveIPAddress(HostNameOrIPAddress, Subnet, AddressType); } }
/// <summary>
/// The port this silo uses for silo-to-silo communication.
/// </summary>
public int Port { get; set; }
/// <summary>
/// The epoch generation number for this silo.
/// </summary>
public int Generation { get; set; }
/// <summary>
/// The IPEndPoint this silo uses for silo-to-silo communication.
/// </summary>
public IPEndPoint Endpoint
{
get { return new IPEndPoint(Address, Port); }
}
/// <summary>
/// The AddressFamilyof the IP address of this silo.
/// </summary>
public AddressFamily AddressType { get; set; }
/// <summary>
/// The IPEndPoint this silo uses for (gateway) silo-to-client communication.
/// </summary>
public IPEndPoint ProxyGatewayEndpoint { get; set; }
internal byte[] Subnet { get; set; } // from global
/// <summary>
/// Whether this is a primary silo (applies for dev settings only).
/// </summary>
public bool IsPrimaryNode { get; internal set; }
/// <summary>
/// Whether this is one of the seed silos (applies for dev settings only).
/// </summary>
public bool IsSeedNode { get; internal set; }
/// <summary>
/// Whether this is silo is a proxying gateway silo.
/// </summary>
public bool IsGatewayNode { get { return ProxyGatewayEndpoint != null; } }
/// <summary>
/// The MaxActiveThreads attribute specifies the maximum number of simultaneous active threads the scheduler will allow.
/// Generally this number should be roughly equal to the number of cores on the node.
/// Using a value of 0 will look at System.Environment.ProcessorCount to decide the number instead.
/// </summary>
public int MaxActiveThreads { get; set; }
/// <summary>
/// The DelayWarningThreshold attribute specifies the work item queuing delay threshold, at which a warning log message is written.
/// That is, if the delay between enqueuing the work item and executing the work item is greater than DelayWarningThreshold, a warning log is written.
/// The default value is 10 seconds.
/// </summary>
public TimeSpan DelayWarningThreshold { get; set; }
/// <summary>
/// ActivationSchedulingQuantum is a soft time limit on the duration of activation macro-turn (a number of micro-turns).
/// If a activation was running its micro-turns longer than this, we will give up the thread.
/// If this is set to zero or a negative number, then the full work queue is drained (MaxWorkItemsPerTurn allowing).
/// </summary>
public TimeSpan ActivationSchedulingQuantum { get; set; }
/// <summary>
/// TurnWarningLengthThreshold is a soft time limit to generate trace warning when the micro-turn executes longer then this period in CPU.
/// </summary>
public TimeSpan TurnWarningLengthThreshold { get; set; }
internal bool InjectMoreWorkerThreads { get; set; }
/// <summary>
/// The LoadShedding element specifies the gateway load shedding configuration for the node.
/// If it does not appear, gateway load shedding is disabled.
/// </summary>
public bool LoadSheddingEnabled { get; set; }
/// <summary>
/// The LoadLimit attribute specifies the system load, in CPU%, at which load begins to be shed.
/// Note that this value is in %, so valid values range from 1 to 100, and a reasonable value is
/// typically between 80 and 95.
/// This value is ignored if load shedding is disabled, which is the default.
/// If load shedding is enabled and this attribute does not appear, then the default limit is 95%.
/// </summary>
public int LoadSheddingLimit { get; set; }
/// <summary>
/// The values for various silo limits.
/// </summary>
public LimitManager LimitManager { get; private set; }
private string traceFilePattern;
/// <summary>
/// </summary>
public Logger.Severity DefaultTraceLevel { get; set; }
/// <summary>
/// </summary>
public IList<Tuple<string, Logger.Severity>> TraceLevelOverrides { get; private set; }
/// <summary>
/// </summary>
public bool WriteMessagingTraces { get; set; }
/// <summary>
/// </summary>
public bool TraceToConsole { get; set; }
/// <summary>
/// </summary>
public string TraceFilePattern
{
get { return traceFilePattern; }
set
{
traceFilePattern = value;
ConfigUtilities.SetTraceFileName(this, siloName, creationTimestamp);
}
}
/// <summary>
/// </summary>
public string TraceFileName { get; set; }
/// <summary>
/// </summary>
public int LargeMessageWarningThreshold { get; set; }
/// <summary>
/// </summary>
public bool PropagateActivityId { get; set; }
/// <summary>
/// </summary>
public int BulkMessageLimit { get; set; }
public string StatisticsProviderName { get; set; }
/// <summary>
/// The MetricsTableWriteInterval attribute specifies the frequency of updating the metrics in Azure table.
/// The default is 30 seconds.
/// </summary>
public TimeSpan StatisticsMetricsTableWriteInterval { get; set; }
/// <summary>
/// The PerfCounterWriteInterval attribute specifies the frequency of updating the windows performance counters.
/// The default is 30 seconds.
/// </summary>
public TimeSpan StatisticsPerfCountersWriteInterval { get; set; }
/// <summary>
/// The LogWriteInterval attribute specifies the frequency of updating the statistics in the log file.
/// The default is 5 minutes.
/// </summary>
public TimeSpan StatisticsLogWriteInterval { get; set; }
/// <summary>
/// The WriteLogStatisticsToTable attribute specifies whether log statistics should also be written into a separate, special Azure table.
/// The default is yes.
/// </summary>
public bool StatisticsWriteLogStatisticsToTable { get; set; }
/// <summary>
/// </summary>
public StatisticsLevel StatisticsCollectionLevel { get; set; }
private string workingStoreDir;
/// <summary>
/// </summary>
internal string WorkingStorageDirectory
{
get { return workingStoreDir ?? (workingStoreDir = GetDefaultWorkingStoreDirectory()); }
set { workingStoreDir = value; }
}
/// <summary>
/// </summary>
public int MinDotNetThreadPoolSize { get; set; }
/// <summary>
/// </summary>
public bool Expect100Continue { get; set; }
/// <summary>
/// </summary>
public int DefaultConnectionLimit { get; set; }
/// <summary>
/// </summary>
public bool UseNagleAlgorithm { get; set; }
internal const string DEFAULT_NODE_NAME = "default";
private static readonly TimeSpan DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD = TimeSpan.FromSeconds(30);
private static readonly TimeSpan DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD = TimeSpan.FromSeconds(30);
private static readonly TimeSpan DEFAULT_STATS_LOG_WRITE_PERIOD = TimeSpan.FromMinutes(5);
internal static readonly StatisticsLevel DEFAULT_STATS_COLLECTION_LEVEL = StatisticsLevel.Info;
private static readonly int DEFAULT_MAX_ACTIVE_THREADS = Math.Max(4, System.Environment.ProcessorCount);
internal static readonly int DEFAULT_MAX_LOCAL_ACTIVATIONS = System.Environment.ProcessorCount;
private const int DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE = 200;
private static readonly int DEFAULT_MIN_DOT_NET_CONNECTION_LIMIT = DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE;
private static readonly TimeSpan DEFAULT_ACTIVATION_SCHEDULING_QUANTUM = TimeSpan.FromMilliseconds(100);
internal const bool INJECT_MORE_WORKER_THREADS = false;
public NodeConfiguration()
{
creationTimestamp = DateTime.UtcNow;
SiloName = "";
HostNameOrIPAddress = "";
DNSHostName = Dns.GetHostName();
Port = 0;
Generation = 0;
AddressType = AddressFamily.InterNetwork;
ProxyGatewayEndpoint = null;
MaxActiveThreads = DEFAULT_MAX_ACTIVE_THREADS;
DelayWarningThreshold = TimeSpan.FromMilliseconds(10000); // 10,000 milliseconds
ActivationSchedulingQuantum = DEFAULT_ACTIVATION_SCHEDULING_QUANTUM;
TurnWarningLengthThreshold = TimeSpan.FromMilliseconds(200);
InjectMoreWorkerThreads = INJECT_MORE_WORKER_THREADS;
LoadSheddingEnabled = false;
LoadSheddingLimit = 95;
DefaultTraceLevel = Logger.Severity.Info;
TraceLevelOverrides = new List<Tuple<string, Logger.Severity>>();
TraceToConsole = true;
TraceFilePattern = "{0}-{1}.log";
WriteMessagingTraces = false;
LargeMessageWarningThreshold = Constants.LARGE_OBJECT_HEAP_THRESHOLD;
PropagateActivityId = Constants.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID;
BulkMessageLimit = Constants.DEFAULT_LOGGER_BULK_MESSAGE_LIMIT;
StatisticsMetricsTableWriteInterval = DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD;
StatisticsPerfCountersWriteInterval = DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD;
StatisticsLogWriteInterval = DEFAULT_STATS_LOG_WRITE_PERIOD;
StatisticsWriteLogStatisticsToTable = true;
StatisticsCollectionLevel = DEFAULT_STATS_COLLECTION_LEVEL;
LimitManager = new LimitManager();
MinDotNetThreadPoolSize = DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE;
// .NET ServicePointManager settings / optimizations
Expect100Continue = false;
DefaultConnectionLimit = DEFAULT_MIN_DOT_NET_CONNECTION_LIMIT;
UseNagleAlgorithm = false;
}
public NodeConfiguration(NodeConfiguration other)
{
creationTimestamp = other.creationTimestamp;
SiloName = other.SiloName;
HostNameOrIPAddress = other.HostNameOrIPAddress;
DNSHostName = other.DNSHostName;
Port = other.Port;
Generation = other.Generation;
AddressType = other.AddressType;
ProxyGatewayEndpoint = other.ProxyGatewayEndpoint;
MaxActiveThreads = other.MaxActiveThreads;
DelayWarningThreshold = other.DelayWarningThreshold;
ActivationSchedulingQuantum = other.ActivationSchedulingQuantum;
TurnWarningLengthThreshold = other.TurnWarningLengthThreshold;
InjectMoreWorkerThreads = other.InjectMoreWorkerThreads;
LoadSheddingEnabled = other.LoadSheddingEnabled;
LoadSheddingLimit = other.LoadSheddingLimit;
DefaultTraceLevel = other.DefaultTraceLevel;
TraceLevelOverrides = new List<Tuple<string, Logger.Severity>>(other.TraceLevelOverrides);
TraceToConsole = other.TraceToConsole;
TraceFilePattern = other.TraceFilePattern;
TraceFileName = other.TraceFileName;
WriteMessagingTraces = other.WriteMessagingTraces;
LargeMessageWarningThreshold = other.LargeMessageWarningThreshold;
PropagateActivityId = other.PropagateActivityId;
BulkMessageLimit = other.BulkMessageLimit;
StatisticsProviderName = other.StatisticsProviderName;
StatisticsMetricsTableWriteInterval = other.StatisticsMetricsTableWriteInterval;
StatisticsPerfCountersWriteInterval = other.StatisticsPerfCountersWriteInterval;
StatisticsLogWriteInterval = other.StatisticsLogWriteInterval;
StatisticsWriteLogStatisticsToTable = other.StatisticsWriteLogStatisticsToTable;
StatisticsCollectionLevel = other.StatisticsCollectionLevel;
LimitManager = new LimitManager(other.LimitManager); // Shallow copy
Subnet = other.Subnet;
MinDotNetThreadPoolSize = other.MinDotNetThreadPoolSize;
Expect100Continue = other.Expect100Continue;
DefaultConnectionLimit = other.DefaultConnectionLimit;
UseNagleAlgorithm = other.UseNagleAlgorithm;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(" Silo Name: ").AppendLine(SiloName);
sb.Append(" Generation: ").Append(Generation).AppendLine();
sb.Append(" Host Name or IP Address: ").AppendLine(HostNameOrIPAddress);
sb.Append(" DNS Host Name: ").AppendLine(DNSHostName);
sb.Append(" Port: ").Append(Port).AppendLine();
sb.Append(" Subnet: ").Append(Subnet == null ? "" : Subnet.ToStrings(x => x.ToString(), ".")).AppendLine();
sb.Append(" Preferred Address Family: ").Append(AddressType).AppendLine();
if (IsGatewayNode)
{
sb.Append(" Proxy Gateway: ").Append(ProxyGatewayEndpoint.ToString()).AppendLine();
}
else
{
sb.Append(" IsGatewayNode: ").Append(IsGatewayNode).AppendLine();
}
sb.Append(" IsPrimaryNode: ").Append(IsPrimaryNode).AppendLine();
sb.Append(" Scheduler: ").AppendLine();
sb.Append(" ").Append(" Max Active Threads: ").Append(MaxActiveThreads).AppendLine();
sb.Append(" ").Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine();
sb.Append(" ").Append(" Delay Warning Threshold: ").Append(DelayWarningThreshold).AppendLine();
sb.Append(" ").Append(" Activation Scheduling Quantum: ").Append(ActivationSchedulingQuantum).AppendLine();
sb.Append(" ").Append(" Turn Warning Length Threshold: ").Append(TurnWarningLengthThreshold).AppendLine();
sb.Append(" ").Append(" Inject More Worker Threads: ").Append(InjectMoreWorkerThreads).AppendLine();
sb.Append(" ").Append(" MinDotNetThreadPoolSize: ").Append(MinDotNetThreadPoolSize).AppendLine();
int workerThreads;
int completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
sb.Append(" ").AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine();
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
sb.Append(" ").AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine();
sb.Append(" ").AppendFormat(" .NET ServicePointManager - DefaultConnectionLimit={0} Expect100Continue={1} UseNagleAlgorithm={2}", DefaultConnectionLimit, Expect100Continue, UseNagleAlgorithm).AppendLine();
sb.Append(" Load Shedding Enabled: ").Append(LoadSheddingEnabled).AppendLine();
sb.Append(" Load Shedding Limit: ").Append(LoadSheddingLimit).AppendLine();
sb.Append(" Debug: ").AppendLine();
sb.Append(ConfigUtilities.TraceConfigurationToString(this));
sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this));
sb.Append(LimitManager);
return sb.ToString();
}
internal void Load(XmlElement root)
{
SiloName = root.LocalName.Equals("Override") ? root.GetAttribute("Node") : DEFAULT_NODE_NAME;
foreach (XmlNode c in root.ChildNodes)
{
var child = c as XmlElement;
if (child == null) continue; // Skip comment lines
switch (child.LocalName)
{
case "Networking":
if (child.HasAttribute("Address"))
{
HostNameOrIPAddress = child.GetAttribute("Address");
}
if (child.HasAttribute("Port"))
{
Port = ConfigUtilities.ParseInt(child.GetAttribute("Port"),
"Non-numeric Port attribute value on Networking element for " + SiloName);
}
if (child.HasAttribute("PreferredFamily"))
{
AddressType = ConfigUtilities.ParseEnum<AddressFamily>(child.GetAttribute("PreferredFamily"),
"Invalid preferred address family on Networking node. Valid choices are 'InterNetwork' and 'InterNetworkV6'");
}
break;
case "ProxyingGateway":
ProxyGatewayEndpoint = ConfigUtilities.ParseIPEndPoint(child, Subnet);
break;
case "Scheduler":
if (child.HasAttribute("MaxActiveThreads"))
{
MaxActiveThreads = ConfigUtilities.ParseInt(child.GetAttribute("MaxActiveThreads"),
"Non-numeric MaxActiveThreads attribute value on Scheduler element for " + SiloName);
if (MaxActiveThreads < 1)
{
MaxActiveThreads = DEFAULT_MAX_ACTIVE_THREADS;
}
}
if (child.HasAttribute("DelayWarningThreshold"))
{
DelayWarningThreshold = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DelayWarningThreshold"),
"Non-numeric DelayWarningThreshold attribute value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("ActivationSchedulingQuantum"))
{
ActivationSchedulingQuantum = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ActivationSchedulingQuantum"),
"Non-numeric ActivationSchedulingQuantum attribute value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("TurnWarningLengthThreshold"))
{
TurnWarningLengthThreshold = ConfigUtilities.ParseTimeSpan(child.GetAttribute("TurnWarningLengthThreshold"),
"Non-numeric TurnWarningLengthThreshold attribute value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("MinDotNetThreadPoolSize"))
{
MinDotNetThreadPoolSize = ConfigUtilities.ParseInt(child.GetAttribute("MinDotNetThreadPoolSize"),
"Invalid ParseInt MinDotNetThreadPoolSize value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("Expect100Continue"))
{
Expect100Continue = ConfigUtilities.ParseBool(child.GetAttribute("Expect100Continue"),
"Invalid ParseBool Expect100Continue value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("DefaultConnectionLimit"))
{
DefaultConnectionLimit = ConfigUtilities.ParseInt(child.GetAttribute("DefaultConnectionLimit"),
"Invalid ParseInt DefaultConnectionLimit value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("UseNagleAlgorithm "))
{
UseNagleAlgorithm = ConfigUtilities.ParseBool(child.GetAttribute("UseNagleAlgorithm "),
"Invalid ParseBool UseNagleAlgorithm value on Scheduler element for " + SiloName);
}
break;
case "LoadShedding":
if (child.HasAttribute("Enabled"))
{
LoadSheddingEnabled = ConfigUtilities.ParseBool(child.GetAttribute("Enabled"),
"Invalid boolean value for Enabled attribute on LoadShedding attribute for " + SiloName);
}
if (child.HasAttribute("LoadLimit"))
{
LoadSheddingLimit = ConfigUtilities.ParseInt(child.GetAttribute("LoadLimit"),
"Invalid integer value for LoadLimit attribute on LoadShedding attribute for " + SiloName);
if (LoadSheddingLimit < 0)
{
LoadSheddingLimit = 0;
}
if (LoadSheddingLimit > 100)
{
LoadSheddingLimit = 100;
}
}
break;
case "Tracing":
ConfigUtilities.ParseTracing(this, child, SiloName);
break;
case "Statistics":
ConfigUtilities.ParseStatistics(this, child, SiloName);
break;
case "Limits":
ConfigUtilities.ParseLimitValues(LimitManager, child, SiloName);
break;
}
}
}
private string GetDefaultWorkingStoreDirectory()
{
string workingStoreLocation = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify);
string cacheDirBase = Path.Combine(workingStoreLocation, "OrleansData");
return cacheDirBase;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F06_Country (editable child object).<br/>
/// This is a generated base class of <see cref="F06_Country"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="F07_RegionObjects"/> of type <see cref="F07_RegionColl"/> (1:M relation to <see cref="F08_Region"/>)<br/>
/// This class is an item of <see cref="F05_CountryColl"/> collection.
/// </remarks>
[Serializable]
public partial class F06_Country : BusinessBase<F06_Country>
{
#region Static Fields
private static int _lastID;
#endregion
#region State Fields
[NotUndoable]
[NonSerialized]
internal int parent_SubContinent_ID = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Countries ID");
/// <summary>
/// Gets the Countries ID.
/// </summary>
/// <value>The Countries ID.</value>
public int Country_ID
{
get { return GetProperty(Country_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Country_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Countries Name");
/// <summary>
/// Gets or sets the Countries Name.
/// </summary>
/// <value>The Countries Name.</value>
public string Country_Name
{
get { return GetProperty(Country_NameProperty); }
set { SetProperty(Country_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="F07_Country_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<F07_Country_Child> F07_Country_SingleObjectProperty = RegisterProperty<F07_Country_Child>(p => p.F07_Country_SingleObject, "F07 Country Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the F07 Country Single Object ("parent load" child property).
/// </summary>
/// <value>The F07 Country Single Object.</value>
public F07_Country_Child F07_Country_SingleObject
{
get { return GetProperty(F07_Country_SingleObjectProperty); }
private set { LoadProperty(F07_Country_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="F07_Country_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<F07_Country_ReChild> F07_Country_ASingleObjectProperty = RegisterProperty<F07_Country_ReChild>(p => p.F07_Country_ASingleObject, "F07 Country ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the F07 Country ASingle Object ("parent load" child property).
/// </summary>
/// <value>The F07 Country ASingle Object.</value>
public F07_Country_ReChild F07_Country_ASingleObject
{
get { return GetProperty(F07_Country_ASingleObjectProperty); }
private set { LoadProperty(F07_Country_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="F07_RegionObjects"/> property.
/// </summary>
public static readonly PropertyInfo<F07_RegionColl> F07_RegionObjectsProperty = RegisterProperty<F07_RegionColl>(p => p.F07_RegionObjects, "F07 Region Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the F07 Region Objects ("parent load" child property).
/// </summary>
/// <value>The F07 Region Objects.</value>
public F07_RegionColl F07_RegionObjects
{
get { return GetProperty(F07_RegionObjectsProperty); }
private set { LoadProperty(F07_RegionObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F06_Country"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="F06_Country"/> object.</returns>
internal static F06_Country NewF06_Country()
{
return DataPortal.CreateChild<F06_Country>();
}
/// <summary>
/// Factory method. Loads a <see cref="F06_Country"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="F06_Country"/> object.</returns>
internal static F06_Country GetF06_Country(SafeDataReader dr)
{
F06_Country obj = new F06_Country();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.LoadProperty(F07_RegionObjectsProperty, F07_RegionColl.NewF07_RegionColl());
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F06_Country"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public F06_Country()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="F06_Country"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(F07_Country_SingleObjectProperty, DataPortal.CreateChild<F07_Country_Child>());
LoadProperty(F07_Country_ASingleObjectProperty, DataPortal.CreateChild<F07_Country_ReChild>());
LoadProperty(F07_RegionObjectsProperty, DataPortal.CreateChild<F07_RegionColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="F06_Country"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Country_IDProperty, dr.GetInt32("Country_ID"));
LoadProperty(Country_NameProperty, dr.GetString("Country_Name"));
// parent properties
parent_SubContinent_ID = dr.GetInt32("Parent_SubContinent_ID");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child <see cref="F07_Country_Child"/> object.
/// </summary>
/// <param name="child">The child object to load.</param>
internal void LoadChild(F07_Country_Child child)
{
LoadProperty(F07_Country_SingleObjectProperty, child);
}
/// <summary>
/// Loads child <see cref="F07_Country_ReChild"/> object.
/// </summary>
/// <param name="child">The child object to load.</param>
internal void LoadChild(F07_Country_ReChild child)
{
LoadProperty(F07_Country_ASingleObjectProperty, child);
}
/// <summary>
/// Inserts a new <see cref="F06_Country"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(F04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddF06_Country", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_SubContinent_ID", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Country_Name", ReadProperty(Country_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Country_IDProperty, (int) cmd.Parameters["@Country_ID"].Value);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="F06_Country"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateF06_Country", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Country_Name", ReadProperty(Country_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="F06_Country"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteF06_Country", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Country_ID", ReadProperty(Country_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(F07_Country_SingleObjectProperty, DataPortal.CreateChild<F07_Country_Child>());
LoadProperty(F07_Country_ASingleObjectProperty, DataPortal.CreateChild<F07_Country_ReChild>());
LoadProperty(F07_RegionObjectsProperty, DataPortal.CreateChild<F07_RegionColl>());
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using Aurora.Framework;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Services.Interfaces;
namespace Aurora.Services.DataService
{
public class LocalUserInfoConnector : IAgentInfoConnector
{
private IGenericData GD;
protected bool m_allowDuplicatePresences = true;
protected bool m_checkLastSeen = true;
private string m_realm = "userinfo";
#region IAgentInfoConnector Members
public void Initialize(IGenericData GenericData, IConfigSource source, IRegistryCore simBase,
string defaultConnectionString)
{
if (source.Configs["AuroraConnectors"].GetString("UserInfoConnector", "LocalConnector") == "LocalConnector")
{
GD = GenericData;
string connectionString = defaultConnectionString;
if (source.Configs[Name] != null)
{
connectionString = source.Configs[Name].GetString("ConnectionString", defaultConnectionString);
m_allowDuplicatePresences =
source.Configs[Name].GetBoolean("AllowDuplicatePresences",
m_allowDuplicatePresences);
m_checkLastSeen =
source.Configs[Name].GetBoolean("CheckLastSeen",
m_checkLastSeen);
}
GD.ConnectToDatabase(connectionString, "UserInfo",
source.Configs["AuroraConnectors"].GetBoolean("ValidateTables", true));
DataManager.DataManager.RegisterPlugin(this);
}
}
public string Name
{
get { return "IAgentInfoConnector"; }
}
public bool Set(UserInfo info)
{
object[] values = new object[13];
values[0] = info.UserID;
values[1] = info.CurrentRegionID;
values[2] = Util.ToUnixTime(DateTime.Now.ToUniversalTime());
//Convert to binary so that it can be converted easily
values[3] = info.IsOnline ? 1 : 0;
values[4] = Util.ToUnixTime(info.LastLogin);
values[5] = Util.ToUnixTime(info.LastLogout);
values[6] = OSDParser.SerializeJsonString(info.Info);
values[7] = info.CurrentRegionID.ToString();
values[8] = info.CurrentPosition.ToString();
values[9] = info.CurrentLookAt.ToString();
values[10] = info.HomeRegionID.ToString();
values[11] = info.HomePosition.ToString();
values[12] = info.HomeLookAt.ToString();
QueryFilter filter = new QueryFilter();
filter.andFilters["UserID"] = info.UserID;
GD.Delete(m_realm, filter);
return GD.Insert(m_realm, values);
}
public void Update(string userID, Dictionary<string, object> values)
{
QueryFilter filter = new QueryFilter();
filter.andFilters["UserID"] = userID;
GD.Update(m_realm, values, null, filter, null, null);
}
public void SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
Dictionary<string, object> values = new Dictionary<string, object>(5);
values["CurrentRegionID"] = regionID;
values["CurrentPosition"] = lastPosition;
values["CurrentLookat"] = lastLookAt;
values["LastSeen"] = Util.ToUnixTime(DateTime.Now.ToUniversalTime());
//Set the last seen and is online since if the user is moving, they are sending updates
values["IsOnline"] = 1;
Update(userID, values);
}
public void SetHomePosition(string userID, UUID regionID, Vector3 Position, Vector3 LookAt)
{
Dictionary<string, object> values = new Dictionary<string, object>(4);
values["HomeRegionID"] = regionID;
values["LastSeen"] = Util.ToUnixTime(DateTime.Now.ToUniversalTime());
values["HomePosition"] = Position;
values["HomeLookat"] = LookAt;
Update(userID, values);
}
private static List<UserInfo> ParseQuery(List<string> query)
{
List<UserInfo> users = new List<UserInfo>();
if (query.Count % 13 == 0)
{
for (int i = 0; i < query.Count; i += 13)
{
UserInfo user = new UserInfo
{
UserID = query[i],
CurrentRegionID = UUID.Parse(query[i + 1]),
IsOnline = query[i + 3] == "1",
LastLogin = Util.ToDateTime(int.Parse(query[i + 4])),
LastLogout = Util.ToDateTime(int.Parse(query[i + 5])),
Info = (OSDMap)OSDParser.DeserializeJson(query[i + 6])
};
try
{
user.CurrentRegionID = UUID.Parse(query[i + 7]);
if (query[i + 8] != "")
user.CurrentPosition = Vector3.Parse(query[i + 8]);
if (query[i + 9] != "")
user.CurrentLookAt = Vector3.Parse(query[i + 9]);
user.HomeRegionID = UUID.Parse(query[i + 10]);
if (query[i + 11] != "")
user.HomePosition = Vector3.Parse(query[i + 11]);
if (query[i + 12] != "")
user.HomeLookAt = Vector3.Parse(query[i + 12]);
}
catch
{
}
users.Add(user);
}
}
return users;
}
public UserInfo Get(string userID, bool checkOnlineStatus, out bool onlineStatusChanged)
{
onlineStatusChanged = false;
QueryFilter filter = new QueryFilter();
filter.andFilters["UserID"] = userID;
List<string> query = GD.Query(new string[1] { "*" }, m_realm, filter, null, null, null);
if (query.Count == 0)
{
return null;
}
UserInfo user = ParseQuery(query)[0];
//Check LastSeen
DateTime timeLastSeen = Util.ToDateTime(int.Parse(query[2]));
DateTime timeNow = DateTime.Now.ToUniversalTime();
if (checkOnlineStatus && m_checkLastSeen && user.IsOnline && (timeLastSeen.AddHours(1) < timeNow))
{
if (user.CurrentRegionID != AgentInfoHelpers.LOGIN_STATUS_LOCKED)
//The login status can be locked with this so that it cannot be changed with this method
{
MainConsole.Instance.Warn("[UserInfoService]: Found a user (" + user.UserID +
") that was not seen within the last hour " +
"(since " + timeLastSeen.ToLocalTime().ToString() + ", time elapsed " +
(timeNow - timeLastSeen).Days + " days, " + (timeNow - timeLastSeen).Hours +
" hours)! Logging them out.");
user.IsOnline = false;
Set(user);
onlineStatusChanged = true;
}
}
return user;
}
public uint RecentlyOnline(uint secondsAgo, bool stillOnline)
{
int now = (int)Utils.DateTimeToUnixTime(DateTime.Now) - (int)secondsAgo;
QueryFilter filter = new QueryFilter();
filter.orGreaterThanEqFilters["LastLogin"] = now;
filter.orGreaterThanEqFilters["LastSeen"] = now;
if (stillOnline)
{
// filter.andGreaterThanFilters["LastLogout"] = now;
filter.andFilters["IsOnline"] = "1";
}
return uint.Parse(GD.Query(new string[1] { "COUNT(UserID)" }, m_realm, filter, null, null, null)[0]);
}
public List<UserInfo> RecentlyOnline(uint secondsAgo, bool stillOnline, Dictionary<string, bool> sort, uint start, uint count)
{
int now = (int)Utils.DateTimeToUnixTime(DateTime.Now) - (int)secondsAgo;
QueryFilter filter = new QueryFilter();
filter.orGreaterThanEqFilters["LastLogin"] = now;
filter.orGreaterThanEqFilters["LastSeen"] = now;
if (stillOnline)
{
// filter.andGreaterThanFilters["LastLogout"] = now;
filter.andFilters["IsOnline"] = "1";
}
List<string> query = GD.Query(new string[] { "*" }, m_realm, filter, sort, start, count);
return ParseQuery(query);
}
#endregion
public void Dispose()
{
}
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class MethodBuilderSetImplementationFlags
{
private const string TestDynamicAssemblyName = "TestDynamicAssembly";
private const string TestDynamicModuleName = "TestDynamicModule";
private const string TestDynamicTypeName = "TestDynamicType";
private const AssemblyBuilderAccess TestAssemblyBuilderAccess = AssemblyBuilderAccess.Run;
private const TypeAttributes TestTypeAttributes = TypeAttributes.Abstract;
private const MethodAttributes TestMethodAttributes = MethodAttributes.Public | MethodAttributes.Static;
private const int MinStringLength = 1;
private const int MaxStringLength = 128;
private const int ByteArraySize = 128;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
private TypeBuilder GetTestTypeBuilder()
{
AssemblyName assemblyName = new AssemblyName(TestDynamicAssemblyName);
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(
assemblyName, TestAssemblyBuilderAccess);
ModuleBuilder moduleBuilder = TestLibrary.Utilities.GetModuleBuilder(assemblyBuilder, TestDynamicModuleName);
return moduleBuilder.DefineType(TestDynamicTypeName, TestTypeAttributes);
}
[Fact]
public void TestWithCodeTypeMask()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.CodeTypeMask;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithForwardRef()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.ForwardRef;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithIL()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.IL;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithInternalCall()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.InternalCall;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithManaged()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.Managed;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithManagedMask()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.ManagedMask;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithNative()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.Native;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithNoInlining()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.NoInlining;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithOPTIL()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.OPTIL;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithPreserveSig()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.PreserveSig;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithRuntime()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.Runtime;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithSynchronized()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.Synchronized;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestWithUnmanaged()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.Unmanaged;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public);
builder.SetImplementationFlags(desiredFlags);
MethodImplAttributes actualFlags = builder.MethodImplementationFlags;
Assert.Equal(desiredFlags, actualFlags);
}
[Fact]
public void TestThrowsExceptionOnTypeCreated()
{
string methodName = null;
methodName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength);
MethodImplAttributes desiredFlags = MethodImplAttributes.Unmanaged;
TypeBuilder typeBuilder = GetTestTypeBuilder();
MethodBuilder builder = typeBuilder.DefineMethod(methodName,
MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual);
Type type = typeBuilder.CreateTypeInfo().AsType();
Assert.Throws<InvalidOperationException>(() => { builder.SetImplementationFlags(desiredFlags); });
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Win32
{
using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics.Tracing;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class UnsafeNativeMethods
{
[DllImport(Interop.Libraries.Kernel32, EntryPoint = "GetTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
internal static extern int GetTimeZoneInformation(out Win32Native.TimeZoneInformation lpTimeZoneInformation);
[DllImport(Interop.Libraries.Kernel32, EntryPoint = "GetDynamicTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
internal static extern int GetDynamicTimeZoneInformation(out Win32Native.DynamicTimeZoneInformation lpDynamicTimeZoneInformation);
//
// BOOL GetFileMUIPath(
// DWORD dwFlags,
// PCWSTR pcwszFilePath,
// PWSTR pwszLanguage,
// PULONG pcchLanguage,
// PWSTR pwszFileMUIPath,
// PULONG pcchFileMUIPath,
// PULONGLONG pululEnumerator
// );
//
[DllImport(Interop.Libraries.Kernel32, EntryPoint = "GetFileMUIPath", SetLastError = true, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetFileMUIPath(
int flags,
[MarshalAs(UnmanagedType.LPWStr)]
String filePath,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder language,
ref int languageLength,
[Out, MarshalAs(UnmanagedType.LPWStr)]
StringBuilder fileMuiPath,
ref int fileMuiPathLength,
ref Int64 enumerator);
[SuppressUnmanagedCodeSecurityAttribute()]
internal static unsafe class ManifestEtw
{
//
// Constants error coded returned by ETW APIs
//
// The event size is larger than the allowed maximum (64k - header).
internal const int ERROR_ARITHMETIC_OVERFLOW = 534;
// Occurs when filled buffers are trying to flush to disk,
// but disk IOs are not happening fast enough.
// This happens when the disk is slow and event traffic is heavy.
// Eventually, there are no more free (empty) buffers and the event is dropped.
internal const int ERROR_NOT_ENOUGH_MEMORY = 8;
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_NOT_SUPPORTED = 50;
internal const int ERROR_INVALID_PARAMETER = 0x57;
//
// ETW Methods
//
internal const int EVENT_CONTROL_CODE_DISABLE_PROVIDER = 0;
internal const int EVENT_CONTROL_CODE_ENABLE_PROVIDER = 1;
internal const int EVENT_CONTROL_CODE_CAPTURE_STATE = 2;
//
// Callback
//
internal unsafe delegate void EtwEnableCallback(
[In] ref Guid sourceId,
[In] int isEnabled,
[In] byte level,
[In] long matchAnyKeywords,
[In] long matchAllKeywords,
[In] EVENT_FILTER_DESCRIPTOR* filterData,
[In] void* callbackContext
);
//
// Registration APIs
//
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe uint EventRegister(
[In] ref Guid providerId,
[In]EtwEnableCallback enableCallback,
[In]void* callbackContext,
[In][Out]ref long registrationHandle
);
//
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern uint EventUnregister([In] long registrationHandle);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe int EventWriteString(
[In] long registrationHandle,
[In] byte level,
[In] long keyword,
[In] string msg
);
[StructLayout(LayoutKind.Sequential)]
unsafe internal struct EVENT_FILTER_DESCRIPTOR
{
public long Ptr;
public int Size;
public int Type;
};
/// <summary>
/// Call the ETW native API EventWriteTransfer and checks for invalid argument error.
/// The implementation of EventWriteTransfer on some older OSes (Windows 2008) does not accept null relatedActivityId.
/// So, for these cases we will retry the call with an empty Guid.
/// </summary>
internal static int EventWriteTransferWrapper(long registrationHandle,
ref EventDescriptor eventDescriptor,
Guid* activityId,
Guid* relatedActivityId,
int userDataCount,
EventProvider.EventData* userData)
{
int HResult = EventWriteTransfer(registrationHandle, ref eventDescriptor, activityId, relatedActivityId, userDataCount, userData);
if (HResult == ERROR_INVALID_PARAMETER && relatedActivityId == null)
{
Guid emptyGuid = Guid.Empty;
HResult = EventWriteTransfer(registrationHandle, ref eventDescriptor, activityId, &emptyGuid, userDataCount, userData);
}
return HResult;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteTransfer", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
private static extern int EventWriteTransfer(
[In] long registrationHandle,
[In] ref EventDescriptor eventDescriptor,
[In] Guid* activityId,
[In] Guid* relatedActivityId,
[In] int userDataCount,
[In] EventProvider.EventData* userData
);
internal enum ActivityControl : uint
{
EVENT_ACTIVITY_CTRL_GET_ID = 1,
EVENT_ACTIVITY_CTRL_SET_ID = 2,
EVENT_ACTIVITY_CTRL_CREATE_ID = 3,
EVENT_ACTIVITY_CTRL_GET_SET_ID = 4,
EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5
};
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
internal static extern int EventActivityIdControl([In] ActivityControl ControlCode, [In][Out] ref Guid ActivityId);
internal enum EVENT_INFO_CLASS
{
BinaryTrackInfo,
SetEnableAllKeywords,
SetTraits,
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventSetInformation", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
internal static extern int EventSetInformation(
[In] long registrationHandle,
[In] EVENT_INFO_CLASS informationClass,
[In] void* eventInformation,
[In] int informationLength);
// Support for EnumerateTraceGuidsEx
internal enum TRACE_QUERY_INFO_CLASS
{
TraceGuidQueryList,
TraceGuidQueryInfo,
TraceGuidQueryProcess,
TraceStackTracingInfo,
MaxTraceSetInfoClass
};
internal struct TRACE_GUID_INFO
{
public int InstanceCount;
public int Reserved;
};
internal struct TRACE_PROVIDER_INSTANCE_INFO
{
public int NextOffset;
public int EnableCount;
public int Pid;
public int Flags;
};
internal struct TRACE_ENABLE_INFO
{
public int IsEnabled;
public byte Level;
public byte Reserved1;
public ushort LoggerId;
public int EnableProperty;
public int Reserved2;
public long MatchAnyKeyword;
public long MatchAllKeyword;
};
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EnumerateTraceGuidsEx", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
internal static extern int EnumerateTraceGuidsEx(
TRACE_QUERY_INFO_CLASS TraceQueryInfoClass,
void* InBuffer,
int InBufferSize,
void* OutBuffer,
int OutBufferSize,
ref int ReturnLength);
}
#if FEATURE_COMINTEROP
[DllImport("combase.dll", PreserveSig = true)]
internal static extern int RoGetActivationFactory(
[MarshalAs(UnmanagedType.HString)] string activatableClassId,
[In] ref Guid iid,
[Out, MarshalAs(UnmanagedType.IInspectable)] out Object factory);
#endif
}
}
| |
//#define SHOW_ASSERT_ERRORS
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using FlatRedBall;
using FlatRedBall.Gui;
using FlatRedBall.ManagedSpriteGroups;
using FlatRedBall.Graphics;
using FlatRedBall.Collections;
using FlatRedBall.Utilities;
using FlatRedBall.Input;
using System.Drawing;
using System.Windows.Forms;
using System.Collections; // for arrayList of sprites in spriteManager
using Microsoft.DirectX;
using Microsoft.DirectX.DirectInput;
using FileManager = FlatRedBall.IO.FileManager;
using SpriteEditor.Gui;
using EditorObjects;
namespace SpriteEditor
{
public class GameForm : EditorObjects.EditorWindow
{
#region Fields
public static SECursor cursor;
public static SpriteEditor.SEPositionedObjects.EditorCamera camera;
#endregion
#region Methods
#region GameForm constructor
public GameForm() : base()
{
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.GameForm_DragDrop);
this.Text = "SpriteEditor - untitled scene";
camera = new SpriteEditor.SEPositionedObjects.EditorCamera(FlatRedBallServices.GlobalContentManager);
SpriteManager.Cameras[0] = camera;
camera.DestinationRectangle =
new Rectangle(0, 0, FlatRedBallServices.ClientWidth, FlatRedBallServices.ClientHeight);
camera.FixAspectRatioYConstant();
if(this.IsDisposed) return;
// this is a little different than what is normally done in the FRBTemplate;
// instead of using the SpriteManager's regularly created Camera, make a new
// EditorCamera and throw that in the SpriteManager's array.
cursor = new SECursor(camera, this);
//GuiManager.Initialize(camera, "genGfx/defaultText.tga", this, cursor);
GuiManager.Cursors[0] = cursor;
FlatRedBallServices.Update(null);
SpriteEditorSettings.Initialize();
SpriteManager.MaxParticleCount = 10000;
GameData.Initialize();
GuiData.Initialize();
GuiData.messages.Initialize(this);
}
#endregion
[STAThread]
static void Main(string[] args)
{
try
{
GameForm frm = new GameForm();
if (frm.IsDisposed)
return;
ProcessCommandLineArguments(args);
EditorWindow.MinimumFrameLength = 1 / 60.0f;
frm.Run(args);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString());
}
}
public override void FrameUpdate()
{
base.FrameUpdate();
GameData.Activity();
DrawShapesAndLines();
}
static void DrawShapesAndLines()
{
Vector3 spriteVector;
#region outline current Sprites
foreach (Sprite s in GameData.EditorLogic.CurrentSprites)
{
spriteVector = s.Position;
Vector3[] vector3 = {
new Vector3(-s.ScaleX, s.ScaleY, 0),
new Vector3( s.ScaleX, s.ScaleY, 0),
new Vector3( s.ScaleX,-s.ScaleY, 0),
new Vector3(-s.ScaleX,-s.ScaleY, 0)};
vector3[0].TransformCoordinate(s.RotationMatrix);
vector3[1].TransformCoordinate(s.RotationMatrix);
vector3[2].TransformCoordinate(s.RotationMatrix);
vector3[3].TransformCoordinate(s.RotationMatrix);
vector3[0] = spriteVector + vector3[0];
vector3[1] = spriteVector + vector3[1];
vector3[2] = spriteVector + vector3[2];
vector3[3] = spriteVector + vector3[3];
}
#endregion
foreach (SpriteFrame sf in GameData.EditorLogic.CurrentSpriteFrames)
{
spriteVector = sf.Position;
Vector3[] vector3 = {
new Vector3(-sf.ScaleX, sf.ScaleY, 0),
new Vector3( sf.ScaleX, sf.ScaleY, 0),
new Vector3( sf.ScaleX,-sf.ScaleY, 0),
new Vector3(-sf.ScaleX,-sf.ScaleY, 0)};
vector3[0].TransformCoordinate(sf.RotationMatrix);
vector3[1].TransformCoordinate(sf.RotationMatrix);
vector3[2].TransformCoordinate(sf.RotationMatrix);
vector3[3].TransformCoordinate(sf.RotationMatrix);
vector3[0] = spriteVector + vector3[0];
vector3[1] = spriteVector + vector3[1];
vector3[2] = spriteVector + vector3[2];
vector3[3] = spriteVector + vector3[3];
}
}
static void ProcessCommandLineArguments(string[] args)
{
//VerifyScnRegistry();
bool replace = true;
foreach (string s in args)
{
if (FileManager.GetExtension(s) == "scn")
{
GuiData.MenuStrip.PerformLoadScn(s, replace);
FlatRedBall.Gui.FileWindow.SetLastDirectory("scn", FileManager.GetDirectory(s));
FlatRedBall.Gui.FileWindow.SetLastDirectory("bmp", FileManager.GetDirectory(s));
FlatRedBall.Gui.FileWindow.SetLastDirectory("srgx", FileManager.GetDirectory(s));
replace = false;
}
else if (FileManager.GetExtension(s) == "scnx")
{
GuiData.MenuStrip.PerformLoadScn(s, replace);
FlatRedBall.Gui.FileWindow.SetLastDirectory("scn", FileManager.GetDirectory(s));
FlatRedBall.Gui.FileWindow.SetLastDirectory("scnx", FileManager.GetDirectory(s));
FlatRedBall.Gui.FileWindow.SetLastDirectory("bmp", FileManager.GetDirectory(s));
FlatRedBall.Gui.FileWindow.SetLastDirectory("srgx", FileManager.GetDirectory(s));
replace = false;
}
}
}
/// <summary>
/// Checks to see if the currently running instance of the sprite editor
/// is associated with the .scn file extension.
/// </summary>
/// <remarks>Currently only attempts to check/associate if the currently
/// logged in user is a windows administrator. Have not fully
/// investigated whether you really need unrestricted access to the registry
/// to create/edit the required registry keys (in HKEY_CLASSES_ROOT), or
/// if there is a way to do the association as a limited user. In
/// the mean time, we will err on the side of caution.</remarks>
static void VerifyScnRegistry()
{
System.Security.Principal.WindowsIdentity winIdent = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal winPrincipal = new System.Security.Principal.WindowsPrincipal(winIdent);
if (winPrincipal.IsInRole(
System.Security.Principal.WindowsBuiltInRole.Administrator))
{
FileAssociationHelper file = new FileAssociationHelper(".scn");
if (!file.IsOpener || !file.IsEditor)
{
DialogResult res = System.Windows.Forms.MessageBox.Show(
"This application is currently not associated with the .scn file extension.\n\nWould you like it to be?",
"File Association",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1);
if (res == DialogResult.Yes)
{
file.Associate();
}
}
}
}
private void GameForm_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
// Assign the file names to a string array, in
// case the user has selected multiple files.
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
try
{
System.Drawing.Point p = this.PointToClient(new Point(e.X, e.Y));
foreach (string fileName in files)
{
string extension = FileManager.GetExtension(fileName);
switch (extension)
{
case "bmp":
case "jpg":
case "tga":
case "png":
case "dds":
GameData.AddSprite(fileName, "");
this.BringToFront();
this.Focus();
break;
case "scnx":
GuiData.MenuStrip.AskToReplaceOrInsertNewScene(fileName);
break;
case "x":
GameData.AddModel(fileName);
break;
}
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return;
}
}
}
#endregion
}
}
| |
//! \file ImageBSG.cs
//! \date Sat Oct 24 17:07:43 2015
//! \brief Bishop graphics image.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using GameRes.Utility;
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace GameRes.Formats.Bishop
{
internal class BsgMetaData : ImageMetaData
{
public int UnpackedSize;
public int ColorMode;
public int CompressionMode;
public int DataOffset;
public int DataSize;
public int PaletteOffset;
}
[Export(typeof(ImageFormat))]
public class BsgFormat : ImageFormat
{
public override string Tag { get { return "BSG"; } }
public override string Description { get { return "Bishop image format"; } }
public override uint Signature { get { return 0x2D535342; } } // 'BSS-'
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = stream.ReadHeader (0x60);
int base_offset = 0;
if (header.AsciiEqual ("BSS-Composition\0"))
base_offset = 0x20;
if (!header.AsciiEqual (base_offset, "BSS-Graphics\0"))
return null;
int type = header[base_offset+0x30];
if (type > 2)
return null;
return new BsgMetaData
{
Width = header.ToUInt16 (base_offset+0x16),
Height = header.ToUInt16 (base_offset+0x18),
OffsetX = header.ToInt16 (base_offset+0x20),
OffsetY = header.ToInt16 (base_offset+0x22),
UnpackedSize = header.ToInt32 (base_offset+0x12),
BPP = 2 == type ? 8 : 32,
ColorMode = type,
CompressionMode = header[base_offset+0x31],
DataOffset = header.ToInt32 (base_offset+0x32)+base_offset,
DataSize = header.ToInt32 (base_offset+0x36),
PaletteOffset = header.ToInt32 (base_offset+0x3A)+base_offset,
};
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
var meta = (BsgMetaData)info;
using (var reader = new BsgReader (stream, meta))
{
reader.Unpack();
return ImageData.CreateFlipped (info, reader.Format, reader.Palette, reader.Data, reader.Stride);
}
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("BsgFormat.Write not implemented");
}
}
internal sealed class BsgReader : IDisposable
{
IBinaryStream m_input;
BsgMetaData m_info;
byte[] m_output;
public byte[] Data { get { return m_output; } }
public PixelFormat Format { get; private set; }
public BitmapPalette Palette { get; private set; }
public int Stride { get; private set; }
public BsgReader (IBinaryStream input, BsgMetaData info)
{
m_info = info;
if (m_info.CompressionMode > 2)
throw new NotSupportedException ("Not supported BSS Graphics compression");
m_input = input;
m_output = new byte[m_info.UnpackedSize];
switch (m_info.ColorMode)
{
case 0:
Format = PixelFormats.Bgra32;
Stride = (int)m_info.Width * 4;
break;
case 1:
Format = PixelFormats.Bgr32;
Stride = (int)m_info.Width * 4;
break;
case 2:
Format = PixelFormats.Indexed8;
Stride = (int)m_info.Width;
Palette = ReadPalette();
break;
}
}
public void Unpack ()
{
m_input.Position = m_info.DataOffset;
if (0 == m_info.CompressionMode)
{
if (1 == m_info.ColorMode)
{
int dst = 0;
for (int count = m_info.DataSize / 3; count > 0; --count)
{
m_input.Read (m_output, dst, 3);
dst += 4;
}
}
else
{
m_input.Read (m_output, 0, m_info.DataSize);
}
}
else
{
Action<int, int> unpacker;
if (1 == m_info.CompressionMode)
unpacker = UnpackRle;
else
unpacker = UnpackLz;
if (0 == m_info.ColorMode)
{
for (int channel = 0; channel < 4; ++channel)
unpacker (channel, 4);
}
else if (1 == m_info.ColorMode)
{
for (int channel = 0; channel < 3; ++channel)
unpacker (channel, 4);
}
else
{
unpacker (0, 1);
}
}
}
void UnpackRle (int dst, int pixel_size)
{
int remaining = m_input.ReadInt32();
while (remaining > 0)
{
int count = m_input.ReadInt8();
--remaining;
if (count >= 0)
{
for (int i = 0; i <= count; ++i)
{
m_output[dst] = m_input.ReadUInt8();
--remaining;
dst += pixel_size;
}
}
else
{
count = 1 - count;
byte repeat = m_input.ReadUInt8();
--remaining;
for (int i = 0; i < count; ++i)
{
m_output[dst] = repeat;
dst += pixel_size;
}
}
}
}
void UnpackLz (int plane, int pixel_size)
{
int dst = plane;
byte control = m_input.ReadUInt8();
int remaining = m_input.ReadInt32() - 5;
while (remaining > 0)
{
byte c = m_input.ReadUInt8();
--remaining;
if (c == control)
{
int offset = m_input.ReadUInt8();
--remaining;
if (offset != control)
{
int count = m_input.ReadUInt8();
--remaining;
if (offset > control)
--offset;
offset *= pixel_size;
while (count --> 0)
{
m_output[dst] = m_output[dst-offset];
dst += pixel_size;
}
continue;
}
}
m_output[dst] = c;
dst += pixel_size;
}
for (int i = plane + pixel_size; i < m_output.Length; i += pixel_size)
m_output[i] += m_output[i-pixel_size];
}
BitmapPalette ReadPalette ()
{
m_input.Position = m_info.PaletteOffset;
return ImageFormat.ReadPalette (m_input.AsStream);
}
#region IDisposable Members
public void Dispose ()
{
}
#endregion
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXWSTASK
{
using System;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// This scenario is designed to test operations related to creation, updating, movement, retrieving, copy and deletion of the task items with or without optional elements in the server.
/// </summary>
[TestClass]
public class S06_OperateTaskItemWithOptionalElements : TestSuiteBase
{
#region Class initialize and clean up
/// <summary>
/// Initialize the test class.
/// </summary>
/// <param name="context">Context to initialize.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
TestClassBase.Initialize(context);
}
/// <summary>
/// Clean up the test class.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test cases
/// <summary>
/// This test case is intended to validate the success response of operating task item without optional elements, returned by CreateItem and GetItem operations.
/// </summary>
[TestCategory("MSOXWSTASK"), TestMethod()]
public void MSOXWSTASK_S06_TC01_OperateTaskItemWithoutOptionalElements()
{
#region Client calls CreateItem operation to create a task item without optional elements.
// Save the ItemId of task item got from the createItem response.
ItemIdType[] createItemIds = this.CreateTasks(new TaskType());
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This create response status should be success!", null);
ItemIdType createItemId = createItemIds[0];
#endregion
#region Client calls GetItem operation to get the task item.
this.GetTasks(createItemId);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This get response status should be success!", null);
#endregion
#region Client calls UpdateItem operation to update the value of taskCompanies element of task item.
ItemIdType[] updateItemIds = this.UpdateTasks(createItemId);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This update response status should be success!", null);
ItemIdType updateItemId = updateItemIds[0];
#endregion
#region Client calls CopyItem operation to copy the created task item.
ItemIdType[] copyItemIds = this.CopyTasks(updateItemId);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This copy response status should be success!", null);
ItemIdType copyItemId = copyItemIds[0];
#endregion
#region Client calls MoveItem operation to move the task item.
ItemIdType[] moveItemIds = this.MoveTasks(updateItemId);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This move response status should be success!", null);
ItemIdType moveItemId = moveItemIds[0];
#endregion
#region Client calls DeleteItem to delete the task items created in the previous steps.
this.DeleteTasks(copyItemId, moveItemId);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This delete response status should be success!", null);
#endregion
}
/// <summary>
/// This test case is intended to validate the success response of operating task item with optional elements, returned by CreateItem and GetItem operations.
/// </summary>
[TestCategory("MSOXWSTASK"), TestMethod()]
public void MSOXWSTASK_S06_TC02_OperateTaskItemWithOptionalElements()
{
#region Client calls CreateItem operation to create a task item with optional elements.
// All the optional elements in task item are set in this method.
string subject = Common.GenerateResourceName(this.Site, "This is a task");
TaskType sentTaskItem = TestSuiteHelper.DefineTaskItem(subject, TaskStatusType.Completed);
// Save the ItemId of task item got from the createItem response.
ItemIdType[] createItemIds = this.CreateTasks(sentTaskItem);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This create response status should be success!", null);
ItemIdType createItemId = createItemIds[0];
#endregion
#region Client call GetItem operation to get the task item.
TaskType[] retrievedTaskItems = this.GetTasks(createItemId);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This get response status should be success!", null);
TaskType retrievedTaskItem = retrievedTaskItems[0];
#endregion
#region Verify the related requirements about sub-elements of TaskType
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R42");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R42
this.Site.CaptureRequirementIfAreEqual<int>(
sentTaskItem.ActualWork,
retrievedTaskItem.ActualWork,
42,
@"[In t:TaskType Complex Type] ActualWork: Specifies an integer value that specifies the actual amount of time that is spent on a task.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R44");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R44
this.Site.CaptureRequirementIfAreEqual<string>(
sentTaskItem.BillingInformation,
retrievedTaskItem.BillingInformation,
44,
@"[In t:TaskType Complex Type] BillingInformation: Specifies a string value that contains billing information for a task.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R47, Expected value:" + sentTaskItem.Companies[0].ToString() + " " + sentTaskItem.Companies[1].ToString() + "Actual value:" + retrievedTaskItem.Companies[0].ToString() + " " + retrievedTaskItem.Companies[1].ToString());
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R47
bool isVerifiedR47 = TestSuiteHelper.CompareStringArray(retrievedTaskItem.Companies, sentTaskItem.Companies);
this.Site.CaptureRequirementIfIsTrue(
isVerifiedR47,
47,
@"[In t:TaskType Complex Type] Companies: Specifies an instance of an array of type string that represents a collection of companies that are associated with a task.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R49, Expected value" + sentTaskItem.Contacts[0].ToString() + " " + sentTaskItem.Contacts[1].ToString() + "Actual value:" + retrievedTaskItem.Contacts[0].ToString() + " " + retrievedTaskItem.Contacts[1].ToString());
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R49
bool isVerifiedR49 = TestSuiteHelper.CompareStringArray(retrievedTaskItem.Contacts, sentTaskItem.Contacts);
this.Site.CaptureRequirementIfIsTrue(
isVerifiedR49,
49,
@"[In t:TaskType Complex Type] Contacts: Specifies an instance of an array of type string that contains a list of contacts that are associated with a task.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R53");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R53
this.Site.CaptureRequirementIfAreEqual<DateTime>(
sentTaskItem.DueDate.Date,
retrievedTaskItem.DueDate.Date,
53,
@"[In t:TaskType Complex Type] DueDate: Specifies an instance of the DateTime structure that represents the date when a task is due.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R58");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R58
this.Site.CaptureRequirementIfAreEqual<string>(
sentTaskItem.Mileage,
retrievedTaskItem.Mileage,
58,
@"[In t:TaskType Complex Type] Mileage: Specifies a string value that represents the mileage for a task.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R63");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R63
this.Site.CaptureRequirementIfAreEqual<DateTime>(
sentTaskItem.StartDate.Date,
retrievedTaskItem.StartDate.Date,
63,
@"[In t:TaskType Complex Type] StartDate: Specifies an instance of the DateTime structure that represents the start date of a task.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R65");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R65
this.Site.CaptureRequirementIfAreEqual<TaskStatusType>(
sentTaskItem.Status,
retrievedTaskItem.Status,
65,
@"[In t:TaskType Complex Type] Status: Specifies one of the valid TaskStatusType simple type enumeration values that represent the status of a task.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R67");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R67
this.Site.CaptureRequirementIfAreEqual<int>(
sentTaskItem.TotalWork,
retrievedTaskItem.TotalWork,
67,
@"[In t:TaskType Complex Type] TotalWork: Specifies an integer value that represents the total amount of work that is associated with a task.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R45");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R45
this.Site.CaptureRequirementIfAreEqual<int>(
sentTaskItem.ChangeCount+1,
retrievedTaskItem.ChangeCount,
45,
@"[In t:TaskType Complex Type] ChangeCount: Specifies an integer value that specifies the number of times the task has changed since it was created.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R48");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R48
this.Site.CaptureRequirementIfAreEqual<DateTime>(
sentTaskItem.CompleteDate.Date,
retrievedTaskItem.CompleteDate.Date,
48,
@"[In t:TaskType Complex Type] CompleteDate: Specifies an instance of the DateTime structure that represents the date on which a task was completed.");
#endregion
#region Client calls UpdateItem operation to update the value of taskCompanies element of task item.
ItemIdType[] updateItemIds = this.UpdateTasks(createItemId);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This update response status should be success!", null);
ItemIdType updateItemId = updateItemIds[0];
#endregion
#region Client calls CopyItem operation to copy the created task item.
ItemIdType[] copyItemIds = this.CopyTasks(updateItemId);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This copy response status should be success!", null);
ItemIdType copyItemId = copyItemIds[0];
#endregion
#region Client calls MoveItem operation to move the task item.
ItemIdType[] moveItemIds = this.MoveTasks(updateItemId);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This move response status should be success!", null);
ItemIdType moveItemId = moveItemIds[0];
#endregion
#region Client calls DeleteItem to delete the task items created in the previous steps.
this.DeleteTasks(copyItemId, moveItemId);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This delete response status should be success!", null);
#endregion
}
/// <summary>
/// This test case is intended to validate the success response of operating task item with IsComplete element.
/// </summary>
[TestCategory("MSOXWSTASK"), TestMethod()]
public void MSOXWSTASK_S06_TC03_OperateTaskItemWithIsCompleteElement()
{
#region Client calls CreateItem operation to create a task item with task Status equal to Completed.
// Save the ItemId of task item got from the createItem response.
string subject = Common.GenerateResourceName(this.Site, "This is a task");
ItemIdType[] createItemIdsFirst = this.CreateTasks(TestSuiteHelper.DefineTaskItem(subject, TaskStatusType.Completed));
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This create response status should be success!", null);
ItemIdType createItemIdFirst = createItemIdsFirst[0];
#endregion
#region Client call GetItem operation to get the task item.
TaskType[] retrievedTaskItemsFirst = this.GetTasks(createItemIdFirst);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This get response status should be success!", null);
TaskType retrievedTaskItemFirst = retrievedTaskItemsFirst[0];
#endregion
#region Verify the IsComplete element value
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R5555");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R5555
this.Site.CaptureRequirementIfIsTrue(
retrievedTaskItemFirst.IsComplete,
5555,
@"[In t:TaskType Complex Type] [IsComplete is] True, indicates a task has been completed.");
#endregion
#region Client calls CreateItem operation to create a task item with task Status equal to InProgress.
// Save the ItemId of task item got from the createItem response.
subject = Common.GenerateResourceName(this.Site, "This is a task");
ItemIdType[] createItemIdsSecond = this.CreateTasks(TestSuiteHelper.DefineTaskItem(subject, TaskStatusType.InProgress));
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This create response status should be success!", null);
ItemIdType createItemIdSecond = createItemIdsSecond[0];
#endregion
#region Client call GetItem operation to get the task item.
TaskType[] retrievedTaskItemsSecond = this.GetTasks(createItemIdSecond);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This get response status should be success!", null);
TaskType retrievedTaskItemSecond = retrievedTaskItemsSecond[0];
#endregion
#region Verify the IsComplete element value
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R5556");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R5556
this.Site.CaptureRequirementIfIsFalse(
retrievedTaskItemSecond.IsComplete,
5556,
@"[In t:TaskType Complex Type] [IsComplete is] False, indicates a task has not been completed.");
#endregion
#region Client calls DeleteItem to delete the task items created in the previous steps.
this.DeleteTasks(createItemIdFirst, createItemIdSecond);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This delete response status should be success!", null);
#endregion
}
/// <summary>
/// This test case is intended to validate the success response of operating task item with IsRecurring element.
/// </summary>
[TestCategory("MSOXWSTASK"), TestMethod()]
public void MSOXWSTASK_S06_TC04_OperateTaskItemWithIsRecurringElement()
{
#region Client calls CreateItem operation to create a task item, which is a recurring task.
// Configure the DailyRegeneratingPatternType.
TaskRecurrenceType taskRecurrence = TestSuiteHelper.GenerateTaskRecurrence(TestSuiteHelper.GenerateDailyRegeneratingPattern, TestSuiteHelper.GenerateNumberedRecurrenceRange);
// Save the ItemId of task item got from the createItem response.
string subject = Common.GenerateResourceName(this.Site, "This is a task");
ItemIdType[] createItemIdsFirst = this.CreateTasks(TestSuiteHelper.DefineTaskItem(subject, taskRecurrence));
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This create response status should be success!", null);
ItemIdType createItemIdFirst = createItemIdsFirst[0];
#endregion
#region Client call GetItem operation to get the task item.
TaskType[] retrievedTaskItemsFirst = this.GetTasks(createItemIdFirst);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This get response status should be success!", null);
TaskType retrievedTaskItemFirst = retrievedTaskItemsFirst[0];
#endregion
#region Verify the IsRecurring element value
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R5666");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R5666
this.Site.CaptureRequirementIfIsTrue(
retrievedTaskItemFirst.IsRecurring,
5666,
@"[In t:TaskType Complex Type] [IsRecurring is] True, indicates a task is part of a recurring task.");
#endregion
#region Client calls CreateItem operation to create a task item, which is not a recurring task.
// Save the ItemId of task item got from the createItem response.
subject = Common.GenerateResourceName(this.Site, "This is a task");
ItemIdType[] createItemIdsSecond = this.CreateTasks(TestSuiteHelper.DefineTaskItem(subject, null));
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This create response status should be success!", null);
ItemIdType createItemIdSecond = createItemIdsSecond[0];
#endregion
#region Client call GetItem operation to get the task item.
TaskType[] retrievedTaskItemsSecond = this.GetTasks(createItemIdSecond);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This get response status should be success!", null);
TaskType retrievedTaskItemSecond = retrievedTaskItemsSecond[0];
#endregion
#region Verify the IsRecurring element value
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSTASK_R5667");
// Verify MS-OXWSTASK requirement: MS-OXWSTASK_R5667
this.Site.CaptureRequirementIfIsFalse(
retrievedTaskItemSecond.IsRecurring,
5667,
@"[In t:TaskType Complex Type] [IsRecurring is] False, indicates a task is not part of a recurring task.");
#endregion
#region Client calls DeleteItem to delete the task items created in the previous steps.
this.DeleteTasks(createItemIdFirst, createItemIdSecond);
Site.Assert.AreEqual<ResponseClassType>(ResponseClassType.Success, (ResponseClassType)this.ResponseClass[0], "This delete response status should be success!", null);
#endregion
}
#endregion
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SchoolBusAPI.Models;
namespace SchoolBusAPI.Models
{
/// <summary>
/// A table of contacts related to various entities in the system. FK fields are used to link contacts to records in the system.
/// </summary>
[MetaDataExtension (Description = "A table of contacts related to various entities in the system. FK fields are used to link contacts to records in the system.")]
public partial class Contact : AuditableEntity, IEquatable<Contact>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public Contact()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Contact" /> class.
/// </summary>
/// <param name="Id">A system-generated unique identifier for a Contact (required).</param>
/// <param name="GivenName">The given name of the contact..</param>
/// <param name="Surname">The surname of the contact..</param>
/// <param name="OrganizationName">The organization name of the contact..</param>
/// <param name="Role">The role of the contact. UI controlled as to whether it is free form or selected from an enumerated list - for initial implementation, the field is freeform..</param>
/// <param name="Notes">A note about the contact maintained by the users..</param>
/// <param name="EmailAddress">The email address for the contact..</param>
/// <param name="WorkPhoneNumber">The work phone number for the contact..</param>
/// <param name="MobilePhoneNumber">The mobile phone number for the contact..</param>
/// <param name="FaxPhoneNumber">The fax phone number for the contact..</param>
/// <param name="Address1">Address 1 line of the address..</param>
/// <param name="Address2">Address 2 line of the address..</param>
/// <param name="City">The City of the address..</param>
/// <param name="Province">The Province of the address..</param>
/// <param name="PostalCode">The postal code of the address..</param>
public Contact(int Id, string GivenName = null, string Surname = null, string OrganizationName = null, string Role = null, string Notes = null, string EmailAddress = null, string WorkPhoneNumber = null, string MobilePhoneNumber = null, string FaxPhoneNumber = null, string Address1 = null, string Address2 = null, string City = null, string Province = null, string PostalCode = null)
{
this.Id = Id;
this.GivenName = GivenName;
this.Surname = Surname;
this.OrganizationName = OrganizationName;
this.Role = Role;
this.Notes = Notes;
this.EmailAddress = EmailAddress;
this.WorkPhoneNumber = WorkPhoneNumber;
this.MobilePhoneNumber = MobilePhoneNumber;
this.FaxPhoneNumber = FaxPhoneNumber;
this.Address1 = Address1;
this.Address2 = Address2;
this.City = City;
this.Province = Province;
this.PostalCode = PostalCode;
}
/// <summary>
/// A system-generated unique identifier for a Contact
/// </summary>
/// <value>A system-generated unique identifier for a Contact</value>
[MetaDataExtension (Description = "A system-generated unique identifier for a Contact")]
public int Id { get; set; }
/// <summary>
/// The given name of the contact.
/// </summary>
/// <value>The given name of the contact.</value>
[MetaDataExtension (Description = "The given name of the contact.")]
[MaxLength(50)]
public string GivenName { get; set; }
/// <summary>
/// The surname of the contact.
/// </summary>
/// <value>The surname of the contact.</value>
[MetaDataExtension (Description = "The surname of the contact.")]
[MaxLength(50)]
public string Surname { get; set; }
/// <summary>
/// The organization name of the contact.
/// </summary>
/// <value>The organization name of the contact.</value>
[MetaDataExtension (Description = "The organization name of the contact.")]
[MaxLength(150)]
public string OrganizationName { get; set; }
/// <summary>
/// The role of the contact. UI controlled as to whether it is free form or selected from an enumerated list - for initial implementation, the field is freeform.
/// </summary>
/// <value>The role of the contact. UI controlled as to whether it is free form or selected from an enumerated list - for initial implementation, the field is freeform.</value>
[MetaDataExtension (Description = "The role of the contact. UI controlled as to whether it is free form or selected from an enumerated list - for initial implementation, the field is freeform.")]
[MaxLength(100)]
public string Role { get; set; }
/// <summary>
/// A note about the contact maintained by the users.
/// </summary>
/// <value>A note about the contact maintained by the users.</value>
[MetaDataExtension (Description = "A note about the contact maintained by the users.")]
[MaxLength(150)]
public string Notes { get; set; }
/// <summary>
/// The email address for the contact.
/// </summary>
/// <value>The email address for the contact.</value>
[MetaDataExtension (Description = "The email address for the contact.")]
[MaxLength(255)]
public string EmailAddress { get; set; }
/// <summary>
/// The work phone number for the contact.
/// </summary>
/// <value>The work phone number for the contact.</value>
[MetaDataExtension (Description = "The work phone number for the contact.")]
[MaxLength(20)]
public string WorkPhoneNumber { get; set; }
/// <summary>
/// The mobile phone number for the contact.
/// </summary>
/// <value>The mobile phone number for the contact.</value>
[MetaDataExtension (Description = "The mobile phone number for the contact.")]
[MaxLength(20)]
public string MobilePhoneNumber { get; set; }
/// <summary>
/// The fax phone number for the contact.
/// </summary>
/// <value>The fax phone number for the contact.</value>
[MetaDataExtension (Description = "The fax phone number for the contact.")]
[MaxLength(20)]
public string FaxPhoneNumber { get; set; }
/// <summary>
/// Address 1 line of the address.
/// </summary>
/// <value>Address 1 line of the address.</value>
[MetaDataExtension (Description = "Address 1 line of the address.")]
[MaxLength(80)]
public string Address1 { get; set; }
/// <summary>
/// Address 2 line of the address.
/// </summary>
/// <value>Address 2 line of the address.</value>
[MetaDataExtension (Description = "Address 2 line of the address.")]
[MaxLength(80)]
public string Address2 { get; set; }
/// <summary>
/// The City of the address.
/// </summary>
/// <value>The City of the address.</value>
[MetaDataExtension (Description = "The City of the address.")]
[MaxLength(100)]
public string City { get; set; }
/// <summary>
/// The Province of the address.
/// </summary>
/// <value>The Province of the address.</value>
[MetaDataExtension (Description = "The Province of the address.")]
[MaxLength(50)]
public string Province { get; set; }
/// <summary>
/// The postal code of the address.
/// </summary>
/// <value>The postal code of the address.</value>
[MetaDataExtension (Description = "The postal code of the address.")]
[MaxLength(15)]
public string PostalCode { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Contact {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" GivenName: ").Append(GivenName).Append("\n");
sb.Append(" Surname: ").Append(Surname).Append("\n");
sb.Append(" OrganizationName: ").Append(OrganizationName).Append("\n");
sb.Append(" Role: ").Append(Role).Append("\n");
sb.Append(" Notes: ").Append(Notes).Append("\n");
sb.Append(" EmailAddress: ").Append(EmailAddress).Append("\n");
sb.Append(" WorkPhoneNumber: ").Append(WorkPhoneNumber).Append("\n");
sb.Append(" MobilePhoneNumber: ").Append(MobilePhoneNumber).Append("\n");
sb.Append(" FaxPhoneNumber: ").Append(FaxPhoneNumber).Append("\n");
sb.Append(" Address1: ").Append(Address1).Append("\n");
sb.Append(" Address2: ").Append(Address2).Append("\n");
sb.Append(" City: ").Append(City).Append("\n");
sb.Append(" Province: ").Append(Province).Append("\n");
sb.Append(" PostalCode: ").Append(PostalCode).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((Contact)obj);
}
/// <summary>
/// Returns true if Contact instances are equal
/// </summary>
/// <param name="other">Instance of Contact to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Contact other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.GivenName == other.GivenName ||
this.GivenName != null &&
this.GivenName.Equals(other.GivenName)
) &&
(
this.Surname == other.Surname ||
this.Surname != null &&
this.Surname.Equals(other.Surname)
) &&
(
this.OrganizationName == other.OrganizationName ||
this.OrganizationName != null &&
this.OrganizationName.Equals(other.OrganizationName)
) &&
(
this.Role == other.Role ||
this.Role != null &&
this.Role.Equals(other.Role)
) &&
(
this.Notes == other.Notes ||
this.Notes != null &&
this.Notes.Equals(other.Notes)
) &&
(
this.EmailAddress == other.EmailAddress ||
this.EmailAddress != null &&
this.EmailAddress.Equals(other.EmailAddress)
) &&
(
this.WorkPhoneNumber == other.WorkPhoneNumber ||
this.WorkPhoneNumber != null &&
this.WorkPhoneNumber.Equals(other.WorkPhoneNumber)
) &&
(
this.MobilePhoneNumber == other.MobilePhoneNumber ||
this.MobilePhoneNumber != null &&
this.MobilePhoneNumber.Equals(other.MobilePhoneNumber)
) &&
(
this.FaxPhoneNumber == other.FaxPhoneNumber ||
this.FaxPhoneNumber != null &&
this.FaxPhoneNumber.Equals(other.FaxPhoneNumber)
) &&
(
this.Address1 == other.Address1 ||
this.Address1 != null &&
this.Address1.Equals(other.Address1)
) &&
(
this.Address2 == other.Address2 ||
this.Address2 != null &&
this.Address2.Equals(other.Address2)
) &&
(
this.City == other.City ||
this.City != null &&
this.City.Equals(other.City)
) &&
(
this.Province == other.Province ||
this.Province != null &&
this.Province.Equals(other.Province)
) &&
(
this.PostalCode == other.PostalCode ||
this.PostalCode != null &&
this.PostalCode.Equals(other.PostalCode)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode(); if (this.GivenName != null)
{
hash = hash * 59 + this.GivenName.GetHashCode();
}
if (this.Surname != null)
{
hash = hash * 59 + this.Surname.GetHashCode();
}
if (this.OrganizationName != null)
{
hash = hash * 59 + this.OrganizationName.GetHashCode();
}
if (this.Role != null)
{
hash = hash * 59 + this.Role.GetHashCode();
}
if (this.Notes != null)
{
hash = hash * 59 + this.Notes.GetHashCode();
}
if (this.EmailAddress != null)
{
hash = hash * 59 + this.EmailAddress.GetHashCode();
}
if (this.WorkPhoneNumber != null)
{
hash = hash * 59 + this.WorkPhoneNumber.GetHashCode();
}
if (this.MobilePhoneNumber != null)
{
hash = hash * 59 + this.MobilePhoneNumber.GetHashCode();
}
if (this.FaxPhoneNumber != null)
{
hash = hash * 59 + this.FaxPhoneNumber.GetHashCode();
}
if (this.Address1 != null)
{
hash = hash * 59 + this.Address1.GetHashCode();
}
if (this.Address2 != null)
{
hash = hash * 59 + this.Address2.GetHashCode();
}
if (this.City != null)
{
hash = hash * 59 + this.City.GetHashCode();
}
if (this.Province != null)
{
hash = hash * 59 + this.Province.GetHashCode();
}
if (this.PostalCode != null)
{
hash = hash * 59 + this.PostalCode.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(Contact left, Contact right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(Contact left, Contact right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Impl;
using NHibernate.Linq;
using Orchard.ContentManagement.Records;
using Orchard.Data;
using NHibernate.Transform;
using NHibernate.SqlCommand;
using Orchard.Utility.Extensions;
namespace Orchard.ContentManagement {
public class DefaultContentQuery : IContentQuery {
private readonly ISessionLocator _sessionLocator;
private ISession _session;
private ICriteria _itemVersionCriteria;
private VersionOptions _versionOptions;
public DefaultContentQuery(IContentManager contentManager, ISessionLocator sessionLocator) {
_sessionLocator = sessionLocator;
ContentManager = contentManager;
}
public IContentManager ContentManager { get; private set; }
ISession BindSession() {
if (_session == null)
_session = _sessionLocator.For(typeof(ContentItemVersionRecord));
return _session;
}
ICriteria BindCriteriaByPath(ICriteria criteria, string path) {
return criteria.GetCriteriaByPath(path) ?? criteria.CreateCriteria(path);
}
ICriteria BindTypeCriteria() {
// ([ContentItemVersionRecord] >join> [ContentItemRecord]) >join> [ContentType]
return BindCriteriaByPath(BindItemCriteria(), "ContentType");
}
ICriteria BindItemCriteria() {
// [ContentItemVersionRecord] >join> [ContentItemRecord]
return BindCriteriaByPath(BindItemVersionCriteria(), "ContentItemRecord");
}
ICriteria BindItemVersionCriteria() {
if (_itemVersionCriteria == null) {
_itemVersionCriteria = BindSession().CreateCriteria<ContentItemVersionRecord>();
_itemVersionCriteria.SetCacheable(true);
}
return _itemVersionCriteria;
}
ICriteria BindPartCriteria<TRecord>() where TRecord : ContentPartRecord {
if (typeof(TRecord).IsSubclassOf(typeof(ContentPartVersionRecord))) {
return BindCriteriaByPath(BindItemVersionCriteria(), typeof(TRecord).Name);
}
return BindCriteriaByPath(BindItemCriteria(), typeof(TRecord).Name);
}
private void ForType(params string[] contentTypeNames) {
if (contentTypeNames != null && contentTypeNames.Length != 0)
BindTypeCriteria().Add(Restrictions.InG("Name", contentTypeNames));
}
public void ForVersion(VersionOptions options) {
_versionOptions = options;
}
private void Where<TRecord>() where TRecord : ContentPartRecord {
// this simply demands an inner join
BindPartCriteria<TRecord>();
}
private void Where<TRecord>(Expression<Func<TRecord, bool>> predicate) where TRecord : ContentPartRecord {
// build a linq to nhibernate expression
var options = new QueryOptions();
var queryProvider = new NHibernateQueryProvider(BindSession(), options);
var queryable = new Query<TRecord>(queryProvider, options).Where(predicate);
// translate it into the nhibernate ICriteria implementation
var criteria = (CriteriaImpl)queryProvider.TranslateExpression(queryable.Expression);
// attach the criterion from the predicate to this query's criteria for the record
var recordCriteria = BindPartCriteria<TRecord>();
foreach (var expressionEntry in criteria.IterateExpressionEntries()) {
recordCriteria.Add(expressionEntry.Criterion);
}
}
private void OrderBy<TRecord, TKey>(Expression<Func<TRecord, TKey>> keySelector) where TRecord : ContentPartRecord {
// build a linq to nhibernate expression
var options = new QueryOptions();
var queryProvider = new NHibernateQueryProvider(BindSession(), options);
var queryable = new Query<TRecord>(queryProvider, options).OrderBy(keySelector);
// translate it into the nhibernate ordering
var criteria = (CriteriaImpl)queryProvider.TranslateExpression(queryable.Expression);
// attaching orderings to the query's criteria
var recordCriteria = BindPartCriteria<TRecord>();
foreach (var ordering in criteria.IterateOrderings()) {
recordCriteria.AddOrder(ordering.Order);
}
}
private void OrderByDescending<TRecord, TKey>(Expression<Func<TRecord, TKey>> keySelector) where TRecord : ContentPartRecord {
// build a linq to nhibernate expression
var options = new QueryOptions();
var queryProvider = new NHibernateQueryProvider(BindSession(), options);
var queryable = new Query<TRecord>(queryProvider, options).OrderByDescending(keySelector);
// translate it into the nhibernate ICriteria implementation
var criteria = (CriteriaImpl)queryProvider.TranslateExpression(queryable.Expression);
// attaching orderings to the query's criteria
var recordCriteria = BindPartCriteria<TRecord>();
foreach (var ordering in criteria.IterateOrderings()) {
recordCriteria.AddOrder(ordering.Order);
}
}
private IEnumerable<ContentItem> Slice(int skip, int count) {
var criteria = BindItemVersionCriteria();
criteria.ApplyVersionOptionsRestrictions(_versionOptions);
criteria.SetFetchMode("ContentItemRecord", FetchMode.Eager);
criteria.SetFetchMode("ContentItemRecord.ContentType", FetchMode.Eager);
// TODO: put 'removed false' filter in place
if (skip != 0) {
criteria = criteria.SetFirstResult(skip);
}
if (count != 0) {
criteria = criteria.SetMaxResults(count);
}
return criteria
.List<ContentItemVersionRecord>()
.Select(x => ContentManager.Get(x.ContentItemRecord.Id, _versionOptions != null && _versionOptions.IsDraftRequired ? _versionOptions : VersionOptions.VersionRecord(x.Id)))
.ToReadOnlyCollection();
}
int Count() {
var criteria = (ICriteria)BindItemVersionCriteria().Clone();
criteria.ClearOrders();
criteria.ApplyVersionOptionsRestrictions(_versionOptions);
return criteria.SetProjection(Projections.RowCount()).UniqueResult<Int32>();
}
IContentQuery<TPart> IContentQuery.ForPart<TPart>() {
return new ContentQuery<TPart>(this);
}
class ContentQuery<T> : IContentQuery<T> where T : IContent {
protected readonly DefaultContentQuery _query;
public ContentQuery(DefaultContentQuery query) {
_query = query;
}
public IContentManager ContentManager {
get { return _query.ContentManager; }
}
IContentQuery<TPart> IContentQuery.ForPart<TPart>() {
return new ContentQuery<TPart>(_query);
}
IContentQuery<T> IContentQuery<T>.ForType(params string[] contentTypes) {
_query.ForType(contentTypes);
return this;
}
IContentQuery<T> IContentQuery<T>.ForVersion(VersionOptions options) {
_query.ForVersion(options);
return this;
}
IEnumerable<T> IContentQuery<T>.List() {
return _query.Slice(0, 0).AsPart<T>();
}
IEnumerable<T> IContentQuery<T>.Slice(int skip, int count) {
return _query.Slice(skip, count).AsPart<T>();
}
int IContentQuery<T>.Count() {
return _query.Count();
}
IContentQuery<T, TRecord> IContentQuery<T>.Join<TRecord>() {
_query.Where<TRecord>();
return new ContentQuery<T, TRecord>(_query);
}
IContentQuery<T, TRecord> IContentQuery<T>.Where<TRecord>(Expression<Func<TRecord, bool>> predicate) {
_query.Where(predicate);
return new ContentQuery<T, TRecord>(_query);
}
IContentQuery<T, TRecord> IContentQuery<T>.OrderBy<TRecord>(Expression<Func<TRecord, object>> keySelector) {
_query.OrderBy(keySelector);
return new ContentQuery<T, TRecord>(_query);
}
IContentQuery<T, TRecord> IContentQuery<T>.OrderByDescending<TRecord>(Expression<Func<TRecord, object>> keySelector) {
_query.OrderByDescending(keySelector);
return new ContentQuery<T, TRecord>(_query);
}
}
class ContentQuery<T, TR> : ContentQuery<T>, IContentQuery<T, TR>
where T : IContent
where TR : ContentPartRecord {
public ContentQuery(DefaultContentQuery query)
: base(query) {
}
IContentQuery<T, TR> IContentQuery<T, TR>.ForVersion(VersionOptions options) {
_query.ForVersion(options);
return this;
}
IContentQuery<T, TR> IContentQuery<T, TR>.Where(Expression<Func<TR, bool>> predicate) {
_query.Where(predicate);
return this;
}
IContentQuery<T, TR> IContentQuery<T, TR>.OrderBy<TKey>(Expression<Func<TR, TKey>> keySelector) {
_query.OrderBy(keySelector);
return this;
}
IContentQuery<T, TR> IContentQuery<T, TR>.OrderByDescending<TKey>(Expression<Func<TR, TKey>> keySelector) {
_query.OrderByDescending(keySelector);
return this;
}
public IContentQuery<T, TR> WithQueryHints(QueryHints hints) {
if (hints == QueryHints.Empty) {
return this;
}
var contentItemVersionCriteria = _query.BindItemVersionCriteria();
var contentItemCriteria = _query.BindItemCriteria();
var contentItemMetadata = _query._session.SessionFactory.GetClassMetadata(typeof(ContentItemRecord));
var contentItemVersionMetadata = _query._session.SessionFactory.GetClassMetadata(typeof(ContentItemVersionRecord));
// break apart and group hints by their first segment
var hintDictionary = hints.Records
.Select(hint => new { Hint = hint, Segments = hint.Split('.') })
.GroupBy(item => item.Segments.FirstOrDefault())
.ToDictionary(grouping => grouping.Key, StringComparer.InvariantCultureIgnoreCase);
// locate hints that match properties in the ContentItemVersionRecord
foreach (var hit in contentItemVersionMetadata.PropertyNames.Where(hintDictionary.ContainsKey).SelectMany(key => hintDictionary[key])) {
contentItemVersionCriteria.SetFetchMode(hit.Hint, FetchMode.Eager);
hit.Segments.Take(hit.Segments.Count() - 1).Aggregate(contentItemVersionCriteria, ExtendCriteria);
}
// locate hints that match properties in the ContentItemRecord
foreach (var hit in contentItemMetadata.PropertyNames.Where(hintDictionary.ContainsKey).SelectMany(key => hintDictionary[key])) {
contentItemVersionCriteria.SetFetchMode("ContentItemRecord." + hit.Hint, FetchMode.Eager);
hit.Segments.Take(hit.Segments.Count() - 1).Aggregate(contentItemCriteria, ExtendCriteria);
}
if (hintDictionary.SelectMany(x => x.Value).Any(x => x.Segments.Count() > 1))
contentItemVersionCriteria.SetResultTransformer(new DistinctRootEntityResultTransformer());
return this;
}
private static ICriteria ExtendCriteria(ICriteria criteria, string segment) {
return criteria.GetCriteriaByPath(segment) ?? criteria.CreateCriteria(segment, JoinType.LeftOuterJoin);
}
public IContentQuery<T, TR> WithQueryHintsFor(string contentType) {
var contentItem = _query.ContentManager.New(contentType);
var contentPartRecords = new List<string>();
foreach (var part in contentItem.Parts) {
var partType = part.GetType().BaseType;
if (partType.IsGenericType && partType.GetGenericTypeDefinition() == typeof(ContentPart<>)) {
var recordType = partType.GetGenericArguments().Single();
contentPartRecords.Add(recordType.Name);
}
}
return WithQueryHints(new QueryHints().ExpandRecords(contentPartRecords));
}
}
}
internal static class CriteriaExtensions {
internal static void ApplyVersionOptionsRestrictions(this ICriteria criteria, VersionOptions versionOptions) {
if (versionOptions == null) {
criteria.Add(Restrictions.Eq("Published", true));
}
else if (versionOptions.IsPublished) {
criteria.Add(Restrictions.Eq("Published", true));
}
else if (versionOptions.IsLatest) {
criteria.Add(Restrictions.Eq("Latest", true));
}
else if (versionOptions.IsDraft && !versionOptions.IsDraftRequired) {
criteria.Add(Restrictions.And(
Restrictions.Eq("Latest", true),
Restrictions.Eq("Published", false)));
}
else if (versionOptions.IsDraft || versionOptions.IsDraftRequired) {
criteria.Add(Restrictions.Eq("Latest", true));
}
else if (versionOptions.IsAllVersions) {
// no-op... all versions will be returned by default
}
else {
throw new ApplicationException("Invalid VersionOptions for content query");
}
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
public class PresenceModule : IRegionModule, IPresenceModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
private bool m_Gridmode = false;
private List<Scene> m_Scenes = new List<Scene>();
// we currently are only interested in root-agents. If the root isn't here, we don't know the region the
// user is in, so we have to ask the messaging server anyway.
private Dictionary<UUID, Scene> m_RootAgents =
new Dictionary<UUID, Scene>();
public event PresenceChange OnPresenceChange;
public event BulkPresenceData OnBulkPresenceData;
public void Initialize(Scene scene, IConfigSource config)
{
lock (m_Scenes)
{
// This is a shared module; Initialize will be called for every region on this server.
// Only check config once for the first region.
if (m_Scenes.Count == 0)
{
IConfig cnf = config.Configs["Messaging"];
if (cnf != null && cnf.GetString(
"PresenceModule", "PresenceModule") !=
"PresenceModule")
return;
cnf = config.Configs["Startup"];
if (cnf != null)
m_Gridmode = cnf.GetBoolean("gridmode", false);
m_Enabled = true;
}
if (m_Gridmode)
NotifyMessageServerOfStartup(scene);
m_Scenes.Add(scene);
}
scene.RegisterModuleInterface<IPresenceModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnSetRootAgentScene += OnSetRootAgentScene;
scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
}
public void PostInitialize()
{
}
public void Close()
{
if (!m_Gridmode || !m_Enabled)
return;
if (OnPresenceChange != null)
{
lock (m_RootAgents)
{
// on shutdown, users are kicked, too
foreach (KeyValuePair<UUID, Scene> pair in m_RootAgents)
{
OnPresenceChange(new PresenceInfo(pair.Key, UUID.Zero));
}
}
}
lock (m_Scenes)
{
foreach (Scene scene in m_Scenes)
NotifyMessageServerOfShutdown(scene);
}
}
public string Name
{
get { return "PresenceModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
// new client doesn't mean necessarily that user logged in, it just means it entered one of the
// the regions on this server
public void OnNewClient(IClientAPI client)
{
client.OnConnectionClosed += OnConnectionClosed;
client.OnLogout += OnLogout;
// KLUDGE: See handler for details.
client.OnEconomyDataRequest += OnEconomyDataRequest;
}
// connection closed just means *one* client connection has been closed. It doesn't mean that the
// user has logged off; it might have just TPed away.
public void OnConnectionClosed(IClientAPI client)
{
// TODO: Have to think what we have to do here...
// Should we just remove the root from the list (if scene matches)?
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)client.Scene;
lock (m_RootAgents)
{
Scene rootScene;
if (!(m_RootAgents.TryGetValue(client.AgentId, out rootScene)) || scene != rootScene)
return;
m_RootAgents.Remove(client.AgentId);
}
// Should it have logged off, we'll do the logout part in OnLogout, even if no root is stored
// anymore. It logged off, after all...
}
// Triggered when the user logs off.
public void OnLogout(IClientAPI client)
{
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)client.Scene;
// On logout, we really remove the client from rootAgents, even if the scene doesn't match
lock (m_RootAgents)
{
if (m_RootAgents.ContainsKey(client.AgentId)) m_RootAgents.Remove(client.AgentId);
}
// now inform the messaging server and anyone who is interested
NotifyMessageServerOfAgentLeaving(client.AgentId, scene.RegionInfo.RegionID, scene.RegionInfo.RegionHandle);
if (OnPresenceChange != null) OnPresenceChange(new PresenceInfo(client.AgentId, UUID.Zero));
}
public void OnSetRootAgentScene(UUID agentID, Scene scene)
{
// OnSetRootAgentScene can be called from several threads at once (with different agentID).
// Concurrent access to m_RootAgents is prone to failure on multi-core/-processor systems without
// correct locking).
lock (m_RootAgents)
{
Scene rootScene;
if (m_RootAgents.TryGetValue(agentID, out rootScene) && scene == rootScene)
{
return;
}
m_RootAgents[agentID] = scene;
}
Util.FireAndForget(delegate(object obj)
{
// inform messaging server that agent changed the region
NotifyMessageServerOfAgentLocation(agentID, scene.RegionInfo.RegionID, scene.RegionInfo.RegionHandle);
});
}
private void OnEconomyDataRequest(IClientAPI client, UUID agentID)
{
// KLUDGE: This is the only way I found to get a message (only) after login was completed and the
// client is connected enough to receive UDP packets.
// This packet seems to be sent only once, just after connection was established to the first
// region after login.
// We use it here to trigger a presence update; the old update-on-login was never be heard by
// the freshly logged in viewer, as it wasn't connected to the region at that time.
// TODO: Feel free to replace this by a better solution if you find one.
// get the agent. This should work every time, as we just got a packet from it
ScenePresence agent = null;
lock (m_Scenes)
{
foreach (Scene scene in m_Scenes)
{
agent = scene.GetScenePresence(agentID);
if (agent != null) break;
}
}
// just to be paranoid...
if (agent == null)
{
m_log.ErrorFormat("[PRESENCE]: Got a packet from agent {0} who can't be found anymore!?", agentID);
return;
}
// we are a bit premature here, but the next packet will switch this child agent to root.
if (OnPresenceChange != null) OnPresenceChange(new PresenceInfo(agentID, agent.Scene.RegionInfo.RegionID));
}
public void OnMakeChildAgent(ScenePresence agent)
{
// OnMakeChildAgent can be called from several threads at once (with different agent).
// Concurrent access to m_RootAgents is prone to failure on multi-core/-processor systems without
// correct locking).
lock (m_RootAgents)
{
Scene rootScene;
if (m_RootAgents.TryGetValue(agent.UUID, out rootScene) && agent.Scene == rootScene)
{
m_RootAgents.Remove(agent.UUID);
}
}
// don't notify the messaging-server; either this agent just had been downgraded and another one will be upgraded
// to root momentarily (which will notify the messaging-server), or possibly it will be closed in a moment,
// which will update the messaging-server, too.
}
private void NotifyMessageServerOfStartup(Scene scene)
{
Hashtable xmlrpcdata = new Hashtable();
xmlrpcdata["RegionUUID"] = scene.RegionInfo.RegionID.ToString();
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
try
{
string methodName = "region_startup";
XmlRpcRequest UpRequest = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse resp = UpRequest.Send(Util.XmlRpcRequestURI(scene.CommsManager.NetworkServersInfo.MessagingURL, methodName), 5000);
Hashtable responseData = (Hashtable)resp.Value;
if (responseData == null || (!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region startup for region {0}", scene.RegionInfo.RegionName);
}
}
catch (WebException)
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region startup for region {0}", scene.RegionInfo.RegionName);
}
}
private void NotifyMessageServerOfShutdown(Scene scene)
{
Hashtable xmlrpcdata = new Hashtable();
xmlrpcdata["RegionUUID"] = scene.RegionInfo.RegionID.ToString();
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
try
{
string methodName = "region_shutdown";
XmlRpcRequest DownRequest = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse resp = DownRequest.Send(Util.XmlRpcRequestURI(scene.CommsManager.NetworkServersInfo.MessagingURL, methodName), 5000);
Hashtable responseData = (Hashtable)resp.Value;
if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region shutdown for region {0}", scene.RegionInfo.RegionName);
}
}
catch (WebException)
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region shutdown for region {0}", scene.RegionInfo.RegionName);
}
}
private void NotifyMessageServerOfAgentLocation(UUID agentID, UUID region, ulong regionHandle)
{
Hashtable xmlrpcdata = new Hashtable();
xmlrpcdata["AgentID"] = agentID.ToString();
xmlrpcdata["RegionUUID"] = region.ToString();
xmlrpcdata["RegionHandle"] = regionHandle.ToString();
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
try
{
string methodName = "agent_location";
XmlRpcRequest LocationRequest = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse resp = LocationRequest.Send(Util.XmlRpcRequestURI(m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL, methodName), 5000);
Hashtable responseData = (Hashtable)resp.Value;
if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent location for {0}", agentID.ToString());
}
}
catch (WebException)
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent location for {0}", agentID.ToString());
}
}
private void NotifyMessageServerOfAgentLeaving(UUID agentID, UUID region, ulong regionHandle)
{
Hashtable xmlrpcdata = new Hashtable();
xmlrpcdata["AgentID"] = agentID.ToString();
xmlrpcdata["RegionUUID"] = region.ToString();
xmlrpcdata["RegionHandle"] = regionHandle.ToString();
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
try
{
string methodName = "agent_leaving";
XmlRpcRequest LeavingRequest = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse resp = LeavingRequest.Send(Util.XmlRpcRequestURI(m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL, methodName), 5000);
Hashtable responseData = (Hashtable)resp.Value;
if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent leaving for {0}", agentID.ToString());
}
}
catch (WebException)
{
m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent leaving for {0}", agentID.ToString());
}
}
}
}
| |
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 SSCompService.Areas.HelpPage.ModelDescriptions;
using SSCompService.Areas.HelpPage.Models;
namespace SSCompService.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 ClosedXML.Excel;
using ClosedXML.Excel.Drawings;
using NUnit.Framework;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
namespace ClosedXML.Tests
{
[TestFixture]
public class XLWorksheetTests
{
private readonly static char[] illegalWorksheetCharacters = "\u0000\u0003:\\/?*[]".ToCharArray();
[Test]
public void ColumnCountTime()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
DateTime start = DateTime.Now;
ws.ColumnCount();
DateTime end = DateTime.Now;
Assert.IsTrue((end - start).TotalMilliseconds < 500);
}
[Test]
public void CopyConditionalFormatsCount()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.AddWorksheet("Sheet1");
ws.Range("A1:C3").AddConditionalFormat().WhenContains("1").Fill.SetBackgroundColor(XLColor.Blue);
ws.Range("A1:C3").Value = 1;
IXLWorksheet ws2 = ws.CopyTo("Sheet2");
Assert.AreEqual(1, ws2.ConditionalFormats.Count());
}
[Test]
public void CopyColumnVisibility()
{
var wb = new XLWorkbook();
var ws = wb.AddWorksheet("Sheet1");
ws.Columns(10, 20).Hide();
ws.CopyTo("Sheet2");
Assert.IsTrue(wb.Worksheet("Sheet2").Column(10).IsHidden);
}
[Test]
public void CopyRowVisibility()
{
var wb = new XLWorkbook();
var ws = wb.AddWorksheet("Sheet1");
ws.Rows(2, 5).Hide();
ws.CopyTo("Sheet2");
Assert.IsTrue(wb.Worksheet("Sheet2").Row(4).IsHidden);
}
[Test]
public void DeletingSheets1()
{
var wb = new XLWorkbook();
wb.Worksheets.Add("Sheet3");
wb.Worksheets.Add("Sheet2");
wb.Worksheets.Add("Sheet1", 1);
wb.Worksheet("Sheet3").Delete();
Assert.AreEqual("Sheet1", wb.Worksheet(1).Name);
Assert.AreEqual("Sheet2", wb.Worksheet(2).Name);
Assert.AreEqual(2, wb.Worksheets.Count);
}
[Test]
public void InsertingSheets1()
{
var wb = new XLWorkbook();
wb.Worksheets.Add("Sheet1");
wb.Worksheets.Add("Sheet2");
wb.Worksheets.Add("Sheet3");
Assert.AreEqual("Sheet1", wb.Worksheet(1).Name);
Assert.AreEqual("Sheet2", wb.Worksheet(2).Name);
Assert.AreEqual("Sheet3", wb.Worksheet(3).Name);
}
[Test]
public void InsertingSheets2()
{
var wb = new XLWorkbook();
wb.Worksheets.Add("Sheet2");
wb.Worksheets.Add("Sheet1", 1);
wb.Worksheets.Add("Sheet3");
Assert.AreEqual("Sheet1", wb.Worksheet(1).Name);
Assert.AreEqual("Sheet2", wb.Worksheet(2).Name);
Assert.AreEqual("Sheet3", wb.Worksheet(3).Name);
}
[Test]
public void InsertingSheets3()
{
var wb = new XLWorkbook();
wb.Worksheets.Add("Sheet3");
wb.Worksheets.Add("Sheet2", 1);
wb.Worksheets.Add("Sheet1", 1);
Assert.AreEqual("Sheet1", wb.Worksheet(1).Name);
Assert.AreEqual("Sheet2", wb.Worksheet(2).Name);
Assert.AreEqual("Sheet3", wb.Worksheet(3).Name);
}
[Test]
public void InsertingSheets4()
{
var wb = new XLWorkbook();
var ws1 = wb.Worksheets.Add();
Assert.AreEqual("Sheet1", ws1.Name);
ws1.Name = "shEEt1";
var ws2 = wb.Worksheets.Add();
Assert.AreEqual("Sheet2", ws2.Name);
wb.Worksheets.Add("SHEET4");
Assert.AreEqual("Sheet5", wb.Worksheets.Add().Name);
Assert.AreEqual("Sheet6", wb.Worksheets.Add().Name);
wb.Worksheets.Add(1);
Assert.AreEqual("Sheet7", wb.Worksheet(1).Name);
}
[Test]
public void AddingDuplicateSheetNameThrowsException()
{
using (var wb = new XLWorkbook())
{
IXLWorksheet ws;
ws = wb.AddWorksheet("Sheet1");
Assert.Throws<ArgumentException>(() => wb.AddWorksheet("Sheet1"));
//Sheet names are case insensitive
Assert.Throws<ArgumentException>(() => wb.AddWorksheet("sheet1"));
}
}
[Test]
public void MergedRanges()
{
IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1");
ws.Range("A1:B2").Merge();
ws.Range("C1:D3").Merge();
ws.Range("D2:E2").Merge();
Assert.AreEqual(2, ws.MergedRanges.Count);
Assert.AreEqual("A1:B2", ws.MergedRanges.First().RangeAddress.ToStringRelative());
Assert.AreEqual("D2:E2", ws.MergedRanges.Last().RangeAddress.ToStringRelative());
Assert.AreEqual("A1:B2", ws.Cell("A2").MergedRange().RangeAddress.ToStringRelative());
Assert.AreEqual("D2:E2", ws.Cell("D2").MergedRange().RangeAddress.ToStringRelative());
Assert.AreEqual(null, ws.Cell("Z10").MergedRange());
}
[Test]
public void RowCountTime()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
DateTime start = DateTime.Now;
ws.RowCount();
DateTime end = DateTime.Now;
Assert.IsTrue((end - start).TotalMilliseconds < 500);
}
[Test]
public void SheetsWithCommas()
{
using (var wb = new XLWorkbook())
{
var sourceSheetName = "Sheet1, Sheet3";
var ws = wb.Worksheets.Add(sourceSheetName);
ws.Cell("A1").Value = 1;
ws.Cell("A2").Value = 2;
ws.Cell("B2").Value = 3;
ws = wb.Worksheets.Add("Formula");
ws.FirstCell().FormulaA1 = string.Format("=SUM('{0}'!A1:A2,'{0}'!B1:B2)", sourceSheetName);
var value = ws.FirstCell().Value;
Assert.AreEqual(6, value);
}
}
[Test]
public void CanRenameWorksheet()
{
using (var wb = new XLWorkbook())
{
var ws1 = wb.AddWorksheet("Sheet1");
var ws2 = wb.AddWorksheet("Sheet2");
ws1.Name = "New sheet name";
Assert.AreEqual("New sheet name", ws1.Name);
ws2.Name = "sheet2";
Assert.AreEqual("sheet2", ws2.Name);
Assert.Throws<ArgumentException>(() => ws1.Name = "SHEET2");
}
}
[Test]
public void TryGetWorksheet()
{
using (var wb = new XLWorkbook())
{
wb.AddWorksheet("Sheet1");
wb.AddWorksheet("Sheet2");
IXLWorksheet ws;
Assert.IsTrue(wb.Worksheets.TryGetWorksheet("Sheet1", out ws));
Assert.IsTrue(wb.Worksheets.TryGetWorksheet("sheet1", out ws));
Assert.IsTrue(wb.Worksheets.TryGetWorksheet("sHEeT1", out ws));
Assert.IsFalse(wb.Worksheets.TryGetWorksheet("Sheeeet2", out ws));
Assert.IsTrue(wb.TryGetWorksheet("Sheet1", out ws));
Assert.IsTrue(wb.TryGetWorksheet("sheet1", out ws));
Assert.IsTrue(wb.TryGetWorksheet("sHEeT1", out ws));
Assert.IsFalse(wb.TryGetWorksheet("Sheeeet2", out ws));
}
}
[Test]
public void HideWorksheet()
{
using (var ms = new MemoryStream())
{
using (var wb = new XLWorkbook())
{
wb.Worksheets.Add("VisibleSheet");
wb.Worksheets.Add("HiddenSheet").Hide();
wb.SaveAs(ms);
}
// unhide the hidden sheet
using (var wb = new XLWorkbook(ms))
{
Assert.AreEqual(XLWorksheetVisibility.Visible, wb.Worksheet("VisibleSheet").Visibility);
Assert.AreEqual(XLWorksheetVisibility.Hidden, wb.Worksheet("HiddenSheet").Visibility);
var ws = wb.Worksheet("HiddenSheet");
ws.Unhide().Name = "NoAlsoVisible";
Assert.AreEqual(XLWorksheetVisibility.Visible, ws.Visibility);
wb.Save();
}
using (var wb = new XLWorkbook(ms))
{
Assert.AreEqual(XLWorksheetVisibility.Visible, wb.Worksheet("VisibleSheet").Visibility);
Assert.AreEqual(XLWorksheetVisibility.Visible, wb.Worksheet("NoAlsoVisible").Visibility);
}
}
}
[Test]
public void CanCopySheetsWithAllAnchorTypes()
{
using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageAnchors.xlsx")))
using (var wb = new XLWorkbook(stream))
{
var ws = wb.Worksheets.First();
ws.CopyTo("Copy1");
var ws2 = wb.Worksheets.Skip(1).First();
ws2.CopyTo("Copy2");
var ws3 = wb.Worksheets.Skip(2).First();
ws3.CopyTo("Copy3");
var ws4 = wb.Worksheets.Skip(3).First();
ws3.CopyTo("Copy4");
}
}
[Test]
public void CannotCopyDeletedWorksheet()
{
using (var wb = new XLWorkbook())
{
wb.AddWorksheet("Sheet1");
var ws = wb.AddWorksheet("Sheet2");
ws.Delete();
Assert.Throws<InvalidOperationException>(() => ws.CopyTo("Copy of Sheet2"));
}
}
[Test]
public void WorksheetNameCannotStartWithApostrophe()
{
var title = "'StartsWithApostrophe";
TestDelegate addWorksheet = () =>
{
using (var wb = new XLWorkbook())
{
wb.Worksheets.Add(title);
}
};
Assert.Throws(typeof(ArgumentException), addWorksheet);
}
[Test]
public void WorksheetNameCannotEndWithApostrophe()
{
var title = "EndsWithApostrophe'";
TestDelegate addWorksheet = () =>
{
using (var wb = new XLWorkbook())
{
wb.Worksheets.Add(title);
}
};
Assert.Throws(typeof(ArgumentException), addWorksheet);
}
[Test]
public void WorksheetNameCannotBeEmpty()
{
Assert.Throws<ArgumentException>(() => new XLWorkbook().AddWorksheet(" "));
}
[TestCaseSource(nameof(illegalWorksheetCharacters))]
public void WorksheetNameCannotContainIllegalCharacters(char c)
{
var proposedName = $"Sheet{c}Name";
Assert.Throws<ArgumentException>(() => new XLWorkbook().AddWorksheet(proposedName));
}
[Test]
public void WorksheetNameCanContainApostrophe()
{
var title = "With'Apostrophe";
var savedTitle = "";
TestDelegate saveAndOpenWorkbook = () =>
{
using (var ms = new MemoryStream())
{
using (var wb = new XLWorkbook())
{
wb.Worksheets.Add(title);
wb.Worksheets.First().Cell(1, 1).FormulaA1 = $"{title}!A2";
wb.SaveAs(ms);
}
using (var wb = new XLWorkbook(ms))
{
savedTitle = wb.Worksheets.First().Name;
}
}
};
Assert.DoesNotThrow(saveAndOpenWorkbook);
Assert.AreEqual(title, savedTitle);
}
[Test]
public void CopyWorksheetPreservesContents()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Cell("A1").Value = "A1 value";
ws1.Cell("A2").Value = 100;
ws1.Cell("D4").Value = new DateTime(2018, 5, 1);
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual("A1 value", ws2.Cell("A1").Value);
Assert.AreEqual(100, ws2.Cell("A2").Value);
Assert.AreEqual(new DateTime(2018, 5, 1), ws2.Cell("D4").Value);
}
}
[Test]
public void CopyWorksheetPreservesFormulae()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Cell("A1").FormulaA1 = "10*10";
ws1.Cell("A2").FormulaA1 = "A1 * 2";
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual("10*10", ws2.Cell("A1").FormulaA1);
Assert.AreEqual("A1 * 2", ws2.Cell("A2").FormulaA1);
}
}
[Test]
public void CopyWorksheetPreservesRowHeights()
{
using (var wb1 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
using (var wb2 = new XLWorkbook())
{
ws1.RowHeight = 55;
ws1.Row(2).Height = 0;
ws1.Row(3).Height = 20;
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.RowHeight, ws2.RowHeight);
for (int i = 1; i <= 3; i++)
{
Assert.AreEqual(ws1.Row(i).Height, ws2.Row(i).Height);
}
}
}
}
[Test]
public void CopyWorksheetPreservesColumnWidths()
{
using (var wb1 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
using (var wb2 = new XLWorkbook())
{
ws1.ColumnWidth = 160;
ws1.Column(2).Width = 0;
ws1.Column(3).Width = 240;
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.ColumnWidth, ws2.ColumnWidth);
for (int i = 1; i <= 3; i++)
{
Assert.AreEqual(ws1.Column(i).Width, ws2.Column(i).Width);
}
}
}
}
[Test]
public void CopyWorksheetPreservesMergedCells()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Range("A:A").Merge();
ws1.Range("B1:C2").Merge();
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.MergedRanges.Count, ws2.MergedRanges.Count);
for (int i = 0; i < ws1.MergedRanges.Count; i++)
{
Assert.AreEqual(ws1.MergedRanges.ElementAt(i).RangeAddress.ToString(),
ws2.MergedRanges.ElementAt(i).RangeAddress.ToString());
}
}
}
[Test]
public void CopyWorksheetAcrossWorkbooksPreservesNamedRanges()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Range("A1:A2").AddToNamed("GLOBAL", XLScope.Workbook);
ws1.Ranges("B1:B2,D1:D2").AddToNamed("LOCAL", XLScope.Worksheet);
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.NamedRanges.Count(), ws2.NamedRanges.Count());
for (int i = 0; i < ws1.NamedRanges.Count(); i++)
{
var nr1 = ws1.NamedRanges.ElementAt(i);
var nr2 = ws2.NamedRanges.ElementAt(i);
Assert.AreEqual(nr1.Ranges.ToString(), nr2.Ranges.ToString());
Assert.AreEqual(nr1.Scope, nr2.Scope);
Assert.AreEqual(nr1.Name, nr2.Name);
Assert.AreEqual(nr1.Visible, nr2.Visible);
Assert.AreEqual(nr1.Comment, nr2.Comment);
}
}
}
[Test]
public void CopyWorksheeInsideWorkbookMakesNamedRangesLocal()
{
using (var wb1 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Range("A1:A2").AddToNamed("GLOBAL", XLScope.Workbook);
ws1.Ranges("B1:B2,D1:D2").AddToNamed("LOCAL", XLScope.Worksheet);
var ws2 = ws1.CopyTo("Copy");
Assert.AreEqual(ws1.NamedRanges.Count(), ws2.NamedRanges.Count());
for (int i = 0; i < ws1.NamedRanges.Count(); i++)
{
var nr1 = ws1.NamedRanges.ElementAt(i);
var nr2 = ws2.NamedRanges.ElementAt(i);
Assert.AreEqual(XLScope.Worksheet, nr2.Scope);
Assert.AreEqual(nr1.Ranges.ToString(), nr2.Ranges.ToString());
Assert.AreEqual(nr1.Name, nr2.Name);
Assert.AreEqual(nr1.Visible, nr2.Visible);
Assert.AreEqual(nr1.Comment, nr2.Comment);
}
}
}
[Test]
public void CopyWorksheetPreservesStyles()
{
using (var ms = new MemoryStream())
using (var wb1 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws1.Range("A1:B2").Style.Font.FontSize = 25;
ws1.Cell("C3").Style.Fill.BackgroundColor = XLColor.Red;
ws1.Cell("C4").Style.Fill.BackgroundColor = XLColor.AliceBlue;
ws1.Cell("C4").Value = "Non empty";
using (var wb2 = new XLWorkbook())
{
var ws2 = ws1.CopyTo(wb2, "Copy");
AssertStylesAreEqual(ws1, ws2);
wb2.SaveAs(ms);
}
using (var wb2 = new XLWorkbook(ms))
{
var ws2 = wb2.Worksheet("Copy");
AssertStylesAreEqual(ws1, ws2);
}
}
void AssertStylesAreEqual(IXLWorksheet ws1, IXLWorksheet ws2)
{
Assert.AreEqual((ws1.Style as XLStyle).Value, (ws2.Style as XLStyle).Value,
"Worksheet styles differ");
var cellsUsed = ws1.Range(ws1.FirstCell(), ws1.LastCellUsed()).Cells();
foreach (var cell in cellsUsed)
{
var style1 = (cell.Style as XLStyle).Value;
var style2 = (ws2.Cell(cell.Address.ToString()).Style as XLStyle).Value;
Assert.AreEqual(style1, style2, $"Cell {cell.Address} styles differ");
}
}
}
[Test]
public void CopyWorksheetPreservesConditionalFormats()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Range("A:A").AddConditionalFormat()
.WhenContains("0").Fill.SetBackgroundColor(XLColor.Red);
var cf = ws1.Range("B1:C2").AddConditionalFormat();
cf.Ranges.Add(ws1.Range("D4:D5"));
cf.WhenEqualOrGreaterThan(100).Font.SetBold();
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.ConditionalFormats.Count(), ws2.ConditionalFormats.Count());
for (int i = 0; i < ws1.ConditionalFormats.Count(); i++)
{
var original = ws1.ConditionalFormats.ElementAt(i);
var copy = ws2.ConditionalFormats.ElementAt(i);
Assert.AreEqual(original.Ranges.Count, copy.Ranges.Count);
for (int j = 0; j < original.Ranges.Count; j++)
{
Assert.AreEqual(original.Ranges.ElementAt(j).RangeAddress.ToString(XLReferenceStyle.A1, false),
copy.Ranges.ElementAt(j).RangeAddress.ToString(XLReferenceStyle.A1, false));
}
Assert.AreEqual((original.Style as XLStyle).Value, (copy.Style as XLStyle).Value);
Assert.AreEqual(original.Values.Single().Value.Value, copy.Values.Single().Value.Value);
}
}
}
[Test]
public void CopyWorksheetPreservesTables()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Cell("A2").Value = "Name";
ws1.Cell("B2").Value = "Count";
ws1.Cell("A3").Value = "John Smith";
ws1.Cell("B3").Value = 50;
ws1.Cell("A4").Value = "Ivan Ivanov";
ws1.Cell("B4").Value = 40;
var table1 = ws1.Range("A2:B4").CreateTable("Test table 1");
table1
.SetShowAutoFilter(true)
.SetShowTotalsRow(true)
.SetEmphasizeFirstColumn(true)
.SetShowColumnStripes(true)
.SetShowRowStripes(true);
table1.Theme = XLTableTheme.TableStyleDark8;
table1.Field(1).TotalsRowFunction = XLTotalsRowFunction.Sum;
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.Tables.Count(), ws2.Tables.Count());
for (int i = 0; i < ws1.Tables.Count(); i++)
{
var original = ws1.Tables.ElementAt(i);
var copy = ws2.Tables.ElementAt(i);
Assert.AreEqual(original.RangeAddress.ToString(XLReferenceStyle.A1, false), copy.RangeAddress.ToString(XLReferenceStyle.A1, false));
Assert.AreEqual(original.Fields.Count(), copy.Fields.Count());
for (int j = 0; j < original.Fields.Count(); j++)
{
var originalField = original.Fields.ElementAt(j);
var copyField = copy.Fields.ElementAt(j);
Assert.AreEqual(originalField.Name, copyField.Name);
Assert.AreEqual(originalField.TotalsRowFormulaA1, copyField.TotalsRowFormulaA1);
Assert.AreEqual(originalField.TotalsRowFunction, copyField.TotalsRowFunction);
}
Assert.AreEqual(original.Name, copy.Name);
Assert.AreEqual(original.ShowAutoFilter, copy.ShowAutoFilter);
Assert.AreEqual(original.ShowColumnStripes, copy.ShowColumnStripes);
Assert.AreEqual(original.ShowHeaderRow, copy.ShowHeaderRow);
Assert.AreEqual(original.ShowRowStripes, copy.ShowRowStripes);
Assert.AreEqual(original.ShowTotalsRow, copy.ShowTotalsRow);
Assert.AreEqual((original.Style as XLStyle).Value, (copy.Style as XLStyle).Value);
Assert.AreEqual(original.Theme, copy.Theme);
}
}
}
[Test]
public void CopyWorksheetPreservesDataValidation()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
var dv1 = ws1.Range("A:A").CreateDataValidation();
dv1.WholeNumber.EqualTo(2);
dv1.ErrorStyle = XLErrorStyle.Warning;
dv1.ErrorTitle = "Number out of range";
dv1.ErrorMessage = "This cell only allows the number 2.";
var dv2 = ws1.Ranges("B2:C3,D4:E5").CreateDataValidation();
dv2.Decimal.GreaterThan(5);
dv2.ErrorStyle = XLErrorStyle.Stop;
dv2.ErrorTitle = "Decimal number out of range";
dv2.ErrorMessage = "This cell only allows decimals greater than 5.";
var dv3 = ws1.Cell("D1").CreateDataValidation();
dv3.TextLength.EqualOrLessThan(10);
dv3.ErrorStyle = XLErrorStyle.Information;
dv3.ErrorTitle = "Text length out of range";
dv3.ErrorMessage = "You entered more than 10 characters.";
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.DataValidations.Count(), ws2.DataValidations.Count());
for (int i = 0; i < ws1.DataValidations.Count(); i++)
{
var original = ws1.DataValidations.ElementAt(i);
var copy = ws2.DataValidations.ElementAt(i);
var originalRanges = string.Join(",", original.Ranges.Select(r => r.RangeAddress.ToString()));
var copyRanges = string.Join(",", original.Ranges.Select(r => r.RangeAddress.ToString()));
Assert.AreEqual(originalRanges, copyRanges);
Assert.AreEqual(original.AllowedValues, copy.AllowedValues);
Assert.AreEqual(original.Operator, copy.Operator);
Assert.AreEqual(original.ErrorStyle, copy.ErrorStyle);
Assert.AreEqual(original.ErrorTitle, copy.ErrorTitle);
Assert.AreEqual(original.ErrorMessage, copy.ErrorMessage);
}
}
}
[Test]
public void CopyWorksheetPreservesPictures()
{
using (var ms = new MemoryStream())
using (var resourceStream = Assembly.GetAssembly(typeof(ClosedXML.Examples.BasicTable))
.GetManifestResourceStream("ClosedXML.Examples.Resources.SampleImage.jpg"))
using (var bitmap = Bitmap.FromStream(resourceStream) as Bitmap)
using (var wb1 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
var picture = ws1.AddPicture(bitmap, "MyPicture")
.WithPlacement(XLPicturePlacement.FreeFloating)
.MoveTo(50, 50)
.WithSize(200, 200);
using (var wb2 = new XLWorkbook())
{
var ws2 = ws1.CopyTo(wb2, "Copy");
AssertPicturesAreEqual(ws1, ws2);
wb2.SaveAs(ms);
}
using (var wb2 = new XLWorkbook(ms))
{
var ws2 = wb2.Worksheet("Copy");
AssertPicturesAreEqual(ws1, ws2);
}
}
void AssertPicturesAreEqual(IXLWorksheet ws1, IXLWorksheet ws2)
{
Assert.AreEqual(ws1.Pictures.Count(), ws2.Pictures.Count());
for (int i = 0; i < ws1.Pictures.Count(); i++)
{
var original = ws1.Pictures.ElementAt(i);
var copy = ws2.Pictures.ElementAt(i);
Assert.AreEqual(ws2, copy.Worksheet);
Assert.AreEqual(original.Format, copy.Format);
Assert.AreEqual(original.Height, copy.Height);
Assert.AreEqual(original.Id, copy.Id);
Assert.AreEqual(original.Left, copy.Left);
Assert.AreEqual(original.Name, copy.Name);
Assert.AreEqual(original.Placement, copy.Placement);
Assert.AreEqual(original.Top, copy.Top);
Assert.AreEqual(original.TopLeftCell.Address.ToString(), copy.TopLeftCell.Address.ToString());
Assert.AreEqual(original.Width, copy.Width);
Assert.AreEqual(original.ImageStream.ToArray(), copy.ImageStream.ToArray(), "Image streams differ");
}
}
}
[Test]
public void CopyWorksheetPreservesPivotTables()
{
using (var ms = new MemoryStream())
using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\PivotTables\PivotTables.xlsx")))
using (var wb = new XLWorkbook(stream))
{
var ws1 = wb.Worksheet("pvt1");
var copyOfws1 = ws1.CopyTo("CopyOfPvt1");
AssertPivotTablesAreEqual(ws1, copyOfws1);
using (var wb2 = new XLWorkbook())
{
// We need to copy the source too. Cross workbook references don't work yet.
wb.Worksheet("PastrySalesData").CopyTo(wb2);
var ws2 = ws1.CopyTo(wb2, "Copy");
AssertPivotTablesAreEqual(ws1, ws2);
wb2.SaveAs(ms);
}
using (var wb2 = new XLWorkbook(ms))
{
var ws2 = wb2.Worksheet("Copy");
AssertPivotTablesAreEqual(ws1, ws2);
}
}
void AssertPivotTablesAreEqual(IXLWorksheet ws1, IXLWorksheet ws2)
{
Assert.AreEqual(ws1.PivotTables.Count(), ws2.PivotTables.Count());
var comparer = new PivotTableComparer();
for (int i = 0; i < ws1.PivotTables.Count(); i++)
{
var original = ws1.PivotTables.ElementAt(i).CastTo<XLPivotTable>();
var copy = ws2.PivotTables.ElementAt(i).CastTo<XLPivotTable>();
Assert.AreEqual(ws2, copy.Worksheet);
Assert.AreNotEqual(original.Guid, copy.Guid);
Assert.IsTrue(comparer.Equals(original, copy));
}
}
}
[Test]
public void CopyWorksheetPreservesSelectedRanges()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.SelectedRanges.RemoveAll();
ws1.SelectedRanges.Add(ws1.Range("E12:H20"));
ws1.SelectedRanges.Add(ws1.Range("B:B"));
ws1.SelectedRanges.Add(ws1.Range("3:6"));
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.SelectedRanges.Count, ws2.SelectedRanges.Count);
for (int i = 0; i < ws1.SelectedRanges.Count; i++)
{
Assert.AreEqual(ws1.SelectedRanges.ElementAt(i).RangeAddress.ToString(),
ws2.SelectedRanges.ElementAt(i).RangeAddress.ToString());
}
}
}
[Test]
public void CopyWorksheetPreservesPageSetup()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.PageSetup.AddHorizontalPageBreak(15);
ws1.PageSetup.AddVerticalPageBreak(5);
ws1.PageSetup
.SetBlackAndWhite()
.SetCenterHorizontally()
.SetCenterVertically()
.SetFirstPageNumber(200)
.SetPageOrientation(XLPageOrientation.Landscape)
.SetPaperSize(XLPaperSize.A5Paper)
.SetScale(89)
.SetShowGridlines()
.SetHorizontalDpi(200)
.SetVerticalDpi(300)
.SetPagesTall(5)
.SetPagesWide(2)
.SetColumnsToRepeatAtLeft(1, 3);
ws1.PageSetup.PrintAreas.Clear();
ws1.PageSetup.PrintAreas.Add("A1:Z200");
ws1.PageSetup.Margins.SetBottom(5).SetTop(6).SetLeft(7).SetRight(8).SetFooter(9).SetHeader(10);
ws1.PageSetup.Header.Left.AddText(XLHFPredefinedText.FullPath, XLHFOccurrence.AllPages);
ws1.PageSetup.Footer.Right.AddText(XLHFPredefinedText.PageNumber, XLHFOccurrence.OddPages);
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.PageSetup.FirstRowToRepeatAtTop, ws2.PageSetup.FirstRowToRepeatAtTop);
Assert.AreEqual(ws1.PageSetup.LastRowToRepeatAtTop, ws2.PageSetup.LastRowToRepeatAtTop);
Assert.AreEqual(ws1.PageSetup.FirstColumnToRepeatAtLeft, ws2.PageSetup.FirstColumnToRepeatAtLeft);
Assert.AreEqual(ws1.PageSetup.LastColumnToRepeatAtLeft, ws2.PageSetup.LastColumnToRepeatAtLeft);
Assert.AreEqual(ws1.PageSetup.PageOrientation, ws2.PageSetup.PageOrientation);
Assert.AreEqual(ws1.PageSetup.PagesWide, ws2.PageSetup.PagesWide);
Assert.AreEqual(ws1.PageSetup.PagesTall, ws2.PageSetup.PagesTall);
Assert.AreEqual(ws1.PageSetup.Scale, ws2.PageSetup.Scale);
Assert.AreEqual(ws1.PageSetup.HorizontalDpi, ws2.PageSetup.HorizontalDpi);
Assert.AreEqual(ws1.PageSetup.VerticalDpi, ws2.PageSetup.VerticalDpi);
Assert.AreEqual(ws1.PageSetup.FirstPageNumber, ws2.PageSetup.FirstPageNumber);
Assert.AreEqual(ws1.PageSetup.CenterHorizontally, ws2.PageSetup.CenterHorizontally);
Assert.AreEqual(ws1.PageSetup.CenterVertically, ws2.PageSetup.CenterVertically);
Assert.AreEqual(ws1.PageSetup.PaperSize, ws2.PageSetup.PaperSize);
Assert.AreEqual(ws1.PageSetup.Margins.Bottom, ws2.PageSetup.Margins.Bottom);
Assert.AreEqual(ws1.PageSetup.Margins.Top, ws2.PageSetup.Margins.Top);
Assert.AreEqual(ws1.PageSetup.Margins.Left, ws2.PageSetup.Margins.Left);
Assert.AreEqual(ws1.PageSetup.Margins.Right, ws2.PageSetup.Margins.Right);
Assert.AreEqual(ws1.PageSetup.Margins.Footer, ws2.PageSetup.Margins.Footer);
Assert.AreEqual(ws1.PageSetup.Margins.Header, ws2.PageSetup.Margins.Header);
Assert.AreEqual(ws1.PageSetup.ScaleHFWithDocument, ws2.PageSetup.ScaleHFWithDocument);
Assert.AreEqual(ws1.PageSetup.AlignHFWithMargins, ws2.PageSetup.AlignHFWithMargins);
Assert.AreEqual(ws1.PageSetup.ShowGridlines, ws2.PageSetup.ShowGridlines);
Assert.AreEqual(ws1.PageSetup.ShowRowAndColumnHeadings, ws2.PageSetup.ShowRowAndColumnHeadings);
Assert.AreEqual(ws1.PageSetup.BlackAndWhite, ws2.PageSetup.BlackAndWhite);
Assert.AreEqual(ws1.PageSetup.DraftQuality, ws2.PageSetup.DraftQuality);
Assert.AreEqual(ws1.PageSetup.PageOrder, ws2.PageSetup.PageOrder);
Assert.AreEqual(ws1.PageSetup.ShowComments, ws2.PageSetup.ShowComments);
Assert.AreEqual(ws1.PageSetup.PrintErrorValue, ws2.PageSetup.PrintErrorValue);
Assert.AreEqual(ws1.PageSetup.PrintAreas.Count(), ws2.PageSetup.PrintAreas.Count());
Assert.AreEqual(ws1.PageSetup.Header.Left.GetText(XLHFOccurrence.AllPages), ws2.PageSetup.Header.Left.GetText(XLHFOccurrence.AllPages));
Assert.AreEqual(ws1.PageSetup.Footer.Right.GetText(XLHFOccurrence.OddPages), ws2.PageSetup.Footer.Right.GetText(XLHFOccurrence.OddPages));
}
}
[Test]
public void CopyWorksheetPreservesSparklineGroups()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
var original = ws1.SparklineGroups.Add("A1:A10", "D1:Z10")
.SetDateRange(ws1.Range("D11:Z11"))
.SetDisplayEmptyCellsAs(XLDisplayBlanksAsValues.Zero)
.SetDisplayHidden(true)
.SetLineWeight(1.5)
.SetShowMarkers(XLSparklineMarkers.All)
.SetStyle(XLSparklineTheme.Colorful3)
.SetType(XLSparklineType.Column);
original.HorizontalAxis
.SetColor(XLColor.Blue)
.SetRightToLeft(true)
.SetVisible(true);
original.VerticalAxis
.SetManualMin(-100.0)
.SetManualMax(100.0);
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(1, ws2.SparklineGroups.Count());
var copy = ws2.SparklineGroups.Single();
Assert.AreEqual(original.Count(), copy.Count());
for (int i = 0; i < original.Count(); i++)
{
Assert.AreSame(ws2, copy.ElementAt(i).Location.Worksheet);
Assert.AreSame(ws2, copy.ElementAt(i).SourceData.Worksheet);
Assert.AreEqual(original.ElementAt(i).Location.Address.ToString(), copy.ElementAt(i).Location.Address.ToString());
Assert.AreEqual(original.ElementAt(i).SourceData.RangeAddress.ToString(), copy.ElementAt(i).SourceData.RangeAddress.ToString());
}
Assert.AreEqual(original.DateRange.RangeAddress.ToString(), copy.DateRange.RangeAddress.ToString());
Assert.AreSame(ws2, copy.DateRange.Worksheet);
Assert.AreEqual(original.DisplayEmptyCellsAs, copy.DisplayEmptyCellsAs);
Assert.AreEqual(original.DisplayHidden, copy.DisplayHidden);
Assert.AreEqual(original.LineWeight, copy.LineWeight, XLHelper.Epsilon);
Assert.AreEqual(original.ShowMarkers, copy.ShowMarkers);
Assert.AreEqual(original.Style, copy.Style);
Assert.AreNotSame(original.Style, copy.Style);
Assert.AreEqual(original.Type, copy.Type);
Assert.AreEqual(original.HorizontalAxis.Color, copy.HorizontalAxis.Color);
Assert.AreEqual(original.HorizontalAxis.DateAxis, copy.HorizontalAxis.DateAxis);
Assert.AreEqual(original.HorizontalAxis.IsVisible, copy.HorizontalAxis.IsVisible);
Assert.AreEqual(original.HorizontalAxis.RightToLeft, copy.HorizontalAxis.RightToLeft);
Assert.AreEqual(original.VerticalAxis.ManualMax, copy.VerticalAxis.ManualMax);
Assert.AreEqual(original.VerticalAxis.ManualMin, copy.VerticalAxis.ManualMin);
Assert.AreEqual(original.VerticalAxis.MaxAxisType, copy.VerticalAxis.MaxAxisType);
Assert.AreEqual(original.VerticalAxis.MinAxisType, copy.VerticalAxis.MinAxisType);
}
}
[Test, Ignore("Muted until #836 is fixed")]
public void CopyWorksheetChangesAbsoluteReferencesInFormulae()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Cell("A1").FormulaA1 = "10*10";
ws1.Cell("A2").FormulaA1 = "Original!A1 * 3";
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual("Copy!A1 * 3", ws2.Cell("A2").FormulaA1);
}
}
[Test, Ignore("Muted until #836 is fixed")]
public void RenameWorksheetChangesAbsoluteReferencesInFormulae()
{
using (var wb1 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Cell("A1").FormulaA1 = "10*10";
ws1.Cell("A2").FormulaA1 = "Original!A1 * 3";
ws1.Name = "Renamed";
Assert.AreEqual("Renamed!A1 * 3", ws1.Cell("A2").FormulaA1);
}
}
[Test]
public void RangesFromDeletedWorksheetContainREF()
{
using (var wb1 = new XLWorkbook())
{
wb1.Worksheets.Add("Sheet1");
var ws2 = wb1.Worksheets.Add("Sheet2");
var range = ws2.Range("A1:B2");
ws2.Delete();
Assert.AreEqual("#REF!A1:B2", range.RangeAddress.ToString());
}
}
[Test]
public void InvalidRowAndColumnIndices()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
Assert.Throws<ArgumentOutOfRangeException>(() => ws.Row(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => ws.Row(XLHelper.MaxRowNumber + 1));
Assert.Throws<ArgumentOutOfRangeException>(() => ws.Column(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => ws.Column(XLHelper.MaxColumnNumber + 1));
}
}
[Test]
public void InvalidSelectedRangeExcluded()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
var range1 = ws.Range("B2:C2");
var range2 = ws.Range("B4:C4");
ws.SelectedRanges.Clear();
ws.SelectedRanges.Add(range1);
ws.SelectedRanges.Add(range2);
ws.Row(4).Delete();
Assert.IsFalse(range2.RangeAddress.IsValid);
Assert.AreEqual(range1, ws.SelectedRanges.Single());
}
}
[Test]
public void InsertColumnsDoesNotIncreaseCellsCount()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var cell1 = ws.Cell("A1");
var cell2 = ws.Cell("AAA50");
var originalCount = (ws as XLWorksheet).Internals.CellsCollection.Count;
ws.Column(1).InsertColumnsBefore(1);
Assert.AreEqual(originalCount, (ws as XLWorksheet).Internals.CellsCollection.Count);
}
}
[Test]
public void InsertRowsDoesNotIncreaseCellsCount()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var cell1 = ws.Cell("A1");
var cell2 = ws.Cell("AAA500");
var originalCount = (ws as XLWorksheet).Internals.CellsCollection.Count;
ws.Row(1).InsertRowsAbove(1);
Assert.AreEqual(originalCount, (ws as XLWorksheet).Internals.CellsCollection.Count);
}
}
[Test]
public void InsertCellsBeforeDoesNotIncreaseCellsCount()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var cell1 = ws.Cell("A1");
var cell2 = ws.Cell("AAA50");
var originalCount = (ws as XLWorksheet).Internals.CellsCollection.Count;
cell1.InsertCellsBefore(1);
Assert.AreEqual(originalCount, (ws as XLWorksheet).Internals.CellsCollection.Count);
}
}
[Test]
public void InsertCellsAboveDoesNotIncreaseCellsCount()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var cell1 = ws.Cell("A1");
var cell2 = ws.Cell("AAA500");
var originalCount = (ws as XLWorksheet).Internals.CellsCollection.Count;
cell1.InsertCellsAbove(1);
Assert.AreEqual(originalCount, (ws as XLWorksheet).Internals.CellsCollection.Count);
}
}
[Test]
public void CellsShiftedTooFarRightArePurged()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var cell1 = ws.Cell("A1");
var cell2 = ws.Cell(1, XLHelper.MaxColumnNumber);
var cell3 = ws.Cell(2, XLHelper.MaxColumnNumber);
cell1.InsertCellsBefore(1);
Assert.AreEqual(2, (ws as XLWorksheet).Internals.CellsCollection.Count);
ws.Column(1).InsertColumnsBefore(1);
Assert.AreEqual(1, (ws as XLWorksheet).Internals.CellsCollection.Count);
}
}
[Test]
public void CellsShiftedTooFarDownArePurged()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var cell1 = ws.Cell("A1");
var cell2 = ws.Cell(XLHelper.MaxRowNumber, 1);
var cell3 = ws.Cell(XLHelper.MaxRowNumber, 2);
cell1.InsertCellsAbove(1);
Assert.AreEqual(2, (ws as XLWorksheet).Internals.CellsCollection.Count);
ws.Row(1).InsertRowsAbove(1);
Assert.AreEqual(1, (ws as XLWorksheet).Internals.CellsCollection.Count);
}
}
[Test]
public void MaxColumnUsedUpdatedWhenColumnDeleted()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var cell1 = ws.Cell("C1");
var cell2 = ws.Cell(1, XLHelper.MaxColumnNumber);
ws.Column(XLHelper.MaxColumnNumber).Delete();
Assert.AreEqual(3, (ws as XLWorksheet).Internals.CellsCollection.MaxColumnUsed);
}
}
[Test]
public void MaxRowUsedUpdatedWhenRowDeleted()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var cell1 = ws.Cell("A3");
var cell2 = ws.Cell(XLHelper.MaxRowNumber, 1);
ws.Row(XLHelper.MaxRowNumber).Delete();
Assert.AreEqual(3, (ws as XLWorksheet).Internals.CellsCollection.MaxRowUsed);
}
}
[Test]
public void ChangeColumnStyleFirst()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("ColumnFirst");
ws.Column(2).Style.Font.SetBold(true);
ws.Row(2).Style.Font.SetItalic(true);
Assert.IsTrue(ws.Cell("B2").Style.Font.Bold);
Assert.IsTrue(ws.Cell("B2").Style.Font.Italic);
}
}
[Test]
public void ChangeRowStyleFirst()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("RowFirst");
ws.Row(2).Style.Font.SetItalic(true);
ws.Column(2).Style.Font.SetBold(true);
Assert.IsTrue(ws.Cell("B2").Style.Font.Bold);
Assert.IsTrue(ws.Cell("B2").Style.Font.Italic);
}
}
[Test]
public void SelectedTabIsActive_WhenInsertBefore()
{
using (var ms = new MemoryStream())
{
using (var wb = new XLWorkbook())
{
var ws1 = wb.AddWorksheet();
ws1.TabSelected = true;
var ws2 = wb.Worksheets.Add(1);
wb.SaveAs(ms);
}
using (var wb = new XLWorkbook(ms))
{
var ws1 = wb.Worksheets.First();
var ws2 = wb.Worksheets.Last();
Assert.IsFalse(ws1.TabActive);
Assert.IsFalse(ws1.TabSelected);
Assert.IsTrue(ws2.TabActive);
Assert.IsTrue(ws2.TabSelected);
}
}
}
[TestCase("noactive_noselected.xlsx")]
[TestCase("noactive_twoselected.xlsx")]
public void FirstSheetIsActive_WhenNotSpecified(string fileName)
{
using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Other\NoActiveSheet\" + fileName)))
using (var wb = new XLWorkbook(stream))
{
Assert.IsTrue(wb.Worksheets.First().TabActive);
Assert.AreEqual(XLWorksheetVisibility.Visible, wb.Worksheets.First().Visibility);
}
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// E11Level111111ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="E11Level111111ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="E10Level11111"/> collection.
/// </remarks>
[Serializable]
public partial class E11Level111111ReChild : BusinessBase<E11Level111111ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int cQarentID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_1_1_1_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_1_Child_Name, "Level_1_1_1_1_1_1 Child Name");
/// <summary>
/// Gets or sets the Level_1_1_1_1_1_1 Child Name.
/// </summary>
/// <value>The Level_1_1_1_1_1_1 Child Name.</value>
public string Level_1_1_1_1_1_1_Child_Name
{
get { return GetProperty(Level_1_1_1_1_1_1_Child_NameProperty); }
set { SetProperty(Level_1_1_1_1_1_1_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="E11Level111111ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="E11Level111111ReChild"/> object.</returns>
internal static E11Level111111ReChild NewE11Level111111ReChild()
{
return DataPortal.CreateChild<E11Level111111ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="E11Level111111ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="E11Level111111ReChild"/> object.</returns>
internal static E11Level111111ReChild GetE11Level111111ReChild(SafeDataReader dr)
{
E11Level111111ReChild obj = new E11Level111111ReChild();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="E11Level111111ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private E11Level111111ReChild()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="E11Level111111ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="E11Level111111ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_1_1_Child_Name"));
cQarentID2 = dr.GetInt32("CQarentID2");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="E11Level111111ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(E10Level11111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddE11Level111111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="E11Level111111ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(E10Level11111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateE11Level111111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="E11Level111111ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(E10Level11111 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteE11Level111111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Avalonia.FreeDesktop;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Input.TextInput;
using Avalonia.Platform.Interop;
using static Avalonia.X11.XLib;
namespace Avalonia.X11
{
partial class X11Window
{
private ITextInputMethodImpl _ime;
private IX11InputMethodControl _imeControl;
private bool _processingIme;
private Queue<(RawKeyEventArgs args, XEvent xev, int keyval, int keycode)> _imeQueue =
new Queue<(RawKeyEventArgs args, XEvent xev, int keyVal, int keyCode)>();
unsafe void CreateIC()
{
if (_x11.HasXim)
{
XGetIMValues(_x11.Xim, XNames.XNQueryInputStyle, out var supported_styles, IntPtr.Zero);
for (var c = 0; c < supported_styles->count_styles; c++)
{
var style = (XIMProperties)supported_styles->supported_styles[c];
if ((int)(style & XIMProperties.XIMPreeditPosition) != 0
&& ((int)(style & XIMProperties.XIMStatusNothing) != 0))
{
XPoint spot = default;
//using var areaS = new Utf8Buffer("area");
using var spotS = new Utf8Buffer("spotLocation");
using var fontS = new Utf8Buffer("fontSet");
var list = XVaCreateNestedList(0,
//areaS, &area,
spotS, &spot,
fontS, _x11.DefaultFontSet,
IntPtr.Zero);
_xic = XCreateIC(_x11.Xim,
XNames.XNClientWindow, _handle,
XNames.XNFocusWindow, _handle,
XNames.XNInputStyle, new IntPtr((int)style),
XNames.XNResourceName, _platform.Options.WmClass,
XNames.XNResourceClass, _platform.Options.WmClass,
XNames.XNPreeditAttributes, list,
IntPtr.Zero);
XFree(list);
break;
}
}
XFree(new IntPtr(supported_styles));
}
if (_xic == IntPtr.Zero)
_xic = XCreateIC(_x11.Xim, XNames.XNInputStyle,
new IntPtr((int)(XIMProperties.XIMPreeditNothing | XIMProperties.XIMStatusNothing)),
XNames.XNClientWindow, _handle, XNames.XNFocusWindow, _handle, IntPtr.Zero);
}
void InitializeIme()
{
var ime = AvaloniaLocator.Current.GetService<IX11InputMethodFactory>()?.CreateClient(_handle);
if (ime == null && _x11.HasXim)
{
var xim = new XimInputMethod(this);
ime = (xim, xim);
}
if (ime != null)
{
(_ime, _imeControl) = ime.Value;
_imeControl.Commit += s =>
ScheduleInput(new RawTextInputEventArgs(_keyboard, (ulong)_x11.LastActivityTimestamp.ToInt64(),
_inputRoot, s));
_imeControl.ForwardKey += ev =>
{
ScheduleInput(new RawKeyEventArgs(_keyboard, (ulong)_x11.LastActivityTimestamp.ToInt64(),
_inputRoot, ev.Type, X11KeyTransform.ConvertKey((X11Key)ev.KeyVal),
(RawInputModifiers)ev.Modifiers));
};
}
}
void UpdateImePosition() => _imeControl?.UpdateWindowInfo(Position, RenderScaling);
void HandleKeyEvent(ref XEvent ev)
{
var index = ev.KeyEvent.state.HasAllFlags(XModifierMask.ShiftMask);
// We need the latin key, since it's mainly used for hotkeys, we use a different API for text anyway
var key = (X11Key)XKeycodeToKeysym(_x11.Display, ev.KeyEvent.keycode, index ? 1 : 0).ToInt32();
// Manually switch the Shift index for the keypad,
// there should be a proper way to do this
if (ev.KeyEvent.state.HasAllFlags(XModifierMask.Mod2Mask)
&& key > X11Key.Num_Lock && key <= X11Key.KP_9)
key = (X11Key)XKeycodeToKeysym(_x11.Display, ev.KeyEvent.keycode, index ? 0 : 1).ToInt32();
var filtered = ScheduleKeyInput(new RawKeyEventArgs(_keyboard, (ulong)ev.KeyEvent.time.ToInt64(), _inputRoot,
ev.type == XEventName.KeyPress ? RawKeyEventType.KeyDown : RawKeyEventType.KeyUp,
X11KeyTransform.ConvertKey(key), TranslateModifiers(ev.KeyEvent.state)), ref ev, (int)key, ev.KeyEvent.keycode);
if (ev.type == XEventName.KeyPress && !filtered)
TriggerClassicTextInputEvent(ref ev);
}
void TriggerClassicTextInputEvent(ref XEvent ev)
{
var text = TranslateEventToString(ref ev);
if (text != null)
ScheduleInput(
new RawTextInputEventArgs(_keyboard, (ulong)ev.KeyEvent.time.ToInt64(), _inputRoot, text),
ref ev);
}
private const int ImeBufferSize = 64 * 1024;
[ThreadStatic] private static IntPtr ImeBuffer;
unsafe string TranslateEventToString(ref XEvent ev)
{
if (ImeBuffer == IntPtr.Zero)
ImeBuffer = Marshal.AllocHGlobal(ImeBufferSize);
var len = Xutf8LookupString(_xic, ref ev, ImeBuffer.ToPointer(), ImeBufferSize,
out _, out var istatus);
var status = (XLookupStatus)istatus;
if (len == 0)
return null;
string text;
if (status == XLookupStatus.XBufferOverflow)
return null;
else
text = Encoding.UTF8.GetString((byte*)ImeBuffer.ToPointer(), len);
if (text == null)
return null;
if (text.Length == 1)
{
if (text[0] < ' ' || text[0] == 0x7f) //Control codes or DEL
return null;
}
return text;
}
bool ScheduleKeyInput(RawKeyEventArgs args, ref XEvent xev, int keyval, int keycode)
{
_x11.LastActivityTimestamp = xev.ButtonEvent.time;
if (_imeControl != null && _imeControl.IsEnabled)
{
if (FilterIme(args, xev, keyval, keycode))
return true;
}
ScheduleInput(args);
return false;
}
bool FilterIme(RawKeyEventArgs args, XEvent xev, int keyval, int keycode)
{
if (_ime == null)
return false;
_imeQueue.Enqueue((args, xev, keyval, keycode));
if (!_processingIme)
ProcessNextImeEvent();
return true;
}
async void ProcessNextImeEvent()
{
if(_processingIme)
return;
_processingIme = true;
try
{
while (_imeQueue.Count != 0)
{
var ev = _imeQueue.Dequeue();
if (_imeControl == null || !await _imeControl.HandleEventAsync(ev.args, ev.keyval, ev.keycode))
{
ScheduleInput(ev.args);
if (ev.args.Type == RawKeyEventType.KeyDown)
TriggerClassicTextInputEvent(ref ev.xev);
}
}
}
finally
{
_processingIme = false;
}
}
}
}
| |
// 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.IO;
using Internal.NativeCrypto;
namespace System.Security.Cryptography
{
public sealed class DSACryptoServiceProvider : DSA, ICspAsymmetricAlgorithm
{
private int _keySize;
private readonly CspParameters _parameters;
private readonly bool _randomKeyContainer;
private SafeKeyHandle _safeKeyHandle;
private SafeProvHandle _safeProvHandle;
private readonly SHA1 _sha1;
private static volatile CspProviderFlags s_useMachineKeyStore = 0;
private bool _disposed;
/// <summary>
/// Initializes a new instance of the DSACryptoServiceProvider class.
/// </summary>
public DSACryptoServiceProvider()
: this(
new CspParameters(CapiHelper.DefaultDssProviderType,
null,
null,
s_useMachineKeyStore))
{
}
/// <summary>
/// Initializes a new instance of the DSACryptoServiceProvider class with the specified key size.
/// </summary>
/// <param name="dwKeySize">The size of the key for the asymmetric algorithm in bits.</param>
public DSACryptoServiceProvider(int dwKeySize)
: this(dwKeySize,
new CspParameters(CapiHelper.DefaultDssProviderType,
null,
null,
s_useMachineKeyStore))
{
}
/// <summary>
/// Initializes a new instance of the DSACryptoServiceProvider class with the specified parameters
/// for the cryptographic service provider (CSP).
/// </summary>
/// <param name="parameters">The parameters for the CSP.</param>
public DSACryptoServiceProvider(CspParameters parameters)
: this(0, parameters)
{
}
/// <summary>
/// Initializes a new instance of the DSACryptoServiceProvider class with the specified key size and parameters
/// for the cryptographic service provider (CSP).
/// </summary>
/// <param name="dwKeySize">The size of the key for the cryptographic algorithm in bits.</param>
/// <param name="parameters">The parameters for the CSP.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 is required by the FIPS 186-2 DSA spec.")]
public DSACryptoServiceProvider(int dwKeySize, CspParameters parameters)
{
if (dwKeySize < 0)
throw new ArgumentOutOfRangeException(nameof(dwKeySize), SR.ArgumentOutOfRange_NeedNonNegNum);
_parameters = CapiHelper.SaveCspParameters(
CapiHelper.CspAlgorithmType.Dss,
parameters,
s_useMachineKeyStore,
out _randomKeyContainer);
_keySize = dwKeySize;
_sha1 = SHA1.Create();
// If this is not a random container we generate, create it eagerly
// in the constructor so we can report any errors now.
if (!_randomKeyContainer)
{
// Force-read the SafeKeyHandle property, which will summon it into existence.
SafeKeyHandle localHandle = SafeKeyHandle;
Debug.Assert(localHandle != null);
}
}
private SafeProvHandle SafeProvHandle
{
get
{
if (_safeProvHandle == null)
{
lock (_parameters)
{
if (_safeProvHandle == null)
{
SafeProvHandle hProv = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer);
Debug.Assert(hProv != null);
Debug.Assert(!hProv.IsInvalid);
Debug.Assert(!hProv.IsClosed);
_safeProvHandle = hProv;
}
}
return _safeProvHandle;
}
return _safeProvHandle;
}
set
{
lock (_parameters)
{
SafeProvHandle current = _safeProvHandle;
if (ReferenceEquals(value, current))
{
return;
}
if (current != null)
{
SafeKeyHandle keyHandle = _safeKeyHandle;
_safeKeyHandle = null;
keyHandle?.Dispose();
current.Dispose();
}
_safeProvHandle = value;
}
}
}
private SafeKeyHandle SafeKeyHandle
{
get
{
if (_safeKeyHandle == null)
{
lock (_parameters)
{
if (_safeKeyHandle == null)
{
SafeKeyHandle hKey = CapiHelper.GetKeyPairHelper(
CapiHelper.CspAlgorithmType.Dss,
_parameters,
_keySize,
SafeProvHandle);
Debug.Assert(hKey != null);
Debug.Assert(!hKey.IsInvalid);
Debug.Assert(!hKey.IsClosed);
_safeKeyHandle = hKey;
}
}
}
return _safeKeyHandle;
}
set
{
lock (_parameters)
{
SafeKeyHandle current = _safeKeyHandle;
if (ReferenceEquals(value, current))
{
return;
}
_safeKeyHandle = value;
current?.Dispose();
}
}
}
/// <summary>
/// Gets a CspKeyContainerInfo object that describes additional information about a cryptographic key pair.
/// </summary>
public CspKeyContainerInfo CspKeyContainerInfo
{
get
{
// Desktop compat: Read the SafeKeyHandle property to force the key to load,
// because it might throw here.
SafeKeyHandle localHandle = SafeKeyHandle;
Debug.Assert(localHandle != null);
return new CspKeyContainerInfo(_parameters, _randomKeyContainer);
}
}
public override int KeySize
{
get
{
byte[] keySize = CapiHelper.GetKeyParameter(SafeKeyHandle, Constants.CLR_KEYLEN);
_keySize = (keySize[0] | (keySize[1] << 8) | (keySize[2] << 16) | (keySize[3] << 24));
return _keySize;
}
}
public override KeySizes[] LegalKeySizes
{
get
{
return new[] { new KeySizes(512, 1024, 64) }; // per FIPS 186-2
}
}
/// <summary>
/// Gets or sets a value indicating whether the key should be persisted in the cryptographic
/// service provider (CSP).
/// </summary>
public bool PersistKeyInCsp
{
get
{
return CapiHelper.GetPersistKeyInCsp(SafeProvHandle);
}
set
{
bool oldPersistKeyInCsp = this.PersistKeyInCsp;
if (value == oldPersistKeyInCsp)
{
return; // Do nothing
}
CapiHelper.SetPersistKeyInCsp(SafeProvHandle, value);
}
}
/// <summary>
/// Gets a value that indicates whether the DSACryptoServiceProvider object contains
/// only a public key.
/// </summary>
public bool PublicOnly
{
get
{
byte[] publicKey = CapiHelper.GetKeyParameter(SafeKeyHandle, Constants.CLR_PUBLICKEYONLY);
return (publicKey[0] == 1);
}
}
/// <summary>
/// Gets or sets a value indicating whether the key should be persisted in the computer's
/// key store instead of the user profile store.
/// </summary>
public static bool UseMachineKeyStore
{
get
{
return (s_useMachineKeyStore == CspProviderFlags.UseMachineKeyStore);
}
set
{
s_useMachineKeyStore = (value ? CspProviderFlags.UseMachineKeyStore : 0);
}
}
public override string KeyExchangeAlgorithm => null;
public override string SignatureAlgorithm => "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
{
_safeKeyHandle.Dispose();
}
if (_safeProvHandle != null && !_safeProvHandle.IsClosed)
{
_safeProvHandle.Dispose();
}
_disposed = true;
}
base.Dispose(disposing);
}
/// <summary>
/// Exports a blob containing the key information associated with an DSACryptoServiceProvider object.
/// </summary>
public byte[] ExportCspBlob(bool includePrivateParameters)
{
return CapiHelper.ExportKeyBlob(includePrivateParameters, SafeKeyHandle);
}
public override DSAParameters ExportParameters(bool includePrivateParameters)
{
byte[] cspBlob = ExportCspBlob(includePrivateParameters);
byte[] cspPublicBlob = null;
if (includePrivateParameters)
{
byte bVersion = CapiHelper.GetKeyBlobHeaderVersion(cspBlob);
if (bVersion <= 2)
{
// Since DSSPUBKEY is used for either public or private key, we got X
// but not Y. To get Y, do another export and ask for public key blob.
cspPublicBlob = ExportCspBlob(false);
}
}
return cspBlob.ToDSAParameters(includePrivateParameters, cspPublicBlob);
}
/// <summary>
/// This method helps Acquire the default CSP and avoids the need for static SafeProvHandle
/// in CapiHelper class
/// </summary>
private SafeProvHandle AcquireSafeProviderHandle()
{
SafeProvHandle safeProvHandle;
CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultDssProviderType), out safeProvHandle);
return safeProvHandle;
}
/// <summary>
/// Imports a blob that represents DSA key information.
/// </summary>
/// <param name="keyBlob">A byte array that represents a DSA key blob.</param>
public void ImportCspBlob(byte[] keyBlob)
{
ThrowIfDisposed();
SafeKeyHandle safeKeyHandle;
if (IsPublic(keyBlob))
{
SafeProvHandle safeProvHandleTemp = AcquireSafeProviderHandle();
CapiHelper.ImportKeyBlob(safeProvHandleTemp, (CspProviderFlags)0, false, keyBlob, out safeKeyHandle);
// The property set will take care of releasing any already-existing resources.
SafeProvHandle = safeProvHandleTemp;
}
else
{
CapiHelper.ImportKeyBlob(SafeProvHandle, _parameters.Flags, false, keyBlob, out safeKeyHandle);
}
// The property set will take care of releasing any already-existing resources.
SafeKeyHandle = safeKeyHandle;
}
public override void ImportParameters(DSAParameters parameters)
{
byte[] keyBlob = parameters.ToKeyBlob();
ImportCspBlob(keyBlob);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead);
}
/// <summary>
/// Computes the hash value of the specified input stream and signs the resulting hash value.
/// </summary>
/// <param name="inputStream">The input data for which to compute the hash.</param>
/// <returns>The DSA signature for the specified data.</returns>
public byte[] SignData(Stream inputStream)
{
byte[] hashVal = _sha1.ComputeHash(inputStream);
return SignHash(hashVal, null);
}
/// <summary>
/// Computes the hash value of the specified input stream and signs the resulting hash value.
/// </summary>
/// <param name="buffer">The input data for which to compute the hash.</param>
/// <returns>The DSA signature for the specified data.</returns>
public byte[] SignData(byte[] buffer)
{
byte[] hashVal = _sha1.ComputeHash(buffer);
return SignHash(hashVal, null);
}
/// <summary>
/// Signs a byte array from the specified start point to the specified end point.
/// </summary>
/// <param name="buffer">The input data to sign.</param>
/// <param name="offset">The offset into the array from which to begin using data.</param>
/// <param name="count">The number of bytes in the array to use as data.</param>
/// <returns>The DSA signature for the specified data.</returns>
public byte[] SignData(byte[] buffer, int offset, int count)
{
byte[] hashVal = _sha1.ComputeHash(buffer, offset, count);
return SignHash(hashVal, null);
}
/// <summary>
/// Verifies the specified signature data by comparing it to the signature computed for the specified data.
/// </summary>
/// <param name="rgbData">The data that was signed.</param>
/// <param name="rgbSignature">The signature data to be verified.</param>
/// <returns>true if the signature verifies as valid; otherwise, false.</returns>
public bool VerifyData(byte[] rgbData, byte[] rgbSignature)
{
byte[] hashVal = _sha1.ComputeHash(rgbData);
return VerifyHash(hashVal, null, rgbSignature);
}
/// <summary>
/// Creates the DSA signature for the specified data.
/// </summary>
/// <param name="rgbHash">The data to be signed.</param>
/// <returns>The digital signature for the specified data.</returns>
public override byte[] CreateSignature(byte[] rgbHash)
{
return SignHash(rgbHash, null);
}
public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature)
{
return VerifyHash(rgbHash, null, rgbSignature);
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
// we're sealed and the base should have checked this before calling us
Debug.Assert(data != null);
Debug.Assert(offset >= 0 && offset <= data.Length);
Debug.Assert(count >= 0 && count <= data.Length - offset);
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
if (hashAlgorithm != HashAlgorithmName.SHA1)
{
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
}
return _sha1.ComputeHash(data, offset, count);
}
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
// we're sealed and the base should have checked this before calling us
Debug.Assert(data != null);
Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));
if (hashAlgorithm != HashAlgorithmName.SHA1)
{
throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
}
return _sha1.ComputeHash(data);
}
/// <summary>
/// Computes the signature for the specified hash value by encrypting it with the private key.
/// </summary>
/// <param name="rgbHash">The hash value of the data to be signed.</param>
/// <param name="str">The name of the hash algorithm used to create the hash value of the data.</param>
/// <returns>The DSA signature for the specified hash value.</returns>
public byte[] SignHash(byte[] rgbHash, string str)
{
if (rgbHash == null)
throw new ArgumentNullException(nameof(rgbHash));
if (PublicOnly)
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm);
if (rgbHash.Length != _sha1.HashSize / 8)
throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHashSize, "SHA1", _sha1.HashSize / 8));
return CapiHelper.SignValue(
SafeProvHandle,
SafeKeyHandle,
_parameters.KeyNumber,
CapiHelper.CALG_DSS_SIGN,
calgHash,
rgbHash);
}
/// <summary>
/// Verifies the specified signature data by comparing it to the signature computed for the specified hash value.
/// </summary>
/// <param name="rgbHash">The hash value of the data to be signed.</param>
/// <param name="str">The name of the hash algorithm used to create the hash value of the data.</param>
/// <param name="rgbSignature">The signature data to be verified.</param>
/// <returns>true if the signature verifies as valid; otherwise, false.</returns>
public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature)
{
if (rgbHash == null)
throw new ArgumentNullException(nameof(rgbHash));
if (rgbSignature == null)
throw new ArgumentNullException(nameof(rgbSignature));
int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm);
return CapiHelper.VerifySign(
SafeProvHandle,
SafeKeyHandle,
CapiHelper.CALG_DSS_SIGN,
calgHash,
rgbHash,
rgbSignature);
}
/// <summary>
/// Find whether a DSS key blob is public.
/// </summary>
private static bool IsPublic(byte[] keyBlob)
{
if (keyBlob == null)
{
throw new ArgumentNullException(nameof(keyBlob));
}
// The CAPI DSS public key representation consists of the following sequence:
// - BLOBHEADER (the first byte is bType)
// - DSSPUBKEY or DSSPUBKEY_VER3 (the first field is the magic field)
// The first byte should be PUBLICKEYBLOB
if (keyBlob[0] != CapiHelper.PUBLICKEYBLOB)
{
return false;
}
// Magic should be DSS_MAGIC or DSS_PUB_MAGIC_VER3
if ((keyBlob[11] != 0x31 && keyBlob[11] != 0x33) || keyBlob[10] != 0x53 || keyBlob[9] != 0x53 || keyBlob[8] != 0x44)
{
return false;
}
return true;
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(DSACryptoServiceProvider));
}
}
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.IO;
using Internal.Cryptography;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography
{
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
internal static partial class ECDsaImplementation
{
#endif
public sealed partial class ECDsaOpenSsl : ECDsa
{
private ECOpenSsl _key;
/// <summary>
/// Create an ECDsaOpenSsl algorithm with a named curve.
/// </summary>
/// <param name="curve">The <see cref="ECCurve"/> representing the curve.</param>
/// <exception cref="ArgumentNullException">if <paramref name="curve" /> is null.</exception>
public ECDsaOpenSsl(ECCurve curve)
{
_key = new ECOpenSsl(curve);
ForceSetKeySize(_key.KeySize);
}
/// <summary>
/// Create an ECDsaOpenSsl algorithm with a random 521 bit key pair.
/// </summary>
public ECDsaOpenSsl()
: this(521)
{
}
/// <summary>
/// Creates a new ECDsaOpenSsl object that will use a randomly generated key of the specified size.
/// </summary>
/// <param name="keySize">Size of the key to generate, in bits.</param>
public ECDsaOpenSsl(int keySize)
{
KeySize = keySize;
// Setting KeySize wakes up _key.
Debug.Assert(_key != null);
}
/// <summary>
/// Set the KeySize without validating against LegalKeySizes.
/// </summary>
/// <param name="newKeySize">The value to set the KeySize to.</param>
private void ForceSetKeySize(int newKeySize)
{
// In the event that a key was loaded via ImportParameters, curve name, or an IntPtr/SafeHandle
// it could be outside of the bounds that we currently represent as "legal key sizes".
// Since that is our view into the underlying component it can be detached from the
// component's understanding. If it said it has opened a key, and this is the size, trust it.
KeySizeValue = newKeySize;
}
public override KeySizes[] LegalKeySizes
{
get
{
// Return the three sizes that can be explicitly set (for backwards compatibility)
return new[] {
new KeySizes(minSize: 256, maxSize: 384, skipSize: 128),
new KeySizes(minSize: 521, maxSize: 521, skipSize: 0),
};
}
}
public override byte[] SignHash(byte[] hash)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
SafeEcKeyHandle key = _key.Value;
int signatureLength = Interop.Crypto.EcDsaSize(key);
byte[] signature = new byte[signatureLength];
if (!Interop.Crypto.EcDsaSign(hash, signature, ref signatureLength, key))
throw Interop.Crypto.CreateOpenSslCryptographicException();
byte[] converted = AsymmetricAlgorithmHelpers.ConvertDerToIeee1363(signature, 0, signatureLength, KeySize);
return converted;
}
public override bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, out int bytesWritten)
{
SafeEcKeyHandle key = _key.Value;
byte[] converted;
int signatureLength = Interop.Crypto.EcDsaSize(key);
byte[] signature = ArrayPool<byte>.Shared.Rent(signatureLength);
try
{
if (!Interop.Crypto.EcDsaSign(hash, new Span<byte>(signature, 0, signatureLength), ref signatureLength, key))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
converted = AsymmetricAlgorithmHelpers.ConvertDerToIeee1363(signature, 0, signatureLength, KeySize);
}
finally
{
Array.Clear(signature, 0, signatureLength);
ArrayPool<byte>.Shared.Return(signature);
}
if (converted.Length <= destination.Length)
{
new ReadOnlySpan<byte>(converted).CopyTo(destination);
bytesWritten = converted.Length;
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
public override bool VerifyHash(byte[] hash, byte[] signature)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
if (signature == null)
throw new ArgumentNullException(nameof(signature));
return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature);
}
public override bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature)
{
// The signature format for .NET is r.Concat(s). Each of r and s are of length BitsToBytes(KeySize), even
// when they would have leading zeroes. If it's the correct size, then we need to encode it from
// r.Concat(s) to SEQUENCE(INTEGER(r), INTEGER(s)), because that's the format that OpenSSL expects.
int expectedBytes = 2 * AsymmetricAlgorithmHelpers.BitsToBytes(KeySize);
if (signature.Length != expectedBytes)
{
// The input isn't of the right length, so we can't sensibly re-encode it.
return false;
}
byte[] openSslFormat = AsymmetricAlgorithmHelpers.ConvertIeee1363ToDer(signature);
SafeEcKeyHandle key = _key.Value;
int verifyResult = Interop.Crypto.EcDsaVerify(hash, openSslFormat, key);
return verifyResult == 1;
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) =>
AsymmetricAlgorithmHelpers.HashData(data, offset, count, hashAlgorithm);
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) =>
AsymmetricAlgorithmHelpers.HashData(data, hashAlgorithm);
protected override bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) =>
AsymmetricAlgorithmHelpers.TryHashData(data, destination, hashAlgorithm, out bytesWritten);
protected override void Dispose(bool disposing)
{
if (disposing)
{
_key.Dispose();
}
base.Dispose(disposing);
}
public override int KeySize
{
get
{
return base.KeySize;
}
set
{
if (KeySize == value)
return;
// Set the KeySize before FreeKey so that an invalid value doesn't throw away the key
base.KeySize = value;
// This is the only place where _key can be null, because it's called by the constructor
// which sets KeySize.
_key?.Dispose();
_key = new ECOpenSsl(this);
}
}
public override void GenerateKey(ECCurve curve)
{
_key.GenerateKey(curve);
// Use ForceSet instead of the property setter to ensure that LegalKeySizes doesn't interfere
// with the already loaded key.
ForceSetKeySize(_key.KeySize);
}
public override void ImportParameters(ECParameters parameters)
{
_key.ImportParameters(parameters);
ForceSetKeySize(_key.KeySize);
}
public override ECParameters ExportExplicitParameters(bool includePrivateParameters) =>
ECOpenSsl.ExportExplicitParameters(_key.Value, includePrivateParameters);
public override ECParameters ExportParameters(bool includePrivateParameters) =>
ECOpenSsl.ExportParameters(_key.Value, includePrivateParameters);
}
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
}
#endif
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
namespace System.Diagnostics.Eventing.Reader
{
public class EventLogRecord : EventRecord
{
private const int SYSTEM_PROPERTY_COUNT = 18;
private readonly EventLogSession _session;
private readonly NativeWrapper.SystemProperties _systemProperties;
private string _containerChannel;
private int[] _matchedQueryIds;
// A dummy object which is used only for the locking.
private readonly object _syncObject;
// Cached DisplayNames for each instance
private string _levelName = null;
private string _taskName = null;
private string _opcodeName = null;
private IEnumerable<string> _keywordsNames = null;
// Cached DisplayNames for each instance
private bool _levelNameReady;
private bool _taskNameReady;
private bool _opcodeNameReady;
private readonly ProviderMetadataCachedInformation _cachedMetadataInformation;
internal EventLogRecord(EventLogHandle handle, EventLogSession session, ProviderMetadataCachedInformation cachedMetadataInfo)
{
_cachedMetadataInformation = cachedMetadataInfo;
Handle = handle;
_session = session;
_systemProperties = new NativeWrapper.SystemProperties();
_syncObject = new object();
}
internal EventLogHandle Handle
{
get;
}
internal void PrepareSystemData()
{
if (_systemProperties.filled)
return;
// Prepare the System Context, if it is not already initialized.
_session.SetupSystemContext();
lock (_syncObject)
{
if (_systemProperties.filled == false)
{
NativeWrapper.EvtRenderBufferWithContextSystem(_session.renderContextHandleSystem, Handle, UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues, _systemProperties, SYSTEM_PROPERTY_COUNT);
_systemProperties.filled = true;
}
}
}
public override int Id
{
get
{
PrepareSystemData();
if (_systemProperties.Id == null)
return 0;
return (int)_systemProperties.Id;
}
}
public override byte? Version
{
get
{
PrepareSystemData();
return _systemProperties.Version;
}
}
public override int? Qualifiers
{
get
{
PrepareSystemData();
return (int?)(uint?)_systemProperties.Qualifiers;
}
}
public override byte? Level
{
get
{
PrepareSystemData();
return _systemProperties.Level;
}
}
public override int? Task
{
get
{
PrepareSystemData();
return (int?)(uint?)_systemProperties.Task;
}
}
public override short? Opcode
{
get
{
PrepareSystemData();
return (short?)(ushort?)_systemProperties.Opcode;
}
}
public override long? Keywords
{
get
{
PrepareSystemData();
return (long?)_systemProperties.Keywords;
}
}
public override long? RecordId
{
get
{
PrepareSystemData();
return (long?)_systemProperties.RecordId;
}
}
public override string ProviderName
{
get
{
PrepareSystemData();
return _systemProperties.ProviderName;
}
}
public override Guid? ProviderId
{
get
{
PrepareSystemData();
return _systemProperties.ProviderId;
}
}
public override string LogName
{
get
{
PrepareSystemData();
return _systemProperties.ChannelName;
}
}
public override int? ProcessId
{
get
{
PrepareSystemData();
return (int?)_systemProperties.ProcessId;
}
}
public override int? ThreadId
{
get
{
PrepareSystemData();
return (int?)_systemProperties.ThreadId;
}
}
public override string MachineName
{
get
{
PrepareSystemData();
return _systemProperties.ComputerName;
}
}
public override System.Security.Principal.SecurityIdentifier UserId
{
get
{
PrepareSystemData();
return _systemProperties.UserId;
}
}
public override DateTime? TimeCreated
{
get
{
PrepareSystemData();
return _systemProperties.TimeCreated;
}
}
public override Guid? ActivityId
{
get
{
PrepareSystemData();
return _systemProperties.ActivityId;
}
}
public override Guid? RelatedActivityId
{
get
{
PrepareSystemData();
return _systemProperties.RelatedActivityId;
}
}
public string ContainerLog
{
get
{
if (_containerChannel != null)
return _containerChannel;
lock (_syncObject)
{
if (_containerChannel == null)
{
_containerChannel = (string)NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventPath);
}
return _containerChannel;
}
}
}
public IEnumerable<int> MatchedQueryIds
{
get
{
if (_matchedQueryIds != null)
return _matchedQueryIds;
lock (_syncObject)
{
if (_matchedQueryIds == null)
{
_matchedQueryIds = (int[])NativeWrapper.EvtGetEventInfo(this.Handle, UnsafeNativeMethods.EvtEventPropertyId.EvtEventQueryIDs);
}
return _matchedQueryIds;
}
}
}
public override EventBookmark Bookmark
{
get
{
EventLogHandle bookmarkHandle = NativeWrapper.EvtCreateBookmark(null);
NativeWrapper.EvtUpdateBookmark(bookmarkHandle, Handle);
string bookmarkText = NativeWrapper.EvtRenderBookmark(bookmarkHandle);
return new EventBookmark(bookmarkText);
}
}
public override string FormatDescription()
{
return _cachedMetadataInformation.GetFormatDescription(this.ProviderName, Handle);
}
public override string FormatDescription(IEnumerable<object> values)
{
if (values == null)
return this.FormatDescription();
// Copy the value IEnumerable to an array.
string[] theValues = Array.Empty<string>();
int i = 0;
foreach (object o in values)
{
if (theValues.Length == i)
Array.Resize(ref theValues, i + 1);
if (o is EventProperty elp)
{
theValues[i] = elp.Value.ToString();
}
else
{
theValues[i] = o.ToString();
}
i++;
}
return _cachedMetadataInformation.GetFormatDescription(this.ProviderName, Handle, theValues);
}
public override string LevelDisplayName
{
get
{
if (_levelNameReady)
return _levelName;
lock (_syncObject)
{
if (_levelNameReady == false)
{
_levelNameReady = true;
_levelName = _cachedMetadataInformation.GetLevelDisplayName(this.ProviderName, Handle);
}
return _levelName;
}
}
}
public override string OpcodeDisplayName
{
get
{
lock (_syncObject)
{
if (_opcodeNameReady == false)
{
_opcodeNameReady = true;
_opcodeName = _cachedMetadataInformation.GetOpcodeDisplayName(this.ProviderName, Handle);
}
return _opcodeName;
}
}
}
public override string TaskDisplayName
{
get
{
if (_taskNameReady == true)
return _taskName;
lock (_syncObject)
{
if (_taskNameReady == false)
{
_taskNameReady = true;
_taskName = _cachedMetadataInformation.GetTaskDisplayName(this.ProviderName, Handle);
}
return _taskName;
}
}
}
public override IEnumerable<string> KeywordsDisplayNames
{
get
{
if (_keywordsNames != null)
return _keywordsNames;
lock (_syncObject)
{
if (_keywordsNames == null)
{
_keywordsNames = _cachedMetadataInformation.GetKeywordDisplayNames(this.ProviderName, Handle);
}
return _keywordsNames;
}
}
}
public override IList<EventProperty> Properties
{
get
{
_session.SetupUserContext();
IList<object> properties = NativeWrapper.EvtRenderBufferWithContextUserOrValues(_session.renderContextHandleUser, Handle);
List<EventProperty> list = new List<EventProperty>();
foreach (object value in properties)
{
list.Add(new EventProperty(value));
}
return list;
}
}
public IList<object> GetPropertyValues(EventLogPropertySelector propertySelector)
{
if (propertySelector == null)
throw new ArgumentNullException(nameof(propertySelector));
return NativeWrapper.EvtRenderBufferWithContextUserOrValues(propertySelector.Handle, Handle);
}
public override string ToXml()
{
StringBuilder renderBuffer = new StringBuilder(2000);
NativeWrapper.EvtRender(EventLogHandle.Zero, Handle, UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventXml, renderBuffer);
return renderBuffer.ToString();
}
protected override void Dispose(bool disposing)
{
try
{
if (Handle != null && !Handle.IsInvalid)
Handle.Dispose();
}
finally
{
base.Dispose(disposing);
}
}
internal static EventLogHandle GetBookmarkHandleFromBookmark(EventBookmark bookmark)
{
if (bookmark == null)
return EventLogHandle.Zero;
EventLogHandle handle = NativeWrapper.EvtCreateBookmark(bookmark.BookmarkText);
return handle;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace EncompassRest.Loans
{
/// <summary>
/// PostClosingConditionLog
/// </summary>
public sealed partial class PostClosingConditionLog : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<string?>? _addedBy;
private DirtyList<LogAlert>? _alerts;
private DirtyValue<string?>? _alertsXml;
private DirtyValue<bool?>? _cleared;
private DirtyValue<string?>? _clearedBy;
private DirtyList<LogComment>? _commentList;
private DirtyValue<string?>? _commentListXml;
private DirtyValue<string?>? _comments;
private DirtyValue<DateTime?>? _dateAddedUtc;
private DirtyValue<DateTime?>? _dateClearedUtc;
private DirtyValue<DateTime?>? _dateExpected;
private DirtyValue<DateTime?>? _dateReceived;
private DirtyValue<DateTime?>? _dateRequestedUtc;
private DirtyValue<DateTime?>? _dateRerequestedUtc;
private DirtyValue<DateTime?>? _dateSentUtc;
private DirtyValue<DateTime?>? _dateUtc;
private DirtyValue<int?>? _daysTillDue;
private DirtyValue<string?>? _description;
private DirtyValue<string?>? _details;
private DirtyValue<bool?>? _expected;
private DirtyValue<bool?>? _fileAttachmentsMigrated;
private DirtyValue<string?>? _guid;
private DirtyValue<string?>? _id;
private DirtyValue<bool?>? _isExternalIndicator;
private DirtyValue<bool?>? _isInternalIndicator;
private DirtyValue<bool?>? _isMarkedRemoved;
private DirtyValue<bool?>? _isPastDue;
private DirtyValue<bool?>? _isSystemSpecificIndicator;
private DirtyValue<int?>? _logRecordIndex;
private DirtyValue<string?>? _pairId;
private DirtyValue<bool?>? _received;
private DirtyValue<string?>? _receivedBy;
private DirtyValue<string?>? _recipient;
private DirtyValue<bool?>? _requested;
private DirtyValue<string?>? _requestedBy;
private DirtyValue<string?>? _requestedFrom;
private DirtyValue<bool?>? _rerequested;
private DirtyValue<string?>? _rerequestedBy;
private DirtyValue<bool?>? _sent;
private DirtyValue<string?>? _sentBy;
private DirtyValue<string?>? _source;
private DirtyValue<string?>? _status;
private DirtyValue<string?>? _statusDescription;
private DirtyValue<string?>? _systemId;
private DirtyValue<string?>? _title;
private DirtyValue<DateTime?>? _updatedDateUtc;
/// <summary>
/// PostClosingConditionLog AddedBy
/// </summary>
public string? AddedBy { get => _addedBy; set => SetField(ref _addedBy, value); }
/// <summary>
/// PostClosingConditionLog Alerts
/// </summary>
[AllowNull]
public IList<LogAlert> Alerts { get => GetField(ref _alerts); set => SetField(ref _alerts, value); }
/// <summary>
/// PostClosingConditionLog AlertsXml
/// </summary>
public string? AlertsXml { get => _alertsXml; set => SetField(ref _alertsXml, value); }
/// <summary>
/// PostClosingConditionLog Cleared
/// </summary>
public bool? Cleared { get => _cleared; set => SetField(ref _cleared, value); }
/// <summary>
/// PostClosingConditionLog ClearedBy
/// </summary>
public string? ClearedBy { get => _clearedBy; set => SetField(ref _clearedBy, value); }
/// <summary>
/// PostClosingConditionLog CommentList
/// </summary>
[AllowNull]
public IList<LogComment> CommentList { get => GetField(ref _commentList); set => SetField(ref _commentList, value); }
/// <summary>
/// PostClosingConditionLog CommentListXml
/// </summary>
public string? CommentListXml { get => _commentListXml; set => SetField(ref _commentListXml, value); }
/// <summary>
/// PostClosingConditionLog Comments
/// </summary>
public string? Comments { get => _comments; set => SetField(ref _comments, value); }
/// <summary>
/// PostClosingConditionLog DateAddedUtc
/// </summary>
public DateTime? DateAddedUtc { get => _dateAddedUtc; set => SetField(ref _dateAddedUtc, value); }
/// <summary>
/// PostClosingConditionLog DateClearedUtc
/// </summary>
public DateTime? DateClearedUtc { get => _dateClearedUtc; set => SetField(ref _dateClearedUtc, value); }
/// <summary>
/// PostClosingConditionLog DateExpected
/// </summary>
public DateTime? DateExpected { get => _dateExpected; set => SetField(ref _dateExpected, value); }
/// <summary>
/// PostClosingConditionLog DateReceived
/// </summary>
public DateTime? DateReceived { get => _dateReceived; set => SetField(ref _dateReceived, value); }
/// <summary>
/// PostClosingConditionLog DateRequestedUtc
/// </summary>
public DateTime? DateRequestedUtc { get => _dateRequestedUtc; set => SetField(ref _dateRequestedUtc, value); }
/// <summary>
/// PostClosingConditionLog DateRerequestedUtc
/// </summary>
public DateTime? DateRerequestedUtc { get => _dateRerequestedUtc; set => SetField(ref _dateRerequestedUtc, value); }
/// <summary>
/// PostClosingConditionLog DateSentUtc
/// </summary>
public DateTime? DateSentUtc { get => _dateSentUtc; set => SetField(ref _dateSentUtc, value); }
/// <summary>
/// PostClosingConditionLog DateUtc
/// </summary>
public DateTime? DateUtc { get => _dateUtc; set => SetField(ref _dateUtc, value); }
/// <summary>
/// PostClosingConditionLog DaysTillDue
/// </summary>
public int? DaysTillDue { get => _daysTillDue; set => SetField(ref _daysTillDue, value); }
/// <summary>
/// PostClosingConditionLog Description
/// </summary>
public string? Description { get => _description; set => SetField(ref _description, value); }
/// <summary>
/// PostClosingConditionLog Details
/// </summary>
public string? Details { get => _details; set => SetField(ref _details, value); }
/// <summary>
/// PostClosingConditionLog Expected
/// </summary>
public bool? Expected { get => _expected; set => SetField(ref _expected, value); }
/// <summary>
/// PostClosingConditionLog FileAttachmentsMigrated
/// </summary>
public bool? FileAttachmentsMigrated { get => _fileAttachmentsMigrated; set => SetField(ref _fileAttachmentsMigrated, value); }
/// <summary>
/// PostClosingConditionLog Guid
/// </summary>
public string? Guid { get => _guid; set => SetField(ref _guid, value); }
/// <summary>
/// PostClosingConditionLog Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// PostClosingConditionLog IsExternalIndicator
/// </summary>
public bool? IsExternalIndicator { get => _isExternalIndicator; set => SetField(ref _isExternalIndicator, value); }
/// <summary>
/// PostClosingConditionLog IsInternalIndicator
/// </summary>
public bool? IsInternalIndicator { get => _isInternalIndicator; set => SetField(ref _isInternalIndicator, value); }
/// <summary>
/// PostClosingConditionLog IsMarkedRemoved
/// </summary>
public bool? IsMarkedRemoved { get => _isMarkedRemoved; set => SetField(ref _isMarkedRemoved, value); }
/// <summary>
/// PostClosingConditionLog IsPastDue
/// </summary>
public bool? IsPastDue { get => _isPastDue; set => SetField(ref _isPastDue, value); }
/// <summary>
/// PostClosingConditionLog IsSystemSpecificIndicator
/// </summary>
public bool? IsSystemSpecificIndicator { get => _isSystemSpecificIndicator; set => SetField(ref _isSystemSpecificIndicator, value); }
/// <summary>
/// PostClosingConditionLog LogRecordIndex
/// </summary>
public int? LogRecordIndex { get => _logRecordIndex; set => SetField(ref _logRecordIndex, value); }
/// <summary>
/// PostClosingConditionLog PairId
/// </summary>
public string? PairId { get => _pairId; set => SetField(ref _pairId, value); }
/// <summary>
/// PostClosingConditionLog Received
/// </summary>
public bool? Received { get => _received; set => SetField(ref _received, value); }
/// <summary>
/// PostClosingConditionLog ReceivedBy
/// </summary>
public string? ReceivedBy { get => _receivedBy; set => SetField(ref _receivedBy, value); }
/// <summary>
/// PostClosingConditionLog Recipient
/// </summary>
public string? Recipient { get => _recipient; set => SetField(ref _recipient, value); }
/// <summary>
/// PostClosingConditionLog Requested
/// </summary>
public bool? Requested { get => _requested; set => SetField(ref _requested, value); }
/// <summary>
/// PostClosingConditionLog RequestedBy
/// </summary>
public string? RequestedBy { get => _requestedBy; set => SetField(ref _requestedBy, value); }
/// <summary>
/// PostClosingConditionLog RequestedFrom
/// </summary>
public string? RequestedFrom { get => _requestedFrom; set => SetField(ref _requestedFrom, value); }
/// <summary>
/// PostClosingConditionLog Rerequested
/// </summary>
public bool? Rerequested { get => _rerequested; set => SetField(ref _rerequested, value); }
/// <summary>
/// PostClosingConditionLog RerequestedBy
/// </summary>
public string? RerequestedBy { get => _rerequestedBy; set => SetField(ref _rerequestedBy, value); }
/// <summary>
/// PostClosingConditionLog Sent
/// </summary>
public bool? Sent { get => _sent; set => SetField(ref _sent, value); }
/// <summary>
/// PostClosingConditionLog SentBy
/// </summary>
public string? SentBy { get => _sentBy; set => SetField(ref _sentBy, value); }
/// <summary>
/// PostClosingConditionLog Source
/// </summary>
public string? Source { get => _source; set => SetField(ref _source, value); }
/// <summary>
/// PostClosingConditionLog Status
/// </summary>
public string? Status { get => _status; set => SetField(ref _status, value); }
/// <summary>
/// PostClosingConditionLog StatusDescription
/// </summary>
public string? StatusDescription { get => _statusDescription; set => SetField(ref _statusDescription, value); }
/// <summary>
/// PostClosingConditionLog SystemId
/// </summary>
public string? SystemId { get => _systemId; set => SetField(ref _systemId, value); }
/// <summary>
/// PostClosingConditionLog Title
/// </summary>
public string? Title { get => _title; set => SetField(ref _title, value); }
/// <summary>
/// PostClosingConditionLog UpdatedDateUtc
/// </summary>
public DateTime? UpdatedDateUtc { get => _updatedDateUtc; set => SetField(ref _updatedDateUtc, value); }
}
}
| |
// ***********************************************************************
// Copyright (c) 2012-2014 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
namespace NUnit.Framework.Api
{
/// <summary>
/// DefaultTestAssemblyBuilder loads a single assembly and builds a TestSuite
/// containing test fixtures present in the assembly.
/// </summary>
public class DefaultTestAssemblyBuilder : ITestAssemblyBuilder
{
static readonly Logger log = InternalTrace.GetLogger(typeof(DefaultTestAssemblyBuilder));
#region Instance Fields
/// <summary>
/// The default suite builder used by the test assembly builder.
/// </summary>
readonly ISuiteBuilder _defaultSuiteBuilder;
private PreFilter _filter;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DefaultTestAssemblyBuilder"/> class.
/// </summary>
public DefaultTestAssemblyBuilder()
{
_defaultSuiteBuilder = new DefaultSuiteBuilder();
}
#endregion
#region Build Methods
/// <summary>
/// Build a suite of tests from a provided assembly
/// </summary>
/// <param name="assembly">The assembly from which tests are to be built</param>
/// <param name="options">A dictionary of options to use in building the suite</param>
/// <returns>
/// A TestSuite containing the tests found in the assembly
/// </returns>
public ITest Build(Assembly assembly, IDictionary<string, object> options)
{
#if NETSTANDARD1_4
log.Debug("Loading {0}", assembly.FullName);
#else
log.Debug("Loading {0} in AppDomain {1}", assembly.FullName, AppDomain.CurrentDomain.FriendlyName);
#endif
string assemblyPath = AssemblyHelper.GetAssemblyPath(assembly);
string suiteName = assemblyPath.Equals("<Unknown>")
? AssemblyHelper.GetAssemblyName(assembly).FullName
: Path.GetFileName(assemblyPath);
return Build(assembly, suiteName, options);
}
/// <summary>
/// Build a suite of tests given the name or the location of an assembly
/// </summary>
/// <param name="assemblyNameOrPath">The name or the location of the assembly.</param>
/// <param name="options">A dictionary of options to use in building the suite</param>
/// <returns>
/// A TestSuite containing the tests found in the assembly
/// </returns>
public ITest Build(string assemblyNameOrPath, IDictionary<string, object> options)
{
#if NETSTANDARD1_4
log.Debug("Loading {0}", assemblyNameOrPath);
#else
log.Debug("Loading {0} in AppDomain {1}", assemblyNameOrPath, AppDomain.CurrentDomain.FriendlyName);
#endif
TestSuite testAssembly = null;
try
{
var assembly = AssemblyHelper.Load(assemblyNameOrPath);
testAssembly = Build(assembly, Path.GetFileName(assemblyNameOrPath), options);
}
catch (Exception ex)
{
testAssembly = new TestAssembly(Path.GetFileName(assemblyNameOrPath));
testAssembly.MakeInvalid(ExceptionHelper.BuildMessage(ex, true));
}
return testAssembly;
}
private TestSuite Build(Assembly assembly, string suiteName, IDictionary<string, object> options)
{
TestSuite testAssembly = null;
try
{
if (options.ContainsKey(FrameworkPackageSettings.DefaultTestNamePattern))
TestNameGenerator.DefaultTestNamePattern = options[FrameworkPackageSettings.DefaultTestNamePattern] as string;
if (options.ContainsKey(FrameworkPackageSettings.WorkDirectory))
TestContext.DefaultWorkDirectory = options[FrameworkPackageSettings.WorkDirectory] as string;
else
TestContext.DefaultWorkDirectory = Directory.GetCurrentDirectory();
if (options.ContainsKey(FrameworkPackageSettings.TestParametersDictionary))
{
var testParametersDictionary = options[FrameworkPackageSettings.TestParametersDictionary] as IDictionary<string, string>;
if (testParametersDictionary != null)
{
foreach (var parameter in testParametersDictionary)
TestContext.Parameters.Add(parameter.Key, parameter.Value);
}
}
else
{
// This cannot be changed without breaking backwards compatibility with old runners.
// Deserializes the way old runners understand.
if (options.ContainsKey(FrameworkPackageSettings.TestParameters))
{
string parameters = options[FrameworkPackageSettings.TestParameters] as string;
if (!string.IsNullOrEmpty(parameters))
foreach (string param in parameters.Split(new[] { ';' }))
{
int eq = param.IndexOf("=");
if (eq > 0 && eq < param.Length - 1)
{
var name = param.Substring(0, eq);
var val = param.Substring(eq + 1);
TestContext.Parameters.Add(name, val);
}
}
}
}
_filter = new PreFilter();
if (options.ContainsKey(FrameworkPackageSettings.LOAD))
foreach (string filterText in (IList)options[FrameworkPackageSettings.LOAD])
_filter.Add(filterText);
var fixtures = GetFixtures(assembly);
testAssembly = BuildTestAssembly(assembly, suiteName, fixtures);
}
catch (Exception ex)
{
testAssembly = new TestAssembly(suiteName);
testAssembly.MakeInvalid(ExceptionHelper.BuildMessage(ex, true));
}
return testAssembly;
}
#endregion
#region Helper Methods
private IList<Test> GetFixtures(Assembly assembly)
{
var fixtures = new List<Test>();
log.Debug("Examining assembly for test fixtures");
var testTypes = GetCandidateFixtureTypes(assembly);
log.Debug("Found {0} classes to examine", testTypes.Count);
#if LOAD_TIMING
System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
timer.Start();
#endif
int testcases = 0;
foreach (Type testType in testTypes)
{
var typeInfo = new TypeWrapper(testType);
// Any exceptions from this call are fatal problems in NUnit itself,
// since this is always DefaultSuiteBuilder and the current implementation
// of DefaultSuiteBuilder.CanBuildFrom cannot invoke any user code.
if (_defaultSuiteBuilder.CanBuildFrom(typeInfo))
{
// We pass the filter for use in selecting methods of the type.
// Any exceptions from this call are fatal problems in NUnit itself,
// since this is always DefaultSuiteBuilder and the current implementation
// of DefaultSuiteBuilder.BuildFrom handles all exceptions from user code.
Test fixture = _defaultSuiteBuilder.BuildFrom(typeInfo, _filter);
fixtures.Add(fixture);
testcases += fixture.TestCaseCount;
}
}
#if LOAD_TIMING
log.Debug("Found {0} fixtures with {1} test cases in {2} seconds", fixtures.Count, testcases, timer.Elapsed);
#else
log.Debug("Found {0} fixtures with {1} test cases", fixtures.Count, testcases);
#endif
return fixtures;
}
private IList<Type> GetCandidateFixtureTypes(Assembly assembly)
{
var result = new List<Type>();
foreach (Type type in assembly.GetTypes())
if (_filter.IsMatch(type))
result.Add(type);
return result;
}
// This method invokes members on the 'System.Diagnostics.Process' class and must satisfy the link demand of
// the full-trust 'PermissionSetAttribute' on this class. Callers of this method have no influence on how the
// Process class is used, so we can safely satisfy the link demand with a 'SecuritySafeCriticalAttribute' rather
// than a 'SecurityCriticalAttribute' and allow use by security transparent callers.
[SecuritySafeCritical]
private TestSuite BuildTestAssembly(Assembly assembly, string suiteName, IList<Test> fixtures)
{
TestSuite testAssembly = new TestAssembly(assembly, suiteName);
if (fixtures.Count == 0)
{
testAssembly.MakeInvalid("Has no TestFixtures");
}
else
{
NamespaceTreeBuilder treeBuilder =
new NamespaceTreeBuilder(testAssembly);
treeBuilder.Add(fixtures);
testAssembly = treeBuilder.RootSuite;
}
testAssembly.ApplyAttributesToTest(assembly);
#if !NETSTANDARD1_4
testAssembly.Properties.Set(PropertyNames.ProcessID, System.Diagnostics.Process.GetCurrentProcess().Id);
testAssembly.Properties.Set(PropertyNames.AppDomain, AppDomain.CurrentDomain.FriendlyName);
#endif
// TODO: Make this an option? Add Option to sort assemblies as well?
testAssembly.Sort();
return testAssembly;
}
#endregion
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Ntfs
{
using System;
using System.Collections.Generic;
using System.IO;
internal delegate void IndexNodeSaveFn();
internal class IndexNode
{
private IndexNodeSaveFn _store;
private int _storageOverhead;
private long _totalSpaceAvailable;
private IndexHeader _header;
private Index _index;
private bool _isRoot;
private List<IndexEntry> _entries;
public IndexNode(IndexNodeSaveFn store, int storeOverhead, Index index, bool isRoot, uint allocatedSize)
{
_store = store;
_storageOverhead = storeOverhead;
_index = index;
_isRoot = isRoot;
_header = new IndexHeader(allocatedSize);
_totalSpaceAvailable = allocatedSize;
IndexEntry endEntry = new IndexEntry(_index.IsFileIndex);
endEntry.Flags |= IndexEntryFlags.End;
_entries = new List<IndexEntry>();
_entries.Add(endEntry);
_header.OffsetToFirstEntry = (uint)(IndexHeader.Size + storeOverhead);
_header.TotalSizeOfEntries = (uint)(_header.OffsetToFirstEntry + endEntry.Size);
}
public IndexNode(IndexNodeSaveFn store, int storeOverhead, Index index, bool isRoot, byte[] buffer, int offset)
{
_store = store;
_storageOverhead = storeOverhead;
_index = index;
_isRoot = isRoot;
_header = new IndexHeader(buffer, offset + 0);
_totalSpaceAvailable = _header.AllocatedSizeOfEntries;
_entries = new List<IndexEntry>();
int pos = (int)_header.OffsetToFirstEntry;
while (pos < _header.TotalSizeOfEntries)
{
IndexEntry entry = new IndexEntry(index.IsFileIndex);
entry.Read(buffer, offset + pos);
_entries.Add(entry);
if ((entry.Flags & IndexEntryFlags.End) != 0)
{
break;
}
pos += entry.Size;
}
}
public IndexHeader Header
{
get { return _header; }
}
public IEnumerable<IndexEntry> Entries
{
get { return _entries; }
}
internal long TotalSpaceAvailable
{
get { return _totalSpaceAvailable; }
set { _totalSpaceAvailable = value; }
}
private long SpaceFree
{
get
{
long entriesTotal = 0;
for (int i = 0; i < _entries.Count; ++i)
{
entriesTotal += _entries[i].Size;
}
int firstEntryOffset = Utilities.RoundUp(IndexHeader.Size + _storageOverhead, 8);
return _totalSpaceAvailable - (entriesTotal + firstEntryOffset);
}
}
public void AddEntry(byte[] key, byte[] data)
{
IndexEntry overflowEntry = AddEntry(new IndexEntry(key, data, _index.IsFileIndex));
if (overflowEntry != null)
{
throw new IOException("Error adding entry - root overflowed");
}
}
public void UpdateEntry(byte[] key, byte[] data)
{
for (int i = 0; i < _entries.Count; ++i)
{
var focus = _entries[i];
int compVal = _index.Compare(key, focus.KeyBuffer);
if (compVal == 0)
{
IndexEntry newEntry = new IndexEntry(focus, key, data);
if (_entries[i].Size != newEntry.Size)
{
throw new NotImplementedException("Changing index entry sizes");
}
_entries[i] = newEntry;
_store();
return;
}
}
throw new IOException("No such index entry");
}
public bool TryFindEntry(byte[] key, out IndexEntry entry, out IndexNode node)
{
foreach (var focus in _entries)
{
if ((focus.Flags & IndexEntryFlags.End) != 0)
{
if ((focus.Flags & IndexEntryFlags.Node) != 0)
{
IndexBlock subNode = _index.GetSubBlock(focus);
return subNode.Node.TryFindEntry(key, out entry, out node);
}
break;
}
else
{
int compVal = _index.Compare(key, focus.KeyBuffer);
if (compVal == 0)
{
entry = focus;
node = this;
return true;
}
else if (compVal < 0 && (focus.Flags & (IndexEntryFlags.End | IndexEntryFlags.Node)) != 0)
{
IndexBlock subNode = _index.GetSubBlock(focus);
return subNode.Node.TryFindEntry(key, out entry, out node);
}
}
}
entry = null;
node = null;
return false;
}
public virtual ushort WriteTo(byte[] buffer, int offset)
{
bool haveSubNodes = false;
uint totalEntriesSize = 0;
foreach (var entry in _entries)
{
totalEntriesSize += (uint)entry.Size;
haveSubNodes |= (entry.Flags & IndexEntryFlags.Node) != 0;
}
_header.OffsetToFirstEntry = (uint)Utilities.RoundUp(IndexHeader.Size + _storageOverhead, 8);
_header.TotalSizeOfEntries = totalEntriesSize + _header.OffsetToFirstEntry;
_header.HasChildNodes = (byte)(haveSubNodes ? 1 : 0);
_header.WriteTo(buffer, offset + 0);
int pos = (int)_header.OffsetToFirstEntry;
foreach (var entry in _entries)
{
entry.WriteTo(buffer, offset + pos);
pos += entry.Size;
}
return IndexHeader.Size;
}
public int CalcEntriesSize()
{
int totalEntriesSize = 0;
foreach (var entry in _entries)
{
totalEntriesSize += entry.Size;
}
return totalEntriesSize;
}
public virtual int CalcSize()
{
int firstEntryOffset = Utilities.RoundUp(IndexHeader.Size + _storageOverhead, 8);
return firstEntryOffset + CalcEntriesSize();
}
public int GetEntry(byte[] key, out bool exactMatch)
{
for (int i = 0; i < _entries.Count; ++i)
{
var focus = _entries[i];
int compVal;
if ((focus.Flags & IndexEntryFlags.End) != 0)
{
exactMatch = false;
return i;
}
else
{
compVal = _index.Compare(key, focus.KeyBuffer);
if (compVal <= 0)
{
exactMatch = compVal == 0;
return i;
}
}
}
throw new IOException("Corrupt index node - no End entry");
}
public bool RemoveEntry(byte[] key, out IndexEntry newParentEntry)
{
bool exactMatch;
int entryIndex = GetEntry(key, out exactMatch);
IndexEntry entry = _entries[entryIndex];
if (exactMatch)
{
if ((entry.Flags & IndexEntryFlags.Node) != 0)
{
IndexNode childNode = _index.GetSubBlock(entry).Node;
IndexEntry rLeaf = childNode.FindLargestLeaf();
byte[] newKey = rLeaf.KeyBuffer;
byte[] newData = rLeaf.DataBuffer;
IndexEntry newEntry;
childNode.RemoveEntry(newKey, out newEntry);
entry.KeyBuffer = newKey;
entry.DataBuffer = newData;
if (newEntry != null)
{
InsertEntryThisNode(newEntry);
}
newEntry = LiftNode(entryIndex);
if (newEntry != null)
{
InsertEntryThisNode(newEntry);
}
newEntry = PopulateEnd();
if (newEntry != null)
{
InsertEntryThisNode(newEntry);
}
// New entry could be larger than old, so may need
// to divide this node...
newParentEntry = EnsureNodeSize();
}
else
{
_entries.RemoveAt(entryIndex);
newParentEntry = null;
}
_store();
return true;
}
else if ((entry.Flags & IndexEntryFlags.Node) != 0)
{
IndexNode childNode = _index.GetSubBlock(entry).Node;
IndexEntry newEntry;
if (childNode.RemoveEntry(key, out newEntry))
{
if (newEntry != null)
{
InsertEntryThisNode(newEntry);
}
newEntry = LiftNode(entryIndex);
if (newEntry != null)
{
InsertEntryThisNode(newEntry);
}
newEntry = PopulateEnd();
if (newEntry != null)
{
InsertEntryThisNode(newEntry);
}
// New entry could be larger than old, so may need
// to divide this node...
newParentEntry = EnsureNodeSize();
_store();
return true;
}
}
newParentEntry = null;
return false;
}
/// <summary>
/// Only valid on the root node, this method moves all entries into a
/// single child node.
/// </summary>
/// <returns>Whether any changes were made.</returns>
internal bool Depose()
{
if (!_isRoot)
{
throw new InvalidOperationException("Only valid on root node");
}
if (_entries.Count == 1)
{
return false;
}
IndexEntry newRootEntry = new IndexEntry(_index.IsFileIndex);
newRootEntry.Flags = IndexEntryFlags.End;
IndexBlock newBlock = _index.AllocateBlock(newRootEntry);
// Set the deposed entries into the new node. Note we updated the parent
// pointers first, because it's possible SetEntries may need to further
// divide the entries to fit into nodes. We mustn't overwrite any changes.
newBlock.Node.SetEntries(_entries, 0, _entries.Count);
_entries.Clear();
_entries.Add(newRootEntry);
return true;
}
/// <summary>
/// Removes redundant nodes (that contain only an 'End' entry).
/// </summary>
/// <param name="entryIndex">The index of the entry that may have a redundant child.</param>
/// <returns>An entry that needs to be promoted to the parent node (if any).</returns>
private IndexEntry LiftNode(int entryIndex)
{
if ((_entries[entryIndex].Flags & IndexEntryFlags.Node) != 0)
{
IndexNode childNode = _index.GetSubBlock(_entries[entryIndex]).Node;
if (childNode._entries.Count == 1)
{
long freeBlock = _entries[entryIndex].ChildrenVirtualCluster;
_entries[entryIndex].Flags = (_entries[entryIndex].Flags & ~IndexEntryFlags.Node) | (childNode._entries[0].Flags & IndexEntryFlags.Node);
_entries[entryIndex].ChildrenVirtualCluster = childNode._entries[0].ChildrenVirtualCluster;
_index.FreeBlock(freeBlock);
}
if ((_entries[entryIndex].Flags & (IndexEntryFlags.Node | IndexEntryFlags.End)) == 0)
{
IndexEntry entry = _entries[entryIndex];
_entries.RemoveAt(entryIndex);
IndexNode nextNode = _index.GetSubBlock(_entries[entryIndex]).Node;
return nextNode.AddEntry(entry);
}
}
return null;
}
private IndexEntry PopulateEnd()
{
if (_entries.Count > 1
&& _entries[_entries.Count - 1].Flags == IndexEntryFlags.End
&& (_entries[_entries.Count - 2].Flags & IndexEntryFlags.Node) != 0)
{
IndexEntry old = _entries[_entries.Count - 2];
_entries.RemoveAt(_entries.Count - 2);
_entries[_entries.Count - 1].ChildrenVirtualCluster = old.ChildrenVirtualCluster;
_entries[_entries.Count - 1].Flags |= IndexEntryFlags.Node;
old.ChildrenVirtualCluster = 0;
old.Flags = IndexEntryFlags.None;
return _index.GetSubBlock(_entries[_entries.Count - 1]).Node.AddEntry(old);
}
return null;
}
private void InsertEntryThisNode(IndexEntry newEntry)
{
bool exactMatch;
int index = GetEntry(newEntry.KeyBuffer, out exactMatch);
if (exactMatch)
{
throw new InvalidOperationException("Entry already exists");
}
else
{
_entries.Insert(index, newEntry);
}
}
private IndexEntry AddEntry(IndexEntry newEntry)
{
bool exactMatch;
int index = GetEntry(newEntry.KeyBuffer, out exactMatch);
if (exactMatch)
{
throw new InvalidOperationException("Entry already exists");
}
if ((_entries[index].Flags & IndexEntryFlags.Node) != 0)
{
IndexEntry ourNewEntry = _index.GetSubBlock(_entries[index]).Node.AddEntry(newEntry);
if (ourNewEntry == null)
{
// No change to this node
return null;
}
InsertEntryThisNode(ourNewEntry);
}
else
{
_entries.Insert(index, newEntry);
}
// If there wasn't enough space, we may need to
// divide this node
IndexEntry newParentEntry = EnsureNodeSize();
_store();
return newParentEntry;
}
private IndexEntry EnsureNodeSize()
{
// While the node is too small to hold the entries, we need to reduce
// the number of entries.
if (SpaceFree < 0)
{
if (_isRoot)
{
Depose();
}
else
{
return Divide();
}
}
return null;
}
/// <summary>
/// Finds the largest leaf entry in this tree.
/// </summary>
/// <returns>The index entry of the largest leaf.</returns>
private IndexEntry FindLargestLeaf()
{
if ((_entries[_entries.Count - 1].Flags & IndexEntryFlags.Node) != 0)
{
return _index.GetSubBlock(_entries[_entries.Count - 1]).Node.FindLargestLeaf();
}
else if (_entries.Count > 1 && (_entries[_entries.Count - 2].Flags & IndexEntryFlags.Node) == 0)
{
return _entries[_entries.Count - 2];
}
else
{
throw new IOException("Invalid index node found");
}
}
/// <summary>
/// Only valid on non-root nodes, this method divides the node in two,
/// adding the new node to the current parent.
/// </summary>
/// <returns>An entry that needs to be promoted to the parent node (if any).</returns>
private IndexEntry Divide()
{
int midEntryIdx = _entries.Count / 2;
IndexEntry midEntry = _entries[midEntryIdx];
// The terminating entry (aka end) for the new node
IndexEntry newTerm = new IndexEntry(_index.IsFileIndex);
newTerm.Flags |= IndexEntryFlags.End;
// The set of entries in the new node
List<IndexEntry> newEntries = new List<IndexEntry>(midEntryIdx + 1);
for (int i = 0; i < midEntryIdx; ++i)
{
newEntries.Add(_entries[i]);
}
newEntries.Add(newTerm);
// Copy the node pointer from the elected 'mid' entry to the new node
if ((midEntry.Flags & IndexEntryFlags.Node) != 0)
{
newTerm.ChildrenVirtualCluster = midEntry.ChildrenVirtualCluster;
newTerm.Flags |= IndexEntryFlags.Node;
}
// Set the new entries into the new node
IndexBlock newBlock = _index.AllocateBlock(midEntry);
// Set the entries into the new node. Note we updated the parent
// pointers first, because it's possible SetEntries may need to further
// divide the entries to fit into nodes. We mustn't overwrite any changes.
newBlock.Node.SetEntries(newEntries, 0, newEntries.Count);
// Forget about the entries moved into the new node, and the entry about
// to be promoted as the new node's pointer
_entries.RemoveRange(0, midEntryIdx + 1);
// Promote the old mid entry
return midEntry;
}
private void SetEntries(IList<IndexEntry> newEntries, int offset, int count)
{
_entries.Clear();
for (int i = 0; i < count; ++i)
{
_entries.Add(newEntries[i + offset]);
}
// Add an end entry, if not present
if (count == 0 || (_entries[_entries.Count - 1].Flags & IndexEntryFlags.End) == 0)
{
IndexEntry end = new IndexEntry(_index.IsFileIndex);
end.Flags = IndexEntryFlags.End;
_entries.Add(end);
}
// Ensure the node isn't over-filled
if (SpaceFree < 0)
{
throw new IOException("Error setting node entries - oversized for node");
}
// Persist the new entries to disk
_store();
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.OData.Query;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Services.Query;
using Microsoft.Data.Edm;
using Microsoft.Data.Edm.Library;
using Microsoft.Data.OData;
using Microsoft.Data.OData.Query;
using Microsoft.Data.OData.Query.SemanticAst;
using Microsoft.Xrm.Sdk.Query;
namespace Adxstudio.Xrm.Web.Http.OData.FetchXml
{
/// <summary>
/// Provides operations to translate <see cref="System.Web.Http.OData.Query.ODataQueryOptions"/> <see cref="System.Web.Http.OData.Query.FilterQueryOption"/> to equivalent filters in FetchXml.
/// </summary>
public class FetchFilterBinder
{
private static bool _applyLogicalNegation;
/// <summary>
/// Bind the <see cref="FilterQueryOption"/> to a FetchXml Filter
/// </summary>
/// <param name="filterQueryOption"><see cref="FilterQueryOption"/></param>
/// <returns><see cref="Filter"/></returns>
public static Filter BindFilterQueryOption(FilterQueryOption filterQueryOption)
{
_applyLogicalNegation = false;
return BindFilterClause(filterQueryOption.FilterClause);
}
protected static Filter BindFilterClause(FilterClause filterClause)
{
return Bind(filterClause.Expression);
}
protected static Filter Bind(QueryNode node)
{
var singleValueNode = node as SingleValueNode;
if (singleValueNode != null)
{
switch (node.Kind)
{
case QueryNodeKind.BinaryOperator:
return BindBinaryOperatorNode(node as BinaryOperatorNode);
case QueryNodeKind.Convert:
return BindConvertNode(node as ConvertNode);
case QueryNodeKind.EntityRangeVariableReference:
return null;
case QueryNodeKind.NonentityRangeVariableReference:
return null;
case QueryNodeKind.UnaryOperator:
return BindUnaryOperatorNode(node as UnaryOperatorNode);
case QueryNodeKind.SingleValueFunctionCall:
var condition = BindSingleValueFunctionCallNode(node as SingleValueFunctionCallNode);
return new Filter { Conditions = new List<Condition> { condition } };
}
}
throw new NotSupportedException(string.Format("Query Nodes of type {0} aren't supported.", node.Kind));
}
private static Condition BindSingleValueFunctionCallNode(SingleValueFunctionCallNode singleValueFunctionCallNode)
{
switch (singleValueFunctionCallNode.Name)
{
case "startswith":
return BindStartsWith(singleValueFunctionCallNode);
case "endswith":
return BindEndsWith(singleValueFunctionCallNode);
case "substringof":
return BindSubstringof(singleValueFunctionCallNode);
default:
throw new NotSupportedException(string.Format("Function call {0} isn't supported.", singleValueFunctionCallNode.Name));
}
}
private static Condition BindStartsWith(SingleValueFunctionCallNode singleValueFunctionCallNode)
{
var arguments = singleValueFunctionCallNode.Arguments.ToList();
if (arguments.Count != 2)
{
throw new ODataException(string.Format("Invalid {0} function call. The 2 required parameters have not been specified.", singleValueFunctionCallNode.Name));
}
var condition = new Condition { Operator = _applyLogicalNegation ? ConditionOperator.NotLike : ConditionOperator.Like };
var singleValuePropertyAccessNode = arguments[0] as SingleValuePropertyAccessNode;
if (singleValuePropertyAccessNode == null)
{
throw new ODataException(string.Format("Invalid {0} function call. A valid property name must be specified as the {1} parameter.", singleValueFunctionCallNode.Name, "first"));
}
condition.Attribute = BindPropertyAccessQueryNode(singleValuePropertyAccessNode);
var constantNode = arguments[1] as ConstantNode;
if (constantNode == null)
{
throw new ODataException(string.Format("Invalid {0} function call. A valid string value must be specified as the {1} parameter.", singleValueFunctionCallNode.Name, "second"));
}
var value = BindConstantNode(constantNode);
if (value == null)
{
throw new ODataException(string.Format("Invalid {0} function call. Null constant not applicable.", singleValueFunctionCallNode.Name));
}
condition.Value = string.Format("{0}%", value);
return condition;
}
private static Condition BindEndsWith(SingleValueFunctionCallNode singleValueFunctionCallNode)
{
var arguments = singleValueFunctionCallNode.Arguments.ToList();
if (arguments.Count != 2)
{
throw new ODataException(string.Format("Invalid {0} function call. The 2 required parameters have not been specified.", singleValueFunctionCallNode.Name));
}
var condition = new Condition { Operator = _applyLogicalNegation ? ConditionOperator.NotLike : ConditionOperator.Like };
var singleValuePropertyAccessNode = arguments[0] as SingleValuePropertyAccessNode;
if (singleValuePropertyAccessNode == null)
{
throw new ODataException(string.Format("Invalid {0} function call. A valid property name must be specified as the {1} parameter.", singleValueFunctionCallNode.Name, "first"));
}
condition.Attribute = BindPropertyAccessQueryNode(singleValuePropertyAccessNode);
var constantNode = arguments[1] as ConstantNode;
if (constantNode == null)
{
throw new ODataException(string.Format("Invalid {0} function call. A valid string value must be specified as the {1} parameter.", singleValueFunctionCallNode.Name, "second"));
}
var value = BindConstantNode(constantNode);
if (value == null)
{
throw new ODataException(string.Format("Invalid {0} function call. Null constant not applicable.", singleValueFunctionCallNode.Name));
}
condition.Value = string.Format("%{0}", value);
return condition;
}
private static Condition BindSubstringof(SingleValueFunctionCallNode singleValueFunctionCallNode)
{
var arguments = singleValueFunctionCallNode.Arguments.ToList();
if (arguments.Count != 2)
{
throw new ODataException(string.Format("Invalid {0} function call. The 2 required parameters have not been specified.", singleValueFunctionCallNode.Name));
}
var condition = new Condition { Operator = _applyLogicalNegation ? ConditionOperator.NotLike : ConditionOperator.Like };
var singleValuePropertyAccessNode = arguments[1] as SingleValuePropertyAccessNode;
if (singleValuePropertyAccessNode == null)
{
throw new ODataException(string.Format("Invalid {0} function call. A valid property name must be specified as the {1} parameter.", singleValueFunctionCallNode.Name, "second"));
}
condition.Attribute = BindPropertyAccessQueryNode(singleValuePropertyAccessNode);
var constantNode = arguments[0] as ConstantNode;
if (constantNode == null)
{
throw new ODataException(string.Format("Invalid {0} function call. A valid string value must be specified as the {1} parameter.", singleValueFunctionCallNode.Name, "first"));
}
var value = BindConstantNode(constantNode);
if (value == null)
{
throw new ODataException(string.Format("Invalid {0} function call. Null constant not applicable.", singleValueFunctionCallNode.Name));
}
condition.Value = string.Format("%{0}%", value);
return condition;
}
private static Filter BindUnaryOperatorNode(UnaryOperatorNode unaryOperatorNode)
{
switch (unaryOperatorNode.OperatorKind)
{
case UnaryOperatorKind.Negate:
throw new NotSupportedException("The Negate arithmetic operator isn't supported.");
case UnaryOperatorKind.Not:
_applyLogicalNegation = true;
break;
default:
throw new NotSupportedException("Unknown UnaryOperatorKind.");
}
return Bind(unaryOperatorNode.Operand);
}
private static string BindPropertyAccessQueryNode(SingleValuePropertyAccessNode singleValuePropertyAccessNode)
{
if (singleValuePropertyAccessNode.Source.TypeReference.Definition.TypeKind == EdmTypeKind.Complex)
{
var type = singleValuePropertyAccessNode.Source.TypeReference.Definition as EdmComplexType;
if (type == null)
{
return singleValuePropertyAccessNode.Property.Name;
}
switch (type.Name)
{
case "OptionSet":
case "EntityReference":
if (singleValuePropertyAccessNode.Property.Name == "Name")
{
throw new ODataException(string.Format("Equality comparison on Complex type {0} property {1} isn't supported.", type.Name, singleValuePropertyAccessNode.Property.Name));
}
var sourceSingleValuePropertyAccessNode = singleValuePropertyAccessNode.Source as SingleValuePropertyAccessNode;
if (sourceSingleValuePropertyAccessNode != null)
{
return sourceSingleValuePropertyAccessNode.Property.Name;
}
break;
}
}
return singleValuePropertyAccessNode.Property.Name;
}
private static object BindConstantNode(ConstantNode constantNode)
{
return constantNode.Value;
}
private static Filter BindConvertNode(ConvertNode convertNode)
{
return Bind(convertNode.Source);
}
private static Filter BindBinaryOperatorNode(BinaryOperatorNode binaryOperatorNode)
{
var filter = new Filter();
switch (binaryOperatorNode.OperatorKind)
{
case BinaryOperatorKind.And:
filter.Type = !_applyLogicalNegation ? LogicalOperator.And : LogicalOperator.Or;
break;
case BinaryOperatorKind.Or:
filter.Type = !_applyLogicalNegation ? LogicalOperator.Or : LogicalOperator.And;
break;
default:
filter.Type = !_applyLogicalNegation ? LogicalOperator.And : LogicalOperator.Or;
break;
}
if (binaryOperatorNode.Left is SingleValuePropertyAccessNode)
{
filter.Conditions = new List<Condition> { CreateBinaryCondition(binaryOperatorNode) };
}
else
{
var left = Bind(binaryOperatorNode.Left);
var right = Bind(binaryOperatorNode.Right);
if (filter.Filters == null)
{
filter.Filters = new List<Filter> { left, right };
}
else
{
filter.Filters.Add(left);
filter.Filters.Add(right);
}
}
return filter;
}
private static Condition CreateBinaryCondition(BinaryOperatorNode binaryOperatorNode)
{
if (binaryOperatorNode.OperatorKind == BinaryOperatorKind.And || binaryOperatorNode.OperatorKind == BinaryOperatorKind.Or)
{
throw new ODataException(string.Format("A binary condition cannot be created when OperatorKind is of type {0}", binaryOperatorNode.OperatorKind));
}
var condition = new Condition();
var singleValuePropertyAccessNode = binaryOperatorNode.Left as SingleValuePropertyAccessNode;
condition.Attribute = BindPropertyAccessQueryNode(singleValuePropertyAccessNode);
object value;
if (binaryOperatorNode.Right is ConvertNode)
{
var convertNode = binaryOperatorNode.Right as ConvertNode;
var constantNode = convertNode.Source;
value = BindConstantNode(constantNode as ConstantNode);
}
else
{
value = BindConstantNode(binaryOperatorNode.Right as ConstantNode);
}
if (value == null)
{
// OData has a null literal for equality comparison, FetchXml requires either that the Null or NotNull operator is specified without a value parameter on the condition
switch (binaryOperatorNode.OperatorKind)
{
case BinaryOperatorKind.Equal:
condition.Operator = !_applyLogicalNegation ? ConditionOperator.Null : ConditionOperator.NotNull;
break;
case BinaryOperatorKind.NotEqual:
condition.Operator = !_applyLogicalNegation ? ConditionOperator.NotNull : ConditionOperator.Null;
break;
default:
throw new ODataException(string.Format("The operator {0} isn't supported for the null literal. Only equality checks are supported.", binaryOperatorNode.OperatorKind));
}
}
else
{
condition.Operator = ToConditionOperator(binaryOperatorNode.OperatorKind);
condition.Value = value;
}
return condition;
}
private static ConditionOperator ToConditionOperator(BinaryOperatorKind binaryOperator)
{
switch (binaryOperator)
{
case BinaryOperatorKind.Equal:
return !_applyLogicalNegation ? ConditionOperator.Equal : ConditionOperator.NotEqual;
case BinaryOperatorKind.NotEqual:
return !_applyLogicalNegation ? ConditionOperator.NotEqual : ConditionOperator.Equal;
case BinaryOperatorKind.GreaterThan:
return !_applyLogicalNegation ? ConditionOperator.GreaterThan : ConditionOperator.LessEqual;
case BinaryOperatorKind.GreaterThanOrEqual:
return !_applyLogicalNegation ? ConditionOperator.GreaterEqual : ConditionOperator.LessThan;
case BinaryOperatorKind.LessThan:
return !_applyLogicalNegation ? ConditionOperator.LessThan : ConditionOperator.GreaterEqual;
case BinaryOperatorKind.LessThanOrEqual:
return !_applyLogicalNegation ? ConditionOperator.LessEqual : ConditionOperator.GreaterThan;
case BinaryOperatorKind.Add:
case BinaryOperatorKind.Subtract:
case BinaryOperatorKind.Multiply:
case BinaryOperatorKind.Divide:
case BinaryOperatorKind.Modulo:
throw new NotSupportedException("Arithmetic operators aren't supported.");
case BinaryOperatorKind.And:
throw new ODataException("The And operator isn't an applicable equality comparison operator.");
case BinaryOperatorKind.Or:
throw new ODataException("The OR operator isn't an applicable equality comparison operator.");
default:
throw new NotSupportedException("Unknown operator.");
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.