context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // namespace System.Reflection { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; #if FEATURE_REMOTING using System.Runtime.Remoting.Metadata; #endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using MemberListType = System.RuntimeType.MemberListType; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; using System.Runtime.CompilerServices; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_MethodInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class MethodInfo : MethodBase, _MethodInfo { #region Constructor protected MethodInfo() { } #endregion public static bool operator ==(MethodInfo left, MethodInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeMethodInfo || right is RuntimeMethodInfo) { return false; } return left.Equals(right); } public static bool operator !=(MethodInfo left, MethodInfo right) { return !(left == right); } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Method; } } #endregion #region Public Abstract\Virtual Members public virtual Type ReturnType { get { throw new NotImplementedException(); } } public virtual ParameterInfo ReturnParameter { get { throw new NotImplementedException(); } } public abstract ICustomAttributeProvider ReturnTypeCustomAttributes { get; } public abstract MethodInfo GetBaseDefinition(); [System.Runtime.InteropServices.ComVisible(true)] public override Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } [System.Runtime.InteropServices.ComVisible(true)] public virtual MethodInfo GetGenericMethodDefinition() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } #endregion #if !FEATURE_CORECLR Type _MethodInfo.GetType() { return base.GetType(); } void _MethodInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _MethodInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _MethodInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _MethodInfo.Invoke in VM\DangerousAPIs.h and // include _MethodInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _MethodInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } [Serializable] internal sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo { #region Private Data Members private IntPtr m_handle; private RuntimeTypeCache m_reflectedTypeCache; private string m_name; private string m_toString; private ParameterInfo[] m_parameters; private ParameterInfo m_returnParameter; private BindingFlags m_bindingFlags; private MethodAttributes m_methodAttributes; private Signature m_signature; private RuntimeType m_declaringType; private object m_keepalive; private INVOCATION_FLAGS m_invocationFlags; #if FEATURE_APPX private bool IsNonW8PFrameworkAPI() { if (m_declaringType.IsArray && IsPublic && !IsStatic) return false; RuntimeAssembly rtAssembly = GetRuntimeAssembly(); if (rtAssembly.IsFrameworkAssembly()) { int ctorToken = rtAssembly.InvocableAttributeCtorToken; if (System.Reflection.MetadataToken.IsNullToken(ctorToken) || !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken)) return true; } if (GetRuntimeType().IsNonW8PFrameworkAPI()) return true; if (IsGenericMethod && !IsGenericMethodDefinition) { foreach (Type t in GetGenericArguments()) { if (((RuntimeType)t).IsNonW8PFrameworkAPI()) return true; } } return false; } internal override bool IsDynamicallyInvokable { get { return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI(); } } #endif internal INVOCATION_FLAGS InvocationFlags { [System.Security.SecuritySafeCritical] get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN; Type declaringType = DeclaringType; // // first take care of all the NO_INVOKE cases. if (ContainsGenericParameters || ReturnType.IsByRef || (declaringType != null && declaringType.ContainsGenericParameters) || ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) || ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject)) { // We don't need other flags if this method cannot be invoked invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } else { // this should be an invocable method, determine the other flags that participate in invocation invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0) { if ( (Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public || (declaringType != null && declaringType.NeedsReflectionSecurityCheck) ) { // If method is non-public, or declaring type is not visible invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; } else if (IsGenericMethod) { Type[] genericArguments = GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (genericArguments[i].NeedsReflectionSecurityCheck) { invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; break; } } } } } #if FEATURE_APPX if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI()) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API; #endif // FEATURE_APPX m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } return m_invocationFlags; } } #endregion #region Constructor [System.Security.SecurityCritical] // auto-generated internal RuntimeMethodInfo( RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive) { Contract.Ensures(!m_handle.IsNull()); Contract.Assert(!handle.IsNullHandle()); Contract.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); m_bindingFlags = bindingFlags; m_declaringType = declaringType; m_keepalive = keepalive; m_handle = handle.Value; m_reflectedTypeCache = reflectedTypeCache; m_methodAttributes = methodAttributes; } #endregion #if FEATURE_REMOTING #region Legacy Remoting Cache // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. // This member is currently being used by Remoting for caching remoting data. If you // need to cache data here, talk to the Remoting team to work out a mechanism, so that // both caching systems can happily work together. private RemotingMethodCachedData m_cachedData; internal RemotingMethodCachedData RemotingCache { get { // This grabs an internal copy of m_cachedData and uses // that instead of looking at m_cachedData directly because // the cache may get cleared asynchronously. This prevents // us from having to take a lock. RemotingMethodCachedData cache = m_cachedData; if (cache == null) { cache = new RemotingMethodCachedData(this); RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); if (ret != null) cache = ret; } return cache; } } #endregion #endif //FEATURE_REMOTING #region Private Methods RuntimeMethodHandleInternal IRuntimeMethodInfo.Value { [System.Security.SecuritySafeCritical] get { return new RuntimeMethodHandleInternal(m_handle); } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } [System.Security.SecurityCritical] // auto-generated private ParameterInfo[] FetchNonReturnParameters() { if (m_parameters == null) m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature); return m_parameters; } [System.Security.SecurityCritical] // auto-generated private ParameterInfo FetchReturnParameter() { if (m_returnParameter == null) m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature); return m_returnParameter; } #endregion #region Internal Members internal override string FormatNameAndSig(bool serialization) { // Serialization uses ToString to resolve MethodInfo overloads. StringBuilder sbName = new StringBuilder(Name); // serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads. // serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString(). TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic; if (IsGenericMethod) sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format)); sbName.Append("("); sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization)); sbName.Append(")"); return sbName.ToString(); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { RuntimeMethodInfo m = o as RuntimeMethodInfo; if ((object)m == null) return false; return m.m_handle == m_handle; } internal Signature Signature { get { if (m_signature == null) m_signature = new Signature(this, m_declaringType); return m_signature; } } internal BindingFlags BindingFlags { get { return m_bindingFlags; } } // Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types internal RuntimeMethodHandle GetMethodHandle() { return new RuntimeMethodHandle(this); } [System.Security.SecuritySafeCritical] // auto-generated internal RuntimeMethodInfo GetParentDefinition() { if (!IsVirtual || m_declaringType.IsInterface) return null; RuntimeType parent = (RuntimeType)m_declaringType.BaseType; if (parent == null) return null; int slot = RuntimeMethodHandle.GetSlot(this); if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot) return null; return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot)); } // Unlike DeclaringType, this will return a valid type even for global methods internal RuntimeType GetDeclaringTypeInternal() { return m_declaringType; } #endregion #region Object Overrides public override String ToString() { if (m_toString == null) m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig(); return m_toString; } public override int GetHashCode() { // See RuntimeMethodInfo.Equals() below. if (IsGenericMethod) return ValueType.GetHashCodeOfPtr(m_handle); else return base.GetHashCode(); } [System.Security.SecuritySafeCritical] // auto-generated public override bool Equals(object obj) { if (!IsGenericMethod) return obj == (object)this; // We cannot do simple object identity comparisons for generic methods. // Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo() // retrieve items from and insert items into s_methodInstantiations which is a CerHashtable. RuntimeMethodInfo mi = obj as RuntimeMethodInfo; if (mi == null || !mi.IsGenericMethod) return false; // now we know that both operands are generic methods IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this); IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi); if (handle1.Value.Value != handle2.Value.Value) return false; Type[] lhs = GetGenericArguments(); Type[] rhs = mi.GetGenericArguments(); if (lhs.Length != rhs.Length) return false; for (int i = 0; i < lhs.Length; i++) { if (lhs[i] != rhs[i]) return false; } if (DeclaringType != mi.DeclaringType) return false; if (ReflectedType != mi.ReflectedType) return false; return true; } #endregion #region ICustomAttributeProvider [System.Security.SecuritySafeCritical] // auto-generated public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit); } [System.Security.SecuritySafeCritical] // auto-generated public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region MemberInfo Overrides public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = RuntimeMethodHandle.GetName(this); return m_name; } } public override Type DeclaringType { get { if (m_reflectedTypeCache.IsGlobal) return null; return m_declaringType; } } public override Type ReflectedType { get { if (m_reflectedTypeCache.IsGlobal) return null; return m_reflectedTypeCache.GetRuntimeType(); } } public override MemberTypes MemberType { get { return MemberTypes.Method; } } public override int MetadataToken { [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeMethodHandle.GetMethodDef(this); } } public override Module Module { get { return GetRuntimeModule(); } } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); } public override bool IsSecurityCritical { #if FEATURE_CORECLR get { return true; } #else get { return RuntimeMethodHandle.IsSecurityCritical(this); } #endif } public override bool IsSecuritySafeCritical { #if FEATURE_CORECLR get { return false; } #else get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); } #endif } public override bool IsSecurityTransparent { #if FEATURE_CORECLR get { return false; } #else get { return RuntimeMethodHandle.IsSecurityTransparent(this); } #endif } #endregion #region MethodBase Overrides [System.Security.SecuritySafeCritical] // auto-generated internal override ParameterInfo[] GetParametersNoCopy() { FetchNonReturnParameters(); return m_parameters; } [System.Security.SecuritySafeCritical] // auto-generated [System.Diagnostics.Contracts.Pure] public override ParameterInfo[] GetParameters() { FetchNonReturnParameters(); if (m_parameters.Length == 0) return m_parameters; ParameterInfo[] ret = new ParameterInfo[m_parameters.Length]; Array.Copy(m_parameters, ret, m_parameters.Length); return ret; } public override MethodImplAttributes GetMethodImplementationFlags() { return RuntimeMethodHandle.GetImplAttributes(this); } internal bool IsOverloaded { get { return m_reflectedTypeCache.GetMethodList(MemberListType.CaseSensitive, Name).Length > 1; } } public override RuntimeMethodHandle MethodHandle { get { Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); return new RuntimeMethodHandle(this); } } public override MethodAttributes Attributes { get { return m_methodAttributes; } } public override CallingConventions CallingConvention { get { return Signature.CallingConvention; } } [System.Security.SecuritySafeCritical] // overrides SafeCritical member #if !FEATURE_CORECLR #pragma warning disable 618 [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)] #pragma warning restore 618 #endif public override MethodBody GetMethodBody() { MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); if (mb != null) mb.m_methodBase = this; return mb; } #endregion #region Invocation Logic(On MemberBase) private void CheckConsistency(Object target) { // only test instance methods if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static) { if (!m_declaringType.IsInstanceOfType(target)) { if (target == null) throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg")); else throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch")); } } } [System.Security.SecuritySafeCritical] private void ThrowNoInvokeException() { // method is ReflectionOnly Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) { throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke")); } // method is on a class that contains stack pointers else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0) { throw new NotSupportedException(); } // method is vararg else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { throw new NotSupportedException(); } // method is generic or on a generic class else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters) { throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenParam")); } // method is abstract class else if (IsAbstract) { throw new MemberAccessException(); } // ByRef return are not allowed in reflection else if (ReturnType.IsByRef) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ByRefReturn")); } throw new TargetException(); } [System.Security.SecuritySafeCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); #region Security Check INVOCATION_FLAGS invocationFlags = InvocationFlags; #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif #if !FEATURE_CORECLR if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) { if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags); } #endif // !FEATURE_CORECLR #endregion return UnsafeInvokeInternal(obj, parameters, arguments); } [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); return UnsafeInvokeInternal(obj, parameters, arguments); } [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) { if (arguments == null || arguments.Length == 0) return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false); else { Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) parameters[index] = arguments[index]; return retValue; } } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] private object[] InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { Signature sig = Signature; // get the signature int formalCount = sig.Arguments.Length; int actualCount = (parameters != null) ? parameters.Length : 0; INVOCATION_FLAGS invocationFlags = InvocationFlags; // INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type) // contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot // be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects. if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0) ThrowNoInvokeException(); // check basic method consistency. This call will throw if there are problems in the target/method relationship CheckConsistency(obj); if (formalCount != actualCount) throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); if (actualCount != 0) return CheckArguments(parameters, binder, invokeAttr, culture, sig); else return null; } #endregion #region MethodInfo Overrides public override Type ReturnType { get { return Signature.ReturnType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return ReturnParameter; } } public override ParameterInfo ReturnParameter { [System.Security.SecuritySafeCritical] // auto-generated get { Contract.Ensures(m_returnParameter != null); FetchReturnParameter(); return m_returnParameter as ParameterInfo; } } [System.Security.SecuritySafeCritical] // auto-generated public override MethodInfo GetBaseDefinition() { if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface) return this; int slot = RuntimeMethodHandle.GetSlot(this); RuntimeType declaringType = (RuntimeType)DeclaringType; RuntimeType baseDeclaringType = declaringType; RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal(); do { int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType); if (cVtblSlots <= slot) break; baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot); baseDeclaringType = declaringType; declaringType = (RuntimeType)declaringType.BaseType; } while (declaringType != null); return(MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle); } [System.Security.SecuritySafeCritical] public override Delegate CreateDelegate(Type delegateType) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // This API existed in v1/v1.1 and only expected to create closed // instance delegates. Constrain the call to BindToMethodInfo to // open delegates only for backwards compatibility. But we'll allow // relaxed signature checking and open static delegates because // there's no ambiguity there (the caller would have to explicitly // pass us a static method or a method with a non-exact signature // and the only change in behavior from v1.1 there is that we won't // fail the call). return CreateDelegateInternal( delegateType, null, DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature, ref stackMark); } [System.Security.SecuritySafeCritical] public override Delegate CreateDelegate(Type delegateType, Object target) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // This API is new in Whidbey and allows the full range of delegate // flexability (open or closed delegates binding to static or // instance methods with relaxed signature checking). The delegate // can also be closed over null. There's no ambiguity with all these // options since the caller is providing us a specific MethodInfo. return CreateDelegateInternal( delegateType, target, DelegateBindingFlags.RelaxedSignature, ref stackMark); } [System.Security.SecurityCritical] private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark) { // Validate the parameters. if (delegateType == null) throw new ArgumentNullException(nameof(delegateType)); Contract.EndContractBlock(); RuntimeType rtType = delegateType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(delegateType)); if (!rtType.IsDelegate()) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(delegateType)); Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark); if (d == null) { throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth")); } return d; } #endregion #region Generics [System.Security.SecuritySafeCritical] // auto-generated public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) { if (methodInstantiation == null) throw new ArgumentNullException(nameof(methodInstantiation)); Contract.EndContractBlock(); RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length]; if (!IsGenericMethodDefinition) throw new InvalidOperationException( Environment.GetResourceString("Arg_NotGenericMethodDefinition", this)); for (int i = 0; i < methodInstantiation.Length; i++) { Type methodInstantiationElem = methodInstantiation[i]; if (methodInstantiationElem == null) throw new ArgumentNullException(); RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType; if (rtMethodInstantiationElem == null) { Type[] methodInstantiationCopy = new Type[methodInstantiation.Length]; for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++) methodInstantiationCopy[iCopy] = methodInstantiation[iCopy]; methodInstantiation = methodInstantiationCopy; return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation); } methodInstantionRuntimeType[i] = rtMethodInstantiationElem; } RuntimeType[] genericParameters = GetGenericArgumentsInternal(); RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters); MethodInfo ret = null; try { ret = RuntimeType.GetMethodBase(ReflectedTypeInternal, RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(this.m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo; } catch (VerificationException e) { RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e); throw; } return ret; } internal RuntimeType[] GetGenericArgumentsInternal() { return RuntimeMethodHandle.GetMethodInstantiationInternal(this); } public override Type[] GetGenericArguments() { Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this); if (types == null) { types = EmptyArray<Type>.Value; } return types; } public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); Contract.EndContractBlock(); return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo; } public override bool IsGenericMethod { get { return RuntimeMethodHandle.HasMethodInstantiation(this); } } public override bool IsGenericMethodDefinition { get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); } } public override bool ContainsGenericParameters { get { if (DeclaringType != null && DeclaringType.ContainsGenericParameters) return true; if (!IsGenericMethod) return false; Type[] pis = GetGenericArguments(); for (int i = 0; i < pis.Length; i++) { if (pis[i].ContainsGenericParameters) return true; } return false; } } #endregion #region ISerializable Implementation [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); if (m_reflectedTypeCache.IsGlobal) throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization")); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, ToString(), SerializationToString(), MemberTypes.Method, IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null); } internal string SerializationToString() { return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true); } #endregion #region Legacy Internal internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark) { IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark); if (method == null) return null; return RuntimeType.GetMethodBase(method); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Caching.Configuration; using System.Runtime.Caching.Hosting; using System.Diagnostics; using System.Security; using System.Threading; namespace System.Runtime.Caching { // CacheMemoryMonitor uses the internal System.SizedReference type to determine // the size of the cache itselt, and helps us know when to drop entries to avoid // exceeding the cache's memory limit. The limit is configurable (see ConfigUtil.cs). internal sealed class CacheMemoryMonitor : MemoryMonitor, IDisposable { private const long PRIVATE_BYTES_LIMIT_2GB = 800 * MEGABYTE; private const long PRIVATE_BYTES_LIMIT_3GB = 1800 * MEGABYTE; private const long PRIVATE_BYTES_LIMIT_64BIT = 1L * TERABYTE; private const int SAMPLE_COUNT = 2; private static IMemoryCacheManager s_memoryCacheManager; private static long s_autoPrivateBytesLimit = -1; private static long s_effectiveProcessMemoryLimit = -1; private MemoryCache _memoryCache; private long[] _cacheSizeSamples; private DateTime[] _cacheSizeSampleTimes; private int _idx; private SRefMultiple _sizedRefMultiple; private int _gen2Count; private long _memoryLimit; internal long MemoryLimit { get { return _memoryLimit; } } private CacheMemoryMonitor() { // hide default ctor } internal CacheMemoryMonitor(MemoryCache memoryCache, int cacheMemoryLimitMegabytes) { _memoryCache = memoryCache; _gen2Count = GC.CollectionCount(2); _cacheSizeSamples = new long[SAMPLE_COUNT]; _cacheSizeSampleTimes = new DateTime[SAMPLE_COUNT]; if (memoryCache.UseMemoryCacheManager) { InitMemoryCacheManager(); // This magic thing connects us to ObjectCacheHost magically. :/ } InitDisposableMembers(cacheMemoryLimitMegabytes); } private void InitDisposableMembers(int cacheMemoryLimitMegabytes) { bool dispose = true; try { _sizedRefMultiple = new SRefMultiple(_memoryCache.AllSRefTargets); SetLimit(cacheMemoryLimitMegabytes); InitHistory(); dispose = false; } finally { if (dispose) { Dispose(); } } } // Auto-generate the private bytes limit: // - On 64bit, the auto value is MIN(60% physical_ram, 1 TB) // - On x86, for 2GB, the auto value is MIN(60% physical_ram, 800 MB) // - On x86, for 3GB, the auto value is MIN(60% physical_ram, 1800 MB) // // - If it's not a hosted environment (e.g. console app), the 60% in the above // formulas will become 100% because in un-hosted environment we don't launch // other processes such as compiler, etc. private static long AutoPrivateBytesLimit { get { long memoryLimit = s_autoPrivateBytesLimit; if (memoryLimit == -1) { bool is64bit = (IntPtr.Size == 8); long totalPhysical = TotalPhysical; long totalVirtual = TotalVirtual; if (totalPhysical != 0) { long recommendedPrivateByteLimit; if (is64bit) { recommendedPrivateByteLimit = PRIVATE_BYTES_LIMIT_64BIT; } else { // Figure out if it's 2GB or 3GB if (totalVirtual > 2 * GIGABYTE) { recommendedPrivateByteLimit = PRIVATE_BYTES_LIMIT_3GB; } else { recommendedPrivateByteLimit = PRIVATE_BYTES_LIMIT_2GB; } } // use 60% of physical RAM long usableMemory = totalPhysical * 3 / 5; memoryLimit = Math.Min(usableMemory, recommendedPrivateByteLimit); } else { // If GlobalMemoryStatusEx fails, we'll use these as our auto-gen private bytes limit memoryLimit = is64bit ? PRIVATE_BYTES_LIMIT_64BIT : PRIVATE_BYTES_LIMIT_2GB; } Interlocked.Exchange(ref s_autoPrivateBytesLimit, memoryLimit); } return memoryLimit; } } public void Dispose() { SRefMultiple sref = _sizedRefMultiple; if (sref != null && Interlocked.CompareExchange(ref _sizedRefMultiple, null, sref) == sref) { sref.Dispose(); } IMemoryCacheManager memoryCacheManager = s_memoryCacheManager; if (memoryCacheManager != null) { memoryCacheManager.ReleaseCache(_memoryCache); } } internal static long EffectiveProcessMemoryLimit { get { long memoryLimit = s_effectiveProcessMemoryLimit; if (memoryLimit == -1) { memoryLimit = AutoPrivateBytesLimit; Interlocked.Exchange(ref s_effectiveProcessMemoryLimit, memoryLimit); } return memoryLimit; } } protected override int GetCurrentPressure() { // Call GetUpdatedTotalCacheSize to update the total // cache size, if there has been a recent Gen 2 Collection. // This update must happen, otherwise the CacheManager won't // know the total cache size. int gen2Count = GC.CollectionCount(2); SRefMultiple sref = _sizedRefMultiple; if (gen2Count != _gen2Count && sref != null) { // update _gen2Count _gen2Count = gen2Count; // the SizedRef is only updated after a Gen2 Collection // increment the index (it's either 1 or 0) Debug.Assert(SAMPLE_COUNT == 2); _idx = _idx ^ 1; // remember the sample time _cacheSizeSampleTimes[_idx] = DateTime.UtcNow; // remember the sample value _cacheSizeSamples[_idx] = sref.ApproximateSize; Dbg.Trace("MemoryCacheStats", "SizedRef.ApproximateSize=" + _cacheSizeSamples[_idx]); IMemoryCacheManager memoryCacheManager = s_memoryCacheManager; if (memoryCacheManager != null) { memoryCacheManager.UpdateCacheSize(_cacheSizeSamples[_idx], _memoryCache); } } // if there's no memory limit, then there's nothing more to do if (_memoryLimit <= 0) { return 0; } long cacheSize = _cacheSizeSamples[_idx]; // use _memoryLimit as an upper bound so that pressure is a percentage (between 0 and 100, inclusive). if (cacheSize > _memoryLimit) { cacheSize = _memoryLimit; } // PerfCounter: Cache Percentage Process Memory Limit Used // = memory used by this process / process memory limit at pressureHigh // Set private bytes used in kilobytes because the counter is a DWORD // PerfCounters.SetCounter(AppPerfCounter.CACHE_PERCENT_PROC_MEM_LIMIT_USED, (int)(cacheSize >> KILOBYTE_SHIFT)); int result = (int)(cacheSize * 100 / _memoryLimit); return result; } internal override int GetPercentToTrim(DateTime lastTrimTime, int lastTrimPercent) { int percent = 0; if (IsAboveHighPressure()) { long cacheSize = _cacheSizeSamples[_idx]; if (cacheSize > _memoryLimit) { percent = Math.Min(100, (int)((cacheSize - _memoryLimit) * 100L / cacheSize)); } #if PERF Debug.WriteLine(string.Format("CacheMemoryMonitor.GetPercentToTrim: percent={0:N}, lastTrimPercent={1:N}{Environment.NewLine}", percent, lastTrimPercent)); #endif } return percent; } internal void SetLimit(int cacheMemoryLimitMegabytes) { long cacheMemoryLimit = cacheMemoryLimitMegabytes; cacheMemoryLimit = cacheMemoryLimit << MEGABYTE_SHIFT; _memoryLimit = 0; // never override what the user specifies as the limit; // only call AutoPrivateBytesLimit when the user does not specify one. if (cacheMemoryLimit == 0 && _memoryLimit == 0) { // Zero means we impose a limit _memoryLimit = EffectiveProcessMemoryLimit; } else if (cacheMemoryLimit != 0 && _memoryLimit != 0) { // Take the min of "cache memory limit" and the host's "process memory limit". _memoryLimit = Math.Min(_memoryLimit, cacheMemoryLimit); } else if (cacheMemoryLimit != 0) { // _memoryLimit is 0, but "cache memory limit" is non-zero, so use it as the limit _memoryLimit = cacheMemoryLimit; } Dbg.Trace("MemoryCacheStats", "CacheMemoryMonitor.SetLimit: _memoryLimit=" + (_memoryLimit >> MEGABYTE_SHIFT) + "Mb"); if (_memoryLimit > 0) { _pressureHigh = 100; _pressureLow = 80; } else { _pressureHigh = 99; _pressureLow = 97; } Dbg.Trace("MemoryCacheStats", "CacheMemoryMonitor.SetLimit: _pressureHigh=" + _pressureHigh + ", _pressureLow=" + _pressureLow); } private static void InitMemoryCacheManager() { if (s_memoryCacheManager == null) { IMemoryCacheManager memoryCacheManager = null; IServiceProvider host = ObjectCache.Host; if (host != null) { memoryCacheManager = host.GetService(typeof(IMemoryCacheManager)) as IMemoryCacheManager; } if (memoryCacheManager != null) { Interlocked.CompareExchange(ref s_memoryCacheManager, memoryCacheManager, null); } } } } }
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for Additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS.UserModel; using System; namespace NPOI.XSSF.UserModel { /** * @author Yegor Kozlov */ public class XSSFFontFormatting : IFontFormatting { CT_Font _font; /*package*/ internal XSSFFontFormatting(CT_Font font) { _font = font; } /** * Get the type of super or subscript for the font * * @return super or subscript option * @see #SS_NONE * @see #SS_SUPER * @see #SS_SUB */ public FontSuperScript EscapementType { get { if (_font.sizeOfVertAlignArray() == 0) return FontSuperScript.None; CT_VerticalAlignFontProperty prop = _font.GetVertAlignArray(0); return (FontSuperScript)(prop.val - 1); } set { _font.SetVertAlignArray(null); if (value != FontSuperScript.None) { _font.AddNewVertAlign().val = (ST_VerticalAlignRun)(value + 1); } } } /** * @return font color index */ public short FontColorIndex { get { if (_font.sizeOfColorArray() == 0) return -1; int idx = 0; CT_Color color = _font.GetColorArray(0); if (color.IsSetIndexed()) idx = (int)color.indexed; return (short)idx; } set { _font.SetColorArray(null); if (value != -1) { var clr=_font.AddNewColor(); clr.indexed = (uint)(value); clr.indexedSpecified = true; } } } public IColor FontColor { get { if (_font.sizeOfColorArray() == 0) return null; return new XSSFColor(_font.GetColorArray(0)); } set { XSSFColor xcolor = XSSFColor.ToXSSFColor(value); if (xcolor == null) { _font.color.Clear(); } else { _font.SetColorArray(0, xcolor.GetCTColor()); } } } /** * Gets the height of the font in 1/20th point units * * @return fontheight (in points/20); or -1 if not modified */ public int FontHeight { get { if (_font.sizeOfSzArray() == 0) return -1; CT_FontSize sz = _font.GetSzArray(0); return (short)(20 * sz.val); } set { _font.SetSzArray(null); if (value != -1) { _font.AddNewSz().val = (double)value / 20; } } } /** * Get the type of underlining for the font * * @return font underlining type * * @see #U_NONE * @see #U_SINGLE * @see #U_DOUBLE * @see #U_SINGLE_ACCOUNTING * @see #U_DOUBLE_ACCOUNTING */ public FontUnderlineType UnderlineType { get { if (_font.sizeOfUArray() == 0) return FontUnderlineType.None; CT_UnderlineProperty u = _font.GetUArray(0); switch (u.val) { case ST_UnderlineValues.single: return FontUnderlineType.Single; case ST_UnderlineValues.@double: return FontUnderlineType.Double; case ST_UnderlineValues.singleAccounting: return FontUnderlineType.SingleAccounting; case ST_UnderlineValues.doubleAccounting: return FontUnderlineType.DoubleAccounting; default: return FontUnderlineType.None; } } set { _font.SetUArray(null); if (value != FontUnderlineType.None) { FontUnderline fenum = FontUnderline.ValueOf(value); ST_UnderlineValues val = (ST_UnderlineValues)(fenum.Value); _font.AddNewU().val = val; } } } /** * Get whether the font weight is Set to bold or not * * @return bold - whether the font is bold or not */ public bool IsBold { get { return _font.SizeOfBArray() == 1 && _font.GetBArray(0).val; } } /** * @return true if font style was Set to <i>italic</i> */ public bool IsItalic { get { return _font.sizeOfIArray() == 1 && _font.GetIArray(0).val; } } /** * Set font style options. * * @param italic - if true, Set posture style to italic, otherwise to normal * @param bold if true, Set font weight to bold, otherwise to normal */ public void SetFontStyle(bool italic, bool bold) { _font.SetIArray(null); _font.SetBArray(null); if (italic) _font.AddNewI().val = true; if (bold) _font.AddNewB().val = true; } /** * Set font style options to default values (non-italic, non-bold) */ public void ResetFontStyle() { _font = new CT_Font(); } } }
// FactListMaker.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.Collections; using CoreUtilities; namespace MefAddIns { /// <summary> /// This handsome little class will take a bit of code /// from SendTextAway but for the purpose of /// building (eventually) a dynamic list of facts on a story board /// /// Step #1 - /// Just get a list of facts in the form /// Ghouls are green[[ghouls]]. Roses are red[[flowers]]. Ghouls eat brains[[ghouls]]. /// /// </summary> public static class FactListMaker { public static int facts = 0; // count all the facts we add so we can pre numbers to them (may 23 2012) public const string SEP_PHRASES = "|| "; public const string SEP_INSIDEPHRASE = "|;"; public static Hashtable GetSearchItems(string sourceText, Hashtable Facts, string ExtraInfoToEncode, string SearchTerm) { // ignore case (May 2013) when doing search parses. sourceText = sourceText.ToLower(); SearchTerm=SearchTerm.ToLower(); if (sourceText.IndexOf(SearchTerm) > -1) { string group = "Found"; string add_me = SearchTerm + SEP_INSIDEPHRASE + "" + SEP_INSIDEPHRASE + ExtraInfoToEncode; // we use SearchTerm as the actually search item if (Facts.ContainsKey(group)) { // add to string list string sList = Facts[group].ToString(); // may 30 2012 - changed the , to a |, sList = sList + SEP_PHRASES + add_me; Facts[group] = sList; } else { // start a tally Facts.Add(group, add_me); } } return Facts; } /// <summary> /// Returns an array of all the found facts /// /// USAGE: hashtable = GetFacts(richText.Text); /// /// Then another routine will take that hashtable and build an on-the-fly /// storyboard out of it. /// /// Ideally clicking the links on the storyboard will take us to the place in the appropriate /// FILE --> which will require more work (add GUID to string somehow??) /// </summary> /// <param name="sourceText"></param> /// <param name="Facts">Assumes Facts has already been prepared</param> /// <param name="ExtraInfoToEncode">If we need to store extra information we do so this weay</param> /// <returns></returns> public static Hashtable GetFacts(string sourceText, Hashtable Facts, string ExtraInfoToEncode) { int nFirstBracket = sourceText.IndexOf("[["); // in case on line with other brackets int end_index = 0; // this will be changed during the iteration to be the end of the last note found while (nFirstBracket > -1) { if (end_index < sourceText.Length) { // may 13 2012 // alternative start point // instead of grabbing frm very beginning, just grab from end of last sentence? // THIS WORKED but woudl grab the end of the first sentence after end_index but // I'd like to sang the end of the nearest //int alternative_start = sourceText.IndexOf('.', end_index, nFirstBracket - end_index); int alternative_start = sourceText.LastIndexOf('.', nFirstBracket); // we don't want to to go back further than the last 'end' if (alternative_start > -1 && alternative_start < nFirstBracket && alternative_start > end_index) { end_index = alternative_start; } string sText = sourceText.Substring(end_index, nFirstBracket - end_index); try { end_index = sourceText.IndexOf("]]", end_index + 1);// Was in the wrong place,nFirstBracket); // in case on line with other brackets } catch (Exception ex) { NewMessage.Show(ex.ToString()); } if (sText != "") { // this is the group, i.e., 'ghouls' string sCode = ""; try { sCode = sourceText.Substring(nFirstBracket + 2, end_index - (nFirstBracket + 2)); } catch (Exception) { /* return?; // we have code messing things up, skip ahead end_index = end_index + 1; sCode = "~scene"; // bug -fix, turn malformed codes into 'skips'*/ } if ( /*sCode.IndexOf("~scene") == -1 && sCode.IndexOf("~center") == -1*/ YomParse.StringContainsASystemKeyword(sCode) == false && sCode != "title") { /* //bug: sText is 'getting' more data than it should. Makes no logical sense // HACK: Just going to trim it a second time. No reason why I should have to do this though int nHackBracketsShouldNotExists = sText.IndexOf("[["); if (nHackBracketsShouldNotExists > -1) { sText = sText.Substring(0, nHackBracketsShouldNotExists); } // END HACK */ // basic format is // Entry;GUID, Entry2;GUID if (ExtraInfoToEncode != "") { sText = sText + SEP_INSIDEPHRASE + ExtraInfoToEncode; } // string cleanup sText = sText.Replace("]]", ""); if (sText.StartsWith(".")) { // trim starting period sText = sText.TrimStart(new char[1] { '.' }); } facts++; string sExtraZero = ""; if (facts < 10) sExtraZero = "0"; // may 12 2012 adding the # of the fact here. sText = sExtraZero + facts.ToString() + SEP_INSIDEPHRASE + sText.Trim(); if (Facts.ContainsKey(sCode)) { // add to string list string sList = Facts[sCode].ToString(); // may 30 2012 - changed the , to a |, sList = sList + SEP_PHRASES + sText; Facts[sCode] = sList; } else { // start a tally Facts.Add(sCode, sText); } } // we don't add ~scene or title // NOW REMOVE the found text + the code // NOPE: We are just using end index to help us here // sourceText = sourceText.Replace(sText + "[[" + sCode +"]]", ""); } nFirstBracket = sourceText.IndexOf("[[", end_index); } else { nFirstBracket = -1; } } return Facts; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using QuantConnect.Configuration; using QuantConnect.Logging; namespace QuantConnect.Brokerages.InteractiveBrokers { /// <summary> /// Handles launching and killing the IB Controller script /// </summary> /// <remarks> /// Requires TWS or IB Gateway and IBController installed to run /// </remarks> public static class InteractiveBrokersGatewayRunner { // process that's running the IB Controller script private static int _scriptProcessId; // parameters needed for restart private static string _ibControllerDirectory; private static string _twsDirectory; private static string _userId; private static string _password; private static string _tradingMode; private static bool _useTws; /// <summary> /// Starts the interactive brokers gateway using values from configuration /// </summary> public static void StartFromConfiguration() { Start(Config.Get("ib-controller-dir"), Config.Get("ib-tws-dir"), Config.Get("ib-user-name"), Config.Get("ib-password"), Config.Get("ib-trading-mode"), Config.GetBool("ib-use-tws") ); } /// <summary> /// Starts the IB Gateway /// </summary> /// <param name="ibControllerDirectory">Directory to the IB controller installation</param> /// <param name="twsDirectory"></param> /// <param name="userId">The log in user id</param> /// <param name="password">The log in password</param> /// <param name="tradingMode">Live or Paper trading modes</param> /// <param name="useTws">True to use Trader Work Station, false to just launch the API gateway</param> public static void Start(string ibControllerDirectory, string twsDirectory, string userId, string password, string tradingMode, bool useTws = false) { _ibControllerDirectory = ibControllerDirectory; _twsDirectory = twsDirectory; _userId = userId; _password = password; _tradingMode = tradingMode; _useTws = useTws; var useTwsSwitch = useTws ? "TWS" : "GATEWAY"; var batchFilename = Path.Combine("InteractiveBrokers", "run-ib-controller.bat"); var bashFilename = Path.Combine("InteractiveBrokers", "run-ib-controller.sh"); try { var file = OS.IsWindows ? batchFilename : bashFilename; var arguments = string.Format("{0} {1} {2} {3} {4} {5} {6}", file, ibControllerDirectory, twsDirectory, userId, password, useTwsSwitch, tradingMode); Log.Trace("InteractiveBrokersGatewayRunner.Start(): Launching IBController for account " + userId + "..."); var processStartInfo = OS.IsWindows ? new ProcessStartInfo("cmd.exe", "/C " + arguments) : new ProcessStartInfo("bash", arguments); processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = false; var process = Process.Start(processStartInfo); _scriptProcessId = process != null ? process.Id : 0; } catch (Exception err) { Log.Error(err); } } /// <summary> /// Stops the IB Gateway /// </summary> public static void Stop() { if (_scriptProcessId == 0) { return; } try { Log.Trace("InteractiveBrokersGatewayRunner.Stop(): Stopping IBController..."); if (OS.IsWindows) { foreach (var process in Process.GetProcesses()) { try { if (process.MainWindowTitle.ToLower().Contains("ibcontroller") || process.MainWindowTitle.ToLower().Contains("ib gateway")) { process.Kill(); Thread.Sleep(2500); } } catch (Exception) { // ignored } } } else { try { Process.Start("pkill", "xvfb-run"); Process.Start("pkill", "java"); Process.Start("pkill", "Xvfb"); Thread.Sleep(2500); } catch (Exception) { // ignored } } _scriptProcessId = 0; } catch (Exception err) { Log.Error(err); } } /// <summary> /// Returns true if IB Gateway is running /// </summary> /// <returns></returns> public static bool IsRunning() { if (_scriptProcessId == 0) { return false; } // do not restart if using TWS instead of Gateway if (_useTws) { return true; } try { return IsIbControllerRunning(); } catch (Exception err) { Log.Error(err); } return false; } /// <summary> /// Restarts the IB Gateway, needed if shut down unexpectedly /// </summary> public static void Restart() { Start(_ibControllerDirectory, _twsDirectory, _userId, _password, _tradingMode, _useTws); // wait a few seconds for IB to start up Thread.Sleep(TimeSpan.FromSeconds(30)); } /// <summary> /// Detects if the IB Controller is running /// </summary> private static bool IsIbControllerRunning() { if (OS.IsWindows) { foreach (var process in Process.GetProcesses()) { try { if (process.MainWindowTitle.ToLower().Contains("ibcontroller")) { return true; } } catch (Exception) { // ignored } } } else { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "bash", Arguments = "-c 'ps aux | grep -v bash | grep java | grep ibgateway'", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; process.Start(); var output = process.StandardOutput.ReadToEnd(); var processFound = output.Contains("java") && output.Contains("ibgateway"); process.WaitForExit(); return processFound; } return false; } private static IEnumerable<Process> GetSpawnedProcesses(int id) { // loop over all the processes and return those that were spawned by the specified processed ID return Process.GetProcesses().Where(x => { try { var parent = ProcessExtensions.Parent(x); if (parent != null) { return parent.Id == id; } } catch { return false; } return false; }); } //http://stackoverflow.com/questions/394816/how-to-get-parent-process-in-net-in-managed-way private static class ProcessExtensions { private static string FindIndexedProcessName(int pid) { var processName = Process.GetProcessById(pid).ProcessName; var processesByName = Process.GetProcessesByName(processName); string processIndexdName = null; for (var index = 0; index < processesByName.Length; index++) { processIndexdName = index == 0 ? processName : processName + "#" + index; var processId = new PerformanceCounter("Process", "ID Process", processIndexdName); if ((int)processId.NextValue() == pid) { return processIndexdName; } } return processIndexdName; } private static Process FindPidFromIndexedProcessName(string indexedProcessName) { var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName); return Process.GetProcessById((int)parentId.NextValue()); } public static Process Parent(Process process) { return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id)); } } } }
// 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. #if FEATURE_REGISTRY using Microsoft.Win32; #endif using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Threading; namespace System.Diagnostics { internal sealed class PerformanceCounterLib { private static string s_computerName; private PerformanceMonitor _performanceMonitor; private string _machineName; private string _perfLcid; private static ConcurrentDictionary<(string machineName, string lcidString), PerformanceCounterLib> s_libraryTable; private Dictionary<int, string> _nameTable; private readonly object _nameTableLock = new object(); private static object s_internalSyncObject; internal PerformanceCounterLib(string machineName, string lcid) { _machineName = machineName; _perfLcid = lcid; } /// <internalonly/> internal static string ComputerName => LazyInitializer.EnsureInitialized(ref s_computerName, ref s_internalSyncObject, () => Interop.Kernel32.GetComputerName()); internal Dictionary<int, string> NameTable { get { if (_nameTable == null) { lock (_nameTableLock) { if (_nameTable == null) _nameTable = GetStringTable(false); } } return _nameTable; } } internal string GetCounterName(int index) { string result; return NameTable.TryGetValue(index, out result) ? result : ""; } internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture) { string lcidString = culture.Name.ToLowerInvariant(); if (machineName.CompareTo(".") == 0) machineName = ComputerName.ToLowerInvariant(); else machineName = machineName.ToLowerInvariant(); LazyInitializer.EnsureInitialized(ref s_libraryTable, ref s_internalSyncObject, () => new ConcurrentDictionary<(string, string), PerformanceCounterLib>()); return PerformanceCounterLib.s_libraryTable.GetOrAdd((machineName, lcidString), (key) => new PerformanceCounterLib(key.machineName, key.lcidString)); } internal byte[] GetPerformanceData(string item) { if (_performanceMonitor == null) { lock (LazyInitializer.EnsureInitialized(ref s_internalSyncObject)) { if (_performanceMonitor == null) _performanceMonitor = new PerformanceMonitor(_machineName); } } return _performanceMonitor.GetData(item); } private Dictionary<int, string> GetStringTable(bool isHelp) { #if FEATURE_REGISTRY Dictionary<int, string> stringTable; RegistryKey libraryKey; libraryKey = Registry.PerformanceData; try { string[] names = null; int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins int waitSleep = 0; // In some stress situations, querying counter values from // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009 // often returns null/empty data back. We should build fault-tolerance logic to // make it more reliable because getting null back once doesn't necessarily mean // that the data is corrupted, most of the time we would get the data just fine // in subsequent tries. while (waitRetries > 0) { try { if (!isHelp) names = (string[])libraryKey.GetValue("Counter " + _perfLcid); else names = (string[])libraryKey.GetValue("Explain " + _perfLcid); if ((names == null) || (names.Length == 0)) { --waitRetries; if (waitSleep == 0) waitSleep = 10; else { System.Threading.Thread.Sleep(waitSleep); waitSleep *= 2; } } else break; } catch (IOException) { // RegistryKey throws if it can't find the value. We want to return an empty table // and throw a different exception higher up the stack. names = null; break; } catch (InvalidCastException) { // Unable to cast object of type 'System.Byte[]' to type 'System.String[]'. // this happens when the registry data store is corrupt and the type is not even REG_MULTI_SZ names = null; break; } } if (names == null) stringTable = new Dictionary<int, string>(); else { stringTable = new Dictionary<int, string>(names.Length / 2); for (int index = 0; index < (names.Length / 2); ++index) { string nameString = names[(index * 2) + 1]; if (nameString == null) nameString = String.Empty; int key; if (!Int32.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key)) { if (isHelp) { // Category Help Table throw new InvalidOperationException(SR.Format(SR.CategoryHelpCorrupt, names[index * 2])); } else { // Counter Name Table throw new InvalidOperationException(SR.Format(SR.CounterNameCorrupt, names[index * 2])); } } stringTable[key] = nameString; } } } finally { libraryKey.Dispose(); } return stringTable; #else return new Dictionary<int, string>(); #endif } internal class PerformanceMonitor { #if FEATURE_REGISTRY private RegistryKey _perfDataKey = null; #endif private string _machineName; internal PerformanceMonitor(string machineName) { _machineName = machineName; Init(); } private void Init() { #if FEATURE_REGISTRY if (ProcessManager.IsRemoteMachine(_machineName)) { _perfDataKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, _machineName); } else { _perfDataKey = Registry.PerformanceData; } #endif } // Win32 RegQueryValueEx for perf data could deadlock (for a Mutex) up to 2mins in some // scenarios before they detect it and exit gracefully. In the mean time, ERROR_BUSY, // ERROR_NOT_READY etc can be seen by other concurrent calls (which is the reason for the // wait loop and switch case below). We want to wait most certainly more than a 2min window. // The current wait time of up to 10mins takes care of the known stress deadlock issues. In most // cases we wouldn't wait for more than 2mins anyways but in worst cases how much ever time // we wait may not be sufficient if the Win32 code keeps running into this deadlock again // and again. A condition very rare but possible in theory. We would get back to the user // in this case with InvalidOperationException after the wait time expires. internal byte[] GetData(string item) { #if FEATURE_REGISTRY int waitRetries = 17; //2^16*10ms == approximately 10mins int waitSleep = 0; byte[] data = null; int error = 0; while (waitRetries > 0) { try { data = (byte[])_perfDataKey.GetValue(item); return data; } catch (IOException e) { error = e.HResult; switch (error) { case Interop.Advapi32.RPCStatus.RPC_S_CALL_FAILED: case Interop.Errors.ERROR_INVALID_HANDLE: case Interop.Advapi32.RPCStatus.RPC_S_SERVER_UNAVAILABLE: Init(); goto case Interop.Kernel32.WAIT_TIMEOUT; case Interop.Kernel32.WAIT_TIMEOUT: case Interop.Errors.ERROR_NOT_READY: case Interop.Errors.ERROR_LOCK_FAILED: case Interop.Errors.ERROR_BUSY: --waitRetries; if (waitSleep == 0) { waitSleep = 10; } else { System.Threading.Thread.Sleep(waitSleep); waitSleep *= 2; } break; default: throw new Win32Exception(error); } } catch (InvalidCastException e) { throw new InvalidOperationException(SR.Format(SR.CounterDataCorrupt, _perfDataKey.ToString()), e); } } throw new Win32Exception(error); #else return Array.Empty<byte>(); #endif } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.AzureStack.Management.Fabric.Admin { using Microsoft.AzureStack; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Fabric; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// InfraRolesOperations operations. /// </summary> internal partial class InfraRolesOperations : IServiceOperations<FabricAdminClient>, IInfraRolesOperations { /// <summary> /// Initializes a new instance of the InfraRolesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal InfraRolesOperations(FabricAdminClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the FabricAdminClient /// </summary> public FabricAdminClient Client { get; private set; } /// <summary> /// Get an infra role description. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='infraRole'> /// Infra role name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<InfraRole>> GetWithHttpMessagesAsync(string location, string infraRole, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (infraRole == null) { throw new ValidationException(ValidationRules.CannotBeNull, "infraRole"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("infraRole", infraRole); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/Microsoft.Fabric.Admin/fabricLocations/{location}/infraRoles/{infraRole}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{infraRole}", System.Uri.EscapeDataString(infraRole)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<InfraRole>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<InfraRole>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a list of all infra roles at a location. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<InfraRole>>> ListWithHttpMessagesAsync(string location, ODataQuery<InfraRole> odataQuery = default(ODataQuery<InfraRole>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("location", location); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/Microsoft.Fabric.Admin/fabricLocations/{location}/infraRoles").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<InfraRole>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<InfraRole>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a list of all infra roles at a location. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<InfraRole>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<InfraRole>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<InfraRole>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// context.cs // // Copyright 2010 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace Baker.Text { internal class JsContext { public JsDocumentContext Document { get; private set; } public int StartLineNumber { get; internal set; } public int StartLinePosition { get; internal set; } public int StartPosition { get; internal set; } public int EndLineNumber { get; internal set; } public int EndLinePosition { get; internal set; } public int EndPosition { get; internal set; } public int SourceOffsetStart { get; internal set; } public int SourceOffsetEnd { get; internal set; } /// <summary> /// Gets and sets the output start line after running an AST through an output visitor /// </summary> public int OutputLine { get; set; } /// <summary> /// Gets and sets the output start column after running an AST through an output visitor /// </summary> public int OutputColumn { get; set; } public JsToken Token { get; internal set; } public JsContext(JsParser parser) : this(new JsDocumentContext(parser)) { } public JsContext(JsDocumentContext document) { if (document == null) { throw new ArgumentNullException("document"); } Document = document; StartLineNumber = 1; EndLineNumber = 1; EndPosition = Document.Source.IfNotNull(s => s.Length); Token = JsToken.None; } public JsContext(JsDocumentContext document, int startLineNumber, int startLinePosition, int startPosition, int endLineNumber, int endLinePosition, int endPosition, JsToken token) : this(document) { StartLineNumber = startLineNumber; StartLinePosition = startLinePosition; StartPosition = startPosition; EndLineNumber = endLineNumber; EndLinePosition = endLinePosition; EndPosition = endPosition; Token = token; } public JsContext Clone() { return new JsContext(this.Document) { StartLineNumber = this.StartLineNumber, StartLinePosition = this.StartLinePosition, StartPosition = this.StartPosition, EndLineNumber = this.EndLineNumber, EndLinePosition = this.EndLinePosition, EndPosition = this.EndPosition, SourceOffsetStart = this.SourceOffsetStart, SourceOffsetEnd = this.SourceOffsetEnd, Token = this.Token, }; } public JsContext FlattenToStart() { // clone the context and flatten the end to be the start position var clone = Clone(); clone.EndLineNumber = clone.StartLineNumber; clone.EndLinePosition = clone.StartLinePosition; clone.EndPosition = clone.StartPosition; return clone; } public JsContext FlattenToEnd() { // clone the context and flatten the start to the end position var clone = Clone(); clone.StartLineNumber = clone.EndLineNumber; clone.StartLinePosition = clone.EndLinePosition; clone.StartPosition = clone.EndPosition; return clone; } public JsContext CombineWith(JsContext other) { return other == null ? this.Clone() : new JsContext(Document) { StartLineNumber = this.StartLineNumber, StartLinePosition = this.StartLinePosition, StartPosition = this.StartPosition, EndLineNumber = other.EndLineNumber, EndLinePosition = other.EndLinePosition, EndPosition = other.EndPosition, SourceOffsetStart = this.SourceOffsetStart, SourceOffsetEnd = other.SourceOffsetEnd, Token = this.Token }; } public int StartColumn { get { return StartPosition - StartLinePosition; } } public int EndColumn { get { return EndPosition - EndLinePosition; } } public bool HasCode { get { return !Document.IsGenerated && EndPosition > StartPosition && EndPosition <= Document.Source.Length && EndPosition != StartPosition; } } public String Code { get { return (!Document.IsGenerated && EndPosition > StartPosition && EndPosition <= Document.Source.Length) ? Document.Source.Substring(StartPosition, EndPosition - StartPosition) : null; } } internal void ReportUndefined(JsLookup lookup) { UndefinedReferenceException ex = new UndefinedReferenceException(lookup, this); Document.ReportUndefined(ex); } internal void ChangeFileContext(string fileContext) { // if the file context is the same, then there's nothing to change if (string.Compare(Document.FileContext, fileContext, StringComparison.OrdinalIgnoreCase) != 0) { // different source. Need to create a clone of the current document context but // with the new file context Document = Document.DifferentFileContext(fileContext); } } internal void HandleError(JsError errorId) { HandleError(errorId, false); } internal void HandleError(JsError errorId, bool forceToError) { if ((errorId != JsError.UndeclaredVariable && errorId != JsError.UndeclaredFunction) || !Document.HasAlreadySeenErrorFor(Code)) { var error = new JsException(errorId, this); if (forceToError) { error.IsError = true; } else { error.IsError = error.Severity < 2; } Document.HandleError(error); } } public JsContext UpdateWith(JsContext other) { if (other != null) { if (other.StartPosition < this.StartPosition) { this.StartPosition = other.StartPosition; this.StartLineNumber = other.StartLineNumber; this.StartLinePosition = other.StartLinePosition; this.SourceOffsetStart = other.SourceOffsetStart; } if (other.EndPosition > this.EndPosition) { this.EndPosition = other.EndPosition; this.EndLineNumber = other.EndLineNumber; this.EndLinePosition = other.EndLinePosition; this.SourceOffsetEnd = other.SourceOffsetEnd; } } return this; } public bool IsBefore(JsContext other) { // this context is BEFORE the other context if it starts on an earlier line, // OR if it starts on the same line but at an earlier column // (or if the other context is null) return other == null || StartLineNumber < other.StartLineNumber || (StartLineNumber == other.StartLineNumber && StartColumn < other.StartColumn); } public override string ToString() { return Code; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Reflection.Runtime.General; using Internal.Runtime; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using Internal.Metadata.NativeFormat; using Internal.NativeFormat; using Internal.TypeSystem; namespace Internal.Runtime.TypeLoader { /// <summary> /// Helper structure describing all info needed to construct dynamic field accessors. /// </summary> public struct FieldAccessMetadata { /// <summary> /// Module containing the relevant metadata, null when not found /// </summary> public TypeManagerHandle MappingTableModule; /// <summary> /// Cookie for field access. This field is set to IntPtr.Zero when the value is not available. /// </summary> public IntPtr Cookie; /// <summary> /// Field access and characteristics bitmask. /// </summary> public FieldTableFlags Flags; /// <summary> /// Field offset, address or cookie based on field access type. /// </summary> public int Offset; } public sealed partial class TypeLoaderEnvironment { /// <summary> /// Try to look up field acccess info for given canon in metadata blobs for all available modules. /// </summary> /// <param name="metadataReader">Metadata reader for the declaring type</param> /// <param name="declaringTypeHandle">Declaring type for the method</param> /// <param name="fieldHandle">Field handle</param> /// <param name="canonFormKind">Canonical form to use</param> /// <param name="fieldAccessMetadata">Output - metadata information for field accessor construction</param> /// <returns>true when found, false otherwise</returns> public static bool TryGetFieldAccessMetadata( MetadataReader metadataReader, RuntimeTypeHandle runtimeTypeHandle, FieldHandle fieldHandle, out FieldAccessMetadata fieldAccessMetadata) { fieldAccessMetadata = default(FieldAccessMetadata); if (TryGetFieldAccessMetadataFromFieldAccessMap( metadataReader, runtimeTypeHandle, fieldHandle, CanonicalFormKind.Specific, ref fieldAccessMetadata)) { return true; } if (TryGetFieldAccessMetadataFromFieldAccessMap( metadataReader, runtimeTypeHandle, fieldHandle, CanonicalFormKind.Universal, ref fieldAccessMetadata)) { return true; } TypeSystemContext context = TypeSystemContextFactory.Create(); bool success = TryGetFieldAccessMetadataFromNativeFormatMetadata( metadataReader, runtimeTypeHandle, fieldHandle, context, ref fieldAccessMetadata); TypeSystemContextFactory.Recycle(context); return success; } /// <summary> /// Try to look up field acccess info for given canon in metadata blobs for all available modules. /// </summary> /// <param name="metadataReader">Metadata reader for the declaring type</param> /// <param name="declaringTypeHandle">Declaring type for the method</param> /// <param name="fieldHandle">Field handle</param> /// <param name="canonFormKind">Canonical form to use</param> /// <param name="fieldAccessMetadata">Output - metadata information for field accessor construction</param> /// <returns>true when found, false otherwise</returns> private static bool TryGetFieldAccessMetadataFromFieldAccessMap( MetadataReader metadataReader, RuntimeTypeHandle declaringTypeHandle, FieldHandle fieldHandle, CanonicalFormKind canonFormKind, ref FieldAccessMetadata fieldAccessMetadata) { CanonicallyEquivalentEntryLocator canonWrapper = new CanonicallyEquivalentEntryLocator(declaringTypeHandle, canonFormKind); TypeManagerHandle fieldHandleModule = ModuleList.Instance.GetModuleForMetadataReader(metadataReader); bool isDynamicType = RuntimeAugments.IsDynamicType(declaringTypeHandle); string fieldName = null; RuntimeTypeHandle declaringTypeHandleDefinition = Instance.GetTypeDefinition(declaringTypeHandle); foreach (NativeFormatModuleInfo mappingTableModule in ModuleList.EnumerateModules(RuntimeAugments.GetModuleFromTypeHandle(declaringTypeHandle))) { NativeReader fieldMapReader; if (!TryGetNativeReaderForBlob(mappingTableModule, ReflectionMapBlob.FieldAccessMap, out fieldMapReader)) continue; NativeParser fieldMapParser = new NativeParser(fieldMapReader, 0); NativeHashtable fieldHashtable = new NativeHashtable(fieldMapParser); ExternalReferencesTable externalReferences = default(ExternalReferencesTable); if (!externalReferences.InitializeCommonFixupsTable(mappingTableModule)) { continue; } var lookup = fieldHashtable.Lookup(canonWrapper.LookupHashCode); NativeParser entryParser; while (!(entryParser = lookup.GetNext()).IsNull) { // Grammar of a hash table entry: // Flags + DeclaringType + MdHandle or Name + Cookie or Ordinal or Offset FieldTableFlags entryFlags = (FieldTableFlags)entryParser.GetUnsigned(); if ((canonFormKind == CanonicalFormKind.Universal) != entryFlags.HasFlag(FieldTableFlags.IsUniversalCanonicalEntry)) continue; RuntimeTypeHandle entryDeclaringTypeHandle = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned()); if (!entryDeclaringTypeHandle.Equals(declaringTypeHandle) && !canonWrapper.IsCanonicallyEquivalent(entryDeclaringTypeHandle)) continue; if (entryFlags.HasFlag(FieldTableFlags.HasMetadataHandle)) { Handle entryFieldHandle = (((int)HandleType.Field << 24) | (int)entryParser.GetUnsigned()).AsHandle(); if (!fieldHandle.Equals(entryFieldHandle)) continue; } else { if (fieldName == null) { QTypeDefinition qTypeDefinition; bool success = Instance.TryGetMetadataForNamedType( declaringTypeHandleDefinition, out qTypeDefinition); Debug.Assert(success); MetadataReader nativeFormatMetadataReader = qTypeDefinition.NativeFormatReader; fieldName = nativeFormatMetadataReader.GetString(fieldHandle.GetField(nativeFormatMetadataReader).Name); } string entryFieldName = entryParser.GetString(); if (fieldName != entryFieldName) continue; } int cookieOrOffsetOrOrdinal = (int)entryParser.GetUnsigned(); int fieldOffset; IntPtr fieldAddressCookie = IntPtr.Zero; if (canonFormKind == CanonicalFormKind.Universal) { if (!TypeLoaderEnvironment.Instance.TryGetFieldOffset(declaringTypeHandle, (uint)cookieOrOffsetOrOrdinal, out fieldOffset)) { Debug.Assert(false); return false; } } else { #if CORERT fieldOffset = cookieOrOffsetOrOrdinal; #else fieldOffset = (int)externalReferences.GetRvaFromIndex((uint)cookieOrOffsetOrOrdinal); #endif } if ((entryFlags & FieldTableFlags.StorageClass) == FieldTableFlags.ThreadStatic) { if (canonFormKind != CanonicalFormKind.Universal) { fieldAddressCookie = RvaToNonGenericStaticFieldAddress(mappingTableModule.Handle, fieldOffset); } if (!entryDeclaringTypeHandle.Equals(declaringTypeHandle)) { // In this case we didn't find an exact match, but we did find a canonically equivalent match // We might be in the dynamic type case, or the canonically equivalent, but not the same case. if (!RuntimeAugments.IsDynamicType(declaringTypeHandle)) { int offsetToCreateCookieFor = fieldOffset; // We're working with a statically generated type, but we didn't find an exact match in the tables if (canonFormKind != CanonicalFormKind.Universal) offsetToCreateCookieFor = checked((int)TypeLoaderEnvironment.GetThreadStaticTypeOffsetFromThreadStaticCookie(fieldAddressCookie)); fieldAddressCookie = TypeLoaderEnvironment.Instance.TryGetThreadStaticFieldOffsetCookieForTypeAndFieldOffset(declaringTypeHandle, checked((uint)offsetToCreateCookieFor)); } } } fieldAccessMetadata.MappingTableModule = mappingTableModule.Handle; fieldAccessMetadata.Cookie = fieldAddressCookie; fieldAccessMetadata.Flags = entryFlags; fieldAccessMetadata.Offset = fieldOffset; return true; } } return false; } private enum FieldAccessStaticDataKind { NonGC, GC, TLS } private static class FieldAccessFlags { public const int RemoteStaticFieldRVA = unchecked((int)0x80000000); } /// <summary> /// This structure describes one static field in an external module. It is represented /// by an indirection cell pointer and an offset within the cell - the final address /// of the static field is essentially *IndirectionCell + Offset. /// </summary> [StructLayout(LayoutKind.Sequential)] private struct RemoteStaticFieldDescriptor { public unsafe IntPtr* IndirectionCell; public int Offset; } /// <summary> /// Resolve a given 32-bit integer (staticFieldRVA) representing a static field address. /// For "local" static fields residing in the module given by moduleHandle, staticFieldRVA /// directly contains the RVA of the static field. For remote static fields residing in other /// modules, staticFieldRVA has the highest bit set (FieldAccessFlags.RemoteStaticFieldRVA) /// and it contains the RVA of a RemoteStaticFieldDescriptor structure residing in the module /// given by moduleHandle that holds a pointer to the indirection cell /// of the remote static field and its offset within the cell. /// </summary> /// <param name="moduleHandle">Reference module handle used for static field lookup</param> /// <param name="staticFieldRVA"> /// RVA of static field for local fields; for remote fields, RVA of a RemoteStaticFieldDescriptor /// structure for the field or-ed with the FieldAccessFlags.RemoteStaticFieldRVA bit /// </param> public static unsafe IntPtr RvaToNonGenericStaticFieldAddress(TypeManagerHandle moduleHandle, int staticFieldRVA) { IntPtr staticFieldAddress; if ((staticFieldRVA & FieldAccessFlags.RemoteStaticFieldRVA) != 0) { RemoteStaticFieldDescriptor* descriptor = (RemoteStaticFieldDescriptor*)(moduleHandle.ConvertRVAToPointer (staticFieldRVA & ~FieldAccessFlags.RemoteStaticFieldRVA)); staticFieldAddress = *descriptor->IndirectionCell + descriptor->Offset; } else staticFieldAddress = (IntPtr)(moduleHandle.ConvertRVAToPointer(staticFieldRVA)); return staticFieldAddress; } /// <summary> /// Try to look up non-gc/gc static effective field bases for a non-generic non-dynamic type. /// </summary> /// <param name="declaringTypeHandle">Declaring type for the method</param> /// <param name="fieldAccessKind">type of static base to find</param> /// <param name="staticsRegionAddress">Output - statics region address info</param> /// <returns>true when found, false otherwise</returns> private static unsafe bool TryGetStaticFieldBaseFromFieldAccessMap( RuntimeTypeHandle declaringTypeHandle, FieldAccessStaticDataKind fieldAccessKind, out IntPtr staticsRegionAddress) { staticsRegionAddress = IntPtr.Zero; byte* comparableStaticRegionAddress = null; CanonicallyEquivalentEntryLocator canonWrapper = new CanonicallyEquivalentEntryLocator(declaringTypeHandle, CanonicalFormKind.Specific); // This function only finds results for non-dynamic, non-generic types if (RuntimeAugments.IsDynamicType(declaringTypeHandle) || RuntimeAugments.IsGenericType(declaringTypeHandle)) return false; foreach (NativeFormatModuleInfo mappingTableModule in ModuleList.EnumerateModules(RuntimeAugments.GetModuleFromTypeHandle(declaringTypeHandle))) { NativeReader fieldMapReader; if (!TryGetNativeReaderForBlob(mappingTableModule, ReflectionMapBlob.FieldAccessMap, out fieldMapReader)) continue; NativeParser fieldMapParser = new NativeParser(fieldMapReader, 0); NativeHashtable fieldHashtable = new NativeHashtable(fieldMapParser); ExternalReferencesTable externalReferences = default(ExternalReferencesTable); if (!externalReferences.InitializeCommonFixupsTable(mappingTableModule)) { continue; } var lookup = fieldHashtable.Lookup(canonWrapper.LookupHashCode); NativeParser entryParser; while (!(entryParser = lookup.GetNext()).IsNull) { // Grammar of a hash table entry: // Flags + DeclaringType + MdHandle or Name + Cookie or Ordinal or Offset FieldTableFlags entryFlags = (FieldTableFlags)entryParser.GetUnsigned(); Debug.Assert(!entryFlags.HasFlag(FieldTableFlags.IsUniversalCanonicalEntry)); if (!entryFlags.HasFlag(FieldTableFlags.Static)) continue; switch (fieldAccessKind) { case FieldAccessStaticDataKind.NonGC: if (entryFlags.HasFlag(FieldTableFlags.IsGcSection)) continue; if (entryFlags.HasFlag(FieldTableFlags.ThreadStatic)) continue; break; case FieldAccessStaticDataKind.GC: if (!entryFlags.HasFlag(FieldTableFlags.IsGcSection)) continue; if (entryFlags.HasFlag(FieldTableFlags.ThreadStatic)) continue; break; case FieldAccessStaticDataKind.TLS: default: // TODO! TLS statics Environment.FailFast("TLS static field access not yet supported"); return false; } RuntimeTypeHandle entryDeclaringTypeHandle = externalReferences.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned()); if (!entryDeclaringTypeHandle.Equals(declaringTypeHandle)) continue; if (entryFlags.HasFlag(FieldTableFlags.HasMetadataHandle)) { // skip metadata handle entryParser.GetUnsigned(); } else { // skip field name entryParser.SkipString(); } int cookieOrOffsetOrOrdinal = (int)entryParser.GetUnsigned(); int fieldOffset = (int)externalReferences.GetRvaFromIndex((uint)cookieOrOffsetOrOrdinal); IntPtr fieldAddress = RvaToNonGenericStaticFieldAddress( mappingTableModule.Handle, fieldOffset); if ((comparableStaticRegionAddress == null) || (comparableStaticRegionAddress > fieldAddress.ToPointer())) { comparableStaticRegionAddress = (byte*)fieldAddress.ToPointer(); } } // Static fields for a type can only be found in at most one module if (comparableStaticRegionAddress != null) break; } if (comparableStaticRegionAddress != null) { staticsRegionAddress = new IntPtr(comparableStaticRegionAddress); return true; } else { return false; } } /// <summary> /// Try to figure out field access information based on type metadata for native format types. /// </summary> /// <param name="metadataReader">Metadata reader for the declaring type</param> /// <param name="declaringTypeHandle">Declaring type for the method</param> /// <param name="fieldHandle">Field handle</param> /// <param name="canonFormKind">Canonical form to use</param> /// <param name="fieldAccessMetadata">Output - metadata information for field accessor construction</param> /// <returns>true when found, false otherwise</returns> private static bool TryGetFieldAccessMetadataFromNativeFormatMetadata( MetadataReader metadataReader, RuntimeTypeHandle declaringTypeHandle, FieldHandle fieldHandle, TypeSystemContext context, ref FieldAccessMetadata fieldAccessMetadata) { Field field = metadataReader.GetField(fieldHandle); string fieldName = metadataReader.GetString(field.Name); TypeDesc declaringType = context.ResolveRuntimeTypeHandle(declaringTypeHandle); #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING if (declaringType is MetadataType) { return TryGetFieldAccessMetadataForNativeFormatType(declaringType, fieldName, ref fieldAccessMetadata); } #endif return false; } /// <summary> /// Locate field on native format type and fill in the field access flags and offset. /// </summary> /// <param name="type">Metadata reader for the declaring type</param> /// <param name="fieldName">Field name</param> /// <param name="fieldAccessMetadata">Output - metadata information for field accessor construction</param> /// <returns>true when found, false otherwise</returns> private static bool TryGetFieldAccessMetadataForNativeFormatType( TypeDesc type, string fieldName, ref FieldAccessMetadata fieldAccessMetadata) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING FieldDesc fieldDesc = type.GetField(fieldName); if (fieldDesc == null) { return false; } fieldAccessMetadata.MappingTableModule = default(TypeManagerHandle); #if SUPPORTS_R2R_LOADING fieldAccessMetadata.MappingTableModule = ModuleList.Instance.GetModuleForMetadataReader(((NativeFormatType)type.GetTypeDefinition()).MetadataReader); #endif fieldAccessMetadata.Offset = fieldDesc.Offset; fieldAccessMetadata.Flags = FieldTableFlags.HasMetadataHandle; if (fieldDesc.IsThreadStatic) { // Specify that the data is thread local fieldAccessMetadata.Flags |= FieldTableFlags.ThreadStatic; // Specify that the general purpose field access routine that only relies on offset should be used. fieldAccessMetadata.Flags |= FieldTableFlags.IsUniversalCanonicalEntry; } else if (fieldDesc.IsStatic) { uint nonGcStaticsRVA = 0; uint gcStaticsRVA = 0; bool nonGenericCase = false; if (type is MetadataType) { // Static fields on Non-Generic types are contained within the module, and their offsets // are adjusted by their static rva base. nonGenericCase = true; #if SUPPORTS_R2R_LOADING if (!TryGetStaticsTableEntry((MetadataType)type, nonGcStaticsRVA: out nonGcStaticsRVA, gcStaticsRVA: out gcStaticsRVA)) #endif { Environment.FailFast( "Failed to locate statics table entry for for field '" + fieldName + "' on type " + type.ToString()); } } if (fieldDesc.HasGCStaticBase) { if ((gcStaticsRVA == 0) && nonGenericCase) { Environment.FailFast( "GC statics region was not found for field '" + fieldName + "' on type " + type.ToString()); } fieldAccessMetadata.Offset += (int)gcStaticsRVA; fieldAccessMetadata.Flags |= FieldTableFlags.IsGcSection; } else { if ((nonGcStaticsRVA == 0) && nonGenericCase) { Environment.FailFast( "Non-GC statics region was not found for field '" + fieldName + "' on type " + type.ToString()); } fieldAccessMetadata.Offset += (int)nonGcStaticsRVA; } fieldAccessMetadata.Flags |= FieldTableFlags.Static; return true; } else { // Instance field fieldAccessMetadata.Flags |= FieldTableFlags.Instance; } return true; #else return false; #endif } } }
using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using DeOps.Implementation.Protocol; namespace DeOps.Services.Trust { public class TrustPacket { public const byte ProjectData = 0x10; public const byte LinkData = 0x20; public const byte UplinkReq = 0x30; public const byte WebCache = 0x40; public const byte Icon = 0x50; public const byte Splash = 0x60; } public class ProjectData : G2Packet { const byte Packet_ID = 0x10; const byte Packet_Name = 0x20; const byte Packet_UserName = 0x30; public uint ID; public string Name = "Unknown"; public string UserName = "Unknown"; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame project = protocol.WritePacket(null, TrustPacket.ProjectData, null); protocol.WritePacket(project, Packet_ID, BitConverter.GetBytes(ID)); protocol.WritePacket(project, Packet_Name, UTF8Encoding.UTF8.GetBytes(Name)); protocol.WritePacket(project, Packet_UserName, UTF8Encoding.UTF8.GetBytes(UserName)); return protocol.WriteFinish(); } } public static ProjectData Decode(G2Header root) { ProjectData project = new ProjectData(); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_ID: project.ID = BitConverter.ToUInt32(child.Data, child.PayloadPos); break; case Packet_Name: project.Name = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_UserName: project.UserName = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; } } return project; } } public class LinkData : G2Packet { const byte Packet_Project = 0x10; const byte Packet_Target = 0x20; const byte Packet_Uplink = 0x30; const byte Packet_Title = 0x40; public uint Project; public byte[] Target; public bool Uplink; public string Title; public ulong TargetID; LinkData() { } // uplink public LinkData(uint project, byte[] target) { Project = project; Target = target; Uplink = true; } // downlink public LinkData(uint project, byte[] target, string title) { Project = project; Target = target; Uplink = false; Title = title; } public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame link = protocol.WritePacket(null, TrustPacket.LinkData, null); protocol.WritePacket(link, Packet_Project, BitConverter.GetBytes(Project)); protocol.WritePacket(link, Packet_Target, Target); protocol.WritePacket(link, Packet_Uplink, BitConverter.GetBytes(Uplink)); if(Title != null) protocol.WritePacket(link, Packet_Title, UTF8Encoding.UTF8.GetBytes(Title)); return protocol.WriteFinish(); } } public static LinkData Decode(G2Header root) { LinkData link = new LinkData(); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Project: link.Project = BitConverter.ToUInt32(child.Data, child.PayloadPos); break; case Packet_Target: link.Target = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); link.TargetID = Utilities.KeytoID(link.Target); break; case Packet_Uplink: link.Uplink = BitConverter.ToBoolean(child.Data, child.PayloadPos); break; case Packet_Title: link.Title = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; } } return link; } } public class UplinkRequest : G2Packet { const byte Packet_ProjectID = 0x10; const byte Packet_LinkVersion = 0x20; const byte Packet_TargetVersion = 0x30; const byte Packet_Key = 0x40; const byte Packet_Target = 0x50; public uint ProjectID; public uint LinkVersion; public uint TargetVersion; public byte[] Key; public byte[] Target; public ulong KeyID; public ulong TargetID; public byte[] Signed; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame request = protocol.WritePacket(null, TrustPacket.UplinkReq, null); protocol.WritePacket(request, Packet_ProjectID, BitConverter.GetBytes(ProjectID)); protocol.WritePacket(request, Packet_LinkVersion, BitConverter.GetBytes(LinkVersion)); protocol.WritePacket(request, Packet_TargetVersion, BitConverter.GetBytes(TargetVersion)); protocol.WritePacket(request, Packet_Key, Key); protocol.WritePacket(request, Packet_Target, Target); return protocol.WriteFinish(); } } public static UplinkRequest Decode(G2Header root) { UplinkRequest request = new UplinkRequest(); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_ProjectID: request.ProjectID = BitConverter.ToUInt32(child.Data, child.PayloadPos); break; case Packet_LinkVersion: request.LinkVersion = BitConverter.ToUInt32(child.Data, child.PayloadPos); break; case Packet_TargetVersion: request.TargetVersion = BitConverter.ToUInt32(child.Data, child.PayloadPos); break; case Packet_Key: request.Key = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); request.KeyID = Utilities.KeytoID(request.Key); break; case Packet_Target: request.Target = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); request.TargetID = Utilities.KeytoID(request.Target); break; } } return request; } } }
using System; using System.Windows.Forms; using System.Drawing; using System.Collections; using PrimerProForms; using PrimerProObjects; using GenLib; namespace PrimerProSearch { /// <summary> /// Tone search for Word List /// </summary> public class ToneWLSearch : Search { //Search parameters private ArrayList m_SelectedTones; // tones to be searched private SearchOptions m_SearchOptions; // search option filter private string m_Title; //search title; private Settings m_Settings; //Application Settings private PSTable m_PSTable; //Parts of Speech private GraphemeInventory m_GI; //Grapheme Inventory private Font m_DefaultFont; //Default Font //Search definition tags private const string kTone = "tone"; //private const string kTitle = "Tone Search"; public ToneWLSearch(int number, Settings s) : base(number, SearchDefinition.kToneWL) { //m_Tone = ""; m_SelectedTones = new ArrayList(); m_SearchOptions = null; m_Settings = s; m_Title = m_Settings.LocalizationTable.GetMessage("ToneWLSearchT"); if (m_Title == "") m_Title = "Tone Search"; m_PSTable = m_Settings.PSTable; m_GI = m_Settings.GraphemeInventory; m_DefaultFont = m_Settings.OptionSettings.GetDefaultFont(); } public ArrayList SelectedTones { get {return m_SelectedTones;} set { m_SelectedTones = value; } } public SearchOptions SearchOptions { get {return m_SearchOptions;} set {m_SearchOptions = value;} } public string Title { get {return m_Title;} } public PSTable PSTable { get {return m_PSTable;} } public GraphemeInventory GI { get {return m_GI;} } public Font DefaultFont { get { return m_DefaultFont; } } public bool SetupSearch() { bool flag = false; //FormToneWL fpb = new FormToneWL(this.GI, this.PSTable, this.DefaultFont); FormToneWL form = new FormToneWL(m_Settings, m_Settings.LocalizationTable); DialogResult dr = form.ShowDialog(); if (dr == DialogResult.OK) { this.SelectedTones = form.SelectedTones; this.SearchOptions = form.SearchOptions; SearchDefinition sd = new SearchDefinition(SearchDefinition.kToneWL); SearchDefinitionParm sdp = null; String strTone = ""; if (form.SelectedTones != null) { if (form.SelectedTones.Count > 0) { for (int i = 0; i < form.SelectedTones.Count; i++) { strTone = form.SelectedTones[i].ToString(); sdp = new SearchDefinitionParm(ToneWLSearch.kTone, strTone); sd.AddSearchParm(sdp); } if (form.SearchOptions != null) sd.AddSearchOptions(form.SearchOptions); this.SearchDefinition = sd; flag = true; } //else MessageBox.Show("No tone was selected"); else { string strMsg = m_Settings.LocalizationTable.GetMessage("ToneWLSearch2"); if (strMsg == "") strMsg = "No tone was selected"; MessageBox.Show(strMsg); } } //else MessageBox.Show("No tone was selected"); else { string strMsg = m_Settings.LocalizationTable.GetMessage("ToneWLSearch2"); if (strMsg == "") strMsg = "No tone was selected"; MessageBox.Show(strMsg); } } return flag; } public bool SetupSearch(SearchDefinition sd) { bool flag = false; SearchOptions so = new SearchOptions(m_PSTable); string strTag = ""; string strContent = ""; for (int i = 0; i < sd.SearchParmsCount(); i++) { strTag = sd.GetSearchParmAt(i).GetTag(); strContent = sd.GetSearchParmAt(i).GetContent(); if (strTag == ToneWLSearch.kTone) { this.SelectedTones.Add(strContent); flag = true; } } this.SearchOptions = sd.MakeSearchOptions(so); this.SearchDefinition = sd; return flag; } public string BuildResults() { string strText = ""; string strSN = Search.TagSN + this.SearchNumber.ToString().Trim(); string str = ""; strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine; strText += this.Title + Environment.NewLine + Environment.NewLine; strText += this.SearchResults; strText += Environment.NewLine; //strText += this.SearchCount.ToString() + " entries found" + Environment.NewLine; str = m_Settings.LocalizationTable.GetMessage("Search2"); if (str == "") str = "entries found"; strText += this.SearchCount.ToString() + Constants.Space + str + Environment.NewLine; strText += Search.TagOpener + Search.TagForwardSlash + strSN + Search.TagCloser; return strText; } public ToneWLSearch ExecuteToneSearch(WordList wl) { ArrayList alTones = this.SelectedTones; int nCount = 0; string strResult = wl.GetDisplayHeadings() + Environment.NewLine; Word wrd = null; int nWord = wl.WordCount(); Grapheme grf = null; for (int i = 0; i < nWord; i++) { wrd = wl.GetWord(i); if (this.SearchOptions == null) { bool found = false; if (alTones.Count > 0) { for (int n = 0; n < wrd.GraphemeCount(); n++) { grf = wrd.GetGrapheme(n); int ndx = 0; do { if (grf.Symbol == alTones[ndx].ToString()) found = true; ndx++; } while ( (!found) && (ndx < this.SelectedTones.Count)); if (found) break; } } if (found) { nCount++; strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine; } } else { if (this.SearchOptions.MatchesWord(wrd)) { if (this.SearchOptions.IsRootOnly) { bool found = false; string strTone = ""; int ndx = 0; do { if (this.SelectedTones.Count > 0) { strTone = this.SelectedTones[ndx].ToString(); if (wrd.Root.DisplayRoot.IndexOf(strTone) >= 0) { if (this.SearchOptions.MatchesPosition(wrd, strTone)) found = true; } ndx++; } } while ((!found) && (ndx < this.SelectedTones.Count)); if (found) { nCount++; strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine; } } else { bool found = false; string strTone = ""; int ndx = 0; do { if (this.SelectedTones.Count > 0) { strTone = this.SelectedTones[ndx].ToString(); if (wrd.DisplayWord.IndexOf(strTone) >= 0) { if (this.SearchOptions.MatchesPosition(wrd, strTone)) found = true; } ndx++; } } while ((!found) && (ndx < this.SelectedTones.Count)); if (found) { nCount++; strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine; } } } } } if (nCount > 0) { this.SearchResults = strResult; this.SearchCount = nCount; } else { //this.SearchResults = "***No Results***"; this.SearchResults = m_Settings.LocalizationTable.GetMessage("Search1"); if (this.SearchResults == "") this.SearchResults = "***No Results***"; this.SearchCount = 0; } return this; } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using Moq.Language.Flow; using Xunit; namespace Moq.Tests { public class ReturnsValidationFixture { private Mock<IType> mock; private ISetup<IType, IType> setup; private ISetup<IType, IType> setupNoArgs; public ReturnsValidationFixture() { this.mock = new Mock<IType>(); this.setup = this.mock.Setup(m => m.Method(It.IsAny<object>(), It.IsAny<object>())); this.setupNoArgs = this.mock.Setup(m => m.MethodNoArgs()); } [Fact] public void Returns_does_not_accept_delegate_without_return_value() { Action<object> delegateWithoutReturnValue = (arg) => { }; var ex = Record.Exception(() => { this.setup.Returns(delegateWithoutReturnValue); }); Assert.IsType<ArgumentException>(ex); } [Fact] public void Returns_does_not_accept_delegate_with_wrong_return_type() { Func<string> delegateWithWrongReturnType = () => "42"; var ex = Record.Exception(() => { this.setup.Returns(delegateWithWrongReturnType); }); Assert.IsType<ArgumentException>(ex); } [Fact] public void Returns_accepts_parameterless_delegate_for_method_without_parameters() { Func<IType> delegateWithoutParameters = () => default(IType); this.setupNoArgs.Returns(delegateWithoutParameters); var ex = Record.Exception(() => { this.mock.Object.MethodNoArgs(); }); Assert.Null(ex); } [Fact] public void Returns_accepts_parameterless_delegate_even_for_method_having_parameters() { Func<IType> delegateWithoutParameters = () => default(IType); this.setup.Returns(delegateWithoutParameters); var ex = Record.Exception(() => { this.mock.Object.Method(42, 3); }); Assert.Null(ex); } [Fact] public void Returns_does_not_accept_delegate_with_wrong_parameter_count() { Func<object, object, object, IType> delegateWithWrongParameterCount = (arg1, arg2, arg3) => default(IType); var ex = Record.Exception(() => { this.setup.Returns(delegateWithWrongParameterCount); }); Assert.IsType<ArgumentException>(ex); } [Fact] public void Returns_accepts_delegate_with_wrong_parameter_types_but_setup_invocation_will_fail() { Func<string, string, IType> delegateWithWrongParameterType = (arg1, arg2) => default(IType); this.setup.Returns(delegateWithWrongParameterType); var ex = Record.Exception(() => { mock.Object.Method(42, 7); }); Assert.IsType<ArgumentException>(ex); // In case you're wondering why this use case isn't "fixed" by properly validating delegates // passed to `Returns`... it's entirely possible that some people might do this: // // mock.Setup(m => m.Method(It.IsAny<int>()).Returns<int>(obj => ...); // mock.Setup(m => m.Method(It.IsAny<string>()).Returns<string>(obj => ...); // // where `Method` has a parameter of type `object`. That is, people might rely on a matcher // to ensure that the return callback delegate invocation (and the cast to `object` that has to // happen) will always succeed. See also the next test, as well as old Google Code issue 267 // in `IssueReportsFixture.cs`. // // While not the cleanest of techniques, it might be useful to some people and probably // shouldn't be broken by eagerly validating everything. } [Fact] public void Returns_accepts_delegate_with_wrong_parameter_types_and_setup_invocation_will_succeed_if_args_convertible() { Func<string, string, IType> delegateWithWrongParameterType = (arg1, arg2) => default(IType); this.setup.Returns(delegateWithWrongParameterType); var ex = Record.Exception(() => { mock.Object.Method(null, null); }); Assert.Null(ex); } [Fact] public void Returns_accepts_parameterless_extension_method_for_method_without_parameters() { Func<IType> delegateWithoutParameters = new ReturnsValidationFixture().ExtensionMethodNoArgs; this.setupNoArgs.Returns(delegateWithoutParameters); var ex = Record.Exception(() => { this.mock.Object.MethodNoArgs(); }); Assert.Null(ex); } [Fact] public void Returns_accepts_parameterless_extension_method_even_for_method_having_parameters() { Func<IType> delegateWithoutParameters = new ReturnsValidationFixture().ExtensionMethodNoArgs; this.setup.Returns(delegateWithoutParameters); var ex = Record.Exception(() => { this.mock.Object.Method(42, 5); }); Assert.Null(ex); } [Fact] public void Returns_does_not_accept_extension_method_with_wrong_parameter_count() { Func<object, object, IType> delegateWithWrongParameterCount = new ReturnsValidationFixture().ExtensionMethod; var ex = Record.Exception(() => { this.setupNoArgs.Returns(delegateWithWrongParameterCount); }); Assert.IsType<ArgumentException>(ex); } [Fact] public void Returns_accepts_extension_method_with_correct_parameter_count() { Func<object, object, IType> delegateWithCorrectParameterCount = new ReturnsValidationFixture().ExtensionMethod; this.setup.Returns(delegateWithCorrectParameterCount); var ex = Record.Exception(() => { this.mock.Object.Method(42, 5); }); Assert.Null(ex); } public interface IType { IType Method(object arg1, object arg2); IType MethodNoArgs(); } } static class ReturnsValidationFixtureExtensions { internal static ReturnsValidationFixture.IType ExtensionMethod(this ReturnsValidationFixture fixture, object arg1, object arg2) { return default(ReturnsValidationFixture.IType); } internal static ReturnsValidationFixture.IType ExtensionMethodNoArgs(this ReturnsValidationFixture fixture) { return default(ReturnsValidationFixture.IType); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace FujiSan.WebAPI.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Primitives; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osu.Framework.Utils; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Skinning; using osuTK; using osuTK.Graphics; namespace osu.Game.Screens.Edit.Compose.Components.Timeline { public class TimelineHitObjectBlueprint : SelectionBlueprint<HitObject> { private const float circle_size = 38; private Container repeatsContainer; public Action<DragEvent> OnDragHandled; [UsedImplicitly] private readonly Bindable<double> startTime; private Bindable<int> indexInCurrentComboBindable; private Bindable<int> comboIndexBindable; private Bindable<Color4> displayColourBindable; private readonly ExtendableCircle circle; private readonly Border border; private readonly Container colouredComponents; private readonly OsuSpriteText comboIndexText; [Resolved] private ISkinSource skin { get; set; } public TimelineHitObjectBlueprint(HitObject item) : base(item) { Anchor = Anchor.CentreLeft; Origin = Anchor.CentreLeft; startTime = item.StartTimeBindable.GetBoundCopy(); startTime.BindValueChanged(time => X = (float)time.NewValue, true); RelativePositionAxes = Axes.X; RelativeSizeAxes = Axes.X; Height = circle_size; AddRangeInternal(new Drawable[] { circle = new ExtendableCircle { RelativeSizeAxes = Axes.Both, Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, }, border = new Border { RelativeSizeAxes = Axes.Both, Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, }, colouredComponents = new Container { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, RelativeSizeAxes = Axes.Both, Children = new Drawable[] { comboIndexText = new OsuSpriteText { Anchor = Anchor.CentreLeft, Origin = Anchor.Centre, Y = -1, Font = OsuFont.Default.With(size: circle_size * 0.5f, weight: FontWeight.Regular), }, } }, }); if (item is IHasDuration) { colouredComponents.Add(new DragArea(item) { OnDragHandled = e => OnDragHandled?.Invoke(e) }); } } protected override void LoadComplete() { base.LoadComplete(); switch (Item) { case IHasDisplayColour displayColour: displayColourBindable = displayColour.DisplayColour.GetBoundCopy(); displayColourBindable.BindValueChanged(_ => updateColour(), true); break; case IHasComboInformation comboInfo: indexInCurrentComboBindable = comboInfo.IndexInCurrentComboBindable.GetBoundCopy(); indexInCurrentComboBindable.BindValueChanged(_ => updateComboIndex(), true); comboIndexBindable = comboInfo.ComboIndexBindable.GetBoundCopy(); comboIndexBindable.BindValueChanged(_ => updateColour(), true); skin.SourceChanged += updateColour; break; } } protected override void OnSelected() { // base logic hides selected blueprints when not selected, but timeline doesn't do that. updateColour(); } protected override void OnDeselected() { // base logic hides selected blueprints when not selected, but timeline doesn't do that. updateColour(); } private void updateComboIndex() => comboIndexText.Text = (indexInCurrentComboBindable.Value + 1).ToString(); private void updateColour() { Color4 colour; switch (Item) { case IHasDisplayColour displayColour: colour = displayColour.DisplayColour.Value; break; case IHasComboInformation combo: { var comboColours = skin.GetConfig<GlobalSkinColours, IReadOnlyList<Color4>>(GlobalSkinColours.ComboColours)?.Value ?? Array.Empty<Color4>(); colour = combo.GetComboColour(comboColours); break; } default: return; } if (IsSelected) { border.Show(); colour = colour.Lighten(0.3f); } else { border.Hide(); } if (Item is IHasDuration duration && duration.Duration > 0) circle.Colour = ColourInfo.GradientHorizontal(colour, colour.Lighten(0.4f)); else circle.Colour = colour; var col = circle.Colour.TopLeft.Linear; colouredComponents.Colour = OsuColour.ForegroundTextColourFor(col); } protected override void Update() { base.Update(); // no bindable so we perform this every update float duration = (float)(Item.GetEndTime() - Item.StartTime); if (Width != duration) { Width = duration; // kind of haphazard but yeah, no bindables. if (Item is IHasRepeats repeats) updateRepeats(repeats); } } private void updateRepeats(IHasRepeats repeats) { repeatsContainer?.Expire(); colouredComponents.Add(repeatsContainer = new Container { RelativeSizeAxes = Axes.Both, }); for (int i = 0; i < repeats.RepeatCount; i++) { repeatsContainer.Add(new Circle { Size = new Vector2(circle_size / 3), Alpha = 0.2f, Anchor = Anchor.CentreLeft, Origin = Anchor.Centre, RelativePositionAxes = Axes.X, X = (float)(i + 1) / (repeats.RepeatCount + 1), }); } } protected override bool ShouldBeConsideredForInput(Drawable child) => true; public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => circle.ReceivePositionalInputAt(screenSpacePos); public override Quad SelectionQuad => circle.ScreenSpaceDrawQuad; public override Vector2 ScreenSpaceSelectionPoint => ScreenSpaceDrawQuad.TopLeft; public class DragArea : Circle { private readonly HitObject hitObject; [Resolved] private Timeline timeline { get; set; } public Action<DragEvent> OnDragHandled; public override bool HandlePositionalInput => hitObject != null; public DragArea(HitObject hitObject) { this.hitObject = hitObject; CornerRadius = circle_size / 2; Masking = true; Size = new Vector2(circle_size, 1); Anchor = Anchor.CentreRight; Origin = Anchor.Centre; RelativePositionAxes = Axes.X; RelativeSizeAxes = Axes.Y; InternalChildren = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, } }; } protected override void LoadComplete() { base.LoadComplete(); updateState(); FinishTransforms(); } protected override bool OnHover(HoverEvent e) { updateState(); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { updateState(); base.OnHoverLost(e); } private bool hasMouseDown; protected override bool OnMouseDown(MouseDownEvent e) { hasMouseDown = true; updateState(); return true; } protected override void OnMouseUp(MouseUpEvent e) { hasMouseDown = false; updateState(); base.OnMouseUp(e); } private void updateState() { if (hasMouseDown) { this.ScaleTo(0.7f, 200, Easing.OutQuint); } else if (IsHovered) { this.ScaleTo(0.8f, 200, Easing.OutQuint); } else { this.ScaleTo(0.6f, 200, Easing.OutQuint); } this.FadeTo(IsHovered || hasMouseDown ? 0.8f : 0.2f, 200, Easing.OutQuint); } [Resolved] private EditorBeatmap beatmap { get; set; } [Resolved] private IBeatSnapProvider beatSnapProvider { get; set; } [Resolved(CanBeNull = true)] private IEditorChangeHandler changeHandler { get; set; } protected override bool OnDragStart(DragStartEvent e) { changeHandler?.BeginChange(); return true; } protected override void OnDrag(DragEvent e) { base.OnDrag(e); OnDragHandled?.Invoke(e); if (timeline.SnapScreenSpacePositionToValidTime(e.ScreenSpaceMousePosition).Time is double time) { switch (hitObject) { case IHasRepeats repeatHitObject: // find the number of repeats which can fit in the requested time. var lengthOfOneRepeat = repeatHitObject.Duration / (repeatHitObject.RepeatCount + 1); var proposedCount = Math.Max(0, (int)Math.Round((time - hitObject.StartTime) / lengthOfOneRepeat) - 1); if (proposedCount == repeatHitObject.RepeatCount) return; repeatHitObject.RepeatCount = proposedCount; beatmap.Update(hitObject); break; case IHasDuration endTimeHitObject: var snappedTime = Math.Max(hitObject.StartTime, beatSnapProvider.SnapTime(time)); if (endTimeHitObject.EndTime == snappedTime || Precision.AlmostEquals(snappedTime, hitObject.StartTime, beatmap.GetBeatLengthAtTime(snappedTime))) return; endTimeHitObject.Duration = snappedTime - hitObject.StartTime; beatmap.Update(hitObject); break; } } } protected override void OnDragEnd(DragEndEvent e) { base.OnDragEnd(e); OnDragHandled?.Invoke(null); changeHandler?.EndChange(); } } public class Border : ExtendableCircle { [BackgroundDependencyLoader] private void load(OsuColour colours) { Content.Child.Alpha = 0; Content.Child.AlwaysPresent = true; Content.BorderColour = colours.Yellow; Content.EdgeEffect = new EdgeEffectParameters(); } } /// <summary> /// A circle with externalised end caps so it can take up the full width of a relative width area. /// </summary> public class ExtendableCircle : CompositeDrawable { protected readonly Circle Content; public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Content.ReceivePositionalInputAt(screenSpacePos); public override Quad ScreenSpaceDrawQuad => Content.ScreenSpaceDrawQuad; public ExtendableCircle() { Padding = new MarginPadding { Horizontal = -circle_size / 2f }; InternalChild = Content = new Circle { BorderColour = OsuColour.Gray(0.75f), BorderThickness = 4, Masking = true, RelativeSizeAxes = Axes.Both, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Radius = 5, Colour = Color4.Black.Opacity(0.4f) } }; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Monitor { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Monitor Client /// </summary> public partial class MonitorClient : ServiceClient<MonitorClient>, IMonitorClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The Azure subscription Id. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IUsageMetricsOperations. /// </summary> public virtual IUsageMetricsOperations UsageMetrics { get; private set; } /// <summary> /// Gets the IActivityLogsOperations. /// </summary> public virtual IActivityLogsOperations ActivityLogs { get; private set; } /// <summary> /// Gets the IEventCategoriesOperations. /// </summary> public virtual IEventCategoriesOperations EventCategories { get; private set; } /// <summary> /// Gets the ITenantActivityLogsOperations. /// </summary> public virtual ITenantActivityLogsOperations TenantActivityLogs { get; private set; } /// <summary> /// Gets the IMetricDefinitionsOperations. /// </summary> public virtual IMetricDefinitionsOperations MetricDefinitions { get; private set; } /// <summary> /// Gets the IMetricsOperations. /// </summary> public virtual IMetricsOperations Metrics { get; private set; } /// <summary> /// Initializes a new instance of the MonitorClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected MonitorClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the MonitorClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected MonitorClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the MonitorClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected MonitorClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the MonitorClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected MonitorClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the MonitorClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MonitorClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MonitorClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MonitorClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MonitorClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MonitorClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MonitorClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MonitorClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { UsageMetrics = new UsageMetricsOperations(this); ActivityLogs = new ActivityLogsOperations(this); EventCategories = new EventCategoriesOperations(this); TenantActivityLogs = new TenantActivityLogsOperations(this); MetricDefinitions = new MetricDefinitionsOperations(this); Metrics = new MetricsOperations(this); BaseUri = new System.Uri("https://management.azure.com"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // Thread tracks managed thread IDs, recycling them when threads die to keep the set of // live IDs compact. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using Internal.Runtime.Augments; using System.Diagnostics; namespace System.Threading { internal class ManagedThreadId { // // Binary tree used to keep track of active thread ids. Each node of the tree keeps track of 32 consecutive ids. // Implemented as immutable collection to avoid locks. Each modification creates a new top level node. // private class ImmutableIdDispenser { private readonly ImmutableIdDispenser _left; // Child nodes private readonly ImmutableIdDispenser _right; private readonly int _used; // Number of ids tracked by this node and all its childs private readonly int _size; // Maximum number of ids that can be tracked by this node and all its childs private readonly uint _bitmap; // Bitmap of ids tracked by this node private const int BitsPerNode = 32; private ImmutableIdDispenser(ImmutableIdDispenser left, ImmutableIdDispenser right, int used, int size, uint bitmap) { _left = left; _right = right; _used = used; _size = size; _bitmap = bitmap; CheckInvariants(); } [Conditional("DEBUG")] private void CheckInvariants() { int actualUsed = 0; uint countBits = _bitmap; while (countBits != 0) { actualUsed += (int)(countBits & 1); countBits >>= 1; } if (_left != null) { Debug.Assert(_left._size == ChildSize); actualUsed += _left._used; } if (_right != null) { Debug.Assert(_right._size == ChildSize); actualUsed += _right._used; } Debug.Assert(actualUsed == _used); Debug.Assert(_used <= _size); } private int ChildSize { get { Debug.Assert((_size / 2) >= (BitsPerNode / 2)); return (_size / 2) - (BitsPerNode / 2); } } public static ImmutableIdDispenser Empty { get { // The empty dispenser has the id=0 allocated, so it is not really empty. // It saves us from dealing with the corner case of true empty dispenser, // and it ensures that IdNone will not be ever given out. return new ImmutableIdDispenser(null, null, 1, BitsPerNode, 1); } } public ImmutableIdDispenser AllocateId(out int id) { if (_used == _size) { id = _size; return new ImmutableIdDispenser(this, null, _size + 1, checked(2 * _size + BitsPerNode), 1); } var bitmap = _bitmap; var left = _left; var right = _right; // Any free bits in current node? if (bitmap != uint.MaxValue) { int bit = 0; while ((bitmap & (uint)(1 << bit)) != 0) bit++; bitmap |= (uint)(1 << bit); id = ChildSize + bit; } else { Debug.Assert(ChildSize > 0); if (left == null) { left = new ImmutableIdDispenser(null, null, 1, ChildSize, 1); id = left.ChildSize; } else if (right == null) { right = new ImmutableIdDispenser(null, null, 1, ChildSize, 1); id = ChildSize + BitsPerNode + right.ChildSize; } else { if (left._used < right._used) { Debug.Assert(left._used < left._size); left = left.AllocateId(out id); } else { Debug.Assert(right._used < right._size); right = right.AllocateId(out id); id += (ChildSize + BitsPerNode); } } } return new ImmutableIdDispenser(left, right, _used + 1, _size, bitmap); } public ImmutableIdDispenser RecycleId(int id) { Debug.Assert(id < _size); if (_used == 1) return null; var bitmap = _bitmap; var left = _left; var right = _right; int childSize = ChildSize; if (id < childSize) { left = left.RecycleId(id); } else { id -= childSize; if (id < BitsPerNode) { Debug.Assert((bitmap & (uint)(1 << id)) != 0); bitmap &= ~(uint)(1 << id); } else { right = right.RecycleId(id - BitsPerNode); } } return new ImmutableIdDispenser(left, right, _used - 1, _size, bitmap); } } public const int IdNone = 0; // The main thread takes the first available id, which is 1. This id will not be recycled until the process exit. // We use this id to detect the main thread and report it as a foreground one. public const int IdMainThread = 1; // We store ManagedThreadId both here and in the Thread.CurrentThread object. We store it here, // because we may need the id very early in the process lifetime (e.g., in ClassConstructorRunner), // when a Thread object cannot be created yet. We also store it in the Thread.CurrentThread object, // because that object may have longer lifetime than the OS thread. [ThreadStatic] private static ManagedThreadId t_currentThreadId; [ThreadStatic] private static int t_currentManagedThreadId; // We have to avoid the static constructors on the ManagedThreadId class, otherwise we can run into stack overflow as first time Current property get called, // the runtime will ensure running the static constructor and this process will call the Current property again (when taking any lock) // System::Environment.get_CurrentManagedThreadId // System::Threading::Lock.Acquire // System::Runtime::CompilerServices::ClassConstructorRunner::Cctor.GetCctor // System::Runtime::CompilerServices::ClassConstructorRunner.EnsureClassConstructorRun // System::Threading::ManagedThreadId.get_Current // System::Environment.get_CurrentManagedThreadId private static ImmutableIdDispenser s_idDispenser; private int _managedThreadId; public int Id => _managedThreadId; public static int AllocateId() { if (s_idDispenser == null) Interlocked.CompareExchange(ref s_idDispenser, ImmutableIdDispenser.Empty, null); int id; var priorIdDispenser = Volatile.Read(ref s_idDispenser); for (;;) { var updatedIdDispenser = priorIdDispenser.AllocateId(out id); var interlockedResult = Interlocked.CompareExchange(ref s_idDispenser, updatedIdDispenser, priorIdDispenser); if (object.ReferenceEquals(priorIdDispenser, interlockedResult)) break; priorIdDispenser = interlockedResult; // we already have a volatile read that we can reuse for the next loop } Debug.Assert(id != IdNone); return id; } public static void RecycleId(int id) { if (id == IdNone) { return; } var priorIdDispenser = Volatile.Read(ref s_idDispenser); for (;;) { var updatedIdDispenser = s_idDispenser.RecycleId(id); var interlockedResult = Interlocked.CompareExchange(ref s_idDispenser, updatedIdDispenser, priorIdDispenser); if (object.ReferenceEquals(priorIdDispenser, interlockedResult)) break; priorIdDispenser = interlockedResult; // we already have a volatile read that we can reuse for the next loop } } public static int Current { get { int currentManagedThreadId = t_currentManagedThreadId; if (currentManagedThreadId == IdNone) return MakeForCurrentThread(); else return currentManagedThreadId; } } public static ManagedThreadId GetCurrentThreadId() { if (t_currentManagedThreadId == IdNone) MakeForCurrentThread(); return t_currentThreadId; } private static int MakeForCurrentThread() { return SetForCurrentThread(new ManagedThreadId()); } public static int SetForCurrentThread(ManagedThreadId threadId) { t_currentThreadId = threadId; t_currentManagedThreadId = threadId.Id; return threadId.Id; } public ManagedThreadId() { _managedThreadId = AllocateId(); } ~ManagedThreadId() { RecycleId(_managedThreadId); } } }
namespace TheCollection.Presentation.Web.Extensions { using System; using System.Collections.Generic; using System.Linq; using AspNetCore.Identity.DocumentDb; using AspNetCore.Identity.DocumentDb.Tools; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using NodaTime; using NodaTime.Serialization.JsonNet; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.NodaTime.AspNetCore; using TheCollection.Api; using TheCollection.Application.Services; using TheCollection.Application.Services.Commands; using TheCollection.Application.Services.Commands.Tea; using TheCollection.Application.Services.Contracts; using TheCollection.Application.Services.Queries; using TheCollection.Application.Services.Queries.Tea; using TheCollection.Application.Services.Translators; using TheCollection.Application.Services.Translators.Tea; using TheCollection.Data.DocumentDB.Extensions; using TheCollection.Data.DocumentDB.Repositories; using TheCollection.Domain; using TheCollection.Domain.Core.Contracts; using TheCollection.Domain.Core.Contracts.Repository; using TheCollection.Domain.Tea; using TheCollection.Infrastructure.Logging; using TheCollection.Infrastructure.Scheduling; using TheCollection.Infrastructure.Scheduling.Tea; using TheCollection.Presentation.Web.Constants; using TheCollection.Presentation.Web.Controllers; using TheCollection.Presentation.Web.Models; using TheCollection.Presentation.Web.Repositories; public static class IServiceCollectionExtensions { public static IServiceCollection WireDependencies(this IServiceCollection services, IConfiguration configuration) { //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton<IActionContextAccessor, ActionContextAccessor>(); services.AddScoped<IUrlHelper>(it => it.GetRequiredService<IUrlHelperFactory>() .GetUrlHelper(it.GetRequiredService<IActionContextAccessor>().ActionContext) ); services.AddSingleton<IDocumentClient>(InitializeDocumentClient( configuration.GetValue<Uri>("DocumentDbClient:EndpointUri"), configuration.GetValue<string>("DocumentDbClient:AuthorizationKey")) ); services.AddSingleton<IClock>(SystemClock.Instance); services.AddSingleton(typeof(ILogger<>), typeof(ConsoleLogger<>)); services.AddTranslators(); services.AddRepositories(); services.AddQueries(); services.AddCommands(); services.AddNotificationServices(); services.AddSchedulingServices(); return services; } public static IServiceCollection AddTranslators(this IServiceCollection services) { #region Domain models to view models services.AddScoped<IAsyncTranslator<Domain.RefValue, Application.Services.ViewModels.RefValue>, RefValueToRefValueTranslator>(); services.AddScoped<IAsyncTranslator<Domain.Tea.Bag, Application.Services.ViewModels.Tea.Bag>, BagToBagViewModelTranslator>(); services.AddScoped<IAsyncTranslator<Domain.Tea.BagType, Application.Services.ViewModels.Tea.BagType>, BagTypeToBagTypeTranslator>(); services.AddScoped<IAsyncTranslator<Domain.Tea.Brand, Application.Services.ViewModels.Tea.Brand>, BrandToBrandTranslator>(); services.AddScoped<IAsyncTranslator<Domain.Tea.Country, Application.Services.ViewModels.Tea.Country>, CountryToCountryViewModelTranslator>(); #endregion (Domain models to view models) #region View models to domain models services.AddScoped<ITranslator<Application.Services.ViewModels.RefValue, Domain.RefValue>, RefValueDtoToRefValueTranslator>(); services.AddScoped<ITranslator<Application.Services.ViewModels.Tea.Bag, Domain.Tea.Bag, Domain.Tea.Bag>, BagViewModelToUpdateBagTranslator>(); services.AddScoped<IAsyncTranslator<Application.Services.ViewModels.Tea.Bag, Domain.Tea.Bag>, BagViewModelToCreateBagTranslator>(); services.AddScoped<ITranslator<Application.Services.ViewModels.Tea.BagType, Domain.Tea.BagType>, BagTypeDtoToBagTypeTranslator>(); services.AddScoped<ITranslator<Application.Services.ViewModels.Tea.Brand, Domain.Tea.Brand>, BrandDtoToBrandTranslator>(); services.AddScoped<ITranslator<Application.Services.ViewModels.Tea.Country, Domain.Tea.Country>, CountryViewModelToCountryTranslator>(); #endregion (View models to domain models) services.AddScoped<ITranslator<ICommandResult, IActionResult>, ICommandResultToIActionResultTranslator>(); services.AddScoped<ITranslator<IQueryResult, IActionResult>, IQueryResultToIActionResultTranslator>(); return services; } public static IServiceCollection AddRepositories(this IServiceCollection services) { services.AddScoped<IGetRepository<IApplicationUser>, WebUserRepository>(); services.AddScoped<IGetAllRepository<IApplicationUser>, WebUserRepository>(); services.AddScoped<IActivityAuthorizer, ActivityAuthorizer>(); services.AddSingleton<ILinqSearchRepository<IActivity>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new SearchRepository<IActivity>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.AspNetIdentity); }); #region Bag services.AddSingleton<ILinqSearchRepository<Bag>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new SearchRepository<Bag>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Bags); }); services.AddSingleton<ISearchRepository<Bag>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new SearchRepository<Bag>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Bags); }); services.AddSingleton<IGetRepository<Bag>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new GetRepository<Bag>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Bags); }); services.AddSingleton<ICreateRepository<Bag>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new CreateRepository<Bag>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Bags); }); services.AddSingleton<IUpdateRepository<Bag>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new UpdateRepository<Bag>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Bags); }); #endregion (Bag) #region BagType services.AddSingleton<ISearchRepository<BagType>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new SearchRepository<BagType>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.BagTypes); }); services.AddSingleton<IGetRepository<BagType>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new GetRepository<BagType>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.BagTypes); }); services.AddSingleton<ICreateRepository<BagType>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new CreateRepository<BagType>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.BagTypes); }); services.AddSingleton<IUpdateRepository<BagType>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new UpdateRepository<BagType>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.BagTypes); }); #endregion (BagType) #region Brand services.AddSingleton<ISearchRepository<Brand>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new SearchRepository<Brand>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Brands); }); services.AddSingleton<IGetRepository<Brand>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new GetRepository<Brand>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Brands); }); services.AddSingleton<ICreateRepository<Brand>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new CreateRepository<Brand>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Brands); }); services.AddSingleton<IUpdateRepository<Brand>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new UpdateRepository<Brand>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Brands); }); #endregion (Brand) #region Country services.AddSingleton<ISearchRepository<Country>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new SearchRepository<Country>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Countries); }); services.AddSingleton<IGetRepository<Country>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new GetRepository<Country>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Countries); }); services.AddSingleton<ICreateRepository<Country>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new CreateRepository<Country>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Countries); }); services.AddSingleton<IUpdateRepository<Country>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new UpdateRepository<Country>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Countries); }); #endregion (Country) #region Image services.AddSingleton<ICreateRepository<Image>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new CreateRepository<Image>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Images); }); #endregion (Image) #region Dashboard services.AddSingleton<IGetRepository<Dashboard<IEnumerable<CountBy<RefValue>>>>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new GetRepository<Dashboard<IEnumerable<CountBy<RefValue>>>>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Statistics); }); services.AddSingleton<IGetRepository<Dashboard<IEnumerable<CountBy<NodaTime.LocalDate>>>>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new GetRepository<Dashboard<IEnumerable<CountBy<NodaTime.LocalDate>>>>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Statistics); }); services.AddSingleton<IUpsertRepository<Dashboard<IEnumerable<CountBy<RefValue>>>>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new UpsertRepository<Dashboard<IEnumerable<CountBy<RefValue>>>>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Statistics); }); services.AddSingleton<IUpsertRepository<Dashboard<IEnumerable<CountBy<NodaTime.LocalDate>>>>>(serviceProvider => { var documentClient = serviceProvider.GetService<IDocumentClient>(); return new UpsertRepository<Dashboard<IEnumerable<CountBy<NodaTime.LocalDate>>>>(documentClient, DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.Statistics); }); #endregion (Dashboard) return services; } public static IServiceCollection AddQueries(this IServiceCollection services) { #region Bag services.AddScoped<SearchQueryHandler<Application.Services.ViewModels.Tea.Bag, Domain.Tea.Bag>, SearchQueryHandler<Application.Services.ViewModels.Tea.Bag, Domain.Tea.Bag>>(); services.AddScoped<GetQueryHandler<Application.Services.ViewModels.Tea.Bag, Domain.Tea.Bag>, GetQueryHandler<Application.Services.ViewModels.Tea.Bag, Domain.Tea.Bag>>(); #endregion (Bag) #region BagType services.AddScoped<SearchQueryHandler<Application.Services.ViewModels.Tea.BagType, Domain.Tea.BagType>, SearchQueryHandler<Application.Services.ViewModels.Tea.BagType, Domain.Tea.BagType>>(); services.AddScoped<GetQueryHandler<Application.Services.ViewModels.Tea.BagType, Domain.Tea.BagType>, GetQueryHandler<Application.Services.ViewModels.Tea.BagType, Domain.Tea.BagType>>(); services.AddScoped<IAsyncQueryHandler<SearchRefValuesQuery<Domain.Tea.BagType>>, SearchRefValuesQueryHandler<Domain.Tea.BagType>>(); #endregion (BagType) #region Brands services.AddScoped<SearchQueryHandler<Application.Services.ViewModels.Tea.Brand, Domain.Tea.Brand>, SearchQueryHandler<Application.Services.ViewModels.Tea.Brand, Domain.Tea.Brand>>(); services.AddScoped<GetQueryHandler<Application.Services.ViewModels.Tea.Brand, Domain.Tea.Brand>, GetQueryHandler<Application.Services.ViewModels.Tea.Brand, Domain.Tea.Brand>>(); services.AddScoped<IAsyncQueryHandler<SearchRefValuesQuery<Domain.Tea.Brand>>, SearchRefValuesQueryHandler<Domain.Tea.Brand>>(); #endregion (Brands) #region Country services.AddScoped<SearchQueryHandler<Application.Services.ViewModels.Tea.Country, Domain.Tea.Country>, SearchQueryHandler<Application.Services.ViewModels.Tea.Country, Domain.Tea.Country>>(); services.AddScoped<GetQueryHandler<Application.Services.ViewModels.Tea.Country, Domain.Tea.Country>, GetQueryHandler<Application.Services.ViewModels.Tea.Country, Domain.Tea.Country>>(); services.AddScoped<IAsyncQueryHandler<SearchRefValuesQuery<Domain.Tea.Country>>, SearchRefValuesQueryHandler<Domain.Tea.Country>>(); #endregion (Country) #region Dashboard services.AddScoped<IAsyncQueryHandler<TotalBagsCountByInsertDateQuery>, TotalBagsCountByInsertDateQueryHandler>(); services.AddScoped<IAsyncQueryHandler<BagsCountByInsertDateQuery>, BagsCountByInsertDateQueryHandler>(); services.AddScoped<IAsyncQueryHandler<BagsCountByBrandsQuery>, BagsCountByBrandsQueryHandler>(); services.AddScoped<IAsyncQueryHandler<BagsCountByBagTypesQuery>, BagsCountByBagTypesQueryHandler>(); #endregion (Dashboard) return services; } public static IServiceCollection AddCommands(this IServiceCollection services) { #region Bag services.AddScoped<IAsyncCommandHandler<UpdateBagCommand>, UpdateBagCommandHandler>(); services.AddScoped<IAsyncCommandHandler<CreateBagCommand>, CreateBagCommandHandler>(); #endregion (Bag) #region BagType services.AddScoped<IAsyncCommandHandler<UpdateCommand<Application.Services.ViewModels.Tea.BagType>, Domain.Tea.BagType>, UpdateCommandHandler<Application.Services.ViewModels.Tea.BagType, Domain.Tea.BagType>>(); services.AddScoped<IAsyncCommandHandler<CreateCommand<Application.Services.ViewModels.Tea.BagType>, Domain.Tea.BagType>, CreateCommandHandler<Application.Services.ViewModels.Tea.BagType, Domain.Tea.BagType>>(); #endregion (BagType) #region Brands services.AddScoped<IAsyncCommandHandler<UpdateCommand<Application.Services.ViewModels.Tea.Brand>, Domain.Tea.Brand>, UpdateCommandHandler<Application.Services.ViewModels.Tea.Brand, Domain.Tea.Brand>>(); services.AddScoped<IAsyncCommandHandler<CreateCommand<Application.Services.ViewModels.Tea.Brand>, Domain.Tea.Brand>, CreateCommandHandler<Application.Services.ViewModels.Tea.Brand, Domain.Tea.Brand>>(); #endregion (Brands) #region Country services.AddScoped<IAsyncCommandHandler<UpdateCommand<Application.Services.ViewModels.Tea.Country>, Domain.Tea.Country>, UpdateCommandHandler<Application.Services.ViewModels.Tea.Country, Domain.Tea.Country>>(); services.AddScoped<IAsyncCommandHandler<CreateCommand<Application.Services.ViewModels.Tea.Country>, Domain.Tea.Country>, CreateCommandHandler<Application.Services.ViewModels.Tea.Country, Domain.Tea.Country>>(); #endregion (Country) #region Dashboard services.AddScoped<IAsyncCommandHandler<CreateBagsCountByBagTypesCommand>, CreateBagsCountByBagTypesCommandHandler>(); services.AddScoped<IAsyncCommandHandler<CreateBagsCountByBrandsCommand>, CreateBagsCountByBrandsCommandHandler>(); services.AddScoped<IAsyncCommandHandler<CreateBagsCountByInsertDateCommand>, CreateBagsCountByInsertDateCommandHandler>(); services.AddScoped<IAsyncCommandHandler<CreateTotalBagsCountByInsertDateCommand>, CreateTotalBagsCountByInsertDateCommandHandler>(); #endregion (Dashboard) services.AddScoped<IAsyncCommandHandler<UploadTeabagImageCommand>, UploadTeabagImageCommandHandler>(); return services; } public static IServiceCollection AddNotificationServices(this IServiceCollection services) { return services; } public static IServiceCollection AddSchedulingServices(this IServiceCollection services) { services.AddSingleton<IScheduledTask, UpdateBagsCountByBagTypeStatisticsTask>(); services.AddSingleton<IScheduledTask, UpdateCountByBrandStatistcsTask>(); services.AddSingleton<IScheduledTask, UpdateBagsCountByInsertDateStatisticsTask>(); services.AddSingleton<IScheduledTask, UpdateTotalCountByInsertDateStatisticsTask>(); services.AddSingleton<IHostedService, SchedulerHostedService>(serviceProvider => { var logger = serviceProvider.GetService<ILogger<SchedulerHostedService>>(); var clock = serviceProvider.GetService<IClock>(); var tasks = serviceProvider.GetServices<IScheduledTask>(); var instance = new SchedulerHostedService(tasks.Select(task => new Scheduler(task, clock))); instance.UnobservedTaskException += (sender, args) => { // log this logger.LogErrorAsync($"{nameof(SchedulerHostedService.UnobservedTaskException)}: {args}").GetAwaiter().GetResult(); args.SetObserved(); }; return instance; }); return services; } public static IServiceCollection AddSwagger(this IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "TheCollection API", Version = "v1" }); var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = { new StringEnumConverter() }, NullValueHandling = NullValueHandling.Ignore }.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); c.ConfigureForNodaTime(settings); }); return services; } public static IServiceCollection AddLoginIdentities(this IServiceCollection services, IConfiguration configuration) { // Add framework services. // consider: https://github.com/imranbaloch/ASPNETIdentityWithOnion services.AddIdentity<WebUser, WebRole>() .AddDocumentDbStores(options => { options.UserStoreDocumentCollection = DocumentDBConstants.Collections.AspNetIdentity; options.RoleStoreDocumentCollection = DocumentDBConstants.Collections.AspNetIdentity; options.Database = DocumentDBConstants.DatabaseId; }) .AddDefaultTokenProviders(); services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.ConfigureApplicationCookie(options => { //options.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo("C:\\TheCollection\\Identity\\artifacts")); options.LoginPath = $"/Account/{nameof(AccountController.Login)}"; options.LogoutPath = $"/Account/{nameof(AccountController.LogOff)}"; }); // Add external authentication middleware below. // To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715 // https://docs.microsoft.com/en-gb/aspnet/core/security/authentication/social/index // https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x services.AddAuthentication() .AddGoogle(options => { options.ClientId = configuration.GetValue<string>("OAuth:Google:ClientId"); options.ClientSecret = configuration.GetValue<string>("OAuth:Google:ClientSecret"); }) .AddFacebook(options => { options.AppId = configuration.GetValue<string>("OAuth:Facebook:ClientId"); options.AppSecret = configuration.GetValue<string>("OAuth:Facebook:ClientSecret"); }) .AddMicrosoftAccount(options => { options.ClientId = configuration.GetValue<string>("OAuth:Microsoft:ClientId"); options.ClientSecret = configuration.GetValue<string>("OAuth:Microsoft:ClientSecret"); }); return services; } static DocumentClient InitializeDocumentClient(Uri endpointUri, string authorizationKey, JsonSerializerSettings serializerSettings = null) { serializerSettings = serializerSettings ?? new JsonSerializerSettings(); serializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); serializerSettings.Converters.Add(new JsonClaimConverter()); serializerSettings.Converters.Add(new TheCollection.Presentation.Web.JsonClaimsPrincipalConverter()); serializerSettings.Converters.Add(new TheCollection.Presentation.Web.JsonClaimsIdentityConverter()); // Create a DocumentClient and an initial collection (if it does not exist yet) for sample purposes var client = new DocumentClient(endpointUri, authorizationKey, serializerSettings, new ConnectionPolicy { EnableEndpointDiscovery = false }, null); client.CreateCollectionIfNotExistsAsync(DocumentDBConstants.DatabaseId, DocumentDBConstants.Collections.AspNetIdentity).Wait(); // handle in application start Configure(IApplicationBuilder) or use IHostedService return client; } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using SalesAssister.Models; namespace SalesAssister.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20160429162306_Initial")] partial class Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("SalesAssister.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("SalesAssister.Models.Client", b => { b.Property<int>("ClientId") .ValueGeneratedOnAdd(); b.Property<string>("Email"); b.Property<string>("Name"); b.Property<string>("Phone"); b.Property<int>("SalesPersonId"); b.HasKey("ClientId"); b.HasAnnotation("Relational:TableName", "Clients"); }); modelBuilder.Entity("SalesAssister.Models.Contact", b => { b.Property<int>("ContactId") .ValueGeneratedOnAdd(); b.Property<int>("ClientId"); b.Property<string>("Notes"); b.Property<int>("SalesPersonId"); b.HasKey("ContactId"); b.HasAnnotation("Relational:TableName", "Contacts"); }); modelBuilder.Entity("SalesAssister.Models.SalesPerson", b => { b.Property<int>("SalesPersonId") .ValueGeneratedOnAdd(); b.Property<string>("Company"); b.Property<string>("Name"); b.HasKey("SalesPersonId"); b.HasAnnotation("Relational:TableName", "SalesPersons"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("SalesAssister.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("SalesAssister.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("SalesAssister.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("SalesAssister.Models.Client", b => { b.HasOne("SalesAssister.Models.SalesPerson") .WithMany() .HasForeignKey("SalesPersonId"); }); modelBuilder.Entity("SalesAssister.Models.Contact", b => { b.HasOne("SalesAssister.Models.Client") .WithMany() .HasForeignKey("ClientId"); b.HasOne("SalesAssister.Models.SalesPerson") .WithMany() .HasForeignKey("SalesPersonId"); }); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. namespace Microsoft.Azure.Search.Models { using System; using System.Collections.Generic; using System.Linq; using System.Text; using Common; /// <summary> /// Defines extension methods for the IndexingParameters class. /// </summary> public static class IndexingParametersExtensions { private const string ParsingModeKey = "parsingMode"; /// <summary> /// Specifies that the indexer will index only the blobs with the file name extensions you specify. Each string is a file extensions with a /// leading dot. For example, ".pdf", ".docx", etc. If you pass the same file extension to this method and ExcludeFileNameExtensions, blobs /// with that extension will be excluded from indexing (that is, ExcludeFileNameExtensions takes precedence). /// See <see href="https://docs.microsoft.com/azure/search/search-howto-indexing-azure-blob-storage" /> for details. /// </summary> /// <param name="parameters">IndexingParameters to configure.</param> /// <param name="extensions">File extensions to include in indexing.</param> /// <remarks> /// This option only applies to indexers that index Azure Blob Storage. /// </remarks> /// <returns>The IndexingParameters instance.</returns> public static IndexingParameters IndexFileNameExtensions(this IndexingParameters parameters, params string[] extensions) { if (extensions?.Length > 0) { Configure( parameters, "indexedFileNameExtensions", extensions.Select(ValidateExtension).Select(FixUpExtension).ToCommaSeparatedString()); } return parameters; } /// <summary> /// Specifies that the indexer will not index blobs with the file name extensions you specify. Each string is a file extensions with a /// leading dot. For example, ".pdf", ".docx", etc. If you pass the same file extension to this method and IndexFileNameExtensions, blobs /// with that extension will be excluded from indexing (that is, this method takes precedence). /// See <see href="https://docs.microsoft.com/azure/search/search-howto-indexing-azure-blob-storage" /> for details. /// </summary> /// <param name="parameters">IndexingParameters to configure.</param> /// <param name="extensions">File extensions to exclude from indexing.</param> /// <remarks> /// This option only applies to indexers that index Azure Blob Storage. /// </remarks> /// <returns>The IndexingParameters instance.</returns> public static IndexingParameters ExcludeFileNameExtensions(this IndexingParameters parameters, params string[] extensions) { if (extensions?.Length > 0) { Configure( parameters, "excludedFileNameExtensions", extensions.Select(ValidateExtension).Select(FixUpExtension).ToCommaSeparatedString()); } return parameters; } /// <summary> /// Specifies which parts of a blob will be indexed by the blob storage indexer. /// </summary> /// <remarks> /// This option only applies to indexers that index Azure Blob Storage. /// <see href="https://docs.microsoft.com/azure/search/search-howto-indexing-azure-blob-storage" /> /// </remarks> /// <param name="parameters">IndexingParameters to configure.</param> /// <param name="extractionMode">A <see cref="BlobExtractionMode" /> value specifying what to index.</param> /// <returns>The IndexingParameters instance.</returns> public static IndexingParameters SetBlobExtractionMode(this IndexingParameters parameters, BlobExtractionMode extractionMode) => Configure(parameters, "dataToExtract", (string)extractionMode); /// <summary> /// Tells the indexer to assume that all blobs contain JSON, which it will then parse such that each blob's JSON will map to a single /// document in the search index. /// See <see href="https://docs.microsoft.com/azure/search/search-howto-index-json-blobs/" /> for details. /// </summary> /// <param name="parameters">IndexingParameters to configure.</param> /// <remarks> /// This option only applies to indexers that index Azure Blob Storage. /// </remarks> /// <returns>The IndexingParameters instance.</returns> public static IndexingParameters ParseJson(this IndexingParameters parameters) => Configure(parameters, ParsingModeKey, "json"); /// <summary> /// Tells the indexer to assume that all blobs contain new-line separated JSON, which it will then parse such that individual JSON entities in each blob /// will map to a single document in the search index. /// See <see href="https://docs.microsoft.com/azure/search/search-howto-index-json-blobs/" /> for details. /// </summary> /// <param name="parameters">IndexingParameters to configure.</param> /// <remarks> /// This option only applies to indexers that index Azure Blob Storage. /// </remarks> /// <returns>The IndexingParameters instance.</returns> public static IndexingParameters ParseJsonLines(this IndexingParameters parameters) => Configure(parameters, ParsingModeKey, "jsonLines"); /// <summary> /// Tells the indexer to assume that all blobs contain JSON arrays, which it will then parse such that each JSON object in each array will /// map to a single document in the search index. /// See <see href="https://docs.microsoft.com/azure/search/search-howto-index-json-blobs" /> for details. /// </summary> /// <param name="parameters">IndexingParameters to configure.</param> /// <param name="documentRoot"> /// An optional JSON Pointer that tells the indexer how to find the JSON array if it's not the top-level JSON property of each blob. If this /// parameter is null or empty, the indexer will assume that the JSON array can be found in the top-level JSON property of each blob. /// Default is null. /// </param> /// <remarks> /// This option only applies to indexers that index Azure Blob Storage. /// </remarks> /// <returns>The IndexingParameters instance.</returns> public static IndexingParameters ParseJsonArrays(this IndexingParameters parameters, string documentRoot = null) { Configure(parameters, ParsingModeKey, "jsonArray"); if (!string.IsNullOrEmpty(documentRoot)) { Configure(parameters, "documentRoot", documentRoot); } return parameters; } /// <summary> /// Tells the indexer to assume that all blobs are delimited text files. Currently only comma-separated value (CSV) text files are supported. /// See <see href="https://docs.microsoft.com/azure/search/search-howto-index-csv-blobs" /> for details. /// </summary> /// <param name="parameters">IndexingParameters to configure.</param> /// <param name="headers"> /// Specifies column headers that the indexer will use to map values to specific fields in the search index. If you don't specify any /// headers, the indexer assumes that the first non-blank line of each blob contains comma-separated headers. /// </param> /// <remarks> /// This option only applies to indexers that index Azure Blob Storage. /// </remarks> /// <returns>The IndexingParameters instance.</returns> public static IndexingParameters ParseDelimitedTextFiles(this IndexingParameters parameters, params string[] headers) { Configure(parameters, ParsingModeKey, "delimitedText"); if (headers?.Length > 0) { Configure(parameters, "delimitedTextHeaders", headers.ToCommaSeparatedString()); } else { Configure(parameters, "firstLineContainsHeaders", true); } return parameters; } /// <summary> /// Tells the indexer to assume that blobs should be parsed as text files in UTF-8 encoding. /// See <see href="https://docs.microsoft.com/azure/search/search-howto-indexing-azure-blob-storage#indexing-plain-text">Indexing plain text</see> for details. /// </summary> /// <param name="parameters">IndexingParameters to configure.</param> /// <returns>The IndexingParameters instance.</returns> public static IndexingParameters ParseText(this IndexingParameters parameters) => ParseText(parameters, Encoding.UTF8); /// <summary> /// Tells the indexer to assume that blobs should be parsed as text files in the desired encoding. /// See <see href="https://docs.microsoft.com/azure/search/search-howto-indexing-azure-blob-storage#indexing-plain-text">Indexing plain text</see> for details. /// </summary> /// <param name="parameters">IndexingParameters to configure.</param> /// <param name="encoding">Encoding used to read the text stored in blobs.</param> /// <returns>The IndexingParameters instance.</returns> public static IndexingParameters ParseText(this IndexingParameters parameters, Encoding encoding) { Throw.IfArgumentNull(encoding, nameof(encoding)); Configure(parameters, ParsingModeKey, "text"); Configure(parameters, "encoding", encoding.WebName); return parameters; } /// <summary> /// Specifies that <see cref="BlobExtractionMode.StorageMetadata" /> blob extraction mode will be /// automatically used for blobs of unsupported content types. This behavior is enabled by default. /// </summary> /// <remarks> /// This option only applies to indexers that index Azure Blob Storage. /// </remarks> /// <param name="parameters">IndexingParameters to configure.</param> /// <returns></returns> /// <returns>The IndexingParameters instance.</returns> [Obsolete("This behavior is now enabled by default, so calling this method is no longer necessary.")] public static IndexingParameters DoNotFailOnUnsupportedContentType(this IndexingParameters parameters) => Configure(parameters, "failOnUnsupportedContentType", false); private static IndexingParameters Configure(IndexingParameters parameters, string key, object value) { Throw.IfArgumentNull(parameters, nameof(parameters)); if (parameters.Configuration == null) { parameters.Configuration = new Dictionary<string, object>(); } parameters.Configuration[key] = value; return parameters; } private static string ValidateExtension(string extension) { if (string.IsNullOrEmpty(extension)) { throw new ArgumentException("Extension cannot be null or empty string."); } if (extension.Contains("*")) { throw new ArgumentException("Extension cannot contain the wildcard character '*'."); } return extension; } private static string FixUpExtension(string extension) { if (!extension.StartsWith(".", StringComparison.Ordinal)) { return "." + extension; } return extension; } } }
//////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Daniel Kollmann // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this list of conditions // and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials provided // with the distribution. // // - Neither the name of Daniel Kollmann 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; using System.Windows.Forms; using System.Reflection; using System.Resources; using Brainiac.Design.Properties; using System.IO; using Brainiac.Design.Nodes; namespace Brainiac.Design { /// <summary> /// This enumeration decribes what type of node is used in the node explorer. /// It is only used for displaying the nodes in the explorer and to handle drag & drop actions. /// </summary> public enum NodeTagType { Behavior, BehaviorFolder, Node, NodeFolder, Event }; /// <summary> /// The NodeTag is used to identify nodes in the explorer. Each TreeViewItem.Tag is a NodeTag. /// It is only used for displaying the nodes in the explorer and to handle drag & drop actions. /// </summary> public class NodeTag { public interface DefaultObject { string Description { get; } string Label { get; } } protected NodeTagType _type; /// <summary> /// The type of the node in the node explorer. /// </summary> public NodeTagType Type { get { return _type; } } protected Type _nodetype; /// <summary> /// The type of the node which will be created in the graph. /// </summary> public Type NodeType { get { return _nodetype; } } protected string _filename; /// <summary> /// The filename of the behaviour which will be loaded when we double-click it. /// </summary> public string Filename { get { return _filename; } set { _filename= value; } } protected DefaultObject _defaults; /// <summary> /// A default instance of a node, used to get its description and things like these. /// The instance is automatically created for each node in the node explorer. /// </summary> public DefaultObject Defaults { get { return _defaults; } } /// <summary> /// Used to replace the default object with a behaviour once loaded. /// </summary> /// <param name="behavior">The behaviour we have loaded.</param> public void AssignLoadedBehavior(BehaviorNode behavior) { Debug.Check(_type ==NodeTagType.Behavior); Debug.Check(_filename ==behavior.FileManager.Filename); _defaults= (DefaultObject)behavior; } /// <summary> /// Creates a new NodeTag and an instance of the node for the defaults. /// </summary> /// <param name="type">The type of the node in the node explorer.</param> /// <param name="nodetype">The type of the node which will be added to the behaviour tree.</param> /// <param name="filename">The filename of the behaviour we want to load. Use string.Empty if the node is not a behaviour.</param> public NodeTag(NodeTagType type, Type nodetype, string filename) { if((type ==NodeTagType.BehaviorFolder || type ==NodeTagType.NodeFolder) && nodetype !=null) throw new Exception(Resources.ExceptionWrongNodeTagType); _type= type; _nodetype= nodetype; _filename= filename; if(nodetype ==null) { _defaults= null; } else { //if(!nodetype.IsSubclassOf(typeof(DefaultObject))) // throw new Exception(Resources.ExceptionNotImplementDefaultObject); if(nodetype.IsSubclassOf(typeof(Events.Event)) && type !=NodeTagType.Event) throw new Exception(Resources.ExceptionWrongNodeTagType); if(nodetype.IsSubclassOf(typeof(Nodes.Node)) && type !=NodeTagType.Node && type !=NodeTagType.Behavior) throw new Exception(Resources.ExceptionWrongNodeTagType); _defaults=type ==NodeTagType.Event ? (DefaultObject)Brainiac.Design.Events.Event.Create(nodetype, null) : (DefaultObject)Nodes.Node.Create(nodetype); } } } /// <summary> /// This enumeration represents the icons which are available for the nodes in the explorer. The order and number must be the same as for the ImageList in the node exploerer. /// </summary> public enum NodeIcon { FlagBlue, FlagGreen, FlagRed, Behavior, BehaviorLoaded, BehaviorModified, Condition, Impulse, Action, Decorator, Sequence, Selector, Parallel, FolderClosed, FolderOpen, Event }; /// <summary> /// This class describes a group which will be shown in the node explorer. /// </summary> public class NodeGroup { protected string _name; /// <summary> /// The name of the group which will be displayed in the node explorer. /// </summary> public string Name { get { return _name; } } protected NodeIcon _icon; /// <summary> /// The icon of the node and its children which will be displayed in the node explorer. /// Notice that for behaviours, other icons than the given one will be used. /// </summary> public NodeIcon Icon { get { return _icon; } } protected List<NodeGroup> _children= new List<NodeGroup>(); /// <summary> /// Groups which will be shown below this one. /// </summary> public IList<NodeGroup> Children { get { return _children.AsReadOnly(); } } protected List<Type> _items= new List<Type>(); /// <summary> /// Nodes which will be shown in this group. /// </summary> public List<Type> Items { get { return _items; } } /// <summary> /// Adds this NodeGroup to the TreeView of the node explorer. /// </summary> /// <param name="pool">The TreeNodeCollection the group and its sub-groups and childrens will be added.</param> public void Register(TreeNodeCollection pool) { // check if this NodeGroup already exists in the node explorer TreeNode tnode= null; foreach(TreeNode node in pool) { if(node.Text ==_name) { tnode= node; break; } } // create a new group if it does not yet exist if(tnode ==null) { tnode= new TreeNode(_name, (int) _icon, (int) _icon); tnode.Tag= new NodeTag(NodeTagType.NodeFolder, null, string.Empty); pool.Add(tnode); } // add the nodes which will be shown in this group foreach(Type item in _items) { NodeTag nodetag= new NodeTag(item.IsSubclassOf(typeof(Nodes.Node)) ? NodeTagType.Node : NodeTagType.Event, item, string.Empty); TreeNode inode= new TreeNode(nodetag.Defaults.Label, (int) _icon, (int) _icon); inode.Tag= nodetag; inode.ToolTipText= nodetag.Defaults.Description; tnode.Nodes.Add(inode); } // add any sub-group foreach(NodeGroup group in _children) group.Register(tnode.Nodes); } /// <summary> /// Defines a new NodeGroup which will be shown in the node explorer. /// </summary> /// <param name="name">The displayed name of the group.</param> /// <param name="icon">The displayed icon of the group and its children.</param> /// <param name="parent">The parent of the group, can be null.</param> public NodeGroup(string name, NodeIcon icon, NodeGroup parent) { _name= name; _icon= icon; if(parent !=null) parent.Children.Add(this); } } /// <summary> /// This class holds information about a file manager which can be used to load and save behaviours. /// </summary> public class FileManagerInfo { /// <summary> /// Returns a file manager which can be used to save or load a behaviour. /// </summary> /// <param name="filename">The name of the file we want to load or we want to save to.</param> /// <param name="node">The behaviour we want to load or save.</param> /// <returns>Returns the file manager which will be created.</returns> public FileManagers.FileManager Create(string filename, Nodes.BehaviorNode node) { object[] prms= new object[2] { filename, node }; return (FileManagers.FileManager) _type.InvokeMember(string.Empty, System.Reflection.BindingFlags.CreateInstance, null, null, prms); } /// <summary> /// Defines a file manager which can be used to load and save behaviours. /// </summary> /// <param name="filemanager">The tpe of the file manager which will be created by this info.</param> /// <param name="filter">The text displayed in the save dialogue when selecting the file format.</param> /// <param name="fileextension">The file extension used to identify which file manager can handle the given file.</param> public FileManagerInfo(Type filemanager, string filter, string fileextension) { _filter= filter; _fileExtension= fileextension.ToLowerInvariant(); _type= filemanager; // the file extension must always start with a dot if(_fileExtension[0] !='.') _fileExtension= '.'+ _fileExtension; } protected Type _type; /// <summary> /// The type of the file manager which will be created. /// </summary> public Type Type { get { return _type; } } protected string _filter; /// <summary> /// The displayed text in the save dialogue when selecting the file format. /// </summary> public string Filter { get { return _filter; } } protected string _fileExtension; /// <summary> /// The extension used to determine which file manager can handle the given file. /// </summary> public string FileExtension { get { return _fileExtension; } } } /// <summary> /// This class holds information about an exporter which can be used to export a behaviour into a format which can be used by the workflow of your game. /// </summary> public class ExporterInfo { /// <summary> /// Creates an instance of an exporter which will be used to export a behaviour. /// To export the behaviour, the Export() method must be called. /// </summary> /// <param name="node">The behaviour you want to export.</param> /// <param name="outputFolder">The folder you want to export the behaviour to.</param> /// <param name="filename">The relative filename you want to export the behaviour to.</param> /// <returns>Returns the created exporter.</returns> public Exporters.Exporter Create(Nodes.BehaviorNode node, string outputFolder, string filename) { object[] prms= new object[] { node, outputFolder, filename }; return (Exporters.Exporter) _type.InvokeMember(string.Empty, System.Reflection.BindingFlags.CreateInstance, null, null, prms); } /// <summary> /// Defines an exporter which can be used to export a behaviour. /// </summary> /// <param name="exporter">The type of the exporter which will be created.</param> /// <param name="description">The description which will be shown when the user must select the exporter (s)he wants to use.</param> /// <param name="mayExportAll">Determines if this exporter may be used to export multiple behaviours. /// This can be important if the output requires further user actions.</param> /// <param name="id">The id of the exporter which will be used by the Brainiac Exporter to identify which exporter to use.</param> public ExporterInfo(Type exporter, string description, bool mayExportAll, string id) { _description= description; _type= exporter; _mayExportAll= mayExportAll; _id= id; } protected Type _type; /// <summary> /// The type of the exporter which will be created. /// </summary> public Type Type { get { return _type; } } protected string _description; /// <summary> /// The displayed text when the user must select which exporter to use. /// </summary> public string Description { get { return _description; } } /// <summary> /// This is needed for the drop down list in the export dialogue to show the correct text. /// </summary> /// <returns>Returns the description of the exporter.</returns> public override string ToString() { return _description; } protected bool _mayExportAll; /// <summary> /// Determines if the exporter can be used when exporting multiple files. For example if further user actions are required. /// </summary> public bool MayExportAll { get { return _mayExportAll; } } private string _id; /// <summary> /// The id used to identify an exporter when being used with the Brainiac Exporter. /// </summary> public string ID { get { return _id; } } } /// <summary> /// The base class for every plugin. The class name of your plugin must be the same as your library. /// </summary> public class Plugin { /// <summary> /// A global list of all plugins which have been loaded. Mainly for internal use. /// </summary> private static List<Assembly> _loadedPlugins= new List<Assembly>(); /// <summary> /// Add a plugin which has been loaded. Mainly for internal use. /// </summary> /// <param name="a"></param> public static void AddLoadedPlugin(Assembly a) { _loadedPlugins.Add(a); } /// <summary> /// Returns the type of a given class name. It searches all loaded plugins for this type. /// </summary> /// <param name="fullname">The name of the class we want to get the type for.</param> /// <returns>Returns the type if found in any loaded plugin. Retuns null if it could not be found.</returns> public static Type GetType(string fullname) { // search base class Type type= Type.GetType(fullname); if(type !=null) return type; // search loaded plugins foreach(Assembly assembly in _loadedPlugins) { type= assembly.GetType(fullname); if(type !=null) return type; } return null; } public static Type FindType(string name) { // search base class Type type= Type.GetType(name); if(type !=null) return type; // search loaded plugins foreach(Assembly assembly in _loadedPlugins) { string fullname= Path.GetFileNameWithoutExtension(assembly.Location) + name; type= assembly.GetType(fullname); if(type !=null) return type; } return null; } protected List<NodeGroup> _nodeGroups= new List<NodeGroup>(); /// <summary> /// Holds a list of any root node group which will be automatically added to the node explorer. /// </summary> public IList<NodeGroup> NodeGroups { get { return _nodeGroups.AsReadOnly(); } } protected List<FileManagerInfo> _fileManagers= new List<FileManagerInfo>(); /// <summary> /// Holds a listof file managers which will be automatically registered. /// </summary> public IList<FileManagerInfo> FileManagers { get { return _fileManagers.AsReadOnly(); } } protected List<ExporterInfo> _exporters= new List<ExporterInfo>(); /// <summary> /// Holds a list of exporters which will be automatically registered. /// </summary> public IList<ExporterInfo> Exporters { get { return _exporters.AsReadOnly(); } } /// <summary> /// Adds the resource manager to the list of available resource managers. /// </summary> /// <returns>List containing local resource manager.</returns> private static List<ResourceManager> AddLocalResources() { List<ResourceManager> list= new List<ResourceManager>(); list.Add(Resources.ResourceManager); return list; } /// <summary> /// This list must contain any resource manager which is avilable. /// </summary> private static List<ResourceManager> __resources= AddLocalResources(); /// <summary> /// Adds a resource manager to the list of all available resource managers. /// </summary> /// <param name="manager">The manager which will be added.</param> public static void AddResourceManager(ResourceManager manager) { if(!__resources.Contains(manager)) __resources.Add(manager); } /// <summary> /// Retrieves a string from all available resource managers. /// </summary> /// <param name="name">The string's name we want to get.</param> /// <returns>Returns name if resource could not be found.</returns> public static string GetResourceString(string name) { foreach(ResourceManager manager in __resources) { string val= manager.GetString(name, Resources.Culture); if(val !=null) return val; } return name; } protected List<AIType> _aiTypes= new List<AIType>(); /// <summary> /// Holds a list of AI types available. /// </summary> public IList<AIType> AITypes { get { return _aiTypes.AsReadOnly(); } } } }
// <copyright file="RiakSecurityManager.cs" company="Basho Technologies, Inc."> // Copyright 2011 - OJ Reeves & Jeremiah Peschka // Copyright 2014 - Basho Technologies, Inc. // // This file is provided 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. // </copyright> namespace RiakClient.Auth { using System; using System.IO; using System.Linq; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using Config; using Extensions; using Messages; using Util; internal class RiakSecurityManager { private static readonly StoreLocation[] StoreLocations = new StoreLocation[] { StoreLocation.CurrentUser, StoreLocation.LocalMachine }; private static readonly string[] SubjectSplit = new[] { ", " }; private readonly string targetHostCommonName; private readonly IRiakAuthenticationConfiguration authConfig; private readonly X509CertificateCollection clientCertificates; private readonly X509Certificate2 certificateAuthorityCert; // Interesting discussion: // http://stackoverflow.com/questions/3780801/whats-the-difference-between-a-public-constructor-in-an-internal-class-and-an-i // http://stackoverflow.com/questions/9302236/why-use-a-public-method-in-an-internal-class internal RiakSecurityManager(string targetHost, IRiakAuthenticationConfiguration authConfig) { if (string.IsNullOrWhiteSpace(targetHost)) { throw new ArgumentNullException("targetHost"); } targetHostCommonName = string.Format("CN={0}", targetHost); this.authConfig = authConfig; if (IsSecurityEnabled) { clientCertificates = GetClientCertificates(); certificateAuthorityCert = GetCertificateAuthorityCert(); } } /// <summary> /// Gets a value indicating whether security is enabled /// </summary> public bool IsSecurityEnabled { get { return (MonoUtil.IsRunningOnMono == false) && (authConfig != null && (!string.IsNullOrWhiteSpace(authConfig.Username))); } } /// <summary> /// Gets a value indicating whether client certs are configured and at least one available /// </summary> public bool ClientCertificatesConfigured { get { return clientCertificates.Count > 0; } } /// <summary> /// Gets the client certs collection /// </summary> public X509CertificateCollection ClientCertificates { get { return clientCertificates; } } /// <summary> /// Method used to validate a server certificate /// </summary> /// <param name="sender">The sender</param> /// <param name="certificate">The server certificate</param> /// <param name="chain">The X509 certificate chain</param> /// <param name="sslPolicyErrors">The set of errors according to SSL policy</param> /// <returns>boolean indicating validity of server certificate</returns> public bool ServerCertificateValidationCallback( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) { return true; } /* * Inspired by the following: * http://msdn.microsoft.com/en-us/library/office/dd633677%28v=exchg.80%29.aspx * http://stackoverflow.com/questions/22076184/how-to-validate-a-certificate * * First, ensure we've got a cert authority file */ if (certificateAuthorityCert != null) { if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0) { // This ensures the presented cert is for the current host if (EnsureServerCertificateSubject(certificate.Subject)) { if (chain != null && chain.ChainStatus != null) { foreach (X509ChainStatus status in chain.ChainStatus) { if (status.Status == X509ChainStatusFlags.UntrustedRoot && EnumerableUtil.NotNullOrEmpty(chain.ChainElements)) { // The root cert must not be installed but we provided a file // See if anything in the chain matches our root cert foreach (X509ChainElement chainElement in chain.ChainElements) { if (chainElement.Certificate.Equals(certificateAuthorityCert)) { return true; } } } else { if (status.Status != X509ChainStatusFlags.NoError) { // If there are any other errors in the certificate chain, the certificate is invalid, // so immediately returns false. return false; } } } } } } } return false; } /// <summary> /// Callback to select a client certificate for authentication /// </summary> /// <param name="sender">The sender</param> /// <param name="targetHost">The host requesting authentication</param> /// <param name="localCertificates">The collection of local certificates</param> /// <param name="remoteCertificate">The remote certificate</param> /// <param name="acceptableIssuers">The collection of acceptable issuers</param> /// <returns>A matching certificate for authentication</returns> public X509Certificate ClientCertificateSelectionCallback( object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { X509Certificate clientCertToPresent = null; /* * NB: * 1st time in here, targetHost == "riak-test" and acceptableIssuers is empty * 2nd time in here, targetHost == "riak-test" and acceptableIssues is one element in array: * OU=Development, O=Basho Technologies, L=Bellevue, S=WA, C=US */ if (EnumerableUtil.NotNullOrEmpty(localCertificates)) { if (EnumerableUtil.NotNullOrEmpty(acceptableIssuers)) { foreach (X509Certificate cert in localCertificates) { if (acceptableIssuers.Any(issuer => cert.Issuer.Contains(issuer))) { clientCertToPresent = cert; break; } } } if (clientCertToPresent == null) { // Hope that this cert is the right one clientCertToPresent = localCertificates[0]; } } return clientCertToPresent; } /// <summary> /// Gets the protobuf object for an authentication request /// </summary> /// <returns>A correctly constructed protobuf object</returns> public RpbAuthReq GetAuthRequest() { return new RpbAuthReq { user = authConfig.Username.ToRiakString(), password = authConfig.Password.ToRiakString() }; } /// <summary> /// Ensures that the server certificate is for the target host /// </summary> /// <param name="serverCertificateSubject">The presented subject</param> /// <returns>boolean indicating validity</returns> private bool EnsureServerCertificateSubject(string serverCertificateSubject) { string serverCommonName = serverCertificateSubject.Split(SubjectSplit, StringSplitOptions.RemoveEmptyEntries) .FirstOrDefault(s => s.StartsWith("CN=")); return targetHostCommonName.Equals(serverCommonName); } /// <summary> /// Gets a file containing the certificate authority certificate /// </summary> /// <returns>An <see cref="X509Certificate2"/> object</returns> private X509Certificate2 GetCertificateAuthorityCert() { X509Certificate2 certificateAuthorityCert = null; if (!string.IsNullOrWhiteSpace(authConfig.CertificateAuthorityFile) && File.Exists(authConfig.CertificateAuthorityFile)) { certificateAuthorityCert = new X509Certificate2(authConfig.CertificateAuthorityFile); } return certificateAuthorityCert; } /// <summary> /// Returns a collection of client certificates from the configuration setting and local stores /// </summary> /// <returns>Returns <see cref="X509CertificateCollection"/> representing available client certificates</returns> private X509CertificateCollection GetClientCertificates() { var clientCertificates = new X509CertificateCollection(); // http://stackoverflow.com/questions/18462064/associate-a-private-key-with-the-x509certificate2-class-in-net if (!string.IsNullOrWhiteSpace(authConfig.ClientCertificateFile)) { if (File.Exists(authConfig.ClientCertificateFile)) { var cert = new X509Certificate2(authConfig.ClientCertificateFile); clientCertificates.Add(cert); } else { const string ErrMsg = "Client certificate file does not exist!"; throw new FileNotFoundException(ErrMsg, authConfig.ClientCertificateFile); } } if (!string.IsNullOrWhiteSpace(authConfig.ClientCertificateSubject)) { foreach (var storeLocation in StoreLocations) { X509Store x509Store = null; try { x509Store = new X509Store(StoreName.My, storeLocation); x509Store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); foreach (var cert in x509Store.Certificates) { if (cert.Subject == authConfig.ClientCertificateSubject) { clientCertificates.Add(cert); } } } finally { x509Store.Close(); } } } if (!(clientCertificates.Count > 0)) { throw new InvalidOperationException("Expected one or more client certificates to be found!"); } return clientCertificates; } } }
// 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.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Overlays.Settings; using osu.Game.Rulesets; using osu.Game.Tournament.Components; using osu.Game.Tournament.Models; using osuTK; namespace osu.Game.Tournament.Screens.Editors { public class SeedingEditorScreen : TournamentEditorScreen<SeedingEditorScreen.SeedingResultRow, SeedingResult> { private readonly TournamentTeam team; protected override BindableList<SeedingResult> Storage => team.SeedingResults; [Resolved(canBeNull: true)] private TournamentSceneManager sceneManager { get; set; } public SeedingEditorScreen(TournamentTeam team, TournamentScreen parentScreen) : base(parentScreen) { this.team = team; } public class SeedingResultRow : CompositeDrawable, IModelBacked<SeedingResult> { public SeedingResult Model { get; } [Resolved] private LadderInfo ladderInfo { get; set; } public SeedingResultRow(TournamentTeam team, SeedingResult round) { Model = round; Masking = true; CornerRadius = 10; SeedingBeatmapEditor beatmapEditor = new SeedingBeatmapEditor(round) { Width = 0.95f }; InternalChildren = new Drawable[] { new Box { Colour = OsuColour.Gray(0.1f), RelativeSizeAxes = Axes.Both, }, new FillFlowContainer { Margin = new MarginPadding(5), Padding = new MarginPadding { Right = 160 }, Spacing = new Vector2(5), Direction = FillDirection.Full, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { new SettingsTextBox { LabelText = "Mod", Width = 0.33f, Current = Model.Mod }, new SettingsSlider<int> { LabelText = "Seed", Width = 0.33f, Current = Model.Seed }, new SettingsButton { Width = 0.2f, Margin = new MarginPadding(10), Text = "Add beatmap", Action = () => beatmapEditor.CreateNew() }, beatmapEditor } }, new DangerousSettingsButton { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, RelativeSizeAxes = Axes.None, Width = 150, Text = "Delete result", Action = () => { Expire(); team.SeedingResults.Remove(Model); }, } }; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } public class SeedingBeatmapEditor : CompositeDrawable { private readonly SeedingResult round; private readonly FillFlowContainer flow; public SeedingBeatmapEditor(SeedingResult round) { this.round = round; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChild = flow = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, ChildrenEnumerable = round.Beatmaps.Select(p => new SeedingBeatmapRow(round, p)) }; } public void CreateNew() { var user = new SeedingBeatmap(); round.Beatmaps.Add(user); flow.Add(new SeedingBeatmapRow(round, user)); } public class SeedingBeatmapRow : CompositeDrawable { private readonly SeedingResult result; public SeedingBeatmap Model { get; } [Resolved] protected IAPIProvider API { get; private set; } private readonly Bindable<int?> beatmapId = new Bindable<int?>(); private readonly Bindable<string> score = new Bindable<string>(); private readonly Container drawableContainer; public SeedingBeatmapRow(SeedingResult result, SeedingBeatmap beatmap) { this.result = result; Model = beatmap; Margin = new MarginPadding(10); RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Masking = true; CornerRadius = 5; InternalChildren = new Drawable[] { new Box { Colour = OsuColour.Gray(0.2f), RelativeSizeAxes = Axes.Both, }, new FillFlowContainer { Margin = new MarginPadding(5), Padding = new MarginPadding { Right = 160 }, Spacing = new Vector2(5), Direction = FillDirection.Horizontal, AutoSizeAxes = Axes.Both, Children = new Drawable[] { new SettingsNumberBox { LabelText = "Beatmap ID", RelativeSizeAxes = Axes.None, Width = 200, Current = beatmapId, }, new SettingsSlider<int> { LabelText = "Seed", RelativeSizeAxes = Axes.None, Width = 200, Current = beatmap.Seed }, new SettingsTextBox { LabelText = "Score", RelativeSizeAxes = Axes.None, Width = 200, Current = score, }, drawableContainer = new Container { Size = new Vector2(100, 70), }, } }, new DangerousSettingsButton { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, RelativeSizeAxes = Axes.None, Width = 150, Text = "Delete Beatmap", Action = () => { Expire(); result.Beatmaps.Remove(beatmap); }, } }; } [BackgroundDependencyLoader] private void load(RulesetStore rulesets) { beatmapId.Value = Model.ID; beatmapId.BindValueChanged(id => { Model.ID = id.NewValue ?? 0; if (id.NewValue != id.OldValue) Model.BeatmapInfo = null; if (Model.BeatmapInfo != null) { updatePanel(); return; } var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = Model.ID }); req.Success += res => { Model.BeatmapInfo = res.ToBeatmap(rulesets); updatePanel(); }; req.Failure += _ => { Model.BeatmapInfo = null; updatePanel(); }; API.Queue(req); }, true); score.Value = Model.Score.ToString(); score.BindValueChanged(str => long.TryParse(str.NewValue, out Model.Score)); } private void updatePanel() { drawableContainer.Clear(); if (Model.BeatmapInfo != null) { drawableContainer.Child = new TournamentBeatmapPanel(Model.BeatmapInfo, result.Mod.Value) { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Width = 300 }; } } } } } protected override SeedingResultRow CreateDrawable(SeedingResult model) => new SeedingResultRow(team, model); } }
using Lucene.Net.Index; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using ArrayUtil = Lucene.Net.Util.ArrayUtil; using AtomicReader = Lucene.Net.Index.AtomicReader; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using DocsEnum = Lucene.Net.Index.DocsEnum; using IndexReader = Lucene.Net.Index.IndexReader; using IndexReaderContext = Lucene.Net.Index.IndexReaderContext; using Similarity = Lucene.Net.Search.Similarities.Similarity; using SimScorer = Lucene.Net.Search.Similarities.Similarity.SimScorer; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; using TermState = Lucene.Net.Index.TermState; using ToStringUtils = Lucene.Net.Util.ToStringUtils; using System.Collections; /// <summary> /// <see cref="MultiPhraseQuery"/> is a generalized version of <see cref="PhraseQuery"/>, with an added /// method <see cref="Add(Term[])"/>. /// <para/> /// To use this class, to search for the phrase "Microsoft app*" first use /// <see cref="Add(Term)"/> on the term "Microsoft", then find all terms that have "app" as /// prefix using <c>MultiFields.GetFields(IndexReader).GetTerms(string)</c>, and use <see cref="MultiPhraseQuery.Add(Term[])"/> /// to add them to the query. /// <para/> /// Collection initializer note: To create and populate a <see cref="MultiPhraseQuery"/> /// in a single statement, you can use the following example as a guide: /// /// <code> /// var multiPhraseQuery = new MultiPhraseQuery() { /// new Term("field", "microsoft"), /// new Term("field", "office") /// }; /// </code> /// Note that as long as you specify all of the parameters, you can use either /// <see cref="Add(Term)"/>, <see cref="Add(Term[])"/>, or <see cref="Add(Term[], int)"/> /// as the method to use to initialize. If there are multiple parameters, each parameter set /// must be surrounded by curly braces. /// </summary> public class MultiPhraseQuery : Query, IEnumerable<Term[]> // LUCENENET specific - implemented IEnumerable<Term[]>, which allows for use of collection initializer. See: https://stackoverflow.com/a/9195144 { private string field; private List<Term[]> termArrays = new List<Term[]>(); private readonly IList<int> positions = new EquatableList<int>(); private int slop = 0; /// <summary> /// Sets the phrase slop for this query. </summary> /// <seealso cref="PhraseQuery.Slop"/> public virtual int Slop { set { if (value < 0) { throw new System.ArgumentException("slop value cannot be negative"); } slop = value; } get { return slop; } } /// <summary> /// Add a single term at the next position in the phrase. </summary> /// <seealso cref="PhraseQuery.Add(Term)"/> public virtual void Add(Term term) { Add(new Term[] { term }); } /// <summary> /// Add multiple terms at the next position in the phrase. Any of the terms /// may match. /// </summary> /// <seealso cref="PhraseQuery.Add(Term)"/> public virtual void Add(Term[] terms) { int position = 0; if (positions.Count > 0) { position = (int)positions[positions.Count - 1] + 1; } Add(terms, position); } /// <summary> /// Allows to specify the relative position of terms within the phrase. /// </summary> /// <seealso cref="PhraseQuery.Add(Term, int)"/> public virtual void Add(Term[] terms, int position) { if (termArrays.Count == 0) { field = terms[0].Field; } for (var i = 0; i < terms.Length; i++) { if (!terms[i].Field.Equals(field, StringComparison.Ordinal)) { throw new System.ArgumentException("All phrase terms must be in the same field (" + field + "): " + terms[i]); } } termArrays.Add(terms); positions.Add(Convert.ToInt32(position)); } /// <summary> /// Returns a List of the terms in the multiphrase. /// Do not modify the List or its contents. /// </summary> public virtual IList<Term[]> GetTermArrays() { return termArrays.AsReadOnly();// Collections.unmodifiableList(TermArrays_Renamed); } /// <summary> /// Returns the relative positions of terms in this phrase. /// </summary> public virtual int[] GetPositions() { var result = new int[positions.Count]; for (int i = 0; i < positions.Count; i++) { result[i] = (int)positions[i]; } return result; } /// <summary> /// Expert: adds all terms occurring in this query to the terms set. Only /// works if this query is in its rewritten (<see cref="Rewrite(IndexReader)"/>) form. /// </summary> /// <exception cref="InvalidOperationException"> If this query is not yet rewritten </exception> public override void ExtractTerms(ISet<Term> terms) { foreach (Term[] arr in termArrays) { foreach (Term term in arr) { terms.Add(term); } } } private class MultiPhraseWeight : Weight { private readonly MultiPhraseQuery outerInstance; private readonly Similarity similarity; private readonly Similarity.SimWeight stats; private readonly IDictionary<Term, TermContext> termContexts = new Dictionary<Term, TermContext>(); public MultiPhraseWeight(MultiPhraseQuery outerInstance, IndexSearcher searcher) { this.outerInstance = outerInstance; this.similarity = searcher.Similarity; IndexReaderContext context = searcher.TopReaderContext; // compute idf var allTermStats = new List<TermStatistics>(); foreach (Term[] terms in outerInstance.termArrays) { foreach (Term term in terms) { TermContext termContext; termContexts.TryGetValue(term, out termContext); if (termContext == null) { termContext = TermContext.Build(context, term); termContexts[term] = termContext; } allTermStats.Add(searcher.TermStatistics(term, termContext)); } } stats = similarity.ComputeWeight(outerInstance.Boost, searcher.CollectionStatistics(outerInstance.field), allTermStats.ToArray()); } public override Query Query { get { return outerInstance; } } public override float GetValueForNormalization() { return stats.GetValueForNormalization(); } public override void Normalize(float queryNorm, float topLevelBoost) { stats.Normalize(queryNorm, topLevelBoost); } public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { Debug.Assert(outerInstance.termArrays.Count > 0); AtomicReader reader = (context.AtomicReader); IBits liveDocs = acceptDocs; PhraseQuery.PostingsAndFreq[] postingsFreqs = new PhraseQuery.PostingsAndFreq[outerInstance.termArrays.Count]; Terms fieldTerms = reader.GetTerms(outerInstance.field); if (fieldTerms == null) { return null; } // Reuse single TermsEnum below: TermsEnum termsEnum = fieldTerms.GetIterator(null); for (int pos = 0; pos < postingsFreqs.Length; pos++) { Term[] terms = outerInstance.termArrays[pos]; DocsAndPositionsEnum postingsEnum; int docFreq; if (terms.Length > 1) { postingsEnum = new UnionDocsAndPositionsEnum(liveDocs, context, terms, termContexts, termsEnum); // coarse -- this overcounts since a given doc can // have more than one term: docFreq = 0; for (int termIdx = 0; termIdx < terms.Length; termIdx++) { Term term = terms[termIdx]; TermState termState = termContexts[term].Get(context.Ord); if (termState == null) { // Term not in reader continue; } termsEnum.SeekExact(term.Bytes, termState); docFreq += termsEnum.DocFreq; } if (docFreq == 0) { // None of the terms are in this reader return null; } } else { Term term = terms[0]; TermState termState = termContexts[term].Get(context.Ord); if (termState == null) { // Term not in reader return null; } termsEnum.SeekExact(term.Bytes, termState); postingsEnum = termsEnum.DocsAndPositions(liveDocs, null, DocsAndPositionsFlags.NONE); if (postingsEnum == null) { // term does exist, but has no positions Debug.Assert(termsEnum.Docs(liveDocs, null, DocsFlags.NONE) != null, "termstate found but no term exists in reader"); throw new InvalidOperationException("field \"" + term.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + term.Text() + ")"); } docFreq = termsEnum.DocFreq; } postingsFreqs[pos] = new PhraseQuery.PostingsAndFreq(postingsEnum, docFreq, (int)outerInstance.positions[pos], terms); } // sort by increasing docFreq order if (outerInstance.slop == 0) { ArrayUtil.TimSort(postingsFreqs); } if (outerInstance.slop == 0) { ExactPhraseScorer s = new ExactPhraseScorer(this, postingsFreqs, similarity.GetSimScorer(stats, context)); if (s.noDocs) { return null; } else { return s; } } else { return new SloppyPhraseScorer(this, postingsFreqs, outerInstance.slop, similarity.GetSimScorer(stats, context)); } } public override Explanation Explain(AtomicReaderContext context, int doc) { Scorer scorer = GetScorer(context, (context.AtomicReader).LiveDocs); if (scorer != null) { int newDoc = scorer.Advance(doc); if (newDoc == doc) { float freq = outerInstance.slop == 0 ? scorer.Freq : ((SloppyPhraseScorer)scorer).SloppyFreq; SimScorer docScorer = similarity.GetSimScorer(stats, context); ComplexExplanation result = new ComplexExplanation(); result.Description = "weight(" + Query + " in " + doc + ") [" + similarity.GetType().Name + "], result of:"; Explanation scoreExplanation = docScorer.Explain(doc, new Explanation(freq, "phraseFreq=" + freq)); result.AddDetail(scoreExplanation); result.Value = scoreExplanation.Value; result.Match = true; return result; } } return new ComplexExplanation(false, 0.0f, "no matching term"); } } public override Query Rewrite(IndexReader reader) { if (termArrays.Count == 0) { BooleanQuery bq = new BooleanQuery(); bq.Boost = Boost; return bq; } // optimize one-term case else if (termArrays.Count == 1) { Term[] terms = termArrays[0]; BooleanQuery boq = new BooleanQuery(true); for (int i = 0; i < terms.Length; i++) { boq.Add(new TermQuery(terms[i]), Occur.SHOULD); } boq.Boost = Boost; return boq; } else { return this; } } public override Weight CreateWeight(IndexSearcher searcher) { return new MultiPhraseWeight(this, searcher); } /// <summary> /// Prints a user-readable version of this query. </summary> public override sealed string ToString(string f) { StringBuilder buffer = new StringBuilder(); if (field == null || !field.Equals(f, StringComparison.Ordinal)) { buffer.Append(field); buffer.Append(":"); } buffer.Append("\""); int k = 0; IEnumerator<Term[]> i = termArrays.GetEnumerator(); int? lastPos = -1; bool first = true; while (i.MoveNext()) { Term[] terms = i.Current; int? position = positions[k]; if (first) { first = false; } else { buffer.Append(" "); for (int j = 1; j < (position - lastPos); j++) { buffer.Append("? "); } } if (terms.Length > 1) { buffer.Append("("); for (int j = 0; j < terms.Length; j++) { buffer.Append(terms[j].Text()); if (j < terms.Length - 1) { buffer.Append(" "); } } buffer.Append(")"); } else { buffer.Append(terms[0].Text()); } lastPos = position; ++k; } buffer.Append("\""); if (slop != 0) { buffer.Append("~"); buffer.Append(slop); } buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } /// <summary> /// Returns <c>true</c> if <paramref name="o"/> is equal to this. </summary> public override bool Equals(object o) { if (!(o is MultiPhraseQuery)) { return false; } MultiPhraseQuery other = (MultiPhraseQuery)o; return this.Boost == other.Boost && this.slop == other.slop && TermArraysEquals(this.termArrays, other.termArrays) && this.positions.Equals(other.positions); } /// <summary> /// Returns a hash code value for this object. </summary> public override int GetHashCode() { //If this doesn't work hash all elements of positions. This was used to reduce time overhead return Number.SingleToInt32Bits(Boost) ^ slop ^ TermArraysHashCode() ^ ((positions.Count == 0) ? 0 : positions.GetHashCode() ^ 0x4AC65113); } // Breakout calculation of the termArrays hashcode private int TermArraysHashCode() { int hashCode = 1; foreach (Term[] termArray in termArrays) { hashCode = 31 * hashCode + (termArray == null ? 0 : Arrays.GetHashCode(termArray)); } return hashCode; } // Breakout calculation of the termArrays equals private bool TermArraysEquals(IList<Term[]> termArrays1, IList<Term[]> termArrays2) { if (termArrays1.Count != termArrays2.Count) { return false; } using (IEnumerator<Term[]> iterator1 = termArrays1.GetEnumerator()) { using (IEnumerator<Term[]> iterator2 = termArrays2.GetEnumerator()) { while (iterator1.MoveNext()) { Term[] termArray1 = iterator1.Current; iterator2.MoveNext(); Term[] termArray2 = iterator2.Current; if (!(termArray1 == null ? termArray2 == null : Arrays.Equals(termArray1, termArray2))) { return false; } } } } return true; } /// <summary> /// Returns an enumerator that iterates through the <see cref="termArrays"/> collection. /// </summary> /// <returns>An enumerator that can be used to iterate through the <see cref="termArrays"/> collection.</returns> // LUCENENET specific public IEnumerator<Term[]> GetEnumerator() { return termArrays.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the <see cref="termArrays"/>. /// </summary> /// <returns>An enumerator that can be used to iterate through the <see cref="termArrays"/> collection.</returns> // LUCENENET specific IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } /// <summary> /// Takes the logical union of multiple <see cref="DocsEnum"/> iterators. /// </summary> // TODO: if ever we allow subclassing of the *PhraseScorer internal class UnionDocsAndPositionsEnum : DocsAndPositionsEnum { private sealed class DocsQueue : Util.PriorityQueue<DocsAndPositionsEnum> { internal DocsQueue(ICollection<DocsAndPositionsEnum> docsEnums) : base(docsEnums.Count) { IEnumerator<DocsAndPositionsEnum> i = docsEnums.GetEnumerator(); while (i.MoveNext()) { DocsAndPositionsEnum postings = i.Current; if (postings.NextDoc() != DocIdSetIterator.NO_MORE_DOCS) { Add(postings); } } } protected internal override bool LessThan(DocsAndPositionsEnum a, DocsAndPositionsEnum b) { return a.DocID < b.DocID; } } /// <summary> /// NOTE: This was IntQueue in Lucene /// </summary> private sealed class Int32Queue { public Int32Queue() { InitializeInstanceFields(); } internal void InitializeInstanceFields() { _array = new int[_arraySize]; } private int _arraySize = 16; private int _index = 0; private int _lastIndex = 0; private int[] _array; internal void Add(int i) { if (_lastIndex == _arraySize) { GrowArray(); } _array[_lastIndex++] = i; } internal int Next() { return _array[_index++]; } internal void Sort() { Array.Sort(_array, _index, _lastIndex); } internal void Clear() { _index = 0; _lastIndex = 0; } internal int Count // LUCENENET NOTE: This was size() in Lucene. { get { return (_lastIndex - _index); } } private void GrowArray() { var newArray = new int[_arraySize * 2]; Array.Copy(_array, 0, newArray, 0, _arraySize); _array = newArray; _arraySize *= 2; } } private int _doc; private int _freq; private readonly DocsQueue _queue; private readonly Int32Queue _posList; private readonly long _cost; public UnionDocsAndPositionsEnum(IBits liveDocs, AtomicReaderContext context, Term[] terms, IDictionary<Term, TermContext> termContexts, TermsEnum termsEnum) { ICollection<DocsAndPositionsEnum> docsEnums = new LinkedList<DocsAndPositionsEnum>(); for (int i = 0; i < terms.Length; i++) { Term term = terms[i]; TermState termState = termContexts[term].Get(context.Ord); if (termState == null) { // Term doesn't exist in reader continue; } termsEnum.SeekExact(term.Bytes, termState); DocsAndPositionsEnum postings = termsEnum.DocsAndPositions(liveDocs, null, DocsAndPositionsFlags.NONE); if (postings == null) { // term does exist, but has no positions throw new InvalidOperationException("field \"" + term.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + term.Text() + ")"); } _cost += postings.GetCost(); docsEnums.Add(postings); } _queue = new DocsQueue(docsEnums); _posList = new Int32Queue(); } public override sealed int NextDoc() { if (_queue.Count == 0) { return NO_MORE_DOCS; } // TODO: move this init into positions(): if the search // doesn't need the positions for this doc then don't // waste CPU merging them: _posList.Clear(); _doc = _queue.Top.DocID; // merge sort all positions together DocsAndPositionsEnum postings; do { postings = _queue.Top; int freq = postings.Freq; for (int i = 0; i < freq; i++) { _posList.Add(postings.NextPosition()); } if (postings.NextDoc() != NO_MORE_DOCS) { _queue.UpdateTop(); } else { _queue.Pop(); } } while (_queue.Count > 0 && _queue.Top.DocID == _doc); _posList.Sort(); _freq = _posList.Count; return _doc; } public override int NextPosition() { return _posList.Next(); } public override int StartOffset { get { return -1; } } public override int EndOffset { get { return -1; } } public override BytesRef GetPayload() { return null; } public override sealed int Advance(int target) { while (_queue.Top != null && target > _queue.Top.DocID) { DocsAndPositionsEnum postings = _queue.Pop(); if (postings.Advance(target) != NO_MORE_DOCS) { _queue.Add(postings); } } return NextDoc(); } public override sealed int Freq { get { return _freq; } } public override sealed int DocID { get { return _doc; } } public override long GetCost() { return _cost; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: addressbook.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Protobuf.Examples.AddressBook { /// <summary>Holder for reflection information generated from addressbook.proto</summary> public static partial class AddressbookReflection { #region Descriptor /// <summary>File descriptor for addressbook.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AddressbookReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChFhZGRyZXNzYm9vay5wcm90bxIIdHV0b3JpYWwi1QEKBlBlcnNvbhIMCgRu", "YW1lGAEgASgJEgoKAmlkGAIgASgFEg0KBWVtYWlsGAMgASgJEiwKBnBob25l", "cxgEIAMoCzIcLnR1dG9yaWFsLlBlcnNvbi5QaG9uZU51bWJlchpHCgtQaG9u", "ZU51bWJlchIOCgZudW1iZXIYASABKAkSKAoEdHlwZRgCIAEoDjIaLnR1dG9y", "aWFsLlBlcnNvbi5QaG9uZVR5cGUiKwoJUGhvbmVUeXBlEgoKBk1PQklMRRAA", "EggKBEhPTUUQARIICgRXT1JLEAIiLwoLQWRkcmVzc0Jvb2sSIAoGcGVvcGxl", "GAEgAygLMhAudHV0b3JpYWwuUGVyc29uQlAKFGNvbS5leGFtcGxlLnR1dG9y", "aWFsQhFBZGRyZXNzQm9va1Byb3Rvc6oCJEdvb2dsZS5Qcm90b2J1Zi5FeGFt", "cGxlcy5BZGRyZXNzQm9va2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.Person), global::Google.Protobuf.Examples.AddressBook.Person.Parser, new[]{ "Name", "Id", "Email", "Phones" }, null, new[]{ typeof(global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber), global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber.Parser, new[]{ "Number", "Type" }, null, null, null)}), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.AddressBook), global::Google.Protobuf.Examples.AddressBook.AddressBook.Parser, new[]{ "People" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// [START messages] /// </summary> public sealed partial class Person : pb::IMessage<Person> { private static readonly pb::MessageParser<Person> _parser = new pb::MessageParser<Person>(() => new Person()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Person> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.Examples.AddressBook.AddressbookReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Person() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Person(Person other) : this() { name_ = other.name_; id_ = other.id_; email_ = other.email_; phones_ = other.phones_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Person Clone() { return new Person(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 2; private int id_; /// <summary> /// Unique ID number for this person. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Id { get { return id_; } set { id_ = value; } } /// <summary>Field number for the "email" field.</summary> public const int EmailFieldNumber = 3; private string email_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Email { get { return email_; } set { email_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "phones" field.</summary> public const int PhonesFieldNumber = 4; private static readonly pb::FieldCodec<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber> _repeated_phones_codec = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber> phones_ = new pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber> Phones { get { return phones_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Person); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Person other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Id != other.Id) return false; if (Email != other.Email) return false; if(!phones_.Equals(other.phones_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Id != 0) hash ^= Id.GetHashCode(); if (Email.Length != 0) hash ^= Email.GetHashCode(); hash ^= phones_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Id != 0) { output.WriteRawTag(16); output.WriteInt32(Id); } if (Email.Length != 0) { output.WriteRawTag(26); output.WriteString(Email); } phones_.WriteTo(output, _repeated_phones_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Id != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Id); } if (Email.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Email); } size += phones_.CalculateSize(_repeated_phones_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Person other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Id != 0) { Id = other.Id; } if (other.Email.Length != 0) { Email = other.Email; } phones_.Add(other.phones_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 16: { Id = input.ReadInt32(); break; } case 26: { Email = input.ReadString(); break; } case 34: { phones_.AddEntriesFrom(input, _repeated_phones_codec); break; } } } } #region Nested types /// <summary>Container for nested types declared in the Person message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum PhoneType { [pbr::OriginalName("MOBILE")] Mobile = 0, [pbr::OriginalName("HOME")] Home = 1, [pbr::OriginalName("WORK")] Work = 2, } public sealed partial class PhoneNumber : pb::IMessage<PhoneNumber> { private static readonly pb::MessageParser<PhoneNumber> _parser = new pb::MessageParser<PhoneNumber>(() => new PhoneNumber()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PhoneNumber> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.Examples.AddressBook.Person.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PhoneNumber() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PhoneNumber(PhoneNumber other) : this() { number_ = other.number_; type_ = other.type_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PhoneNumber Clone() { return new PhoneNumber(this); } /// <summary>Field number for the "number" field.</summary> public const int NumberFieldNumber = 1; private string number_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Number { get { return number_; } set { number_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 2; private global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType type_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType Type { get { return type_; } set { type_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PhoneNumber); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PhoneNumber other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Number != other.Number) return false; if (Type != other.Type) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Number.Length != 0) hash ^= Number.GetHashCode(); if (Type != 0) hash ^= Type.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Number.Length != 0) { output.WriteRawTag(10); output.WriteString(Number); } if (Type != 0) { output.WriteRawTag(16); output.WriteEnum((int) Type); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Number.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Number); } if (Type != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PhoneNumber other) { if (other == null) { return; } if (other.Number.Length != 0) { Number = other.Number; } if (other.Type != 0) { Type = other.Type; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Number = input.ReadString(); break; } case 16: { type_ = (global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType) input.ReadEnum(); break; } } } } } } #endregion } /// <summary> /// Our address book file is just one of these. /// </summary> public sealed partial class AddressBook : pb::IMessage<AddressBook> { private static readonly pb::MessageParser<AddressBook> _parser = new pb::MessageParser<AddressBook>(() => new AddressBook()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<AddressBook> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.Examples.AddressBook.AddressbookReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AddressBook() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AddressBook(AddressBook other) : this() { people_ = other.people_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AddressBook Clone() { return new AddressBook(this); } /// <summary>Field number for the "people" field.</summary> public const int PeopleFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Protobuf.Examples.AddressBook.Person> _repeated_people_codec = pb::FieldCodec.ForMessage(10, global::Google.Protobuf.Examples.AddressBook.Person.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person> people_ = new pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Protobuf.Examples.AddressBook.Person> People { get { return people_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as AddressBook); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(AddressBook other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!people_.Equals(other.people_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= people_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { people_.WriteTo(output, _repeated_people_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += people_.CalculateSize(_repeated_people_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(AddressBook other) { if (other == null) { return; } people_.Add(other.people_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { people_.AddEntriesFrom(input, _repeated_people_codec); break; } } } } } #endregion } #endregion Designer generated code
using UnityEngine; using System.Collections; using System.Collections.Generic; #region Enums public enum GestureRecognitionState { /// <summary> /// The gesture recognizer is ready and waiting for the correct initial input conditions to begin /// </summary> Ready, /// <summary> /// The gesture recognition has just begun /// </summary> Started, /// <summary> /// The gesture is still ongoing and recognizer state has changed since last frame /// </summary> InProgress, /// <summary> /// The gesture detected a user input that invalidated it /// </summary> Failed, /// <summary> /// The gesture was succesfully recognized (used by continuous gestures) /// </summary> Ended, /// <summary> /// The gesture was succesfully recognized (used by discreet gestures) /// </summary> Recognized = Ended, /* ----------- INTERNAL -------------- */ /// <summary> /// FOR INTERNAL USE ONLY (not an actual state) /// Used to tell the gesture to fail and immeditaly retry recognition (used by multi-tap) /// </summary> FailAndRetry, } /// <summary> /// The reset mode determines when to reset a GestureRecognizer after it fails or succeeds (GestureState.Failed or GestureState.Recognized) /// </summary> public enum GestureResetMode { /// <summary> /// Use the recommended value for this gesture recognizer /// </summary> Default, /// <summary> /// The gesture recognizer will reset on the next Update() /// </summary> NextFrame, /// <summary> /// The gesture recognizer will reset at the end of the current multitouch sequence /// </summary> EndOfTouchSequence, } #endregion public abstract class Gesture { public delegate void EventHandler( Gesture gesture ); public event EventHandler OnStateChanged; // finger cluster internal int ClusterId = 0; GestureRecognizer recognizer; float startTime = 0; Vector2 startPosition = Vector2.zero; Vector2 position = Vector2.zero; GestureRecognitionState state = GestureRecognitionState.Ready; GestureRecognitionState prevState = GestureRecognitionState.Ready; FingerGestures.FingerList fingers = new FingerGestures.FingerList(); /// <summary> /// Convenience operator - so you can go if( !gesture ) instead of if( gesture == null ) /// </summary> public static implicit operator bool( Gesture gesture ) { return gesture != null; } /// <summary> /// The fingers that began the gesture /// </summary> public FingerGestures.FingerList Fingers { get { return fingers; } internal set { fingers = value; } } /// <summary> /// The gesture recognizer that owns this gesture /// </summary> public GestureRecognizer Recognizer { get { return recognizer; } internal set { recognizer = value; } } /// <summary> /// Time at which gesture recognition started /// </summary> public float StartTime { get { return startTime; } internal set { startTime = value; } } /// <summary> /// Averaged start position /// </summary> public Vector2 StartPosition { get { return startPosition; } internal set { startPosition = value; } } /// <summary> /// Averaged current position /// </summary> public Vector2 Position { get { return position; } internal set { position = value; } } /// <summary> /// Get or set the current gesture state /// </summary> public GestureRecognitionState State { get { return state; } set { if( state != value ) { prevState = state; state = value; if( OnStateChanged != null ) OnStateChanged( this ); } } } /// <summary> /// Get the previous gesture state /// </summary> public GestureRecognitionState PreviousState { get { return prevState; } } /// <summary> /// Amount of time elapsed since the gesture recognition started (in seconds) /// </summary> public float ElapsedTime { get { return Time.time - StartTime; } } #region Object Picking / Raycasting GameObject startSelection; // object picked at StartPosition GameObject selection; // object picked at current Position ScreenRaycastData lastRaycast = new ScreenRaycastData(); /// <summary> /// GameObject that was at the gesture start position /// </summary> public GameObject StartSelection { get { return startSelection; } internal set { startSelection = value; } } /// <summary> /// GameObject currently located at this gesture position /// </summary> public GameObject Selection { get { return selection; } internal set { selection = value; } } /// <summary> /// Last raycast hit result /// </summary> public ScreenRaycastData Raycast { get { return lastRaycast; } internal set { lastRaycast = value; } } internal GameObject PickObject( ScreenRaycaster raycaster, Vector2 screenPos ) { if( !raycaster || !raycaster.enabled ) return null; if( !raycaster.Raycast( screenPos, out lastRaycast ) ) return null; return lastRaycast.GameObject; } internal void PickStartSelection( ScreenRaycaster raycaster ) { StartSelection = PickObject( raycaster, StartPosition ); Selection = StartSelection; } internal void PickSelection( ScreenRaycaster raycaster ) { Selection = PickObject( raycaster, Position ); } #endregion } /// <summary> /// Type-safe/generic version of GestureRecognizer base class /// </summary> public abstract class GestureRecognizerTS<T> : GestureRecognizer where T : Gesture, new() { List<T> gestures; public delegate void GestureEventHandler( T gesture ); public event GestureEventHandler OnGesture; protected override void Start() { base.Start(); InitGestures(); } protected override void OnEnable() { base.OnEnable(); // support recompilation while running #if UNITY_EDITOR InitGestures(); #endif } void InitGestures() { if( gestures == null ) { gestures = new List<T>(); for( int i = 0; i < MaxSimultaneousGestures; ++i ) AddGesture(); } } protected T AddGesture() { T gesture = CreateGesture(); gesture.Recognizer = this; gesture.OnStateChanged += OnStateChanged; gestures.Add( gesture ); return gesture; } /// <summary> /// Get the gestures list (not all of them are necessarily active) /// </summary> public List<T> Gestures { get { return gestures; } } /// <summary> /// This controls whether or not the gesture recognition should begin /// </summary> /// <param name="touches">The active touches</param> protected virtual bool CanBegin( T gesture, FingerGestures.IFingerList touches ) { if( touches.Count != RequiredFingerCount ) return false; if( IsExclusive && FingerGestures.Touches.Count != RequiredFingerCount ) return false; // check with the delegate (provided we have one set) if( Delegate && Delegate.enabled && !Delegate.CanBegin( gesture, touches ) ) return false; return true; } /// <summary> /// Method called when the gesture recognizer has just started recognizing a valid gesture /// </summary> /// <param name="touches">The active touches</param> protected abstract void OnBegin( T gesture, FingerGestures.IFingerList touches ); /// <summary> /// Method called on each frame that the gesture recognizer is in an active state /// </summary> /// <param name="touches">The active touches</param> /// <returns>The new state the gesture recognizer should be in</returns> protected abstract GestureRecognitionState OnRecognize( T gesture, FingerGestures.IFingerList touches ); /// <summary> /// Return the default target used when sending gesture event notifications to selected object /// </summary> protected virtual GameObject GetDefaultSelectionForSendMessage( T gesture ) { return gesture.Selection; } /// <summary> /// Instantiate a new gesture object /// </summary> protected virtual T CreateGesture() { return new T(); } public override System.Type GetGestureType() { return typeof( T ); } protected virtual void OnStateChanged( Gesture gesture ) { //Debug.Log( this.GetType().Name + " changed state from " + gesture.PreviousState + " to " + gesture.State ); } protected virtual T FindGestureByCluster( FingerClusterManager.Cluster cluster ) { return gestures.Find( g => g.ClusterId == cluster.Id ); } protected virtual T MatchActiveGestureToCluster( FingerClusterManager.Cluster cluster ) { return null; } protected virtual T FindFreeGesture() { return gestures.Find( g => g.State == GestureRecognitionState.Ready ); } protected virtual void Reset( T gesture ) { ReleaseFingers( gesture ); gesture.ClusterId = 0; gesture.Fingers.Clear(); gesture.State = GestureRecognitionState.Ready; } #region Updates static FingerGestures.FingerList tempTouchList = new FingerGestures.FingerList(); public virtual void Update() { if( IsExclusive ) { UpdateExclusive(); } else if( RequiredFingerCount == 1 ) { UpdatePerFinger(); } else // 2+ fingers { if( SupportFingerClustering && ClusterManager ) UpdateUsingClusters(); else UpdateExclusive(); } } // consider all the current touches void UpdateExclusive() { // only one gesture to track T gesture = gestures[0]; FingerGestures.IFingerList touches = FingerGestures.Touches; if( gesture.State == GestureRecognitionState.Ready ) { if( CanBegin( gesture, touches ) ) Begin( gesture, 0, touches ); } UpdateGesture( gesture, touches ); } // consider each touch individually, independently of the rest void UpdatePerFinger() { for( int i = 0; i < FingerGestures.Instance.MaxFingers && i < MaxSimultaneousGestures; ++i ) { FingerGestures.Finger finger = FingerGestures.GetFinger( i ); T gesture = gestures[i]; FingerGestures.FingerList touches = tempTouchList; touches.Clear(); if( finger.IsDown ) touches.Add( finger ); if( gesture.State == GestureRecognitionState.Ready ) { if( CanBegin( gesture, touches ) ) Begin( gesture, 0, touches ); } UpdateGesture( gesture, touches ); } } // use the finger clusters as touch list sources (used for handling simultaneous multi-finger gestures) void UpdateUsingClusters() { // force cluster manager to update now (ensures we have most up to date finger state) ClusterManager.Update(); for( int i = 0; i < ClusterManager.Clusters.Count; ++i ) ProcessCluster( ClusterManager.Clusters[i] ); for( int i = 0; i < gestures.Count; ++i ) { T g = gestures[i]; FingerClusterManager.Cluster cluster = ClusterManager.FindClusterById( g.ClusterId ); FingerGestures.IFingerList touches = ( cluster != null ) ? cluster.Fingers : EmptyFingerList; UpdateGesture( g, touches ); } } protected virtual void ProcessCluster( FingerClusterManager.Cluster cluster ) { // this cluster already has a gesture associated to it if( FindGestureByCluster( cluster ) != null ) return; // only consider clusters that match our gesture's required finger count if( cluster.Fingers.Count != RequiredFingerCount ) return; // give a chance to an active gesture to claim that cluster T gesture = MatchActiveGestureToCluster( cluster ); // found an active gesture to rebind the cluster to if( gesture != null ) { //Debug.Log( "Gesture " + gesture + " claimed finger cluster #" + cluster.Id ); // reassign cluster id gesture.ClusterId = cluster.Id; } else { // no claims - find an inactive gesture gesture = FindFreeGesture(); // out of gestures if( gesture == null ) return; // did we recognize the beginning a valid gesture? if( !CanBegin( gesture, cluster.Fingers ) ) return; Begin( gesture, cluster.Id, cluster.Fingers ); } } #endregion void ReleaseFingers( T gesture ) { for( int i = 0; i < gesture.Fingers.Count; ++i ) Release( gesture.Fingers[i] ); } void Begin( T gesture, int clusterId, FingerGestures.IFingerList touches ) { //Debug.Log( "Beginning " + this.GetType().Name ); gesture.ClusterId = clusterId; gesture.StartTime = Time.time; // sanity check #if UNITY_EDITOR if( gesture.Fingers.Count > 0 ) Debug.LogWarning( this.name + " begin gesture with fingers list not properly released" ); #endif for( int i = 0; i < touches.Count; ++i ) { FingerGestures.Finger finger = touches[i]; gesture.Fingers.Add( finger ); Acquire( finger ); } OnBegin( gesture, touches ); gesture.PickStartSelection( Raycaster ); gesture.State = GestureRecognitionState.Started; } protected virtual FingerGestures.IFingerList GetTouches( T gesture ) { if( SupportFingerClustering && ClusterManager ) { FingerClusterManager.Cluster cluster = ClusterManager.FindClusterById( gesture.ClusterId ); return ( cluster != null ) ? cluster.Fingers : EmptyFingerList; } return FingerGestures.Touches; } protected virtual void UpdateGesture( T gesture, FingerGestures.IFingerList touches ) { if( gesture.State == GestureRecognitionState.Ready ) return; if( gesture.State == GestureRecognitionState.Started ) gesture.State = GestureRecognitionState.InProgress; switch( gesture.State ) { case GestureRecognitionState.InProgress: { GestureRecognitionState newState = OnRecognize( gesture, touches ); if( newState == GestureRecognitionState.FailAndRetry ) { // special case for MultiTap when the Nth tap in the sequence is performed out of the tolerance radius, // fail the gesture and immeditaly reattempt a Begin() on it using current touch data // this will trigger the fail event gesture.State = GestureRecognitionState.Failed; // save the clusterId we're currently assigned to (reset will clear it) int clusterId = gesture.ClusterId; // reset gesture state Reset( gesture ); // attempt to restart recognition right away with current touch data if( CanBegin( gesture, touches ) ) Begin( gesture, clusterId, touches ); } else { if( newState == GestureRecognitionState.InProgress ) { gesture.PickSelection( Raycaster ); } gesture.State = newState; } } break; case GestureRecognitionState.Recognized: // Ended case GestureRecognitionState.Failed: { // release the fingers right away so another recognizer can use them, even though this one isn't reset yet if( gesture.PreviousState != gesture.State ) // only do this the first time we enter this state ReleaseFingers( gesture ); // check if we should reset the gesture now if( ResetMode == GestureResetMode.NextFrame || ( ResetMode == GestureResetMode.EndOfTouchSequence && touches.Count == 0 ) ) Reset( gesture ); } break; default: Debug.LogError( this + " - Unhandled state: " + gesture.State + ". Failing gesture." ); gesture.State = GestureRecognitionState.Failed; break; } } protected void RaiseEvent( T gesture ) { if( OnGesture != null ) OnGesture( gesture ); FingerGestures.FireEvent( gesture ); if( UseSendMessage && !string.IsNullOrEmpty( EventMessageName ) ) { if( EventMessageTarget ) EventMessageTarget.SendMessage( EventMessageName, gesture, SendMessageOptions.DontRequireReceiver ); if( SendMessageToSelection != SelectionType.None ) { GameObject sel = null; switch( SendMessageToSelection ) { case SelectionType.Default: sel = GetDefaultSelectionForSendMessage( gesture ); break; case SelectionType.CurrentSelection: sel = gesture.Selection; break; case SelectionType.StartSelection: sel = gesture.StartSelection; break; } if( sel && sel != EventMessageTarget ) sel.SendMessage( EventMessageName, gesture, SendMessageOptions.DontRequireReceiver ); } } } } public abstract class GestureRecognizer : MonoBehaviour { protected static readonly FingerGestures.IFingerList EmptyFingerList = new FingerGestures.FingerList(); public enum SelectionType { Default = 0, StartSelection, CurrentSelection, None, } /// <summary> /// Number of fingers required to perform this gesture /// </summary> [SerializeField] int requiredFingerCount = 1; /// <summary> /// Specify the unit to use for the distance properties /// </summary> public DistanceUnit DistanceUnit = DistanceUnit.Centimeters; /// <summary> /// Maximum number of simultaneous gestures the recognizer can keep track of /// </summary> public int MaxSimultaneousGestures = 1; /// <summary> /// Get or set the reset mode for this gesture recognizer /// </summary> public GestureResetMode ResetMode = GestureResetMode.Default; /// <summary> /// ScreenRaycaster to use to detect scene objects this gesture is interacting with /// </summary> public ScreenRaycaster Raycaster; /// <summary> /// Get or set the finger cluster manager /// </summary> public FingerClusterManager ClusterManager; /// <summary> /// Optional reference to a gesture recognizer delegate /// </summary> public GestureRecognizerDelegate Delegate = null; /// <summary> /// Use Unity's SendMessage() to broadcast the gesture event to MessageTarget /// </summary> public bool UseSendMessage = true; public string EventMessageName; // null -> default to GetDefaultEventMessageName() public GameObject EventMessageTarget; // null -> default to current gameobject public SelectionType SendMessageToSelection = SelectionType.Default; /// <summary> /// When the exclusive flag is set, this gesture recognizer will only detect the gesture when the total number /// of active touches on the device is equal to RequiredFingerCount (FingerGestures.Touches.Count == RequiredFingerCount) /// </summary> public bool IsExclusive = false; /// <summary> /// Exact number of touches required for the gesture to be recognized /// </summary> public virtual int RequiredFingerCount { get { return requiredFingerCount; } set { requiredFingerCount = value; } } /// <summary> /// Does this type of recognizer support finger clustering to track simultaneous multi-finger gestures? /// </summary> public virtual bool SupportFingerClustering { get { return true; } } /// <summary> /// Get the default reset mode for this gesture recognizer. /// Derived classes can override this to specify a different default value /// </summary> public virtual GestureResetMode GetDefaultResetMode() { return GestureResetMode.EndOfTouchSequence; } /// <summary> /// Return the default name of the method to invoke on the message target /// </summary> public abstract string GetDefaultEventMessageName(); /// <summary> /// Return type description of the internal gesture class used by the recognizer (used by editor) /// </summary> public abstract System.Type GetGestureType(); protected virtual void Awake() { if( string.IsNullOrEmpty( EventMessageName ) ) EventMessageName = GetDefaultEventMessageName(); if( ResetMode == GestureResetMode.Default ) ResetMode = GetDefaultResetMode(); if( !EventMessageTarget ) EventMessageTarget = this.gameObject; if( !Raycaster ) Raycaster = GetComponent<ScreenRaycaster>(); } protected virtual void OnEnable() { if( FingerGestures.Instance ) FingerGestures.Register( this ); else Debug.LogError( "Failed to register gesture recognizer " + this + " - FingerGestures instance is not available." ); } protected virtual void OnDisable() { if( FingerGestures.Instance ) FingerGestures.Unregister( this ); } protected void Acquire( FingerGestures.Finger finger ) { if( !finger.GestureRecognizers.Contains( this ) ) finger.GestureRecognizers.Add( this ); } protected bool Release( FingerGestures.Finger finger ) { return finger.GestureRecognizers.Remove( this ); } protected virtual void Start() { if( !FingerGestures.Instance ) { Debug.LogWarning( "FingerGestures instance not found in current scene. Disabling recognizer: " + this ); enabled = false; return; } if( !ClusterManager && SupportFingerClustering ) { ClusterManager = GetComponent<FingerClusterManager>(); if( !ClusterManager ) ClusterManager = FingerGestures.DefaultClusterManager; } } #region Utils /// <summary> /// Check if all the touches in the list started recently /// </summary> /// <param name="touches">The touches to evaluate</param> /// <returns>True if the age of each touch in the list is under a set threshold</returns> protected bool Young( FingerGestures.IFingerList touches ) { FingerGestures.Finger oldestTouch = touches.GetOldest(); if( oldestTouch == null ) return false; float elapsedTimeSinceFirstTouch = Time.time - oldestTouch.StarTime; return elapsedTimeSinceFirstTouch < 0.25f; } /// <summary> /// Convert a distance specified in the unit currently set by DistanceUnit property, and /// returns a distance in pixels /// </summary> public float ToPixels( float distance ) { return distance.Convert( DistanceUnit, DistanceUnit.Pixels ); } /// <summary> /// Convert distance to pixels and returns the square of pixel distance /// This is NOT the same as converting the square of the distance and converting it to pixels /// </summary> public float ToSqrPixels( float distance ) { float pixelDist = ToPixels( distance ); return pixelDist * pixelDist; } #endregion }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; using System; using System.IO; namespace OpenSim.Server.Handlers.Asset { public class AssetServiceConnector : ServiceConnector { private IAssetService m_AssetService; private string m_ConfigName = "AssetService"; public AssetServiceConnector(IConfigSource config, IHttpServer server, string configName) : base(config, server, configName) { if (configName != String.Empty) m_ConfigName = configName; IConfig serverConfig = config.Configs[m_ConfigName]; if (serverConfig == null) throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName)); string assetService = serverConfig.GetString("LocalServiceModule", String.Empty); if (assetService == String.Empty) throw new Exception("No LocalServiceModule in config file"); Object[] args = new Object[] { config, m_ConfigName }; m_AssetService = ServerUtils.LoadPlugin<IAssetService>(assetService, args); if (m_AssetService == null) throw new Exception(String.Format("Failed to load AssetService from {0}; config is {1}", assetService, m_ConfigName)); bool allowDelete = serverConfig.GetBoolean("AllowRemoteDelete", false); bool allowDeleteAllTypes = serverConfig.GetBoolean("AllowRemoteDeleteAllTypes", false); AllowedRemoteDeleteTypes allowedRemoteDeleteTypes; if (!allowDelete) { allowedRemoteDeleteTypes = AllowedRemoteDeleteTypes.None; } else { if (allowDeleteAllTypes) allowedRemoteDeleteTypes = AllowedRemoteDeleteTypes.All; else allowedRemoteDeleteTypes = AllowedRemoteDeleteTypes.MapTile; } server.AddStreamHandler(new AssetServerGetHandler(m_AssetService)); server.AddStreamHandler(new AssetServerPostHandler(m_AssetService)); server.AddStreamHandler(new AssetServerDeleteHandler(m_AssetService, allowedRemoteDeleteTypes)); server.AddStreamHandler(new AssetsExistHandler(m_AssetService)); MainConsole.Instance.Commands.AddCommand("Assets", false, "show asset", "show asset <ID>", "Show asset information", HandleShowAsset); MainConsole.Instance.Commands.AddCommand("Assets", false, "delete asset", "delete asset <ID>", "Delete asset from database", HandleDeleteAsset); MainConsole.Instance.Commands.AddCommand("Assets", false, "dump asset", "dump asset <ID>", "Dump asset to a file", "The filename is the same as the ID given.", HandleDumpAsset); } private void HandleDeleteAsset(string module, string[] args) { if (args.Length < 3) { MainConsole.Instance.Output("Syntax: delete asset <ID>"); return; } AssetBase asset = m_AssetService.Get(args[2]); if (asset == null || asset.Data.Length == 0) { MainConsole.Instance.OutputFormat("Could not find asset with ID {0}", args[2]); return; } if (!m_AssetService.Delete(asset.ID)) MainConsole.Instance.OutputFormat("ERROR: Could not delete asset {0} {1}", asset.ID, asset.Name); else MainConsole.Instance.OutputFormat("Deleted asset {0} {1}", asset.ID, asset.Name); } private void HandleDumpAsset(string module, string[] args) { if (args.Length < 3) { MainConsole.Instance.Output("Usage is dump asset <ID>"); return; } UUID assetId; string rawAssetId = args[2]; if (!UUID.TryParse(rawAssetId, out assetId)) { MainConsole.Instance.OutputFormat("ERROR: {0} is not a valid ID format", rawAssetId); return; } AssetBase asset = m_AssetService.Get(assetId.ToString()); if (asset == null) { MainConsole.Instance.OutputFormat("ERROR: No asset found with ID {0}", assetId); return; } string fileName = rawAssetId; if (!ConsoleUtil.CheckFileDoesNotExist(MainConsole.Instance, fileName)) return; using (FileStream fs = new FileStream(fileName, FileMode.CreateNew)) { using (BinaryWriter bw = new BinaryWriter(fs)) { bw.Write(asset.Data); } } MainConsole.Instance.OutputFormat("Asset dumped to file {0}", fileName); } private void HandleShowAsset(string module, string[] args) { if (args.Length < 3) { MainConsole.Instance.Output("Syntax: show asset <ID>"); return; } AssetBase asset = m_AssetService.Get(args[2]); if (asset == null || asset.Data.Length == 0) { MainConsole.Instance.Output("Asset not found"); return; } int i; MainConsole.Instance.OutputFormat("Name: {0}", asset.Name); MainConsole.Instance.OutputFormat("Description: {0}", asset.Description); MainConsole.Instance.OutputFormat("Type: {0} (type number = {1})", (AssetType)asset.Type, asset.Type); MainConsole.Instance.OutputFormat("Content-type: {0}", asset.Metadata.ContentType); MainConsole.Instance.OutputFormat("Size: {0} bytes", asset.Data.Length); MainConsole.Instance.OutputFormat("Temporary: {0}", asset.Temporary ? "yes" : "no"); MainConsole.Instance.OutputFormat("Flags: {0}", asset.Metadata.Flags); for (i = 0; i < 5; i++) { int off = i * 16; if (asset.Data.Length <= off) break; int len = 16; if (asset.Data.Length < off + len) len = asset.Data.Length - off; byte[] line = new byte[len]; Array.Copy(asset.Data, off, line, 0, len); string text = BitConverter.ToString(line); MainConsole.Instance.Output(String.Format("{0:x4}: {1}", off, text)); } } } }
#region License // Copyright (c) 2006-2007, ClearCanvas Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * 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 ClearCanvas Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. #endregion namespace XnatWebBrowser.View.WinForms { partial class XnatWebBrowserComponentControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(XnatWebBrowserComponentControl)); this._browser = new System.Windows.Forms.WebBrowser(); this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer(); this._statusBar = new System.Windows.Forms.StatusStrip(); this._browserProgress = new System.Windows.Forms.ToolStripProgressBar(); this._browserStatus = new System.Windows.Forms.ToolStripStatusLabel(); this._toolbar = new System.Windows.Forms.ToolStrip(); this._back = new System.Windows.Forms.ToolStripButton(); this._forward = new System.Windows.Forms.ToolStripButton(); this._stop = new System.Windows.Forms.ToolStripButton(); this._refresh = new System.Windows.Forms.ToolStripButton(); this._address = new System.Windows.Forms.ToolStripComboBox(); this._go = new System.Windows.Forms.ToolStripButton(); this._progressLogo = new System.Windows.Forms.ToolStripLabel(); this._shortcutToolbar = new System.Windows.Forms.ToolStrip(); this.toolStripContainer1.BottomToolStripPanel.SuspendLayout(); this.toolStripContainer1.ContentPanel.SuspendLayout(); this.toolStripContainer1.TopToolStripPanel.SuspendLayout(); this.toolStripContainer1.SuspendLayout(); this._statusBar.SuspendLayout(); this._toolbar.SuspendLayout(); this.SuspendLayout(); // // _browser // this._browser.Dock = System.Windows.Forms.DockStyle.Fill; this._browser.Location = new System.Drawing.Point(0, 0); this._browser.MinimumSize = new System.Drawing.Size(20, 20); this._browser.Name = "_browser"; this._browser.Size = new System.Drawing.Size(584, 440); this._browser.TabIndex = 0; // // toolStripContainer1 // // // toolStripContainer1.BottomToolStripPanel // this.toolStripContainer1.BottomToolStripPanel.Controls.Add(this._statusBar); // // toolStripContainer1.ContentPanel // this.toolStripContainer1.ContentPanel.Controls.Add(this._browser); this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(584, 440); this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.toolStripContainer1.Location = new System.Drawing.Point(0, 0); this.toolStripContainer1.Name = "toolStripContainer1"; this.toolStripContainer1.Size = new System.Drawing.Size(584, 526); this.toolStripContainer1.TabIndex = 1; this.toolStripContainer1.Text = "toolStripContainer1"; // // toolStripContainer1.TopToolStripPanel // this.toolStripContainer1.TopToolStripPanel.Controls.Add(this._toolbar); this.toolStripContainer1.TopToolStripPanel.Controls.Add(this._shortcutToolbar); // // _statusBar // this._statusBar.Dock = System.Windows.Forms.DockStyle.None; this._statusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this._browserProgress, this._browserStatus}); this._statusBar.Location = new System.Drawing.Point(0, 0); this._statusBar.Name = "_statusBar"; this._statusBar.Size = new System.Drawing.Size(584, 22); this._statusBar.TabIndex = 1; this._statusBar.Text = "statusStrip1"; // // _browserProgress // this._browserProgress.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this._browserProgress.Name = "_browserProgress"; this._browserProgress.Size = new System.Drawing.Size(100, 16); // // _browserStatus // this._browserStatus.Name = "_browserStatus"; this._browserStatus.Size = new System.Drawing.Size(0, 17); // // _toolbar // this._toolbar.Dock = System.Windows.Forms.DockStyle.None; this._toolbar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this._toolbar.ImageScalingSize = new System.Drawing.Size(32, 32); this._toolbar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this._back, this._forward, this._stop, this._refresh, this._address, this._go, this._progressLogo}); this._toolbar.Location = new System.Drawing.Point(0, 0); this._toolbar.Name = "_toolbar"; this._toolbar.Size = new System.Drawing.Size(584, 39); this._toolbar.Stretch = true; this._toolbar.TabIndex = 0; // // _back // this._back.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this._back.Image = ((System.Drawing.Image)(resources.GetObject("_back.Image"))); this._back.ImageTransparentColor = System.Drawing.Color.Magenta; this._back.Name = "_back"; this._back.Size = new System.Drawing.Size(36, 36); this._back.Text = "Back"; // // _forward // this._forward.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this._forward.Image = ((System.Drawing.Image)(resources.GetObject("_forward.Image"))); this._forward.ImageTransparentColor = System.Drawing.Color.Magenta; this._forward.Name = "_forward"; this._forward.Size = new System.Drawing.Size(36, 36); this._forward.Text = "Forward"; // // _stop // this._stop.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this._stop.Image = ((System.Drawing.Image)(resources.GetObject("_stop.Image"))); this._stop.ImageTransparentColor = System.Drawing.Color.Magenta; this._stop.Name = "_stop"; this._stop.Size = new System.Drawing.Size(36, 36); this._stop.Text = "toolStripButton1"; this._stop.ToolTipText = "Stop"; // // _refresh // this._refresh.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this._refresh.Image = ((System.Drawing.Image)(resources.GetObject("_refresh.Image"))); this._refresh.ImageTransparentColor = System.Drawing.Color.Magenta; this._refresh.Name = "_refresh"; this._refresh.Size = new System.Drawing.Size(36, 36); this._refresh.Text = "toolStripButton1"; this._refresh.ToolTipText = "Refresh"; // // _address // this._address.Name = "_address"; this._address.Size = new System.Drawing.Size(350, 39); this._address.ToolTipText = "Address"; // // _go // this._go.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this._go.Image = ((System.Drawing.Image)(resources.GetObject("_go.Image"))); this._go.ImageTransparentColor = System.Drawing.Color.Magenta; this._go.Name = "_go"; this._go.Size = new System.Drawing.Size(36, 36); this._go.Text = "toolStripButton1"; this._go.ToolTipText = "Go"; // // _progressLogo // this._progressLogo.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this._progressLogo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this._progressLogo.Name = "_progressLogo"; this._progressLogo.Size = new System.Drawing.Size(0, 36); // // _shortcutToolbar // this._shortcutToolbar.Dock = System.Windows.Forms.DockStyle.None; this._shortcutToolbar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this._shortcutToolbar.Location = new System.Drawing.Point(0, 39); this._shortcutToolbar.Name = "_shortcutToolbar"; this._shortcutToolbar.Size = new System.Drawing.Size(584, 25); this._shortcutToolbar.Stretch = true; this._shortcutToolbar.TabIndex = 1; // // XnatWebBrowserComponentControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.toolStripContainer1); this.Name = "WebBrowserComponentControl"; this.Size = new System.Drawing.Size(584, 526); this.toolStripContainer1.BottomToolStripPanel.ResumeLayout(false); this.toolStripContainer1.BottomToolStripPanel.PerformLayout(); this.toolStripContainer1.ContentPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.PerformLayout(); this.toolStripContainer1.ResumeLayout(false); this.toolStripContainer1.PerformLayout(); this._statusBar.ResumeLayout(false); this._statusBar.PerformLayout(); this._toolbar.ResumeLayout(false); this._toolbar.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.WebBrowser _browser; private System.Windows.Forms.ToolStripContainer toolStripContainer1; private System.Windows.Forms.ToolStrip _toolbar; private System.Windows.Forms.ToolStripButton _back; private System.Windows.Forms.ToolStripButton _forward; private System.Windows.Forms.ToolStripButton _stop; private System.Windows.Forms.ToolStripButton _refresh; private System.Windows.Forms.ToolStripComboBox _address; private System.Windows.Forms.ToolStripButton _go; private System.Windows.Forms.ToolStripLabel _progressLogo; private System.Windows.Forms.StatusStrip _statusBar; private System.Windows.Forms.ToolStripStatusLabel _browserStatus; private System.Windows.Forms.ToolStripProgressBar _browserProgress; private System.Windows.Forms.ToolStrip _shortcutToolbar; } }
using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using DeOps.Implementation.Dht; using DeOps.Implementation.Protocol.Net; using DeOps.Services.Location; namespace DeOps.Implementation.Protocol.Special { public class TunnelPacket : G2Packet { const byte Packet_Source = 0x10; const byte Packet_Target = 0x20; const byte Packet_SourceServer = 0x30; const byte Packet_TargetServer = 0x40; public TunnelAddress Source; public TunnelAddress Target; public DhtAddress SourceServer; public DhtAddress TargetServer; public byte[] Payload; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame tunnel = protocol.WritePacket(null, RootPacket.Tunnel, Payload); protocol.WritePacket(tunnel, Packet_Source, Source.ToBytes()); protocol.WritePacket(tunnel, Packet_Target, Target.ToBytes()); if (SourceServer != null) SourceServer.WritePacket(protocol, tunnel, Packet_SourceServer); if (TargetServer != null) TargetServer.WritePacket(protocol, tunnel, Packet_TargetServer); return protocol.WriteFinish(); } } public static TunnelPacket Decode(G2Header root) { TunnelPacket tunnel = new TunnelPacket(); if (G2Protocol.ReadPayload(root)) tunnel.Payload = Utilities.ExtractBytes(root.Data, root.PayloadPos, root.PayloadSize); G2Protocol.ResetPacket(root); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Source: tunnel.Source = TunnelAddress.FromBytes(child.Data, child.PayloadPos); break; case Packet_Target: tunnel.Target = TunnelAddress.FromBytes(child.Data, child.PayloadPos); break; case Packet_SourceServer: tunnel.SourceServer = DhtAddress.ReadPacket(child); break; case Packet_TargetServer: tunnel.TargetServer = DhtAddress.ReadPacket(child); break; } } return tunnel; } } public class InvitePacket { public const byte Info = 0x10; public const byte Contact = 0x20; public const byte WebCache = 0x30; } public class OneWayInvite : G2Packet { const byte Packet_UserName = 0x10; const byte Packet_OpName = 0x20; const byte Packet_OpAccess = 0x30; const byte Packet_OpID = 0x40; public string UserName; public string OpName; public AccessType OpAccess; public byte[] OpID; public List<DhtContact> Contacts = new List<DhtContact>(); public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame invite = protocol.WritePacket(null, InvitePacket.Info, null); protocol.WritePacket(invite, Packet_UserName, UTF8Encoding.UTF8.GetBytes(UserName)); protocol.WritePacket(invite, Packet_OpName, UTF8Encoding.UTF8.GetBytes(OpName)); protocol.WritePacket(invite, Packet_OpAccess, BitConverter.GetBytes((byte)OpAccess)); protocol.WritePacket(invite, Packet_OpID, OpID); return protocol.WriteFinish(); } } public static OneWayInvite Decode(G2Header root) { OneWayInvite invite = new OneWayInvite(); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_UserName: invite.UserName = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_OpName: invite.OpName = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_OpAccess: invite.OpAccess = (AccessType)child.Data[child.PayloadPos]; break; case Packet_OpID: invite.OpID = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); break; } } return invite; } } public class FilePacket { public const byte SubHash = 0x10; } public class SubHashPacket : G2Packet { const byte Packet_ChunkSize = 0x10; const byte Packet_TotalCount = 0x20; const byte Packet_SubHashes = 0x30; public int ChunkSize; // in KB, 128kb chunks public int TotalCount; public byte[] SubHashes; // 100 chunks per packet - 10*200 = 2,000kb packets public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame subhash = protocol.WritePacket(null, FilePacket.SubHash, null); protocol.WritePacket(subhash, Packet_ChunkSize, BitConverter.GetBytes(ChunkSize)); protocol.WritePacket(subhash, Packet_TotalCount, BitConverter.GetBytes(TotalCount)); protocol.WritePacket(subhash, Packet_SubHashes, SubHashes); return protocol.WriteFinish(); } } public static SubHashPacket Decode(G2Header root) { SubHashPacket subhash = new SubHashPacket(); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_ChunkSize: subhash.ChunkSize = BitConverter.ToInt32(child.Data, child.PayloadPos); break; case Packet_TotalCount: subhash.TotalCount = BitConverter.ToInt32(child.Data, child.PayloadPos); break; case Packet_SubHashes: subhash.SubHashes = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); break; } } return subhash; } } public class LargeDataPacket : G2Packet { const byte Packet_Size= 0x10; const byte Packet_Hash = 0x20; byte Name; public int Size; public byte[] Hash; public byte[] Data; public LargeDataPacket(byte name, int size, byte[] hash) { Name = name; Size = size; Hash = hash; } public LargeDataPacket(byte name, byte[] data) { Name = name; Data = data; } public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { // first packet is size if (Size > 0) { G2Frame split = protocol.WritePacket(null, Name, null); protocol.WritePacket(split, Packet_Size, BitConverter.GetBytes(Size)); if(Hash != null) protocol.WritePacket(split, Packet_Hash, Hash); } // following packets are data else protocol.WritePacket(null, Name, Data); return protocol.WriteFinish(); } } public static bool Decode(G2Header root, byte[] destination, ref int pos) { // data packet if (G2Protocol.ReadPayload(root)) { Buffer.BlockCopy(root.Data, root.PayloadPos, destination, pos, root.PayloadSize); pos += root.PayloadSize; return true; } return false; } public static LargeDataPacket Decode(G2Header root) { LargeDataPacket packet = new LargeDataPacket(root.Name, 0, null); // size packet G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; if (child.Name == Packet_Size) packet.Size = BitConverter.ToInt32(child.Data, child.PayloadPos); if (child.Name == Packet_Hash) packet.Hash = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); } return packet; } public static void Write(PacketStream stream, byte name, byte[] data) { // empty file if (data == null) { stream.WritePacket(new LargeDataPacket(name, 0, null)); return; } // write header packet byte[] hash = new SHA1Managed().ComputeHash(data); stream.WritePacket(new LargeDataPacket(name, data.Length, hash)); int pos = 0; int left = data.Length; while (left > 0) { int amount = (left > 2000) ? 2000 : left; left -= amount; stream.WritePacket(new LargeDataPacket(name, Utilities.ExtractBytes(data, pos, amount))); pos += amount; } } public static byte[] Read(LargeDataPacket start, PacketStream stream, byte name) { byte[] data = new byte[start.Size]; int pos = 0; G2Header root = null; while (stream.ReadPacket(ref root)) if (root.Name == name) { if (!LargeDataPacket.Decode(root, data, ref pos)) break; // done, break if (pos == start.Size) break; } // unknown packet, break else break; if (start != null && data != null) if(Utilities.MemCompare(start.Hash, new SHA1Managed().ComputeHash(data))) return data; return null; } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using FlatRedBall.AI.Pathfinding; using FlatRedBall.Gui; using FlatRedBall.Input; using FlatRedBall.Math; using EditorObjects; using AIEditor.Gui; using FlatRedBall.Math.Geometry; using FlatRedBall.Content.Polygon; using FlatRedBall.Content.AI.Pathfinding; #if FRB_XNA using Keys = Microsoft.Xna.Framework.Input.Keys; using FlatRedBall.IO; using EditorObjects.EditorSettings; #endif namespace AIEditor { public static class EditorData { #region Fields public const string ContentManagerName = "PolygonEditor Content Manager"; static Scene mScene = new Scene(); //static PositionedObjectList<Polygon> mPolygonList; static ShapeCollection mShapeCollection = new ShapeCollection(); static NodeNetwork mNodeNetwork = new NodeNetwork(); static EditingLogic mEditingLogic; public static EditorProperties EditorProperties = new EditorProperties(); #region XML Docs /// <summary> /// Displays the X and Y axes to help the user find the origin. /// </summary> #endregion static WorldAxesDisplay mWorldAxesDisplay; #endregion #region Properties public static EditingLogic EditingLogic { get { return mEditingLogic; } } public static string LastLoadedFile { get; set; } public static NodeNetwork NodeNetwork { get { return mNodeNetwork; } set { // Need to clean up the old NodeNetwork mNodeNetwork = value; mNodeNetwork.Visible = true; GuiData.NodeNetworkPropertyGrid.SelectedObject = mNodeNetwork; } } public static Scene Scene { get { return mScene; } //set //{ // if (mScene != null) // { // FlatRedBallServices.Unload(ContentManagerName); // SpriteManager.RemoveScene(mScene, true); // } // mScene = value; // SpriteManager.AddScene(mScene); //} } public static ShapeCollection ShapeCollection { get { return mShapeCollection; } } #endregion #region Methods #region Public Methods public static void CloseCurrentScene() { mScene.RemoveFromManagers(true); } public static void CreateNew() { RemoveNodeNetwork(); } public static void Initialize() { mWorldAxesDisplay = new WorldAxesDisplay(); mEditingLogic = new EditingLogic(); #if FRB_MDX Form1.TitleText = "AIEditor - Editing unsaved file"; #else FlatRedBallServices.Owner.Text = "AIEditor - Editing unsaved file"; #endif } public static void LoadNodeNetwork(string fileName, bool copyYToZ, bool flipY, bool makeYZero) { RemoveNodeNetwork(); FlatRedBall.Content.AI.Pathfinding.NodeNetworkSave nodeNetworkSave = FlatRedBall.Content.AI.Pathfinding.NodeNetworkSave.FromFile(fileName); string possibleCompanionFile = FileManager.RemoveExtension(fileName) + "." + AIEditorPropertiesSave.Extension; if (FileManager.FileExists(possibleCompanionFile)) { AIEditorPropertiesSave aieps = AIEditorPropertiesSave.Load(possibleCompanionFile); if (aieps.Camera != null) { aieps.Camera.SetCamera(SpriteManager.Camera); } //if(aieps.BoundsCamera != null) //{ // aieps.BoundsCamera.SetCamera( } #region Modify loaded NodeNetwork if necessary (copyYToZ, flipY, makeYZero) if (copyYToZ) { foreach (PositionedNodeSave pns in nodeNetworkSave.PositionedNodes) { pns.Y = pns.Z; } } if (flipY) { foreach (PositionedNodeSave pns in nodeNetworkSave.PositionedNodes) { pns.Y = -pns.Y; } } if (makeYZero) { foreach (PositionedNodeSave pns in nodeNetworkSave.PositionedNodes) { pns.Z = 0; } } #endregion LastLoadedFile = fileName; #if FRB_MDX Form1.TitleText = "AIEditor - Editing " + fileName; #else FlatRedBallServices.Owner.Text = "AIEditor - Editing " + fileName; #endif string error; NodeNetwork = nodeNetworkSave.ToNodeNetwork(out error); if (!string.IsNullOrEmpty(error)) { System.Windows.Forms.MessageBox.Show(error); } } public static void LoadPolygonList(string fileName) { ShapeManager.Remove<Polygon>( mShapeCollection.Polygons); PolygonSaveList polygonSaveList = PolygonSaveList.FromFile(fileName); mShapeCollection.Polygons.AddRange( polygonSaveList.ToPolygonList()); ShapeManager.AddPolygonList(mShapeCollection.Polygons); LastLoadedFile = fileName; } public static void LoadScene(string fileName) { if (mScene != null) { FlatRedBallServices.Unload(ContentManagerName); SpriteManager.RemoveScene(mScene, true); } FlatRedBall.Content.SpriteEditorScene ses = FlatRedBall.Content.SpriteEditorScene.FromFile(fileName); mScene = ses.ToScene(EditorData.ContentManagerName); SpriteManager.AddScene(mScene); LastLoadedFile = fileName; } public static void LoadShapeCollection(string fileName) { bool replace = true; if (replace) { mShapeCollection.RemoveFromManagers(); mShapeCollection.Clear(); mShapeCollection = FlatRedBallServices.Load<ShapeCollection>(fileName, ContentManagerName); mShapeCollection.AddToManagers(); LastLoadedFile = fileName; } } public static void Update() { mEditingLogic.Update(); PerformKeyboardShortcuts(); //PerformMouseCameraControl(); mNodeNetwork.UpdateShapes(); } #endregion #region Private Methods private static void PerformKeyboardShortcuts() { if (InputManager.ReceivingInput != null) return; InputManager.Keyboard.ControlPositionedObject(SpriteManager.Camera, SpriteManager.Camera.Z * -.6f); GuiData.ToolsWindow.ListenForShortcuts(); if ((InputManager.Keyboard.KeyDown(Keys.LeftControl) || InputManager.Keyboard.KeyDown(Keys.RightControl)) && InputManager.Keyboard.KeyPushed(Keys.C)) { mEditingLogic.CopyCurrentPositionedNodes(); } } private static void RemoveNodeNetwork() { if (mNodeNetwork != null) { mNodeNetwork.Visible = false; } // The editor depends on the NodeNetwork not being null mNodeNetwork = new NodeNetwork(); } #endregion #endregion } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Candles.Algo File: CandleManager.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Candles { using System; using System.Collections.Generic; using System.Linq; using Ecng.Collections; using Ecng.Common; using Ecng.ComponentModel; using MoreLinq; using StockSharp.Algo.Storages; using StockSharp.Algo.Candles.Compression; using StockSharp.Logging; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// The candles manager. /// </summary> public class CandleManager : BaseLogReceiver, ICandleManager { private sealed class CandleManagerSourceList : SynchronizedList<ICandleManagerSource>, ICandleManagerSourceList { private sealed class SourceInfo : Disposable { private readonly ICandleManagerSource _source; private readonly CandleManager _manager; public SourceInfo(ICandleManagerSource source, CandleManager manager) { if (source == null) throw new ArgumentNullException(nameof(source)); _source = source; _manager = manager; _source.Processing += OnProcessing; _source.Error += _manager.RaiseError; _source.CandleManager = _manager; } private void OnProcessing(CandleSeries series, Candle candle) { //if (candle.Series == null) //{ // candle.Series = series; // candle.Source = _source; //} _manager.Container.AddCandle(series, candle); } protected override void DisposeManaged() { base.DisposeManaged(); _source.Processing -= OnProcessing; _source.Error -= _manager.RaiseError; _source.Dispose(); } } private readonly SynchronizedDictionary<ICandleManagerSource, SourceInfo> _info = new SynchronizedDictionary<ICandleManagerSource,SourceInfo>(); private readonly CandleManager _manager; public CandleManagerSourceList(CandleManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); _manager = manager; } protected override void OnAdded(ICandleManagerSource item) { Subscribe(item); base.OnAdded(item); } protected override bool OnRemoving(ICandleManagerSource item) { UnSubscribe(item); return base.OnRemoving(item); } protected override void OnInserted(int index, ICandleManagerSource item) { Subscribe(item); base.OnInserted(index, item); } protected override bool OnClearing() { foreach (var item in this) UnSubscribe(item); return base.OnClearing(); } private void Subscribe(ICandleManagerSource source) { _info.Add(source, new SourceInfo(source, _manager)); } private void UnSubscribe(ICandleManagerSource source) { lock (_info.SyncRoot) { var info = _info[source]; info.Dispose(); _info.Remove(source); } } } private sealed class ExternalCandleSource : Disposable, ICandleManagerSource { private readonly HashSet<CandleSeries> _series = new HashSet<CandleSeries>(); private readonly IExternalCandleSource _source; public ExternalCandleSource(IExternalCandleSource source) { if (source == null) throw new ArgumentNullException(nameof(source)); _source = source; _source.NewCandles += OnNewCandles; _source.Stopped += OnStopped; } public int SpeedPriority => 1; public event Action<CandleSeries, Candle> Processing; public event Action<CandleSeries> Stopped; event Action<Exception> ICandleSource<Candle>.Error { add { } remove { } } IEnumerable<Range<DateTimeOffset>> ICandleSource<Candle>.GetSupportedRanges(CandleSeries series) { return _source.GetSupportedRanges(series); } void ICandleSource<Candle>.Start(CandleSeries series, DateTimeOffset from, DateTimeOffset to) { _series.Add(series); _source.SubscribeCandles(series, from, to); } void ICandleSource<Candle>.Stop(CandleSeries series) { _series.Remove(series); _source.UnSubscribeCandles(series); } private void OnNewCandles(CandleSeries series, IEnumerable<Candle> candles) { if (!_series.Contains(series)) return; foreach (var c in candles) { var candle = c.Clone(); candle.State = CandleStates.Active; Processing?.Invoke(series, candle); candle.State = CandleStates.Finished; Processing?.Invoke(series, candle); } } private void OnStopped(CandleSeries series) { Stopped?.Invoke(series); } /// <summary> /// Release resources. /// </summary> protected override void DisposeManaged() { _source.NewCandles -= OnNewCandles; _source.Stopped -= OnStopped; base.DisposeManaged(); } ICandleManager ICandleManagerSource.CandleManager { get; set; } } private readonly SynchronizedDictionary<CandleSeries, CandleSourceEnumerator<ICandleManagerSource, Candle>> _series = new SynchronizedDictionary<CandleSeries, CandleSourceEnumerator<ICandleManagerSource, Candle>>(); /// <summary> /// Initializes a new instance of the <see cref="CandleManager"/>. /// </summary> public CandleManager() { var builderContainer = new CandleBuilderContainer(); Sources = new CandleManagerSourceList(this) { new StorageCandleSource(), new TimeFrameCandleBuilder(builderContainer), new TickCandleBuilder(builderContainer), new VolumeCandleBuilder(builderContainer), new RangeCandleBuilder(builderContainer), new RenkoCandleBuilder(builderContainer), new PnFCandleBuilder(builderContainer), }; } /// <summary> /// Initializes a new instance of the <see cref="CandleManager"/>. /// </summary> /// <param name="builderSource">The data source for <see cref="ICandleBuilder"/>.</param> public CandleManager(ICandleBuilderSource builderSource) : this() { if (builderSource == null) throw new ArgumentNullException(nameof(builderSource)); Sources.OfType<ICandleBuilder>().ForEach(b => b.Sources.Add(builderSource)); } /// <summary> /// Initializes a new instance of the <see cref="CandleManager"/>. /// </summary> /// <param name="connector">The connection to trading system to create the source for tick trades by default.</param> public CandleManager(IConnector connector) : this(new TradeCandleBuilderSource(connector)) { var externalSource = connector as IExternalCandleSource; if (externalSource != null) Sources.Add(new ExternalCandleSource(externalSource)); } private ICandleManagerContainer _container = new CandleManagerContainer(); /// <summary> /// The data container. /// </summary> public ICandleManagerContainer Container { get { return _container; } set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value == _container) return; _container.Dispose(); _container = value; } } private IStorageRegistry _storageRegistry; /// <summary> /// The data storage. To be sent to all sources that implement the interface <see cref="IStorageCandleSource"/>. /// </summary> public IStorageRegistry StorageRegistry { get { return _storageRegistry; } set { _storageRegistry = value; Sources.OfType<IStorageCandleSource>().ForEach(s => s.StorageRegistry = value); } } /// <summary> /// All currently active candles series started via <see cref="Start"/>. /// </summary> public IEnumerable<CandleSeries> Series { get { return _series.SyncGet(d => d.Keys.ToArray()); } } /// <summary> /// Candles sources. /// </summary> public ICandleManagerSourceList Sources { get; } /// <summary> /// The source priority by speed (0 - the best). /// </summary> public int SpeedPriority { get { throw new NotSupportedException(); } } /// <summary> /// A new value for processing occurrence event. /// </summary> public event Action<CandleSeries, Candle> Processing; /// <summary> /// The series processing end event. /// </summary> public event Action<CandleSeries> Stopped; /// <summary> /// The candles creating error event. /// </summary> public event Action<Exception> Error; /// <summary> /// To get time ranges for which this source of passed candles series has data. /// </summary> /// <param name="series">Candles series.</param> /// <returns>Time ranges.</returns> public virtual IEnumerable<Range<DateTimeOffset>> GetSupportedRanges(CandleSeries series) { if (series == null) throw new ArgumentNullException(nameof(series)); return Sources.SelectMany(s => s.GetSupportedRanges(series)).JoinRanges().ToArray(); } /// <summary> /// To send data request. /// </summary> /// <param name="series">The candles series for which data receiving should be started.</param> /// <param name="from">The initial date from which you need to get data.</param> /// <param name="to">The final date by which you need to get data.</param> public virtual void Start(CandleSeries series, DateTimeOffset from, DateTimeOffset to) { if (series == null) throw new ArgumentNullException(nameof(series)); CandleSourceEnumerator<ICandleManagerSource, Candle> enumerator; lock (_series.SyncRoot) { if (_series.ContainsKey(series)) throw new ArgumentException(LocalizedStrings.Str650Params.Put(series), nameof(series)); enumerator = new CandleSourceEnumerator<ICandleManagerSource, Candle>(series, from, to, series.Security is IndexSecurity ? (IEnumerable<ICandleManagerSource>)new[] { new IndexSecurityCandleManagerSource(this, from, to) } : Sources, c => { Processing?.Invoke(series, c); return c.OpenTime; }, () => { //Stop(series); _series.Remove(series); Stopped?.Invoke(series); }); _series.Add(series, enumerator); //series.CandleManager = this; series.From = from; series.To = to; Container.Start(series, from, to); } enumerator.Start(); } /// <summary> /// To stop data receiving starting through <see cref="Start"/>. /// </summary> /// <param name="series">Candles series.</param> public virtual void Stop(CandleSeries series) { if (series == null) throw new ArgumentNullException(nameof(series)); var enumerator = _series.TryGetValue(series); if (enumerator == null) return; enumerator.Stop(); } /// <summary> /// To call the event <see cref="CandleManager.Error"/>. /// </summary> /// <param name="error">Error info.</param> protected virtual void RaiseError(Exception error) { Error?.Invoke(error); this.AddErrorLog(error); } /// <summary> /// Release resources. /// </summary> protected override void DisposeManaged() { lock (Sources.SyncRoot) { Sources.ForEach(s => s.Dispose()); Sources.Clear(); } Container.Dispose(); base.DisposeManaged(); } } }
// Copyright 2016 Google Inc. 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. // The controller is not available for versions of Unity without the // GVR native integration. using UnityEngine; #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) using UnityEngine.VR; using System; using System.Collections; using Gvr.Internal; /// Represents the controller's current connection state. /// All values and semantics below (except for Error) are /// from gvr_types.h in the GVR C API. public enum GvrConnectionState { /// Indicates that an error has occurred. Error = -1, /// Indicates that the controller is disconnected. Disconnected = 0, /// Indicates that the device is scanning for controllers. Scanning = 1, /// Indicates that the device is connecting to a controller. Connecting = 2, /// Indicates that the device is connected to a controller. Connected = 3, }; /// Represents the API status of the current controller state. /// Values and semantics from gvr_types.h in the GVR C API. public enum GvrControllerApiStatus { /// A Unity-localized error occurred. /// This is the only value that isn't in gvr_types.h. Error = -1, /// API is happy and healthy. This doesn't mean the controller itself /// is connected, it just means that the underlying service is working /// properly. Ok = 0, /// Any other status represents a permanent failure that requires /// external action to fix: /// API failed because this device does not support controllers (API is too /// low, or other required feature not present). Unsupported = 1, /// This app was not authorized to use the service (e.g., missing permissions, /// the app is blacklisted by the underlying service, etc). NotAuthorized = 2, /// The underlying VR service is not present. Unavailable = 3, /// The underlying VR service is too old, needs upgrade. ApiServiceObsolete = 4, /// The underlying VR service is too new, is incompatible with current client. ApiClientObsolete = 5, /// The underlying VR service is malfunctioning. Try again later. ApiMalfunction = 6, }; /// Represents the controller's current battery level. /// Values and semantics from gvr_types.h in the GVR C API. public enum GvrControllerBatteryLevel { /// A Unity-localized error occurred. /// This is the only value that isn't in gvr_types.h. Error = -1, /// The battery state is currently unreported Unknown = 0, /// Equivalent to 1 out of 5 bars on the battery indicator CriticalLow = 1, /// Equivalent to 2 out of 5 bars on the battery indicator Low = 2, /// Equivalent to 3 out of 5 bars on the battery indicator Medium = 3, /// Equivalent to 4 out of 5 bars on the battery indicator AlmostFull = 4, /// Equivalent to 5 out of 5 bars on the battery indicator Full = 5, }; #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) /// Main entry point for the Daydream controller API. /// /// To use this API, add this behavior to a GameObject in your scene, or use the /// GvrControllerMain prefab. There can only be one object with this behavior on your scene. /// /// This is a singleton object. /// /// To access the controller state, simply read the static properties of this class. For example, /// to know the controller's current orientation, use GvrController.Orientation. public class GvrController : MonoBehaviour { #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) private static GvrController instance; private static IControllerProvider controllerProvider; private ControllerState controllerState = new ControllerState(); private IEnumerator controllerUpdate; private WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame(); /// Event handler for receiving button, track pad, and IMU updates from the controller. public delegate void OnControllerUpdateEvent(); public event OnControllerUpdateEvent OnControllerUpdate; public enum EmulatorConnectionMode { OFF, USB, WIFI, } /// Indicates how we connect to the controller emulator. [Tooltip("How to connect to the emulator: USB cable (recommended) or WIFI.")] public EmulatorConnectionMode emulatorConnectionMode = EmulatorConnectionMode.USB; /// Returns the arm model instance associated with the controller. public static GvrArmModel ArmModel { get { return instance != null ? instance.GetComponent<GvrArmModel>() : null; } } /// Returns the controller's current connection state. public static GvrConnectionState State { get { return instance != null ? instance.controllerState.connectionState : GvrConnectionState.Error; } } /// Returns the API status of the current controller state. public static GvrControllerApiStatus ApiStatus { get { return instance != null ? instance.controllerState.apiStatus : GvrControllerApiStatus.Error; } } /// Returns the controller's current orientation in space, as a quaternion. /// The space in which the orientation is represented is the usual Unity space, with /// X pointing to the right, Y pointing up and Z pointing forward. Therefore, to make an /// object in your scene have the same orientation as the controller, simply assign this /// quaternion to the GameObject's transform.rotation. public static Quaternion Orientation { get { return instance != null ? instance.controllerState.orientation : Quaternion.identity; } } /// Returns the controller's gyroscope reading. The gyroscope indicates the angular /// about each of its local axes. The controller's axes are: X points to the right, /// Y points perpendicularly up from the controller's top surface and Z lies /// along the controller's body, pointing towards the front. The angular speed is given /// in radians per second, using the right-hand rule (positive means a right-hand rotation /// about the given axis). public static Vector3 Gyro { get { return instance != null ? instance.controllerState.gyro : Vector3.zero; } } /// Returns the controller's accelerometer reading. The accelerometer indicates the /// effect of acceleration and gravity in the direction of each of the controller's local /// axes. The controller's local axes are: X points to the right, Y points perpendicularly /// up from the controller's top surface and Z lies along the controller's body, pointing /// towards the front. The acceleration is measured in meters per second squared. Note that /// gravity is combined with acceleration, so when the controller is resting on a table top, /// it will measure an acceleration of 9.8 m/s^2 on the Y axis. The accelerometer reading /// will be zero on all three axes only if the controller is in free fall, or if the user /// is in a zero gravity environment like a space station. public static Vector3 Accel { get { return instance != null ? instance.controllerState.accel : Vector3.zero; } } /// If true, the user is currently touching the controller's touchpad. public static bool IsTouching { get { return instance != null ? instance.controllerState.isTouching : false; } } /// If true, the user just started touching the touchpad. This is an event flag (it is true /// for only one frame after the event happens, then reverts to false). public static bool TouchDown { get { return instance != null ? instance.controllerState.touchDown : false; } } /// If true, the user just stopped touching the touchpad. This is an event flag (it is true /// for only one frame after the event happens, then reverts to false). public static bool TouchUp { get { return instance != null ? instance.controllerState.touchUp : false; } } public static Vector2 TouchPos { get { return instance != null ? instance.controllerState.touchPos : Vector2.zero; } } /// If true, the user is currently performing the recentering gesture. Most apps will want /// to pause the interaction while this remains true. public static bool Recentering { get { return instance != null ? instance.controllerState.recentering : false; } } /// If true, the user just completed the recenter gesture. The controller's orientation is /// now being reported in the new recentered coordinate system (the controller's orientation /// when recentering was completed was remapped to mean "forward"). This is an event flag /// (it is true for only one frame after the event happens, then reverts to false). /// The headset is recentered together with the controller. public static bool Recentered { get { return instance != null ? instance.controllerState.recentered : false; } } /// If true, the click button (touchpad button) is currently being pressed. This is not /// an event: it represents the button's state (it remains true while the button is being /// pressed). public static bool ClickButton { get { return instance != null ? instance.controllerState.clickButtonState : false; } } /// If true, the click button (touchpad button) was just pressed. This is an event flag: /// it will be true for only one frame after the event happens. public static bool ClickButtonDown { get { return instance != null ? instance.controllerState.clickButtonDown : false; } } /// If true, the click button (touchpad button) was just released. This is an event flag: /// it will be true for only one frame after the event happens. public static bool ClickButtonUp { get { return instance != null ? instance.controllerState.clickButtonUp : false; } } /// If true, the app button (touchpad button) is currently being pressed. This is not /// an event: it represents the button's state (it remains true while the button is being /// pressed). public static bool AppButton { get { return instance != null ? instance.controllerState.appButtonState : false; } } /// If true, the app button was just pressed. This is an event flag: it will be true for /// only one frame after the event happens. public static bool AppButtonDown { get { return instance != null ? instance.controllerState.appButtonDown : false; } } /// If true, the app button was just released. This is an event flag: it will be true for /// only one frame after the event happens. public static bool AppButtonUp { get { return instance != null ? instance.controllerState.appButtonUp : false; } } // Always false in the emulator. public static bool HomeButtonDown { get { return instance != null ? instance.controllerState.homeButtonDown : false; } } // Always false in the emulator. public static bool HomeButtonState { get { return instance != null ? instance.controllerState.homeButtonState : false; } } /// If State == GvrConnectionState.Error, this contains details about the error. public static string ErrorDetails { get { if (instance != null) { return instance.controllerState.connectionState == GvrConnectionState.Error ? instance.controllerState.errorDetails : ""; } else { return "GvrController instance not found in scene. It may be missing, or it might " + "not have initialized yet."; } } } // Returns the GVR C library controller state pointer (gvr_controller_state*). public static IntPtr StatePtr { get { return instance != null? instance.controllerState.gvrPtr : IntPtr.Zero; } } /// If true, the user is currently touching the controller's touchpad. public static bool IsCharging { get { return instance != null ? instance.controllerState.isCharging : false; } } /// If true, the user is currently touching the controller's touchpad. public static GvrControllerBatteryLevel BatteryLevel { get { return instance != null ? instance.controllerState.batteryLevel : GvrControllerBatteryLevel.Error; } } void Awake() { if (instance != null) { Debug.LogError("More than one GvrController instance was found in your scene. " + "Ensure that there is only one GvrController."); this.enabled = false; return; } instance = this; if (controllerProvider == null) { controllerProvider = ControllerProviderFactory.CreateControllerProvider(this); } // Keep screen on here, in case there isn't a GvrViewerMain prefab in the scene. // This ensures the behaviour for: // (a) Cardboard apps on pre-integration Unity versions - they must have GvrViewerMain in a scene. // (b) Daydream apps - these must be on GVR-integrated Unity versions, and must have GvrControllerMain. // Cardboard-only apps on the native integration are likely to have GvrViewerMain in their scene; otherwise, // the line below can be added to any script of the developer's choice. Screen.sleepTimeout = SleepTimeout.NeverSleep; } void OnDestroy() { instance = null; } private void UpdateController() { controllerProvider.ReadState(controllerState); #if UNITY_EDITOR // If a headset recenter was requested, do it now. if (controllerState.recentered) { GvrViewer sdk = GvrViewer.Instance; if (sdk) { sdk.Recenter(); } else { for (int i = 0; i < Camera.allCameras.Length; i++) { Camera cam = Camera.allCameras[i]; // Do not reset pitch, which is how it works on the device. cam.transform.rotation = Quaternion.Euler(cam.transform.rotation.eulerAngles.x, 0, 0); } } } #endif // UNITY_EDITOR } void OnApplicationPause(bool paused) { if (null == controllerProvider) return; if (paused) { controllerProvider.OnPause(); } else { controllerProvider.OnResume(); } } void OnEnable() { controllerUpdate = EndOfFrame(); StartCoroutine(controllerUpdate); } void OnDisable() { StopCoroutine(controllerUpdate); } IEnumerator EndOfFrame() { while (true) { // This must be done at the end of the frame to ensure that all GameObjects had a chance // to read transient controller state (e.g. events, etc) for the current frame before // it gets reset. yield return waitForEndOfFrame; UpdateController(); if (OnControllerUpdate != null) { OnControllerUpdate(); } } } #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) }
/* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using Common.Logging; using Quartz; using Quartz.Simpl; using Quartz.Xml; using Spring.Collections; using Spring.Context; using Spring.Core.IO; using Spring.Transaction; using Spring.Transaction.Support; namespace Spring.Scheduling.Quartz { /// <summary> /// Common base class for accessing a Quartz Scheduler, i.e. for registering jobs, /// triggers and listeners on a <see cref="IScheduler" /> instance. /// </summary> /// <remarks> /// For concrete usage, check out the <see cref="SchedulerFactoryObject" /> and /// <see cref="SchedulerAccessorObject" /> classes. ///</remarks> /// <author>Juergen Hoeller</author> /// <author>Marko Lahma (.NET)</author> public abstract class SchedulerAccessor : IResourceLoaderAware { /// <summary> /// Logger instance. /// </summary> private readonly ILog logger; private bool overwriteExistingJobs; private string[] jobSchedulingDataLocations; private IList jobDetails; private IDictionary calendars; private IList triggers; private ISchedulerListener[] schedulerListeners; private IJobListener[] globalJobListeners; private IJobListener[] jobListeners; private ITriggerListener[] globalTriggerListeners; private ITriggerListener[] triggerListeners; private IPlatformTransactionManager transactionManager; /// <summary> /// Resource loader instance for sub-classes /// </summary> private IResourceLoader resourceLoader; /// <summary> /// Initializes a new instance of the <see cref="SchedulerAccessor"/> class. /// </summary> protected SchedulerAccessor() { logger = LogManager.GetLogger(GetType()); } /// <summary> /// Set whether any jobs defined on this SchedulerFactoryObject should overwrite /// existing job definitions. Default is "false", to not overwrite already /// registered jobs that have been read in from a persistent job store. /// </summary> public virtual bool OverwriteExistingJobs { set { overwriteExistingJobs = value; } } /// <summary> /// Set the locations of Quartz job definition XML files that follow the /// "job_scheduling_data_1_5" XSD. Can be specified to automatically /// register jobs that are defined in such files, possibly in addition /// to jobs defined directly on this SchedulerFactoryObject. /// </summary> /// <seealso cref="XMLSchedulingDataProcessor" /> public virtual string[] JobSchedulingDataLocations { set { jobSchedulingDataLocations = value; } } /// <summary> /// Set the location of a Quartz job definition XML file that follows the /// "job_scheduling_data" XSD. Can be specified to automatically /// register jobs that are defined in such a file, possibly in addition /// to jobs defined directly on this SchedulerFactoryObject. /// </summary> /// <seealso cref="XMLSchedulingDataProcessor" /> public virtual string JobSchedulingDataLocation { set { jobSchedulingDataLocations = new string[] {value}; } } /// <summary> /// Register a list of JobDetail objects with the Scheduler that /// this FactoryObject creates, to be referenced by Triggers. /// This is not necessary when a Trigger determines the JobDetail /// itself: In this case, the JobDetail will be implicitly registered /// in combination with the Trigger. /// </summary> /// <seealso cref="Triggers" /> /// <seealso cref="IJobDetail" /> /// <seealso cref="JobDetailObject" /> /// <seealso cref="IJobDetailAwareTrigger" /> /// <seealso cref="ITrigger.JobKey" /> public virtual IJobDetail[] JobDetails { set { // Use modifiable ArrayList here, to allow for further adding of // JobDetail objects during autodetection of JobDetailAwareTriggers. jobDetails = new List<IJobDetail>(value); } } /// <summary> /// Register a list of Quartz ICalendar objects with the Scheduler /// that this FactoryObject creates, to be referenced by Triggers. /// </summary> /// <value>Map with calendar names as keys as Calendar objects as values</value> /// <seealso cref="ICalendar" /> /// <seealso cref="ITrigger.CalendarName" /> public virtual IDictionary Calendars { set { calendars = value; } } /// <summary> /// Register a list of Trigger objects with the Scheduler that /// this FactoryObject creates. /// </summary> /// <remarks> /// If the Trigger determines the corresponding JobDetail itself, /// the job will be automatically registered with the Scheduler. /// Else, the respective JobDetail needs to be registered via the /// "jobDetails" property of this FactoryObject. /// </remarks> /// <seealso cref="JobDetails" /> /// <seealso cref="IJobDetail" /> /// <seealso cref="IJobDetailAwareTrigger" /> /// <seealso cref="CronTriggerObject" /> /// <seealso cref="SimpleTriggerObject" /> public virtual ITrigger[] Triggers { set { triggers = new ArrayList(value); } } /// <summary> /// Specify Quartz SchedulerListeners to be registered with the Scheduler. /// </summary> public virtual ISchedulerListener[] SchedulerListeners { set { schedulerListeners = value; } } /// <summary> /// Specify global Quartz JobListeners to be registered with the Scheduler. /// Such JobListeners will apply to all Jobs in the Scheduler. /// </summary> public virtual IJobListener[] GlobalJobListeners { set { globalJobListeners = value; } } /// <summary> /// Specify named Quartz JobListeners to be registered with the Scheduler. /// Such JobListeners will only apply to Jobs that explicitly activate /// them via their name. /// </summary> /// <seealso cref="IJobListener.Name" /> public virtual IJobListener[] JobListeners { set { jobListeners = value; } } /// <summary> /// Specify global Quartz TriggerListeners to be registered with the Scheduler. /// Such TriggerListeners will apply to all Triggers in the Scheduler. /// </summary> public virtual ITriggerListener[] GlobalTriggerListeners { set { globalTriggerListeners = value; } } /// <summary> /// Specify named Quartz TriggerListeners to be registered with the Scheduler. /// Such TriggerListeners will only apply to Triggers that explicitly activate /// them via their name. /// </summary> /// <seealso cref="ITriggerListener.Name" /> public virtual ITriggerListener[] TriggerListeners { set { triggerListeners = value; } } /// <summary> /// Set the transaction manager to be used for registering jobs and triggers /// that are defined by this SchedulerFactoryObject. Default is none; setting /// this only makes sense when specifying a DataSource for the Scheduler. /// </summary> public virtual IPlatformTransactionManager TransactionManager { set { transactionManager = value; } } /// <summary> /// Sets the <see cref="Spring.Core.IO.IResourceLoader"/> /// that this object runs in. /// </summary> /// <value></value> /// <remarks> /// Invoked <b>after</b> population of normal objects properties but /// before an init callback such as /// <see cref="Spring.Objects.Factory.IInitializingObject"/>'s /// <see cref="Spring.Objects.Factory.IInitializingObject.AfterPropertiesSet()"/> /// or a custom init-method. Invoked <b>before</b> setting /// <see cref="Spring.Context.IApplicationContextAware"/>'s /// <see cref="Spring.Context.IApplicationContextAware.ApplicationContext"/> /// property. /// </remarks> public virtual IResourceLoader ResourceLoader { set { resourceLoader = value; } protected get { return resourceLoader; } } /// <summary> /// Logger instance. /// </summary> protected ILog Logger { get { return logger; } } /// <summary> /// Register jobs and triggers (within a transaction, if possible). /// </summary> protected virtual void RegisterJobsAndTriggers() { ITransactionStatus transactionStatus = null; if (transactionManager != null) { transactionStatus = transactionManager.GetTransaction(new DefaultTransactionDefinition()); } try { if (jobSchedulingDataLocations != null) { XMLSchedulingDataProcessor dataProcessor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); dataProcessor.OverWriteExistingData = overwriteExistingJobs; foreach (string location in jobSchedulingDataLocations) { dataProcessor.ProcessFileAndScheduleJobs(location, GetScheduler()); } } // Register JobDetails. if (jobDetails != null) { foreach (IJobDetail jobDetail in jobDetails) { AddJobToScheduler(jobDetail); } } else { // Create empty list for easier checks when registering triggers. jobDetails = new LinkedList(); } // Register Calendars. if (calendars != null) { foreach (DictionaryEntry entry in calendars) { string calendarName = (string) entry.Key; ICalendar calendar = (ICalendar) entry.Value; GetScheduler().AddCalendar(calendarName, calendar, true, true); } } // Register Triggers. if (triggers != null) { foreach (ITrigger trigger in triggers) { AddTriggerToScheduler(trigger); } } } catch (Exception ex) { if (transactionStatus != null) { try { transactionManager.Rollback(transactionStatus); } catch (TransactionException) { logger.Error("Job registration exception overridden by rollback exception", ex); throw; } } if (ex is SchedulerException) { throw; } throw new SchedulerException("Registration of jobs and triggers failed: " + ex.Message); } if (transactionStatus != null) { transactionManager.Commit(transactionStatus); } } /// <summary> /// Add the given job to the Scheduler, if it doesn't already exist. /// Overwrites the job in any case if "overwriteExistingJobs" is set. /// </summary> /// <param name="jobDetail">the job to add</param> /// <returns><code>true</code> if the job was actually added, <code>false</code> if it already existed before</returns> private bool AddJobToScheduler(IJobDetail jobDetail) { if (overwriteExistingJobs || GetScheduler().GetJobDetail(jobDetail.Key) == null) { GetScheduler().AddJob(jobDetail, true, true); return true; } else { return false; } } /// <summary> /// Add the given trigger to the Scheduler, if it doesn't already exist. /// Overwrites the trigger in any case if "overwriteExistingJobs" is set. /// </summary> /// <param name="trigger">the trigger to add</param> /// <returns><code>true</code> if the trigger was actually added, <code>false</code> if it already existed before</returns> private bool AddTriggerToScheduler(ITrigger trigger) { bool triggerExists = (GetScheduler().GetTrigger(trigger.Key) != null); if (!triggerExists || this.overwriteExistingJobs) { // Check if the Trigger is aware of an associated JobDetail. if (trigger is IJobDetailAwareTrigger) { IJobDetail jobDetail = ((IJobDetailAwareTrigger) trigger).JobDetail; // Automatically register the JobDetail too. if (!jobDetails.Contains(jobDetail) && AddJobToScheduler(jobDetail)) { jobDetails.Add(jobDetail); } } if (!triggerExists) { try { GetScheduler().ScheduleJob(trigger); } catch (ObjectAlreadyExistsException ex) { if (logger.IsDebugEnabled) { logger.Debug( "Unexpectedly found existing trigger, assumably due to cluster race condition: " + ex.Message + " - can safely be ignored"); } if (overwriteExistingJobs) { GetScheduler().RescheduleJob(trigger.Key, trigger); } } } else { GetScheduler().RescheduleJob(trigger.Key, trigger); } return true; } else { return false; } } /// <summary> /// Register all specified listeners with the Scheduler. /// </summary> protected virtual void RegisterListeners() { if (schedulerListeners != null) { for (int i = 0; i < schedulerListeners.Length; i++) { GetScheduler().ListenerManager.AddSchedulerListener(schedulerListeners[i]); } } if (globalJobListeners != null) { foreach (IJobListener jobListener in globalJobListeners) { GetScheduler().ListenerManager.AddJobListener(jobListener); } } if (jobListeners != null && jobListeners.Length > 0) { throw new InvalidOperationException("Non-global JobListeners not supported on Quartz 2 - " + "manually register a Matcher against the Quartz ListenerManager instead"); } if (globalTriggerListeners != null) { foreach (ITriggerListener triggerListener in globalTriggerListeners) { GetScheduler().ListenerManager.AddTriggerListener(triggerListener); } } if (triggerListeners != null && triggerListeners.Length > 0) { throw new InvalidOperationException("Non-global TriggerListeners not supported on Quartz 2 - " + "manually register a Matcher against the Quartz ListenerManager instead"); } } /// <summary> /// Template method that determines the Scheduler to operate on. /// To be implemented by subclasses. /// </summary> /// <returns></returns> protected abstract IScheduler GetScheduler(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using System.Threading; using System.Runtime.ExceptionServices; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { [Trait("connection", "tcp")] public static class ConnectionPoolTest { private static readonly string _tcpConnStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = false }).ConnectionString; private static readonly string _tcpMarsConnStr = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString; [CheckConnStrSetupFact] public static void ConnectionPool_NonMars() { RunDataTestForSingleConnString(_tcpConnStr); } [CheckConnStrSetupFact] public static void ConnectionPool_Mars() { RunDataTestForSingleConnString(_tcpMarsConnStr); } private static void RunDataTestForSingleConnString(string tcpConnectionString) { BasicConnectionPoolingTest(tcpConnectionString); ClearAllPoolsTest(tcpConnectionString); #if MANAGED_SNI && DEBUG KillConnectionTest(tcpConnectionString); #endif ReclaimEmancipatedOnOpenTest(tcpConnectionString); } /// <summary> /// Tests that using the same connection string results in the same pool\internal connection and a different string results in a different pool\internal connection /// </summary> /// <param name="connectionString"></param> private static void BasicConnectionPoolingTest(string connectionString) { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); InternalConnectionWrapper internalConnection = new InternalConnectionWrapper(connection); ConnectionPoolWrapper connectionPool = new ConnectionPoolWrapper(connection); connection.Close(); SqlConnection connection2 = new SqlConnection(connectionString); connection2.Open(); Assert.True(internalConnection.IsInternalConnectionOf(connection2), "New connection does not use same internal connection"); Assert.True(connectionPool.ContainsConnection(connection2), "New connection is in a different pool"); connection2.Close(); SqlConnection connection3 = new SqlConnection(connectionString + ";App=SqlConnectionPoolUnitTest;"); connection3.Open(); Assert.False(internalConnection.IsInternalConnectionOf(connection3), "Connection with different connection string uses same internal connection"); Assert.False(connectionPool.ContainsConnection(connection3), "Connection with different connection string uses same connection pool"); connection3.Close(); connectionPool.Cleanup(); SqlConnection connection4 = new SqlConnection(connectionString); connection4.Open(); Assert.True(internalConnection.IsInternalConnectionOf(connection4), "New connection does not use same internal connection"); Assert.True(connectionPool.ContainsConnection(connection4), "New connection is in a different pool"); connection4.Close(); } #if MANAGED_SNI && DEBUG /// <summary> /// Tests if killing the connection using the InternalConnectionWrapper is working /// </summary> /// <param name="connectionString"></param> private static void KillConnectionTest(string connectionString) { InternalConnectionWrapper wrapper = null; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); wrapper = new InternalConnectionWrapper(connection); using (SqlCommand command = new SqlCommand("SELECT 5;", connection)) { DataTestUtility.AssertEqualsWithDescription(5, command.ExecuteScalar(), "Incorrect scalar result."); } wrapper.KillConnection(); } using (SqlConnection connection2 = new SqlConnection(connectionString)) { connection2.Open(); Assert.False(wrapper.IsInternalConnectionOf(connection2), "New connection has internal connection that was just killed"); using (SqlCommand command = new SqlCommand("SELECT 5;", connection2)) { DataTestUtility.AssertEqualsWithDescription(5, command.ExecuteScalar(), "Incorrect scalar result."); } } } #endif /// <summary> /// Tests if clearing all of the pools does actually remove the pools /// </summary> /// <param name="connectionString"></param> private static void ClearAllPoolsTest(string connectionString) { SqlConnection.ClearAllPools(); Assert.True(0 == ConnectionPoolWrapper.AllConnectionPools().Length, "Pools exist after clearing all pools"); SqlConnection connection = new SqlConnection(connectionString); connection.Open(); ConnectionPoolWrapper pool = new ConnectionPoolWrapper(connection); connection.Close(); ConnectionPoolWrapper[] allPools = ConnectionPoolWrapper.AllConnectionPools(); DataTestUtility.AssertEqualsWithDescription(1, allPools.Length, "Incorrect number of pools exist."); Assert.True(allPools[0].Equals(pool), "Saved pool is not in the list of all pools"); DataTestUtility.AssertEqualsWithDescription(1, pool.ConnectionCount, "Saved pool has incorrect number of connections"); SqlConnection.ClearAllPools(); Assert.True(0 == ConnectionPoolWrapper.AllConnectionPools().Length, "Pools exist after clearing all pools"); DataTestUtility.AssertEqualsWithDescription(0, pool.ConnectionCount, "Saved pool has incorrect number of connections."); } /// <summary> /// Checks if an 'emancipated' internal connection is reclaimed when a new connection is opened AND we hit max pool size /// NOTE: 'emancipated' means that the internal connection's SqlConnection has fallen out of scope and has no references, but was not explicitly disposed\closed /// </summary> /// <param name="connectionString"></param> private static void ReclaimEmancipatedOnOpenTest(string connectionString) { string newConnectionString = (new SqlConnectionStringBuilder(connectionString) { MaxPoolSize = 1 }).ConnectionString; SqlConnection.ClearAllPools(); InternalConnectionWrapper internalConnection = CreateEmancipatedConnection(newConnectionString); ConnectionPoolWrapper connectionPool = internalConnection.ConnectionPool; GC.Collect(); GC.WaitForPendingFinalizers(); DataTestUtility.AssertEqualsWithDescription(1, connectionPool.ConnectionCount, "Wrong number of connections in the pool."); DataTestUtility.AssertEqualsWithDescription(0, connectionPool.FreeConnectionCount, "Wrong number of free connections in the pool."); using (SqlConnection connection = new SqlConnection(newConnectionString)) { connection.Open(); Assert.True(internalConnection.IsInternalConnectionOf(connection), "Connection has wrong internal connection"); Assert.True(connectionPool.ContainsConnection(connection), "Connection is in wrong connection pool"); } } private static void ReplacementConnectionUsesSemaphoreTest(string connectionString) { string newConnectionString = (new SqlConnectionStringBuilder(connectionString) { MaxPoolSize = 2, ConnectTimeout = 5 }).ConnectionString; SqlConnection.ClearAllPools(); SqlConnection liveConnection = new SqlConnection(newConnectionString); SqlConnection deadConnection = new SqlConnection(newConnectionString); liveConnection.Open(); deadConnection.Open(); InternalConnectionWrapper deadConnectionInternal = new InternalConnectionWrapper(deadConnection); InternalConnectionWrapper liveConnectionInternal = new InternalConnectionWrapper(liveConnection); deadConnectionInternal.KillConnection(); deadConnection.Close(); liveConnection.Close(); Task<InternalConnectionWrapper>[] tasks = new Task<InternalConnectionWrapper>[3]; Barrier syncBarrier = new Barrier(tasks.Length); Func<InternalConnectionWrapper> taskFunction = (() => ReplacementConnectionUsesSemaphoreTask(newConnectionString, syncBarrier)); for (int i = 0; i < tasks.Length; i++) { tasks[i] = Task.Factory.StartNew<InternalConnectionWrapper>(taskFunction); } bool taskWithLiveConnection = false; bool taskWithNewConnection = false; bool taskWithCorrectException = false; Task waitAllTask = Task.Factory.ContinueWhenAll(tasks, (completedTasks) => { foreach (var item in completedTasks) { if (item.Status == TaskStatus.Faulted) { // One task should have a timeout exception if ((!taskWithCorrectException) && (item.Exception.InnerException is InvalidOperationException) && (item.Exception.InnerException.Message.StartsWith(SystemDataResourceManager.Instance.ADP_PooledOpenTimeout))) taskWithCorrectException = true; else if (!taskWithCorrectException) { // Rethrow the unknown exception ExceptionDispatchInfo exceptionInfo = ExceptionDispatchInfo.Capture(item.Exception); exceptionInfo.Throw(); } } else if (item.Status == TaskStatus.RanToCompletion) { // One task should get the live connection if (item.Result.Equals(liveConnectionInternal)) { if (!taskWithLiveConnection) taskWithLiveConnection = true; } else if (!item.Result.Equals(deadConnectionInternal) && !taskWithNewConnection) taskWithNewConnection = true; } else Console.WriteLine("ERROR: Task in unknown state: {0}", item.Status); } }); waitAllTask.Wait(); Assert.True(taskWithLiveConnection && taskWithNewConnection && taskWithCorrectException, string.Format("Tasks didn't finish as expected.\nTask with live connection: {0}\nTask with new connection: {1}\nTask with correct exception: {2}\n", taskWithLiveConnection, taskWithNewConnection, taskWithCorrectException)); } private static InternalConnectionWrapper ReplacementConnectionUsesSemaphoreTask(string connectionString, Barrier syncBarrier) { InternalConnectionWrapper internalConnection = null; using (SqlConnection connection = new SqlConnection(connectionString)) { try { connection.Open(); internalConnection = new InternalConnectionWrapper(connection); } catch { syncBarrier.SignalAndWait(); throw; } syncBarrier.SignalAndWait(); } return internalConnection; } private static InternalConnectionWrapper CreateEmancipatedConnection(string connectionString) { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); return new InternalConnectionWrapper(connection); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Security; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime { // This is a set of stub methods implementing the support for the IReadOnlyDictionary`2 interface on WinRT // objects that support IMapView`2. Used by the interop mashaling infrastructure. // // The methods on this class must be written VERY carefully to avoid introducing security holes. // That's because they are invoked with special "this"! The "this" object // for all of these methods are not IMapViewToIReadOnlyDictionaryAdapter objects. Rather, they are of type // IMapView<K, V>. No actual IMapViewToIReadOnlyDictionaryAdapter object is ever instantiated. Thus, you will see // a lot of expressions that cast "this" to "IMapView<K, V>". [DebuggerDisplay("Count = {Count}")] internal sealed class IMapViewToIReadOnlyDictionaryAdapter { private IMapViewToIReadOnlyDictionaryAdapter() { Debug.Assert(false, "This class is never instantiated"); } // V this[K key] { get } internal V Indexer_Get<K, V>(K key) { if (key == null) throw new ArgumentNullException(nameof(key)); Contract.EndContractBlock(); IMapView<K, V> _this = Unsafe.As<IMapView<K, V>>(this); return Lookup(_this, key); } // IEnumerable<K> Keys { get } internal IEnumerable<K> Keys<K, V>() { IMapView<K, V> _this = Unsafe.As<IMapView<K, V>>(this); IReadOnlyDictionary<K, V> roDictionary = (IReadOnlyDictionary<K, V>)_this; return new ReadOnlyDictionaryKeyCollection<K, V>(roDictionary); } // IEnumerable<V> Values { get } internal IEnumerable<V> Values<K, V>() { IMapView<K, V> _this = Unsafe.As<IMapView<K, V>>(this); IReadOnlyDictionary<K, V> roDictionary = (IReadOnlyDictionary<K, V>)_this; return new ReadOnlyDictionaryValueCollection<K, V>(roDictionary); } // bool ContainsKey(K key) [Pure] internal bool ContainsKey<K, V>(K key) { if (key == null) throw new ArgumentNullException(nameof(key)); IMapView<K, V> _this = Unsafe.As<IMapView<K, V>>(this); return _this.HasKey(key); } // bool TryGetValue(TKey key, out TValue value) internal bool TryGetValue<K, V>(K key, out V value) { if (key == null) throw new ArgumentNullException(nameof(key)); IMapView<K, V> _this = Unsafe.As<IMapView<K, V>>(this); // It may be faster to call HasKey then Lookup. On failure, we would otherwise // throw an exception from Lookup. if (!_this.HasKey(key)) { value = default(V); return false; } try { value = _this.Lookup(key); return true; } catch (Exception ex) // Still may hit this case due to a race condition { if (HResults.E_BOUNDS == ex._HResult) { value = default(V); return false; } throw; } } #region Helpers private static V Lookup<K, V>(IMapView<K, V> _this, K key) { Contract.Requires(null != key); try { return _this.Lookup(key); } catch (Exception ex) { if (HResults.E_BOUNDS == ex._HResult) throw new KeyNotFoundException(SR.Arg_KeyNotFound); throw; } } #endregion Helpers } // Note: One day we may make these return IReadOnlyCollection<T> [DebuggerDisplay("Count = {Count}")] internal sealed class ReadOnlyDictionaryKeyCollection<TKey, TValue> : IEnumerable<TKey> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; public ReadOnlyDictionaryKeyCollection(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; } /* public void CopyTo(TKey[] array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) throw new ArgumentException(SR.Arg_IndexOutOfRangeException); if (array.Length - index < dictionary.Count) throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); int i = index; foreach (KeyValuePair<TKey, TValue> mapping in dictionary) { array[i++] = mapping.Key; } } public int Count { get { return dictionary.Count; } } public bool Contains(TKey item) { return dictionary.ContainsKey(item); } */ IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<TKey>)this).GetEnumerator(); } public IEnumerator<TKey> GetEnumerator() { return new ReadOnlyDictionaryKeyEnumerator<TKey, TValue>(dictionary); } } // public class ReadOnlyDictionaryKeyCollection<TKey, TValue> internal sealed class ReadOnlyDictionaryKeyEnumerator<TKey, TValue> : IEnumerator<TKey> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> enumeration; public ReadOnlyDictionaryKeyEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; enumeration = dictionary.GetEnumerator(); } void IDisposable.Dispose() { enumeration.Dispose(); } public bool MoveNext() { return enumeration.MoveNext(); } Object IEnumerator.Current { get { return ((IEnumerator<TKey>)this).Current; } } public TKey Current { get { return enumeration.Current.Key; } } public void Reset() { enumeration = dictionary.GetEnumerator(); } } // class ReadOnlyDictionaryKeyEnumerator<TKey, TValue> [DebuggerDisplay("Count = {Count}")] internal sealed class ReadOnlyDictionaryValueCollection<TKey, TValue> : IEnumerable<TValue> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; public ReadOnlyDictionaryValueCollection(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; } /* public void CopyTo(TValue[] array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) throw new ArgumentException(SR.Arg_IndexOutOfRangeException); if (array.Length - index < dictionary.Count) throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); int i = index; foreach (KeyValuePair<TKey, TValue> mapping in dictionary) { array[i++] = mapping.Value; } } public int Count { get { return dictionary.Count; } } public bool Contains(TValue item) { EqualityComparer<TValue> comparer = EqualityComparer<TValue>.Default; foreach (TValue value in this) if (comparer.Equals(item, value)) return true; return false; } */ IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<TValue>)this).GetEnumerator(); } public IEnumerator<TValue> GetEnumerator() { return new ReadOnlyDictionaryValueEnumerator<TKey, TValue>(dictionary); } } // public class ReadOnlyDictionaryValueCollection<TKey, TValue> internal sealed class ReadOnlyDictionaryValueEnumerator<TKey, TValue> : IEnumerator<TValue> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> enumeration; public ReadOnlyDictionaryValueEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; enumeration = dictionary.GetEnumerator(); } void IDisposable.Dispose() { enumeration.Dispose(); } public bool MoveNext() { return enumeration.MoveNext(); } Object IEnumerator.Current { get { return ((IEnumerator<TValue>)this).Current; } } public TValue Current { get { return enumeration.Current.Value; } } public void Reset() { enumeration = dictionary.GetEnumerator(); } } // class ReadOnlyDictionaryValueEnumerator<TKey, TValue> }
/* Copyright 2019 Esri 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 ESRI.ArcGIS.ADF.BaseClasses; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.ArcMapUI; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Framework; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.SystemUI; using Microsoft.VisualBasic.Compatibility.VB6; using System; using System.Collections; using System.Data; using System.Diagnostics; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace AlgorithmicColorRamp { [System.Runtime.InteropServices.ProgId("AlgorithmicColorRamp.clsAlgColorRamp")] public class AlgorithmicColorRamp : ESRI.ArcGIS.Desktop.AddIns.Button { private frmAlgorithmicColorRamp frmAlgoColorRamp = new frmAlgorithmicColorRamp(); public AlgorithmicColorRamp() { } protected override void OnClick() { // // When the utility is selected, check that we have a currently selected // feature layer with a ClassBreaksRenderer already set. First we get the contents view. // IContentsView ContentsView = null; ContentsView = ArcMap.Document.CurrentContentsView; // // If we have a DisplayView active // object VarSelectedItem = null; IGeoFeatureLayer GeoFeatureLayer = null; IClassBreaksRenderer ClassBreaksRenderer = null; IEnumColors pColors = null; int lngCount = 0; IHsvColor HsvColor = null; IClone ClonedSymbol = null; ISymbol NewSymbol = null; IActiveView ActiveView = null; //AlgorithimcColorRamp contains HSV colors. if (ContentsView is TOCDisplayView) { if (ContentsView.SelectedItem is DBNull) { // // If we don't have anything selected. // MessageBox.Show("SelectedItem is Null C#." + "Select a layer in the Table of Contents.", "No Layer Selected", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // // Get the selected Item. // VarSelectedItem = ContentsView.SelectedItem; // // Selected Item should implement the IGeoFeatureLayer interface - therefore we // have selected a feature layer with a Renderer property (Note: Other interfaces // also have a Renderer property, which may behave differently. // if (VarSelectedItem is IGeoFeatureLayer) { GeoFeatureLayer = (IGeoFeatureLayer)VarSelectedItem; // // Set the cached property to true, so we can refresh this layer // without refreshing all the layers, when we have changed the symbols. // GeoFeatureLayer.Cached = true; // // Check we have an existing ClassBreaksRenderer. // if (GeoFeatureLayer.Renderer is IClassBreaksRenderer) { ClassBreaksRenderer = (IClassBreaksRenderer)GeoFeatureLayer.Renderer; // // If successful so far we can go ahead and open the Form. This allows the // user to change the properties of the new RandomColorRamp. // frmAlgoColorRamp.m_lngClasses = ClassBreaksRenderer.BreakCount; frmAlgoColorRamp.ShowDialog(); // // Return the selected colors enumeration. pColors = frmAlgoColorRamp.m_enumNewColors; if (pColors == null) { // // User has cancelled the form, or not set a ramp. // //MsgBox("Colors object is empty. Exit Sub") return; } // // Set the new random colors onto the Symbol array of the ClassBreaksRenderer. // pColors.Reset(); // Because you never know if the enumeration has been // iterated before being passed back. int tempFor1 = ClassBreaksRenderer.BreakCount; for (lngCount = 0; lngCount < tempFor1; lngCount++) { // // For each Value in the ClassBreaksRenderer, we clone the existing // Fill symbol (so that all the properties are faithful preserved, // and set its color from our new AlgorithmicColorRamp. // IClone symClone; symClone = (IClone)ClassBreaksRenderer.get_Symbol(lngCount); ClonedSymbol = CloneMe(ref (symClone)); // // Now the ClonedSymbol variable holds a copy of the existing // Symbol, we can change the assigned Color. We set the new // symbol onto the Symbol array of the Renderer. ' // HsvColor = (IHsvColor)pColors.Next(); NewSymbol = SetColorOfUnknownSymbol(ClonedSymbol, HsvColor); if (NewSymbol != null) ClassBreaksRenderer.set_Symbol(lngCount, NewSymbol); } // // Refresh the table of contents and the changed layer. // ActiveView = (IActiveView)ArcMap.Document.FocusMap; ActiveView.ContentsChanged(); ArcMap.Document.UpdateContents(); ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, GeoFeatureLayer, null); } } } } public IClone CloneMe(ref IClone OriginalClone) { IClone tempCloneMe = null; // // This function clones the input object. // tempCloneMe = null; if (OriginalClone != null) tempCloneMe = OriginalClone.Clone(); return tempCloneMe; } private ISymbol SetColorOfUnknownSymbol(IClone ClonedSymbol, IColor Color) { ISymbol tempSetColorOfUnknownSymbol = null; // // This function takes an IClone interface, works out the underlying coclass // (which should be some kind of symbol) and then sets the Color property // according to the passed in color. // tempSetColorOfUnknownSymbol = null; if (ClonedSymbol == null) return tempSetColorOfUnknownSymbol; // // Here we figure out which kind of symbol we have. For the simple symbol // types, simply setting the color property is OK. However, more complex // symbol types require further investigation. // IFillSymbol FillSymbol = null; IMarkerFillSymbol MarkerFillSymbol = null; IMarkerSymbol MarkerSymbol_A = null; ILineFillSymbol LineFillSymbol = null; ILineSymbol LineSymbol = null; IPictureFillSymbol PictureFillSymbol = null; IMarkerSymbol MarkerSymbol_B = null; IPictureMarkerSymbol PictureMarkerSymbol = null; IMarkerLineSymbol MarkerLineSymbol = null; IMarkerSymbol MarkerSymbol_C = null; ILineSymbol LineSymbol_B = null; if (ClonedSymbol is ISymbol) { // // Check for Fill symbols. // if (ClonedSymbol is IFillSymbol) { // // Check for SimpleFillSymbols or MultiLevelFillSymbols. // if ((ClonedSymbol is ISimpleFillSymbol) | (ClonedSymbol is IMultiLayerFillSymbol)) { FillSymbol = (IFillSymbol)ClonedSymbol; // // Here we simply change the color of the Fill. // FillSymbol.Color = Color; tempSetColorOfUnknownSymbol = (ISymbol)FillSymbol; // // Check for MarkerFillSymbols. // } else if (ClonedSymbol is IMarkerFillSymbol) { MarkerFillSymbol = (IMarkerFillSymbol)ClonedSymbol; // // Here we change the color of the MarkerSymbol. // MarkerSymbol_A = (IMarkerSymbol)SetColorOfUnknownSymbol((IClone)MarkerFillSymbol.MarkerSymbol, Color); MarkerFillSymbol.MarkerSymbol = MarkerSymbol_A; tempSetColorOfUnknownSymbol = (ISymbol)MarkerFillSymbol; // // Check for LineFillSymbols. // } else if (ClonedSymbol is ILineFillSymbol) { LineFillSymbol = (ILineFillSymbol)ClonedSymbol; // // Here we change the color of the LineSymbol. // LineSymbol = (ILineSymbol)SetColorOfUnknownSymbol((IClone)LineFillSymbol.LineSymbol, Color); LineFillSymbol.LineSymbol = LineSymbol; tempSetColorOfUnknownSymbol = (ISymbol)LineFillSymbol; // // Check for PictureFillSymbols. // } else if (ClonedSymbol is IPictureFillSymbol) { PictureFillSymbol = (IPictureFillSymbol)ClonedSymbol; // // Here we simply change the color of the BackgroundColor. // PictureFillSymbol.BackgroundColor = Color; tempSetColorOfUnknownSymbol = (ISymbol)PictureFillSymbol; } // // Check for Marker symbols. // } else if (ClonedSymbol is IMarkerSymbol) { // // Check for SimpleMarkerSymbols, ArrowMarkerSymbols or // CharacterMarkerSymbols. // if ((ClonedSymbol is IMultiLayerMarkerSymbol) | (ClonedSymbol is ISimpleMarkerSymbol) | (ClonedSymbol is IArrowMarkerSymbol) | (ClonedSymbol is ICharacterMarkerSymbol)) { MarkerSymbol_B = (IMarkerSymbol)ClonedSymbol; // // For these types, we simply change the color property. // MarkerSymbol_B.Color = Color; tempSetColorOfUnknownSymbol = (ISymbol)MarkerSymbol_B; // // Check for PictureMarkerSymbols. // } else if (ClonedSymbol is IPictureMarkerSymbol) { PictureMarkerSymbol = (IPictureMarkerSymbol)ClonedSymbol; // // Here we change the BackgroundColor property. // PictureMarkerSymbol.Color = Color; tempSetColorOfUnknownSymbol = (ISymbol)PictureMarkerSymbol; } // // Check for Line symbols. // } else if (ClonedSymbol is ILineSymbol) { // // Check for MarkerLine symbols. // if (ClonedSymbol is IMarkerLineSymbol) { MarkerLineSymbol = (IMarkerLineSymbol)ClonedSymbol; // // Here we change the color of the MarkerSymbol. // MarkerSymbol_C = (IMarkerSymbol)SetColorOfUnknownSymbol((IClone)MarkerLineSymbol.MarkerSymbol, Color); MarkerLineSymbol.MarkerSymbol = MarkerSymbol_C; tempSetColorOfUnknownSymbol = (ISymbol)MarkerLineSymbol; // // Check for other Line symbols. // } else if ((ClonedSymbol is ISimpleLineSymbol) | (ClonedSymbol is IHashLineSymbol) | (ClonedSymbol is ICartographicLineSymbol)) { LineSymbol_B = (ILineSymbol)ClonedSymbol; LineSymbol_B.Color = Color; tempSetColorOfUnknownSymbol = (ISymbol)LineSymbol_B; } } } return tempSetColorOfUnknownSymbol; } protected override void OnUpdate() { Enabled = ArcMap.Application != null; } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using JetBrains.Annotations; namespace NLog.UnitTests { using System; using System.Collections.Generic; using System.Linq; using System.IO; using Xunit; using NLog.Common; using NLog.Config; using NLog.Targets; #if NET4_5 using System.Threading.Tasks; using Microsoft.Practices.Unity; #endif public class LogManagerTests : NLogTestBase { [Fact] public void GetLoggerTest() { ILogger loggerA = LogManager.GetLogger("A"); ILogger loggerA2 = LogManager.GetLogger("A"); ILogger loggerB = LogManager.GetLogger("B"); Assert.Same(loggerA, loggerA2); Assert.NotSame(loggerA, loggerB); Assert.Equal("A", loggerA.Name); Assert.Equal("B", loggerB.Name); } [Fact] public void GarbageCollectionTest() { string uniqueLoggerName = Guid.NewGuid().ToString(); ILogger loggerA1 = LogManager.GetLogger(uniqueLoggerName); GC.Collect(); ILogger loggerA2 = LogManager.GetLogger(uniqueLoggerName); Assert.Same(loggerA1, loggerA2); } static WeakReference GetWeakReferenceToTemporaryLogger() { string uniqueLoggerName = Guid.NewGuid().ToString(); return new WeakReference(LogManager.GetLogger(uniqueLoggerName)); } [Fact] public void GarbageCollection2Test() { WeakReference wr = GetWeakReferenceToTemporaryLogger(); // nobody's holding a reference to this Logger anymore, so GC.Collect(2) should free it GC.Collect(); Assert.False(wr.IsAlive); } [Fact] public void NullLoggerTest() { ILogger l = LogManager.CreateNullLogger(); Assert.Equal(String.Empty, l.Name); } [Fact] public void ThrowExceptionsTest() { FileTarget ft = new FileTarget(); ft.FileName = ""; // invalid file name SimpleConfigurator.ConfigureForTargetLogging(ft); LogManager.ThrowExceptions = false; LogManager.GetLogger("A").Info("a"); LogManager.ThrowExceptions = true; try { LogManager.GetLogger("A").Info("a"); Assert.True(false, "Should not be reached."); } catch { Assert.True(true); } LogManager.ThrowExceptions = false; } //[Fact(Skip="Side effects to other unit tests.")] public void GlobalThresholdTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog globalThreshold='Info'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Assert.Equal(LogLevel.Info, LogManager.GlobalThreshold); // nothing gets logged because of globalThreshold LogManager.GetLogger("A").Debug("xxx"); AssertDebugLastMessage("debug", ""); // lower the threshold LogManager.GlobalThreshold = LogLevel.Trace; LogManager.GetLogger("A").Debug("yyy"); AssertDebugLastMessage("debug", "yyy"); // raise the threshold LogManager.GlobalThreshold = LogLevel.Info; // this should be yyy, meaning that the target is in place // only rules have been modified. LogManager.GetLogger("A").Debug("zzz"); AssertDebugLastMessage("debug", "yyy"); LogManager.Shutdown(); LogManager.Configuration = null; } [Fact] public void DisableLoggingTest_UsingStatement() { const string LoggerConfig = @" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='DisableLoggingTest_UsingStatement_A' levels='Trace' writeTo='debug' /> <logger name='DisableLoggingTest_UsingStatement_B' levels='Error' writeTo='debug' /> </rules> </nlog>"; // Disable/Enable logging should affect ALL the loggers. ILogger loggerA = LogManager.GetLogger("DisableLoggingTest_UsingStatement_A"); ILogger loggerB = LogManager.GetLogger("DisableLoggingTest_UsingStatement_B"); LogManager.Configuration = CreateConfigurationFromString(LoggerConfig); // The starting state for logging is enable. Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); loggerA.Trace("---"); AssertDebugLastMessage("debug", "---"); using (LogManager.DisableLogging()) { Assert.False(LogManager.IsLoggingEnabled()); // The last of LastMessage outside using statement should be returned. loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "---"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "---"); } Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); LogManager.Shutdown(); LogManager.Configuration = null; } [Fact] public void DisableLoggingTest_WithoutUsingStatement() { const string LoggerConfig = @" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='DisableLoggingTest_WithoutUsingStatement_A' levels='Trace' writeTo='debug' /> <logger name='DisableLoggingTest_WithoutUsingStatement_B' levels='Error' writeTo='debug' /> </rules> </nlog>"; // Disable/Enable logging should affect ALL the loggers. ILogger loggerA = LogManager.GetLogger("DisableLoggingTest_WithoutUsingStatement_A"); ILogger loggerB = LogManager.GetLogger("DisableLoggingTest_WithoutUsingStatement_B"); LogManager.Configuration = CreateConfigurationFromString(LoggerConfig); // The starting state for logging is enable. Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); loggerA.Trace("---"); AssertDebugLastMessage("debug", "---"); LogManager.DisableLogging(); Assert.False(LogManager.IsLoggingEnabled()); // The last value of LastMessage before DisableLogging() should be returned. loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "---"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "---"); LogManager.EnableLogging(); Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); LogManager.Shutdown(); LogManager.Configuration = null; } private int _reloadCounter = 0; private void WaitForConfigReload(int counter) { while (_reloadCounter < counter) { System.Threading.Thread.Sleep(100); } } private void OnConfigReloaded(object sender, LoggingConfigurationReloadedEventArgs e) { Console.WriteLine("OnConfigReloaded success={0}", e.Succeeded); _reloadCounter++; } private bool IsMacOsX() { #if MONO if (Directory.Exists("/Library/Frameworks/Mono.framework/")) { return true; } #endif return false; } [Fact] public void AutoReloadTest() { if (IsMacOsX()) { // skip this on Mac OS, since it requires root permissions for // filesystem watcher return; } using (new InternalLoggerScope()) { string fileName = Path.GetTempFileName(); try { _reloadCounter = 0; LogManager.ConfigurationReloaded += OnConfigReloaded; using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } LogManager.Configuration = new XmlLoggingConfiguration(fileName); AssertDebugCounter("debug", 0); ILogger logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); InternalLogger.Info("Rewriting test file..."); // now write the file again using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } InternalLogger.Info("Rewritten."); WaitForConfigReload(1); logger.Debug("aaa"); AssertDebugLastMessage("debug", "xxx aaa"); // write the file again, this time make an error using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } WaitForConfigReload(2); logger.Debug("bbb"); AssertDebugLastMessage("debug", "xxx bbb"); // write the corrected file again using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='zzz ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } WaitForConfigReload(3); logger.Debug("ccc"); AssertDebugLastMessage("debug", "zzz ccc"); } finally { LogManager.ConfigurationReloaded -= OnConfigReloaded; if (File.Exists(fileName)) File.Delete(fileName); } } } [Fact] public void GivenCurrentClass_WhenGetCurrentClassLogger_ThenLoggerShouldBeCurrentClass() { var logger = LogManager.GetCurrentClassLogger(); Assert.Equal(this.GetType().FullName, logger.Name); } private static class ImAStaticClass { [UsedImplicitly] private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger(); static ImAStaticClass() { } public static void DummyToInvokeInitializers() { } } [Fact] public void GetCurrentClassLogger_static_class() { ImAStaticClass.DummyToInvokeInitializers(); } private abstract class ImAAbstractClass { /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> protected ImAAbstractClass() { Logger Logger = NLog.LogManager.GetCurrentClassLogger(); } } private class InheritedFromAbstractClass : ImAAbstractClass { } /// <summary> /// Creating instance in a static ctor should not be a problm /// </summary> [Fact] public void GetCurrentClassLogger_abstract_class() { var instance = new InheritedFromAbstractClass(); } /// <summary> /// I'm a class which isn't inhereting from Logger /// </summary> private class ImNotALogger { } /// <summary> /// ImNotALogger inherits not from Logger , but should not throw an exception /// </summary> [Fact] public void GetLogger_wrong_loggertype_should_continue() { var instance = LogManager.GetLogger("a", typeof(ImNotALogger)); Assert.NotNull(instance); } /// <summary> /// ImNotALogger inherits not from Logger , but should not throw an exception /// </summary> [Fact] public void GetLogger_wrong_loggertype_should_continue_even_if_class_is_static() { var instance = LogManager.GetLogger("a", typeof(ImAStaticClass)); Assert.NotNull(instance); } #if NET4_0 || NET4_5 [Fact] public void GivenLazyClass_WhenGetCurrentClassLogger_ThenLoggerNameShouldBeCurrentClass() { var logger = new Lazy<ILogger>(LogManager.GetCurrentClassLogger); Assert.Equal(this.GetType().FullName, logger.Value.Name); } #endif #if NET4_5 /// <summary> /// target for <see cref="ThreadSafe_getCurrentClassLogger_test"/> /// </summary> private static MemoryQueueTarget mTarget = new MemoryQueueTarget(500); /// <summary> /// target for <see cref="ThreadSafe_getCurrentClassLogger_test"/> /// </summary> private static MemoryQueueTarget mTarget2 = new MemoryQueueTarget(500); /// <summary> /// Note: THe problem can be reproduced when: debugging the unittest + "break when exception is thrown" checked in visual studio. /// /// https://github.com/NLog/NLog/issues/500 /// </summary> [Fact] public void ThreadSafe_getCurrentClassLogger_test() { using (var c = new UnityContainer()) { var r = Enumerable.Range(1, 100); //reported with 10. Task.Run(() => { //need for init LogManager.Configuration = new LoggingConfiguration(); LogManager.Configuration.AddTarget("memory", mTarget); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, mTarget)); LogManager.Configuration.AddTarget("memory2", mTarget2); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, mTarget2)); LogManager.ReconfigExistingLoggers(); }); Parallel.ForEach(r, a => { var res = c.Resolve<ClassA>(); }); mTarget.Layout = @"${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message} ${exception:format=tostring}"; mTarget2.Layout = @"${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message} ${exception:format=tostring}"; } } /// <summary> /// target for <see cref="ThreadSafe_getCurrentClassLogger_test"/> /// </summary> [Target("Memory")] public sealed class MemoryQueueTarget : TargetWithLayout { private int maxSize; public MemoryQueueTarget() : this(1) { } public MemoryQueueTarget(string name) { this.Name = name; } public MemoryQueueTarget(int size) { this.Logs = new Queue<string>(); this.maxSize = size; } public Queue<string> Logs { get; private set; } protected override void Write(LogEventInfo logEvent) { string msg = this.Layout.Render(logEvent); if (msg.Length > 100) msg = msg.Substring(0, 100) + "..."; this.Logs.Enqueue(msg); while (this.Logs.Count > maxSize) { Logs.Dequeue(); } } } /// <summary> /// class for <see cref="ThreadSafe_getCurrentClassLogger_test"/> /// </summary> public class ClassA { private static Logger logger = LogManager.GetCurrentClassLogger(); public ClassA(ClassB dd) { logger.Info("Hi there A"); } } /// <summary> /// class for <see cref="ThreadSafe_getCurrentClassLogger_test"/> /// </summary> public class ClassB { private static Logger logger = LogManager.GetCurrentClassLogger(); public ClassB(ClassC dd) { logger.Info("Hi there B"); } } /// <summary> /// class for <see cref="ThreadSafe_getCurrentClassLogger_test"/> /// </summary> public class ClassC { private static Logger logger = LogManager.GetCurrentClassLogger(); public ClassC(ClassD dd) { logger.Info("Hi there C"); } } /// <summary> /// class for <see cref="ThreadSafe_getCurrentClassLogger_test"/> /// </summary> public class ClassD { private static Logger logger = LogManager.GetCurrentClassLogger(); public ClassD() { logger.Info("Hi there D"); } } #endif } }
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 PushSystem.Areas.HelpPage.ModelDescriptions; using PushSystem.Areas.HelpPage.Models; namespace PushSystem.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); } } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Diagnostics; using System.Linq; using CocosSharp; using FarseerPhysics.Collision; using FarseerPhysics.Collision.Shapes; using FarseerPhysics.Common; using FarseerPhysics.DebugViews; using FarseerPhysics.Dynamics; using FarseerPhysics.Factories; using FarseerPhysics.TestBed.Framework; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace FarseerPhysics.TestBed.Tests { /// <summary> /// This tests stacking. It also shows how to use World.Query() /// and AABB.TestOverlap(). /// /// This callback is called by World.QueryAABB(). We find all the fixtures /// that overlap an AABB. Of those, we use AABB.TestOverlap() to determine which fixtures /// overlap a circle. Up to 4 overlapped fixtures will be highlighted with a yellow border. /// </summary> public class PolyShapesCallback { private const int MaxCount = 4; internal CircleShape Circle = new CircleShape(0, 0); internal DebugViewXNA DebugDraw; internal Transform Transform; private int _count; private void DrawFixture(Fixture fixture) { Color color = new Color(0.95f, 0.95f, 0.6f); Transform xf; fixture.Body.GetTransform(out xf); switch (fixture.Shape.ShapeType) { case ShapeType.Circle: { CircleShape circle = (CircleShape)fixture.Shape; Vector2 center = MathUtils.Multiply(ref xf, circle.Position); float radius = circle.Radius; DebugDraw.DrawSolidCircle(center, radius, Vector2.Zero, color); } break; case ShapeType.Polygon: { PolygonShape poly = (PolygonShape)fixture.Shape; int vertexCount = poly.Vertices.Count; Debug.Assert(vertexCount <= Settings.MaxPolygonVertices); CCVector2[] vertices = new CCVector2[Settings.MaxPolygonVertices]; for (int i = 0; i < vertexCount; ++i) { vertices[i] = (CCVector2)MathUtils.Multiply(ref xf, poly.Vertices[i]); } DebugDraw.DrawSolidPolygon(vertices, vertexCount, color); } break; } } /// <summary> /// Called for each fixture found in the query AABB. /// </summary> /// <param name="fixture">The fixture.</param> /// <returns>false to terminate the query.</returns> public bool ReportFixture(Fixture fixture) { if (_count == MaxCount) { return false; } Body body = fixture.Body; Shape shape = fixture.Shape; Transform xf; body.GetTransform(out xf); bool overlap = AABB.TestOverlap(shape, 0, Circle, 0, ref xf, ref Transform); if (overlap) { DrawFixture(fixture); ++_count; } return true; } } public class PolyShapesTest : Test { private const int MaxBodies = 256; private Body[] _bodies = new Body[MaxBodies]; private int _bodyIndex; private CircleShape _circle = new CircleShape(0, 0); private PolygonShape[] _polygons = new PolygonShape[4]; private PolyShapesTest() { // Ground body { Body ground = BodyFactory.CreateBody(World); EdgeShape shape = new EdgeShape(new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f)); ground.CreateFixture(shape); } { Vertices vertices = new Vertices(3); vertices.Add(new Vector2(-0.5f, 0.0f)); vertices.Add(new Vector2(0.5f, 0.0f)); vertices.Add(new Vector2(0.0f, 1.5f)); _polygons[0] = new PolygonShape(vertices, 1); } { Vertices vertices3 = new Vertices(3); vertices3.Add(new Vector2(-0.1f, 0.0f)); vertices3.Add(new Vector2(0.1f, 0.0f)); vertices3.Add(new Vector2(0.0f, 1.5f)); _polygons[1] = new PolygonShape(vertices3, 1); } { const float w = 1.0f; float b = w / (2.0f + (float)Math.Sqrt(2.0)); float s = (float)Math.Sqrt(2.0) * b; Vertices vertices8 = new Vertices(8); vertices8.Add(new Vector2(0.5f * s, 0.0f)); vertices8.Add(new Vector2(0.5f * w, b)); vertices8.Add(new Vector2(0.5f * w, b + s)); vertices8.Add(new Vector2(0.5f * s, w)); vertices8.Add(new Vector2(-0.5f * s, w)); vertices8.Add(new Vector2(-0.5f * w, b + s)); vertices8.Add(new Vector2(-0.5f * w, b)); vertices8.Add(new Vector2(-0.5f * s, 0.0f)); _polygons[2] = new PolygonShape(vertices8, 1); } { Vertices box = PolygonTools.CreateRectangle(0.5f, 0.5f); _polygons[3] = new PolygonShape(box, 1); } { _circle.Radius = 0.5f; } _bodyIndex = 0; } private void Create(int index) { if (_bodies[_bodyIndex] != null) { World.RemoveBody(_bodies[_bodyIndex]); _bodies[_bodyIndex] = null; } _bodies[_bodyIndex] = BodyFactory.CreateBody(World); _bodies[_bodyIndex].BodyType = BodyType.Dynamic; float x = Rand.RandomFloat(-2.0f, 2.0f); _bodies[_bodyIndex].Position = new Vector2(x, 10.0f); _bodies[_bodyIndex].Rotation = Rand.RandomFloat(-Settings.Pi, Settings.Pi); if (index == 4) { _bodies[_bodyIndex].AngularDamping = 0.02f; } if (index < 4) { Fixture fixture = _bodies[_bodyIndex].CreateFixture(_polygons[index]); fixture.Friction = 0.3f; } else { Fixture fixture = _bodies[_bodyIndex].CreateFixture(_circle); fixture.Friction = 0.3f; } _bodyIndex = (_bodyIndex + 1) % MaxBodies; } private void DestroyBody() { for (int i = 0; i < MaxBodies; ++i) { if (_bodies[i] != null) { World.RemoveBody(_bodies[i]); _bodies[i] = null; return; } } } public override void Keyboard(KeyboardManager keyboardManager) { if (keyboardManager.IsNewKeyPress(Keys.D1)) { Create(0); } if (keyboardManager.IsNewKeyPress(Keys.D2)) { Create(1); } if (keyboardManager.IsNewKeyPress(Keys.D3)) { Create(2); } if (keyboardManager.IsNewKeyPress(Keys.D4)) { Create(3); } if (keyboardManager.IsNewKeyPress(Keys.D5)) { Create(4); } if (keyboardManager.IsNewKeyPress(Keys.A)) { for (int i = 0; i < MaxBodies; i += 2) { if (_bodies[i] != null) { bool enabled = _bodies[i].Enabled; _bodies[i].Enabled = !enabled; } } } if (keyboardManager.IsNewKeyPress(Keys.D)) { DestroyBody(); } base.Keyboard(keyboardManager); } public override void Update(GameSettings settings, GameTime gameTime) { base.Update(settings, gameTime); PolyShapesCallback callback = new PolyShapesCallback(); callback.Circle.Radius = 2.0f; callback.Circle.Position = new Vector2(0.0f, 2.1f); callback.Transform.SetIdentity(); callback.DebugDraw = DebugView; AABB aabb; callback.Circle.ComputeAABB(out aabb, ref callback.Transform, 0); DebugView.BeginCustomDraw(); World.QueryAABB(callback.ReportFixture, ref aabb); Color color = new Color(0.4f, 0.7f, 0.8f); DebugView.DrawCircle(callback.Circle.Position, callback.Circle.Radius, color); DebugView.EndCustomDraw(); DebugView.DrawString(50, TextLine, "Press 1-5 to drop stuff"); TextLine += 15; DebugView.DrawString(50, TextLine, "Press a to (de)activate some bodies"); TextLine += 15; DebugView.DrawString(50, TextLine, "Press d to destroy a body"); TextLine += 15; } internal static Test Create() { return new PolyShapesTest(); } } }
using System; using ChainUtils.BouncyCastle.Crypto.Parameters; using ChainUtils.BouncyCastle.Math; using ChainUtils.BouncyCastle.Security; namespace ChainUtils.BouncyCastle.Crypto.Generators { /** * generate suitable parameters for GOST3410. */ public class Gost3410ParametersGenerator { private int size; private int typeproc; private SecureRandom init_random; /** * initialise the key generator. * * @param size size of the key * @param typeProcedure type procedure A,B = 1; A',B' - else * @param random random byte source. */ public void Init( int size, int typeProcedure, SecureRandom random) { this.size = size; typeproc = typeProcedure; init_random = random; } //Procedure A private int procedure_A(int x0, int c, BigInteger[] pq, int size) { //Verify and perform condition: 0<x<2^16; 0<c<2^16; c - odd. while(x0<0 || x0>65536) { x0 = init_random.NextInt()/32768; } while((c<0 || c>65536) || (c/2==0)) { c = init_random.NextInt()/32768 + 1; } var C = BigInteger.ValueOf(c); var constA16 = BigInteger.ValueOf(19381); //step1 var y = new BigInteger[1]; // begin length = 1 y[0] = BigInteger.ValueOf(x0); //step 2 var t = new int[1]; // t - orders; begin length = 1 t[0] = size; var s = 0; for (var i=0; t[i]>=17; i++) { // extension array t var tmp_t = new int[t.Length + 1]; /////////////// Array.Copy(t,0,tmp_t,0,t.Length); // extension t = new int[tmp_t.Length]; // array t Array.Copy(tmp_t, 0, t, 0, tmp_t.Length); /////////////// t[i+1] = t[i]/2; s = i+1; } //step3 var p = new BigInteger[s+1]; p[s] = new BigInteger("8003",16); //set min prime number length 16 bit var m = s-1; //step4 for (var i=0; i<s; i++) { var rm = t[m]/16; //step5 step6: for(;;) { //step 6 var tmp_y = new BigInteger[y.Length]; //////////////// Array.Copy(y,0,tmp_y,0,y.Length); // extension y = new BigInteger[rm+1]; // array y Array.Copy(tmp_y,0,y,0,tmp_y.Length); //////////////// for (var j=0; j<rm; j++) { y[j+1] = (y[j].Multiply(constA16).Add(C)).Mod(BigInteger.Two.Pow(16)); } //step 7 var Ym = BigInteger.Zero; for (var j=0; j<rm; j++) { Ym = Ym.Add(y[j].ShiftLeft(16*j)); } y[0] = y[rm]; //step 8 //step 9 var N = BigInteger.One.ShiftLeft(t[m]-1).Divide(p[m+1]).Add( Ym.ShiftLeft(t[m]-1).Divide(p[m+1].ShiftLeft(16*rm))); if (N.TestBit(0)) { N = N.Add(BigInteger.One); } //step 10 for(;;) { //step 11 var NByLastP = N.Multiply(p[m+1]); if (NByLastP.BitLength > t[m]) { goto step6; //step 12 } p[m] = NByLastP.Add(BigInteger.One); //step13 if (BigInteger.Two.ModPow(NByLastP, p[m]).CompareTo(BigInteger.One) == 0 && BigInteger.Two.ModPow(N, p[m]).CompareTo(BigInteger.One) != 0) { break; } N = N.Add(BigInteger.Two); } if (--m < 0) { pq[0] = p[0]; pq[1] = p[1]; return y[0].IntValue; //return for procedure B step 2 } break; //step 14 } } return y[0].IntValue; } //Procedure A' private long procedure_Aa(long x0, long c, BigInteger[] pq, int size) { //Verify and perform condition: 0<x<2^32; 0<c<2^32; c - odd. while(x0<0 || x0>4294967296L) { x0 = init_random.NextInt()*2; } while((c<0 || c>4294967296L) || (c/2==0)) { c = init_random.NextInt()*2+1; } var C = BigInteger.ValueOf(c); var constA32 = BigInteger.ValueOf(97781173); //step1 var y = new BigInteger[1]; // begin length = 1 y[0] = BigInteger.ValueOf(x0); //step 2 var t = new int[1]; // t - orders; begin length = 1 t[0] = size; var s = 0; for (var i=0; t[i]>=33; i++) { // extension array t var tmp_t = new int[t.Length + 1]; /////////////// Array.Copy(t,0,tmp_t,0,t.Length); // extension t = new int[tmp_t.Length]; // array t Array.Copy(tmp_t, 0, t, 0, tmp_t.Length); /////////////// t[i+1] = t[i]/2; s = i+1; } //step3 var p = new BigInteger[s+1]; p[s] = new BigInteger("8000000B",16); //set min prime number length 32 bit var m = s-1; //step4 for (var i=0; i<s; i++) { var rm = t[m]/32; //step5 step6: for(;;) { //step 6 var tmp_y = new BigInteger[y.Length]; //////////////// Array.Copy(y,0,tmp_y,0,y.Length); // extension y = new BigInteger[rm+1]; // array y Array.Copy(tmp_y,0,y,0,tmp_y.Length); //////////////// for (var j=0; j<rm; j++) { y[j+1] = (y[j].Multiply(constA32).Add(C)).Mod(BigInteger.Two.Pow(32)); } //step 7 var Ym = BigInteger.Zero; for (var j=0; j<rm; j++) { Ym = Ym.Add(y[j].ShiftLeft(32*j)); } y[0] = y[rm]; //step 8 //step 9 var N = BigInteger.One.ShiftLeft(t[m]-1).Divide(p[m+1]).Add( Ym.ShiftLeft(t[m]-1).Divide(p[m+1].ShiftLeft(32*rm))); if (N.TestBit(0)) { N = N.Add(BigInteger.One); } //step 10 for(;;) { //step 11 var NByLastP = N.Multiply(p[m+1]); if (NByLastP.BitLength > t[m]) { goto step6; //step 12 } p[m] = NByLastP.Add(BigInteger.One); //step13 if (BigInteger.Two.ModPow(NByLastP, p[m]).CompareTo(BigInteger.One) == 0 && BigInteger.Two.ModPow(N, p[m]).CompareTo(BigInteger.One) != 0) { break; } N = N.Add(BigInteger.Two); } if (--m < 0) { pq[0] = p[0]; pq[1] = p[1]; return y[0].LongValue; //return for procedure B' step 2 } break; //step 14 } } return y[0].LongValue; } //Procedure B private void procedure_B(int x0, int c, BigInteger[] pq) { //Verify and perform condition: 0<x<2^16; 0<c<2^16; c - odd. while(x0<0 || x0>65536) { x0 = init_random.NextInt()/32768; } while((c<0 || c>65536) || (c/2==0)) { c = init_random.NextInt()/32768 + 1; } var qp = new BigInteger[2]; BigInteger q = null, Q = null, p = null; var C = BigInteger.ValueOf(c); var constA16 = BigInteger.ValueOf(19381); //step1 x0 = procedure_A(x0, c, qp, 256); q = qp[0]; //step2 x0 = procedure_A(x0, c, qp, 512); Q = qp[0]; var y = new BigInteger[65]; y[0] = BigInteger.ValueOf(x0); const int tp = 1024; var qQ = q.Multiply(Q); step3: for(;;) { //step 3 for (var j=0; j<64; j++) { y[j+1] = (y[j].Multiply(constA16).Add(C)).Mod(BigInteger.Two.Pow(16)); } //step 4 var Y = BigInteger.Zero; for (var j=0; j<64; j++) { Y = Y.Add(y[j].ShiftLeft(16*j)); } y[0] = y[64]; //step 5 //step 6 var N = BigInteger.One.ShiftLeft(tp-1).Divide(qQ).Add( Y.ShiftLeft(tp-1).Divide(qQ.ShiftLeft(1024))); if (N.TestBit(0)) { N = N.Add(BigInteger.One); } //step 7 for(;;) { //step 11 var qQN = qQ.Multiply(N); if (qQN.BitLength > tp) { goto step3; //step 9 } p = qQN.Add(BigInteger.One); //step10 if (BigInteger.Two.ModPow(qQN, p).CompareTo(BigInteger.One) == 0 && BigInteger.Two.ModPow(q.Multiply(N), p).CompareTo(BigInteger.One) != 0) { pq[0] = p; pq[1] = q; return; } N = N.Add(BigInteger.Two); } } } //Procedure B' private void procedure_Bb(long x0, long c, BigInteger[] pq) { //Verify and perform condition: 0<x<2^32; 0<c<2^32; c - odd. while(x0<0 || x0>4294967296L) { x0 = init_random.NextInt()*2; } while((c<0 || c>4294967296L) || (c/2==0)) { c = init_random.NextInt()*2+1; } var qp = new BigInteger[2]; BigInteger q = null, Q = null, p = null; var C = BigInteger.ValueOf(c); var constA32 = BigInteger.ValueOf(97781173); //step1 x0 = procedure_Aa(x0, c, qp, 256); q = qp[0]; //step2 x0 = procedure_Aa(x0, c, qp, 512); Q = qp[0]; var y = new BigInteger[33]; y[0] = BigInteger.ValueOf(x0); const int tp = 1024; var qQ = q.Multiply(Q); step3: for(;;) { //step 3 for (var j=0; j<32; j++) { y[j+1] = (y[j].Multiply(constA32).Add(C)).Mod(BigInteger.Two.Pow(32)); } //step 4 var Y = BigInteger.Zero; for (var j=0; j<32; j++) { Y = Y.Add(y[j].ShiftLeft(32*j)); } y[0] = y[32]; //step 5 //step 6 var N = BigInteger.One.ShiftLeft(tp-1).Divide(qQ).Add( Y.ShiftLeft(tp-1).Divide(qQ.ShiftLeft(1024))); if (N.TestBit(0)) { N = N.Add(BigInteger.One); } //step 7 for(;;) { //step 11 var qQN = qQ.Multiply(N); if (qQN.BitLength > tp) { goto step3; //step 9 } p = qQN.Add(BigInteger.One); //step10 if (BigInteger.Two.ModPow(qQN, p).CompareTo(BigInteger.One) == 0 && BigInteger.Two.ModPow(q.Multiply(N), p).CompareTo(BigInteger.One) != 0) { pq[0] = p; pq[1] = q; return; } N = N.Add(BigInteger.Two); } } } /** * Procedure C * procedure generates the a value from the given p,q, * returning the a value. */ private BigInteger procedure_C(BigInteger p, BigInteger q) { var pSub1 = p.Subtract(BigInteger.One); var pSub1Divq = pSub1.Divide(q); for(;;) { var d = new BigInteger(p.BitLength, init_random); // 1 < d < p-1 if (d.CompareTo(BigInteger.One) > 0 && d.CompareTo(pSub1) < 0) { var a = d.ModPow(pSub1Divq, p); if (a.CompareTo(BigInteger.One) != 0) { return a; } } } } /** * which generates the p , q and a values from the given parameters, * returning the Gost3410Parameters object. */ public Gost3410Parameters GenerateParameters() { var pq = new BigInteger[2]; BigInteger q = null, p = null, a = null; int x0, c; long x0L, cL; if (typeproc==1) { x0 = init_random.NextInt(); c = init_random.NextInt(); switch(size) { case 512: procedure_A(x0, c, pq, 512); break; case 1024: procedure_B(x0, c, pq); break; default: throw new ArgumentException("Ooops! key size 512 or 1024 bit."); } p = pq[0]; q = pq[1]; a = procedure_C(p, q); //System.out.println("p:"+p.toString(16)+"\n"+"q:"+q.toString(16)+"\n"+"a:"+a.toString(16)); //System.out.println("p:"+p+"\n"+"q:"+q+"\n"+"a:"+a); return new Gost3410Parameters(p, q, a, new Gost3410ValidationParameters(x0, c)); } else { x0L = init_random.NextLong(); cL = init_random.NextLong(); switch(size) { case 512: procedure_Aa(x0L, cL, pq, 512); break; case 1024: procedure_Bb(x0L, cL, pq); break; default: throw new InvalidOperationException("Ooops! key size 512 or 1024 bit."); } p = pq[0]; q = pq[1]; a = procedure_C(p, q); //System.out.println("p:"+p.toString(16)+"\n"+"q:"+q.toString(16)+"\n"+"a:"+a.toString(16)); //System.out.println("p:"+p+"\n"+"q:"+q+"\n"+"a:"+a); return new Gost3410Parameters(p, q, a, new Gost3410ValidationParameters(x0L, cL)); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Torshify.Core.Managers; namespace Torshify.Core.Native { internal class NativeSession : NativeObject, ISession { #region Fields private readonly byte[] _applicationKey; private readonly SessionOptions _options; private IPlaylistContainer _playlistContainer; private IPlaylist _starredPlaylist; private Thread _mainThread; private Thread _eventThread; private AutoResetEvent _mainThreadNotification; private Queue<DelegateInvoker> _eventQueue; private NativeSessionCallbacks _callbacks; private readonly object _eventQueueLock = new object(); #endregion Fields #region Constructors public NativeSession(byte[] applicationKey, SessionOptions options) : base(null, IntPtr.Zero) { _applicationKey = applicationKey; _options = options; } #endregion Constructors #region Events public event EventHandler<SessionEventArgs> ConnectionError; public event EventHandler<SessionEventArgs> EndOfTrack; public event EventHandler<SessionEventArgs> Exception; public event EventHandler<SessionEventArgs> LoginComplete; public event EventHandler<SessionEventArgs> LogMessage; public event EventHandler<SessionEventArgs> LogoutComplete; public event EventHandler<SessionEventArgs> MessageToUser; public event EventHandler<SessionEventArgs> MetadataUpdated; public event EventHandler<MusicDeliveryEventArgs> MusicDeliver; public event EventHandler<SessionEventArgs> PlayTokenLost; public event EventHandler<SessionEventArgs> StartPlayback; public event EventHandler<SessionEventArgs> StopPlayback; public event EventHandler<SessionEventArgs> StreamingError; public event EventHandler<SessionEventArgs> UserinfoUpdated; public event EventHandler<SessionEventArgs> OfflineStatusUpdated; public event EventHandler<SessionEventArgs> OfflineError; public event EventHandler<CredentialsBlobEventArgs> CredentialsBlobUpdated; public event EventHandler<SessionEventArgs> ConnectionStateUpdated; public event EventHandler<SessionEventArgs> ScrobbleError; public event EventHandler<PrivateSessionModeChangedEventArgs> PrivateSessionModeChanged; #endregion Events #region Properties public IPlaylistContainer PlaylistContainer { get { ConnectionState connectionState = ConnectionState; if (connectionState == ConnectionState.Disconnected || connectionState == ConnectionState.LoggedOut) { return null; } AssertHandle(); return _playlistContainer; } } public IPlaylist Starred { get { if (ConnectionState != ConnectionState.LoggedIn) { return null; } AssertHandle(); if (_starredPlaylist == null) { lock (Spotify.Mutex) { _starredPlaylist = PlaylistManager.Get(this, Spotify.sp_session_starred_create(Handle)); } } return _starredPlaylist; } } public ConnectionState ConnectionState { get { if (!IsInvalid) { try { lock (Spotify.Mutex) { return Spotify.sp_session_connectionstate(Handle); } } catch { return ConnectionState.Undefined; } } return ConnectionState.Undefined; } } public IUser LoggedInUser { get { if (ConnectionState != ConnectionState.LoggedIn) { return null; } AssertHandle(); lock (Spotify.Mutex) { return UserManager.Get(this, Spotify.sp_session_user(Handle)); } } } public int LoggedInUserCountry { get { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_user_country(Handle); } } } public bool IsVolumeNormalizationEnabled { get { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_get_volume_normalization(Handle); } } set { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_set_volume_normalization(Handle, value); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } } public bool IsPrivateSessionEnabled { get { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_is_private_session(Handle); } } set { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_set_private_session(Handle, value); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } } public override ISession Session { get { return this; } } #endregion Properties #region Public Methods public void Login(string userName, string password, bool rememberMe = false) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_login(Handle, userName, password, rememberMe, null); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } public void LoginWithBlob(string userName, string blob) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_login(Handle, userName, null, false, blob); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } public void Relogin() { AssertHandle(); lock (Spotify.Mutex) { var error = Spotify.sp_session_relogin(Handle); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } public void ForgetStoredLogin() { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_forget_me(Handle); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } public string GetRememberedUser() { AssertHandle(); int bufferSize = Spotify.STRINGBUFFER_SIZE; try { int userNameLength; StringBuilder builder = new StringBuilder(bufferSize); lock (Spotify.Mutex) { userNameLength = Spotify.sp_session_remembered_user(Handle, builder, bufferSize); } if (userNameLength == -1) { return string.Empty; } return builder.ToString(); } catch { return string.Empty; } } public void Logout() { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_logout(Handle); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } } public Error PlayerLoad(ITrack track) { AssertHandle(); INativeObject nativeObject = track as INativeObject; if (nativeObject == null) { throw new ArgumentException("Invalid argument"); } lock (Spotify.Mutex) { return Spotify.sp_session_player_load(Handle, nativeObject.Handle); } } public Error PlayerPrefetch(ITrack track) { AssertHandle(); INativeObject nativeObject = track as INativeObject; if (nativeObject == null) { throw new ArgumentException("Invalid argument"); } lock (Spotify.Mutex) { return Spotify.sp_session_player_prefetch(Handle, nativeObject.GetHandle()); } } public Error PlayerPause() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_player_play(Handle, false); } } public Error PlayerPlay() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_player_play(Handle, true); } } public Error PlayerSeek(TimeSpan offset) { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_player_seek(Handle, (int)offset.TotalMilliseconds); } } public Error PlayerUnload() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_session_player_unload(Handle); } } public ISearch Search( string query, int trackOffset, int trackCount, int albumOffset, int albumCount, int artistOffset, int artistCount, int playlistOffset, int playlistCount, SearchType searchType, object userData = null) { AssertHandle(); var search = new NativeSearch( this, query, trackOffset, trackCount, albumOffset, albumCount, artistOffset, artistCount, playlistOffset, playlistCount, searchType, userData); search.Initialize(); return search; } public IAlbumBrowse Browse(IAlbum album, object userData = null) { if (!(album is INativeObject)) { throw new ArgumentException("Invalid type"); } AssertHandle(); var browse = new NativeAlbumBrowse(this, album, userData); browse.Initialize(); return browse; } public IArtistBrowse Browse(IArtist artist, object userData = null) { return Browse(artist, ArtistBrowseType.Full, userData); } public IArtistBrowse Browse(IArtist artist, ArtistBrowseType browseType, object userData = null) { if (!(artist is INativeObject)) { throw new ArgumentException("Invalid type"); } AssertHandle(); var browse = new NativeArtistBrowse(this, artist.GetHandle(), browseType); browse.Initialize(); return browse; } public IToplistBrowse Browse(ToplistType type, int encodedCountryCode, object userData = null) { AssertHandle(); var browse = new NativeToplistBrowse(this, type, encodedCountryCode, userData); browse.Initialize(); return browse; } public IToplistBrowse Browse(ToplistType type, object userData = null) { return Browse(type, (int)ToplistSpecialRegion.Everywhere, userData); } public IToplistBrowse Browse(ToplistType type, string userName, object userData = null) { AssertHandle(); var browse = new NativeToplistBrowse(this, type, userName, userData); browse.Initialize(); return browse; } public IToplistBrowse BrowseCurrentUser(ToplistType type, object userData = null) { return Browse(type, null, userData); } public IImage GetImage(string id) { AssertHandle(); if (id == null) { throw new ArgumentNullException("id"); } if (id.Length != 40) { throw new ArgumentException("invalid id", "id"); } var image = new NativeImage(this, id); image.Initialize(); return image; } public ISession SetPreferredBitrate(Bitrate bitrate) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_preferred_bitrate(Handle, bitrate); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } return this; } public ISession SetPreferredOfflineBitrate(Bitrate bitrate, bool resync) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_preferred_offline_bitrate(Handle, bitrate, resync); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } return this; } public ISession SetConnectionType(ConnectionType connectionType) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_set_connection_type(Handle, connectionType); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } return this; } public ISession SetConnectionRules(ConnectionRule connectionRule) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_set_connection_rules(Handle, connectionRule); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } return this; } public ISession SetCacheSize(uint megabytes) { AssertHandle(); lock (Spotify.Mutex) { Error error = Spotify.sp_session_set_cache_size(Handle, megabytes); if (error != Error.OK) { throw new TorshifyException(error.GetMessage(), error); } } return this; } public int GetNumberOfOfflineTracksRemainingToSync() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_offline_tracks_to_sync(Handle); } } public int GetNumberOfOfflinePlaylists() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_offline_num_playlists(Handle); } } public OfflineSyncStatus GetOfflineSyncStatus() { AssertHandle(); var syncStatus = new OfflineSyncStatus(); lock (Spotify.Mutex) { Spotify.SpotifyOfflineSyncStatus offlineSyncStatus = new Spotify.SpotifyOfflineSyncStatus(); Spotify.sp_offline_sync_get_status(Handle, ref offlineSyncStatus); syncStatus.CopiedBytes = offlineSyncStatus.CopiedBytes; syncStatus.CopiedTracks = offlineSyncStatus.CopiedTracks; syncStatus.DoneBytes = offlineSyncStatus.DoneBytes; syncStatus.DoneTracks = offlineSyncStatus.DoneTracks; syncStatus.ErrorTracks = offlineSyncStatus.ErrorTracks; syncStatus.IsSyncing = offlineSyncStatus.Syncing; syncStatus.QueuedBytes = offlineSyncStatus.QueuedBytes; syncStatus.QueuedTracks = offlineSyncStatus.QueuedTracks; } return syncStatus; } public IPlaylist GetStarredForUser(string canonicalUserName) { if (ConnectionState != ConnectionState.LoggedIn) { return null; } AssertHandle(); lock (Spotify.Mutex) { IntPtr starredPtr = Spotify.sp_session_starred_for_user_create(Handle, canonicalUserName); return PlaylistManager.Get(this, starredPtr); } } public IPlaylistContainer GetPlaylistContainerForUser(string canonicalUsername) { if (ConnectionState != ConnectionState.LoggedIn) { return null; } AssertHandle(); lock (Spotify.Mutex) { IntPtr containerPtr = Spotify.sp_session_publishedcontainer_for_user_create(Handle, canonicalUsername); return PlaylistContainerManager.Get(this, containerPtr); } } public Error FlushCaches() { lock (Spotify.Mutex) { return Spotify.sp_session_flush_caches(Handle); } } public override void Initialize() { _callbacks = new NativeSessionCallbacks(this); if (!string.IsNullOrEmpty(_options.SettingsLocation)) { Directory.CreateDirectory(_options.SettingsLocation); } var sessionConfig = new Spotify.SpotifySessionConfig { ApiVersion = Spotify.SPOTIFY_API_VERSION, CacheLocation = _options.CacheLocation, SettingsLocation = _options.SettingsLocation, UserAgent = _options.UserAgent, CompressPlaylists = _options.CompressPlaylists, DontSaveMetadataForPlaylists = _options.DontSavePlaylistMetadata, InitiallyUnloadPlaylists = _options.InitiallyUnloadPlaylists, ApplicationKey = Marshal.AllocHGlobal(_applicationKey.Length), ApplicationKeySize = _applicationKey.Length, Callbacks = _callbacks.CallbackHandle, DeviceID = _options.DeviceID, TraceFile = _options.TraceFileLocation, Proxy = _options.Proxy, ProxyUsername = _options.ProxyUsername, ProxyPassword = _options.ProxyPassword }; try { Marshal.Copy(_applicationKey, 0, sessionConfig.ApplicationKey, _applicationKey.Length); lock (Spotify.Mutex) { IntPtr sessionPtr; Error res = Spotify.sp_session_create(ref sessionConfig, out sessionPtr); if (res != Error.OK) { throw new TorshifyException(res.GetMessage(), res); } Handle = sessionPtr; } } finally { if (sessionConfig.ApplicationKey != IntPtr.Zero) { Marshal.FreeHGlobal(sessionConfig.ApplicationKey); sessionConfig.ApplicationKey = IntPtr.Zero; } } _mainThreadNotification = new AutoResetEvent(false); _mainThread = new Thread(MainThreadLoop); _mainThread.Name = "MainLoop"; _mainThread.IsBackground = true; _mainThread.Start(); _eventQueue = new Queue<DelegateInvoker>(); _eventThread = new Thread(EventThreadLoop); _eventThread.Name = "EventLoop"; _eventThread.IsBackground = true; _eventThread.Start(); AppDomain.CurrentDomain.ProcessExit += OnHostProcessExit; } #endregion Public Methods #region Internal Methods internal void Queue(DelegateInvoker delegateInvoker) { lock (_eventQueueLock) { _eventQueue.Enqueue(delegateInvoker); Monitor.Pulse(_eventQueueLock); } } internal void OnNotifyMainThread() { _mainThreadNotification.Set(); } internal void OnException(SessionEventArgs e) { Exception.RaiseEvent(this, e); } internal void OnLoginComplete(SessionEventArgs e) { if (e.Status == Error.OK) { _playlistContainer = PlaylistContainerManager.Get(this, Spotify.sp_session_playlistcontainer(Handle)); } LoginComplete.RaiseEvent(this, e); } internal void OnLogoutComplete(SessionEventArgs e) { LogoutComplete.RaiseEvent(this, e); } internal void OnLogMessage(SessionEventArgs e) { LogMessage.RaiseEvent(this, e); } internal void OnConnectionError(SessionEventArgs e) { ConnectionError.RaiseEvent(this, e); } internal void OnEndOfTrack(SessionEventArgs e) { EndOfTrack.RaiseEvent(this, e); } internal void OnMessageToUser(SessionEventArgs e) { MessageToUser.RaiseEvent(this, e); } internal void OnMetadataUpdated(SessionEventArgs e) { MetadataUpdated.RaiseEvent(this, e); } internal void OnMusicDeliver(MusicDeliveryEventArgs e) { MusicDeliver.RaiseEvent(this, e); } internal void OnPlayTokenLost(SessionEventArgs e) { PlayTokenLost.RaiseEvent(this, e); } internal void OnStartPlayback(SessionEventArgs e) { StartPlayback.RaiseEvent(this, e); } internal void OnStopPlayback(SessionEventArgs e) { StopPlayback.RaiseEvent(this, e); } internal void OnStreamingError(SessionEventArgs e) { StreamingError.RaiseEvent(this, e); } internal void OnUserinfoUpdated(SessionEventArgs e) { UserinfoUpdated.RaiseEvent(this, e); } internal void OnOfflineStatusUpdated(SessionEventArgs e) { OfflineStatusUpdated.RaiseEvent(this, e); } internal void OnOfflineError(SessionEventArgs e) { OfflineError.RaiseEvent(this, e); } internal void OnCredentialsBlobUpdated(CredentialsBlobEventArgs e) { CredentialsBlobUpdated.RaiseEvent(this, e); } internal void OnConnectionStateUpdated(SessionEventArgs e) { ConnectionStateUpdated.RaiseEvent(this, e); } internal void OnScrobbleError(SessionEventArgs e) { ScrobbleError.RaiseEvent(this, e); } internal void OnPrivateSessionModeChanged(PrivateSessionModeChangedEventArgs e) { PrivateSessionModeChanged.RaiseEvent(this, e); } #endregion Internal Methods #region Protected Methods protected override void Dispose(bool disposing) { if (disposing) { // Dispose managed } // Dispose unmanaged if (!IsInvalid) { try { _mainThreadNotification.Set(); lock (_eventQueueLock) { Monitor.Pulse(_eventQueueLock); } if (_callbacks != null) { _callbacks.Dispose(); _callbacks = null; } PlaylistTrackManager.RemoveAll(this); TrackManager.DisposeAll(this); LinkManager.RemoveAll(this); UserManager.RemoveAll(this); PlaylistContainerManager.RemoveAll(this); PlaylistManager.RemoveAll(this); ContainerPlaylistManager.RemoveAll(this); ArtistManager.RemoveAll(); AlbumManager.RemoveAll(); SessionManager.Remove(Handle); lock (Spotify.Mutex) { Error error = Error.OK; if (ConnectionState == ConnectionState.LoggedIn) { error = Spotify.sp_session_logout(Handle); Debug.WriteLineIf(error != Error.OK, error.GetMessage()); } Ensure(() => error = Spotify.sp_session_release(Handle)); Debug.WriteLineIf(error != Error.OK, error.GetMessage()); } } catch { // Ignore } finally { Debug.WriteLine("Session disposed"); } } base.Dispose(disposing); } #endregion Protected Methods #region Private Methods private void OnHostProcessExit(object sender, EventArgs e) { Dispose(); } private void MainThreadLoop() { int waitTime = 0; while (!IsInvalid && waitTime >= 0) { _mainThreadNotification.WaitOne(waitTime, false); do { lock (Spotify.Mutex) { try { if (IsInvalid) { break; } Error error = Spotify.sp_session_process_events(Handle, out waitTime); if (error != Error.OK) { Debug.WriteLine(Spotify.sp_error_message(error)); } } catch { waitTime = 1000; } } } while (waitTime == 0); } Debug.WriteLine("Main loop exiting."); } private void EventThreadLoop() { while (!IsInvalid) { DelegateInvoker invoker = null; lock (_eventQueueLock) { if (_eventQueue.Count == 0) { Monitor.Wait(_eventQueueLock); } if (_eventQueue.Count > 0) { invoker = _eventQueue.Dequeue(); } } if (invoker != null) { try { invoker.Execute(); } catch (Exception ex) { OnException(new SessionEventArgs(ex.ToString())); } } } Debug.WriteLine("Event loop exiting"); } #endregion Private Methods } }
//============================================================================= // System : Sandcastle Help File Builder Utilities // File : DocumentationSourceCollection.cs // Author : Eric Woodruff ([email protected]) // Updated : 09/04/2008 // Note : Copyright 2006-2008, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains a collection class used to hold the documentation // sources. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.0.0.0 08/03/2006 EFW Created the code // 1.4.0.2 05/11/2007 EFW Added the ability to sort the collection // 1.6.0.2 11/10/2007 EFW Moved CommentFileList to XmlCommentsFileCollection // 1.6.0.7 04/16/2008 EFW Added support for wildcards // 1.8.0.0 06/23/2008 EFW Rewrote to support MSBuild project format //============================================================================= using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Text; using System.Xml; namespace SandcastleBuilder.Utils { /// <summary> /// This collection class is used to hold the documentation sources /// </summary> /// <remarks>A documentation source is an assembly, an XML comments file, /// a Visual Studio project (C#, VB.NET, or J#), or a Visual Studio /// solution containing one or more C#, VB.NET or J# projects.</remarks> public class DocumentationSourceCollection : BindingList<DocumentationSource> { #region Private data members //===================================================================== private SandcastleProject projectFile; private bool isDirty; #endregion #region Properties //===================================================================== /// <summary> /// This is used to get or set the dirty state of the collection /// </summary> public bool IsDirty { get { foreach(DocumentationSource ds in this) if(ds.IsDirty) return true; return isDirty; } set { foreach(DocumentationSource ds in this) ds.IsDirty = value; isDirty = value; } } /// <summary> /// This read-only property returns a list of assemblies in the /// collection. /// </summary> public Collection<string> Assemblies { get { Collection<string> assemblies = new Collection<string>(); foreach(DocumentationSource ds in this) foreach(string file in DocumentationSource.Assemblies( ds.SourceFile, ds.IncludeSubFolders)) assemblies.Add(file); return assemblies; } } /// <summary> /// This read-only property returns a list of XML comments files in the /// collection. /// </summary> public Collection<string> CommentsFiles { get { Collection<string> comments = new Collection<string>(); foreach(DocumentationSource ds in this) foreach(string file in DocumentationSource.CommentsFiles( ds.SourceFile, ds.IncludeSubFolders)) comments.Add(file); return comments; } } #endregion #region Constructor //===================================================================== /// <summary> /// Internal constructor /// </summary> /// <param name="project">The project that owns the collection</param> internal DocumentationSourceCollection(SandcastleProject project) { projectFile = project; } #endregion #region Sort the collection //===================================================================== /// <summary> /// This is used to sort the collection in ascending order. /// </summary> public void Sort() { ((List<DocumentationSource>)base.Items).Sort( delegate(DocumentationSource x, DocumentationSource y) { return String.Compare(x.SourceDescription, y.SourceDescription, StringComparison.CurrentCultureIgnoreCase); }); base.OnListChanged(new ListChangedEventArgs( ListChangedType.Reset, -1)); } #endregion #region Read/write doc sources from/to XML //===================================================================== /// <summary> /// This is used to load existing documentation sources from the /// project file. /// </summary> /// <param name="docSources">The documentation source items</param> /// <remarks>The information is stored as an XML fragment</remarks> internal void FromXml(string docSources) { XmlTextReader xr = null; string sourceFile, config, platform; bool subFolders; try { xr = new XmlTextReader(docSources, XmlNodeType.Element, new XmlParserContext(null, null, null, XmlSpace.Default)); xr.Namespaces = false; xr.MoveToContent(); while(!xr.EOF) { if(xr.NodeType == XmlNodeType.Element && xr.Name == "DocumentationSource") { sourceFile = xr.GetAttribute("sourceFile"); config = xr.GetAttribute("configuration"); platform = xr.GetAttribute("platform"); subFolders = Convert.ToBoolean(xr.GetAttribute( "subFolders"), CultureInfo.InvariantCulture); this.Add(sourceFile, config, platform, subFolders); } xr.Read(); } } finally { if(xr != null) xr.Close(); isDirty = false; } } /// <summary> /// This is used to write the documentation source info to an XML /// fragment ready for storing in the project file. /// </summary> /// <returns>The XML fragment containing the documentation sources</returns> internal string ToXml() { MemoryStream ms = new MemoryStream(10240); XmlTextWriter xw = null; try { xw = new XmlTextWriter(ms, new UTF8Encoding(false)); xw.Formatting = Formatting.Indented; foreach(DocumentationSource ds in this) { xw.WriteStartElement("DocumentationSource"); xw.WriteAttributeString("sourceFile", ds.SourceFile.PersistablePath); if(!String.IsNullOrEmpty(ds.Configuration)) xw.WriteAttributeString("configuration", ds.Configuration); if(!String.IsNullOrEmpty(ds.Platform)) xw.WriteAttributeString("platform", ds.Platform); if(ds.IncludeSubFolders) xw.WriteAttributeString("subFolders", ds.IncludeSubFolders.ToString()); xw.WriteEndElement(); } xw.Flush(); return Encoding.UTF8.GetString(ms.ToArray()); } finally { if(xw != null) xw.Close(); ms.Dispose(); } } #endregion #region Add a new doc source to the project //===================================================================== /// <summary> /// Add a new item to the collection /// </summary> /// <param name="filename">The filename to add</param> /// <param name="config">The configuration to use for projects</param> /// <param name="platform">The platform to use for projects</param> /// <param name="subFolders">True to include subfolders, false to /// only search the top-level folder.</param> /// <returns>The <see cref="DocumentationSource" /> added to the /// project or the existing item if the filename already exists in the /// collection.</returns> /// <remarks>The <see cref="DocumentationSource" /> constructor is /// internal so that we control creation of the items and can /// associate them with the project.</remarks> public DocumentationSource Add(string filename, string config, string platform, bool subFolders) { DocumentationSource item; // Make the path relative to the project if possible if(Path.IsPathRooted(filename)) filename = FilePath.AbsoluteToRelativePath(projectFile.BasePath, filename); item = new DocumentationSource(filename, config, platform, subFolders, projectFile); if(!base.Contains(item)) base.Add(item); else item = base[base.IndexOf(item)]; return item; } #endregion #region Method overrides //===================================================================== /// <summary> /// This is overridden to mark the collection as dirty when it changes /// </summary> /// <param name="e">The event arguments</param> protected override void OnListChanged(ListChangedEventArgs e) { isDirty = true; base.OnListChanged(e); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Windows.Forms; using VersionOne.ServiceHost.ConfigurationTool.BZ; using VersionOne.ServiceHost.ConfigurationTool.Entities; using VersionOne.ServiceHost.ConfigurationTool.UI; using VersionOne.ServiceHost.ConfigurationTool.UI.Controls; using VersionOne.ServiceHost.ConfigurationTool.UI.Interfaces; namespace VersionOne.ServiceHost.ConfigurationTool { public class ConfigurationFormController : IConfigurationController, IFormController { private IConfigurationView view; private ServiceHostConfiguration settings; private string currentFileNameValue = string.Empty; private readonly IFacade facadeImpl; private readonly IUIFactory uiFactory; #region IConfigurationController Members public IConfigurationView View { get { return view; } } public ServiceHostConfiguration Settings { get { return settings; } } public string ApplicationVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public string CurrentFileName { get { return currentFileNameValue; } } public ConfigurationFormController(IFacade facade, IUIFactory uiFactory) { facadeImpl = facade; this.uiFactory = uiFactory; settings = facade.CreateConfiguration(); } public void ShowPage(string pageKey) { try { var newView = uiFactory.GetNextPage(pageKey, Settings, this); View.HeaderText = pageKey; View.CurrentControl = newView; } catch (DependencyFailureException ex) { view.ShowErrorMessage(ex.Message); } catch (V1ConnectionRequiredException) { view.ShowErrorMessage("To open the page, valid V1 connection is required"); } } public void RegisterView(IConfigurationView configurationView) { if (configurationView == null) { throw new InvalidOperationException("View must be initialized"); } view = configurationView; configurationView.Controller = this; } public void PrepareView() { view.GenerateSnapshotMenuItemEnabled = false; view.NewFileMenuItemEnabled = false; view.OpenFileMenuItemEnabled = true; view.OptionsMenuItemEnabled = false; view.SaveFileAsMenuItemEnabled = true; view.SaveFileMenuItemEnabled = true; if (facadeImpl.AnyFileExists(Facade.ConfigurationFileNames)) { LoadFromAnyDefaultFile(); } else { view.SetServiceNodesAndRedraw(null, null); view.SetCoreServiceNodesEnabled(false); } } private void LoadFromAnyDefaultFile() { foreach (var fileName in Facade.ConfigurationFileNames) { if (facadeImpl.FileExists(fileName)) { LoadFromFile(fileName); return; } } } public void SaveToFile(string fileName) { if (string.IsNullOrEmpty(fileName)) { fileName = Facade.ConfigurationFileNames[0]; } InvokeBeforeSave(); var result = facadeImpl.SaveConfigurationToFile(Settings, fileName); if (result.IsValid) { settings.HasChanged = false; return; } var sb = new StringBuilder("Cannot save settings to file. The following errors were encountered: "); foreach (var error in result.GeneralErrors) { AppendErrorString(sb, error); } foreach (var entity in result.InvalidEntities.Keys) { AppendErrorString(sb, GetInvalidPageErrorMessage(entity, result.InvalidEntities[entity])); } view.ShowErrorMessage(sb.ToString()); } private static void AppendErrorString(StringBuilder sb, string message) { sb.AppendFormat("{0} {1}", Environment.NewLine, message); } private string GetInvalidPageErrorMessage(BaseServiceEntity entity, IEnumerable<string> messages) { var pageName = uiFactory.ResolvePageNameByEntity(entity); return string.Format("{0} page contains invalid data:{1}{2}{3}", pageName, Environment.NewLine, "-", string.Join(Environment.NewLine + "-", messages.ToArray())); } public void LoadFromFile(string fileName) { try { settings = facadeImpl.LoadConfigurationFromFile(fileName); new DependencyValidator(facadeImpl).CheckServiceDependencies(settings); facadeImpl.ResetConnection(); ShowPage("General"); view.SetServiceNodesAndRedraw(uiFactory.GetCoreServiceNames(settings), uiFactory.GetCustomServiceNames(settings)); view.SetCoreServiceNodesEnabled(false); currentFileNameValue = fileName; } catch (InvalidFilenameException ex) { view.ShowErrorMessage(ex.Message); } catch (DependencyFailureException) { settings = facadeImpl.CreateConfiguration(); view.SetServiceNodesAndRedraw(null, null); view.ShowErrorMessage(Resources.ServiceDependenciesInFileInvalid); } } public bool ValidatePageAvailability(string pageKey) { var model = uiFactory.ResolveModel(pageKey, settings); try { if (model is BaseServiceEntity) { new DependencyValidator(facadeImpl).CheckVersionOneDependency((BaseServiceEntity)model); } } catch (V1ConnectionRequiredException) { View.ShowErrorMessage(Resources.V1ConnectionRequiredForPage); return false; } return true; } #endregion #region IFormController Members public void SetCoreServiceNodesEnabled(bool enabled) { View.SetCoreServiceNodesEnabled(enabled); } public void FailApplication(string message) { view.ShowErrorMessage("Could not load application dependency. Application will be closed."); facadeImpl.LogMessage(message); Environment.Exit(-1); } public event EventHandler BeforeSave; private void InvokeBeforeSave() { if (BeforeSave != null) { BeforeSave(this, EventArgs.Empty); } } #endregion } }
/* * 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.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenSim; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.ApplicationPlugins.RegionModulesController { [Extension(Path = "/OpenSim/Startup", Id = "LoadRegions", NodeName = "Plugin")] public class RegionModulesControllerPlugin : IRegionModulesController, IApplicationPlugin { // Logger private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Controls whether we load modules from Mono.Addins. /// </summary> /// <remarks>For debug purposes. Defaults to true.</remarks> public bool LoadModulesFromAddins { get; set; } // Config access private OpenSimBase m_openSim; // Our name private string m_name; // Internal lists to collect information about modules present private List<TypeExtensionNode> m_nonSharedModules = new List<TypeExtensionNode>(); private List<TypeExtensionNode> m_sharedModules = new List<TypeExtensionNode>(); // List of shared module instances, for adding to Scenes private List<ISharedRegionModule> m_sharedInstances = new List<ISharedRegionModule>(); public RegionModulesControllerPlugin() { LoadModulesFromAddins = true; } #region IApplicationPlugin implementation public void Initialise (OpenSimBase openSim) { m_openSim = openSim; m_openSim.ApplicationRegistry.RegisterInterface<IRegionModulesController>(this); m_log.DebugFormat("[REGIONMODULES]: Initializing..."); if (!LoadModulesFromAddins) return; // Who we are string id = AddinManager.CurrentAddin.Id; // Make friendly name int pos = id.LastIndexOf("."); if (pos == -1) m_name = id; else m_name = id.Substring(pos + 1); // The [Modules] section in the ini file IConfig modulesConfig = m_openSim.ConfigSource.Source.Configs["Modules"]; if (modulesConfig == null) modulesConfig = m_openSim.ConfigSource.Source.AddConfig("Modules"); Dictionary<RuntimeAddin, IList<int>> loadedModules = new Dictionary<RuntimeAddin, IList<int>>(); // Scan modules and load all that aren't disabled foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes("/OpenSim/RegionModules")) AddNode(node, modulesConfig, loadedModules); foreach (KeyValuePair<RuntimeAddin, IList<int>> loadedModuleData in loadedModules) { m_log.InfoFormat( "[REGIONMODULES]: From plugin {0}, (version {1}), loaded {2} modules, {3} shared, {4} non-shared {5} unknown", loadedModuleData.Key.Id, loadedModuleData.Key.Version, loadedModuleData.Value[0] + loadedModuleData.Value[1] + loadedModuleData.Value[2], loadedModuleData.Value[0], loadedModuleData.Value[1], loadedModuleData.Value[2]); } // Load and init the module. We try a constructor with a port // if a port was given, fall back to one without if there is // no port or the more specific constructor fails. // This will be removed, so that any module capable of using a port // must provide a constructor with a port in the future. // For now, we do this so migration is easy. // foreach (TypeExtensionNode node in m_sharedModules) { Object[] ctorArgs = new Object[] { (uint)0 }; // Read the config again string moduleString = modulesConfig.GetString("Setup_" + node.Id, String.Empty); // Test to see if we want this module if (moduleString == "disabled") continue; // Get the port number, if there is one if (moduleString != String.Empty) { // Get the port number from the string string[] moduleParts = moduleString.Split(new char[] { '/' }, 2); if (moduleParts.Length > 1) ctorArgs[0] = Convert.ToUInt32(moduleParts[0]); } // Try loading and initilaizing the module, using the // port if appropriate ISharedRegionModule module = null; try { module = (ISharedRegionModule)Activator.CreateInstance( node.Type, ctorArgs); } catch { module = (ISharedRegionModule)Activator.CreateInstance( node.Type); } // OK, we're up and running m_sharedInstances.Add(module); module.Initialise(m_openSim.ConfigSource.Source); } } public void PostInitialise () { m_log.DebugFormat("[REGIONMODULES]: PostInitializing..."); // Immediately run PostInitialise on shared modules foreach (ISharedRegionModule module in m_sharedInstances) { module.PostInitialise(); } } #endregion #region IPlugin implementation private void AddNode( TypeExtensionNode node, IConfig modulesConfig, Dictionary<RuntimeAddin, IList<int>> loadedModules) { IList<int> loadedModuleData; if (!loadedModules.ContainsKey(node.Addin)) loadedModules.Add(node.Addin, new List<int> { 0, 0, 0 }); loadedModuleData = loadedModules[node.Addin]; if (node.Type.GetInterface(typeof(ISharedRegionModule).ToString()) != null) { if (CheckModuleEnabled(node, modulesConfig)) { m_log.DebugFormat("[REGIONMODULES]: Found shared region module {0}, class {1}", node.Id, node.Type); m_sharedModules.Add(node); loadedModuleData[0]++; } } else if (node.Type.GetInterface(typeof(INonSharedRegionModule).ToString()) != null) { if (CheckModuleEnabled(node, modulesConfig)) { m_log.DebugFormat("[REGIONMODULES]: Found non-shared region module {0}, class {1}", node.Id, node.Type); m_nonSharedModules.Add(node); loadedModuleData[1]++; } } else { m_log.WarnFormat("[REGIONMODULES]: Found unknown type of module {0}, class {1}", node.Id, node.Type); loadedModuleData[2]++; } } // We don't do that here // public void Initialise () { throw new System.NotImplementedException(); } #endregion #region IDisposable implementation // Cleanup // public void Dispose () { // We expect that all regions have been removed already while (m_sharedInstances.Count > 0) { m_sharedInstances[0].Close(); m_sharedInstances.RemoveAt(0); } m_sharedModules.Clear(); m_nonSharedModules.Clear(); } #endregion public string Version { get { return AddinManager.CurrentAddin.Version; } } public string Name { get { return m_name; } } #region Region Module interfacesController implementation /// <summary> /// Check that the given module is no disabled in the [Modules] section of the config files. /// </summary> /// <param name="node"></param> /// <param name="modulesConfig">The config section</param> /// <returns>true if the module is enabled, false if it is disabled</returns> protected bool CheckModuleEnabled(TypeExtensionNode node, IConfig modulesConfig) { // Get the config string string moduleString = modulesConfig.GetString("Setup_" + node.Id, String.Empty); // We have a selector if (moduleString != String.Empty) { // Allow disabling modules even if they don't have // support for it if (moduleString == "disabled") return false; // Split off port, if present string[] moduleParts = moduleString.Split(new char[] { '/' }, 2); // Format is [port/][class] string className = moduleParts[0]; if (moduleParts.Length > 1) className = moduleParts[1]; // Match the class name if given if (className != String.Empty && node.Type.ToString() != className) return false; } return true; } // The root of all evil. // This is where we handle adding the modules to scenes when they // load. This means that here we deal with replaceable interfaces, // nonshared modules, etc. // public void AddRegionToModules (Scene scene) { Dictionary<Type, ISharedRegionModule> deferredSharedModules = new Dictionary<Type, ISharedRegionModule>(); Dictionary<Type, INonSharedRegionModule> deferredNonSharedModules = new Dictionary<Type, INonSharedRegionModule>(); // We need this to see if a module has already been loaded and // has defined a replaceable interface. It's a generic call, // so this can't be used directly. It will be used later Type s = scene.GetType(); MethodInfo mi = s.GetMethod("RequestModuleInterface"); // This will hold the shared modules we actually load List<ISharedRegionModule> sharedlist = new List<ISharedRegionModule>(); // Iterate over the shared modules that have been loaded // Add them to the new Scene foreach (ISharedRegionModule module in m_sharedInstances) { // Here is where we check if a replaceable interface // is defined. If it is, the module is checked against // the interfaces already defined. If the interface is // defined, we simply skip the module. Else, if the module // defines a replaceable interface, we add it to the deferred // list. Type replaceableInterface = module.ReplaceableInterface; if (replaceableInterface != null) { MethodInfo mii = mi.MakeGenericMethod(replaceableInterface); if (mii.Invoke(scene, new object[0]) != null) { m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString()); continue; } deferredSharedModules[replaceableInterface] = module; m_log.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name); continue; } m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1}", scene.RegionInfo.RegionName, module.Name); module.AddRegion(scene); scene.AddRegionModule(module.Name, module); sharedlist.Add(module); } IConfig modulesConfig = m_openSim.ConfigSource.Source.Configs["Modules"]; // Scan for, and load, nonshared modules List<INonSharedRegionModule> list = new List<INonSharedRegionModule>(); foreach (TypeExtensionNode node in m_nonSharedModules) { Object[] ctorArgs = new Object[] {0}; // Read the config string moduleString = modulesConfig.GetString("Setup_" + node.Id, String.Empty); // We may not want to load this at all if (moduleString == "disabled") continue; // Get the port number, if there is one if (moduleString != String.Empty) { // Get the port number from the string string[] moduleParts = moduleString.Split(new char[] {'/'}, 2); if (moduleParts.Length > 1) ctorArgs[0] = Convert.ToUInt32(moduleParts[0]); } // Actually load it INonSharedRegionModule module = null; Type[] ctorParamTypes = new Type[ctorArgs.Length]; for (int i = 0; i < ctorParamTypes.Length; i++) ctorParamTypes[i] = ctorArgs[i].GetType(); if (node.Type.GetConstructor(ctorParamTypes) != null) module = (INonSharedRegionModule)Activator.CreateInstance(node.Type, ctorArgs); else module = (INonSharedRegionModule)Activator.CreateInstance(node.Type); // Check for replaceable interfaces Type replaceableInterface = module.ReplaceableInterface; if (replaceableInterface != null) { MethodInfo mii = mi.MakeGenericMethod(replaceableInterface); if (mii.Invoke(scene, new object[0]) != null) { m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString()); continue; } deferredNonSharedModules[replaceableInterface] = module; m_log.DebugFormat("[REGIONMODULE]: Deferred load of {0}", module.Name); continue; } m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1}", scene.RegionInfo.RegionName, module.Name); // Initialise the module module.Initialise(m_openSim.ConfigSource.Source); list.Add(module); } // Now add the modules that we found to the scene. If a module // wishes to override a replaceable interface, it needs to // register it in Initialise, so that the deferred module // won't load. foreach (INonSharedRegionModule module in list) { module.AddRegion(scene); scene.AddRegionModule(module.Name, module); } // Now all modules without a replaceable base interface are loaded // Replaceable modules have either been skipped, or omitted. // Now scan the deferred modules here foreach (ISharedRegionModule module in deferredSharedModules.Values) { // Determine if the interface has been replaced Type replaceableInterface = module.ReplaceableInterface; MethodInfo mii = mi.MakeGenericMethod(replaceableInterface); if (mii.Invoke(scene, new object[0]) != null) { m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString()); continue; } m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to shared module {1} (deferred)", scene.RegionInfo.RegionName, module.Name); // Not replaced, load the module module.AddRegion(scene); scene.AddRegionModule(module.Name, module); sharedlist.Add(module); } // Same thing for nonshared modules, load them unless overridden List<INonSharedRegionModule> deferredlist = new List<INonSharedRegionModule>(); foreach (INonSharedRegionModule module in deferredNonSharedModules.Values) { // Check interface override Type replaceableInterface = module.ReplaceableInterface; if (replaceableInterface != null) { MethodInfo mii = mi.MakeGenericMethod(replaceableInterface); if (mii.Invoke(scene, new object[0]) != null) { m_log.DebugFormat("[REGIONMODULE]: Not loading {0} because another module has registered {1}", module.Name, replaceableInterface.ToString()); continue; } } m_log.DebugFormat("[REGIONMODULE]: Adding scene {0} to non-shared module {1} (deferred)", scene.RegionInfo.RegionName, module.Name); module.Initialise(m_openSim.ConfigSource.Source); list.Add(module); deferredlist.Add(module); } // Finally, load valid deferred modules foreach (INonSharedRegionModule module in deferredlist) { module.AddRegion(scene); scene.AddRegionModule(module.Name, module); } // This is needed for all module types. Modules will register // Interfaces with scene in AddScene, and will also need a means // to access interfaces registered by other modules. Without // this extra method, a module attempting to use another modules's // interface would be successful only depending on load order, // which can't be depended upon, or modules would need to resort // to ugly kludges to attempt to request interfaces when needed // and unneccessary caching logic repeated in all modules. // The extra function stub is just that much cleaner // foreach (ISharedRegionModule module in sharedlist) { module.RegionLoaded(scene); } foreach (INonSharedRegionModule module in list) { module.RegionLoaded(scene); } scene.AllModulesLoaded(); } public void RemoveRegionFromModules (Scene scene) { foreach (IRegionModuleBase module in scene.RegionModules.Values) { m_log.DebugFormat("[REGIONMODULE]: Removing scene {0} from module {1}", scene.RegionInfo.RegionName, module.Name); module.RemoveRegion(scene); if (module is INonSharedRegionModule) { // as we were the only user, this instance has to die module.Close(); } } scene.RegionModules.Clear(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** Purpose: Generic hash table implementation ** ** #DictionaryVersusHashtableThreadSafety ** Hashtable has multiple reader/single writer (MR/SW) thread safety built into ** certain methods and properties, whereas Dictionary doesn't. If you're ** converting framework code that formerly used Hashtable to Dictionary, it's ** important to consider whether callers may have taken a dependence on MR/SW ** thread safety. If a reader writer lock is available, then that may be used ** with a Dictionary to get the same thread safety guarantee. ** ** Reader writer locks don't exist in silverlight, so we do the following as a ** result of removing non-generic collections from silverlight: ** 1. If the Hashtable was fully synchronized, then we replace it with a ** Dictionary with full locks around reads/writes (same thread safety ** guarantee). ** 2. Otherwise, the Hashtable has the default MR/SW thread safety behavior, ** so we do one of the following on a case-by-case basis: ** a. If the race condition can be addressed by rearranging the code and using a temp ** variable (for example, it's only populated immediately after created) ** then we address the race condition this way and use Dictionary. ** b. If there's concern about degrading performance with the increased ** locking, we ifdef with FEATURE_NONGENERIC_COLLECTIONS so we can at ** least use Hashtable in the desktop build, but Dictionary with full ** locks in silverlight builds. Note that this is heavier locking than ** MR/SW, but this is the only option without rewriting (or adding back) ** the reader writer lock. ** c. If there's no performance concern (e.g. debug-only code) we ** consistently replace Hashtable with Dictionary plus full locks to ** reduce complexity. ** d. Most of serialization is dead code in silverlight. Instead of updating ** those Hashtable occurences in serialization, we carved out references ** to serialization such that this code doesn't need to build in ** silverlight. ===========================================================*/ namespace System.Collections.Generic { using System; using System.Collections; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Security.Permissions; [DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.InteropServices.ComVisible(false)] public class Dictionary<TKey,TValue>: IDictionary<TKey,TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback { private struct Entry { public int hashCode; // Lower 31 bits of hash code, -1 if unused public int next; // Index of next entry, -1 if last public TKey key; // Key of entry public TValue value; // Value of entry } private int[] buckets; private Entry[] entries; private int count; private int version; private int freeList; private int freeCount; private IEqualityComparer<TKey> comparer; private KeyCollection keys; private ValueCollection values; private Object _syncRoot; // constants for serialization private const String VersionName = "Version"; private const String HashSizeName = "HashSize"; // Must save buckets.Length private const String KeyValuePairsName = "KeyValuePairs"; private const String ComparerName = "Comparer"; public Dictionary(): this(0, null) {} public Dictionary(int capacity): this(capacity, null) {} public Dictionary(IEqualityComparer<TKey> comparer): this(0, comparer) {} public Dictionary(int capacity, IEqualityComparer<TKey> comparer) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); if (capacity > 0) Initialize(capacity); this.comparer = comparer ?? EqualityComparer<TKey>.Default; #if FEATURE_RANDOMIZED_STRING_HASHING && FEATURE_CORECLR if (HashHelpers.s_UseRandomizedStringHashing && comparer == EqualityComparer<string>.Default) { this.comparer = (IEqualityComparer<TKey>) NonRandomizedStringEqualityComparer.Default; } #endif // FEATURE_RANDOMIZED_STRING_HASHING && FEATURE_CORECLR } public Dictionary(IDictionary<TKey,TValue> dictionary): this(dictionary, null) {} public Dictionary(IDictionary<TKey,TValue> dictionary, IEqualityComparer<TKey> comparer): this(dictionary != null? dictionary.Count: 0, comparer) { if( dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } // It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case, // avoid the enumerator allocation and overhead by looping through the entries array directly. // We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain // back-compat with subclasses that may have overridden the enumerator behavior. if (dictionary.GetType() == typeof(Dictionary<TKey,TValue>)) { Dictionary<TKey,TValue> d = (Dictionary<TKey,TValue>)dictionary; int count = d.count; Entry[] entries = d.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { Add(entries[i].key, entries[i].value); } } return; } foreach (KeyValuePair<TKey,TValue> pair in dictionary) { Add(pair.Key, pair.Value); } } protected Dictionary(SerializationInfo info, StreamingContext context) { //We can't do anything with the keys and values until the entire graph has been deserialized //and we have a resonable estimate that GetHashCode is not going to fail. For the time being, //we'll just cache this. The graph is not valid until OnDeserialization has been called. HashHelpers.SerializationInfoTable.Add(this, info); } public IEqualityComparer<TKey> Comparer { get { return comparer; } } public int Count { get { return count - freeCount; } } public KeyCollection Keys { get { Contract.Ensures(Contract.Result<KeyCollection>() != null); if (keys == null) keys = new KeyCollection(this); return keys; } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { if (keys == null) keys = new KeyCollection(this); return keys; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { if (keys == null) keys = new KeyCollection(this); return keys; } } public ValueCollection Values { get { Contract.Ensures(Contract.Result<ValueCollection>() != null); if (values == null) values = new ValueCollection(this); return values; } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { if (values == null) values = new ValueCollection(this); return values; } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { if (values == null) values = new ValueCollection(this); return values; } } public TValue this[TKey key] { get { int i = FindEntry(key); if (i >= 0) return entries[i].value; ThrowHelper.ThrowKeyNotFoundException(); return default(TValue); } set { Insert(key, value, false); } } public void Add(TKey key, TValue value) { Insert(key, value, true); } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { Add(keyValuePair.Key, keyValuePair.Value); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if( i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) { return true; } return false; } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if( i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) { Remove(keyValuePair.Key); return true; } return false; } public void Clear() { if (count > 0) { for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; Array.Clear(entries, 0, count); freeList = -1; count = 0; freeCount = 0; version++; } } public bool ContainsKey(TKey key) { return FindEntry(key) >= 0; } public bool ContainsValue(TValue value) { if (value == null) { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0 && entries[i].value == null) return true; } } else { EqualityComparer<TValue> c = EqualityComparer<TValue>.Default; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0 && c.Equals(entries[i].value, value)) return true; } } return false; } private void CopyTo(KeyValuePair<TKey,TValue>[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length ) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = this.count; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { array[index++] = new KeyValuePair<TKey,TValue>(entries[i].key, entries[i].value); } } } public Enumerator GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } [System.Security.SecurityCritical] // auto-generated_required public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info); } info.AddValue(VersionName, version); #if FEATURE_RANDOMIZED_STRING_HASHING info.AddValue(ComparerName, HashHelpers.GetEqualityComparerForSerialization(comparer), typeof(IEqualityComparer<TKey>)); #else info.AddValue(ComparerName, comparer, typeof(IEqualityComparer<TKey>)); #endif info.AddValue(HashSizeName, buckets == null ? 0 : buckets.Length); //This is the length of the bucket array. if( buckets != null) { KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[Count]; CopyTo(array, 0); info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[])); } } private int FindEntry(TKey key) { if( key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (buckets != null) { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i; } } return -1; } private void Initialize(int capacity) { int size = HashHelpers.GetPrime(capacity); buckets = new int[size]; for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; entries = new Entry[size]; freeList = -1; } private void Insert(TKey key, TValue value, bool add) { if( key == null ) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (buckets == null) Initialize(0); int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; int targetBucket = hashCode % buckets.Length; #if FEATURE_RANDOMIZED_STRING_HASHING int collisionCount = 0; #endif for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) { if (add) { #if FEATURE_CORECLR ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); #else ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); #endif } entries[i].value = value; version++; return; } #if FEATURE_RANDOMIZED_STRING_HASHING collisionCount++; #endif } int index; if (freeCount > 0) { index = freeList; freeList = entries[index].next; freeCount--; } else { if (count == entries.Length) { Resize(); targetBucket = hashCode % buckets.Length; } index = count; count++; } entries[index].hashCode = hashCode; entries[index].next = buckets[targetBucket]; entries[index].key = key; entries[index].value = value; buckets[targetBucket] = index; version++; #if FEATURE_RANDOMIZED_STRING_HASHING #if FEATURE_CORECLR // In case we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing // in this case will be EqualityComparer<string>.Default. // Note, randomized string hashing is turned on by default on coreclr so EqualityComparer<string>.Default will // be using randomized string hashing if (collisionCount > HashHelpers.HashCollisionThreshold && comparer == NonRandomizedStringEqualityComparer.Default) { comparer = (IEqualityComparer<TKey>) EqualityComparer<string>.Default; Resize(entries.Length, true); } #else if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer)) { comparer = (IEqualityComparer<TKey>) HashHelpers.GetRandomizedEqualityComparer(comparer); Resize(entries.Length, true); } #endif // FEATURE_CORECLR #endif } public virtual void OnDeserialization(Object sender) { SerializationInfo siInfo; HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo); if (siInfo==null) { // It might be necessary to call OnDeserialization from a container if the container object also implements // OnDeserialization. However, remoting will call OnDeserialization again. // We can return immediately if this function is called twice. // Note we set remove the serialization info from the table at the end of this method. return; } int realVersion = siInfo.GetInt32(VersionName); int hashsize = siInfo.GetInt32(HashSizeName); comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>)); if( hashsize != 0) { buckets = new int[hashsize]; for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; entries = new Entry[hashsize]; freeList = -1; KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[]) siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[])); if (array==null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys); } for (int i=0; i<array.Length; i++) { if ( array[i].Key == null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey); } Insert(array[i].Key, array[i].Value, true); } } else { buckets = null; } version = realVersion; HashHelpers.SerializationInfoTable.Remove(this); } private void Resize() { Resize(HashHelpers.ExpandPrime(count), false); } private void Resize(int newSize, bool forceNewHashCodes) { Contract.Assert(newSize >= entries.Length); int[] newBuckets = new int[newSize]; for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1; Entry[] newEntries = new Entry[newSize]; Array.Copy(entries, 0, newEntries, 0, count); if(forceNewHashCodes) { for (int i = 0; i < count; i++) { if(newEntries[i].hashCode != -1) { newEntries[i].hashCode = (comparer.GetHashCode(newEntries[i].key) & 0x7FFFFFFF); } } } for (int i = 0; i < count; i++) { if (newEntries[i].hashCode >= 0) { int bucket = newEntries[i].hashCode % newSize; newEntries[i].next = newBuckets[bucket]; newBuckets[bucket] = i; } } buckets = newBuckets; entries = newEntries; } public bool Remove(TKey key) { if(key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (buckets != null) { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; int bucket = hashCode % buckets.Length; int last = -1; for (int i = buckets[bucket]; i >= 0; last = i, i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) { if (last < 0) { buckets[bucket] = entries[i].next; } else { entries[last].next = entries[i].next; } entries[i].hashCode = -1; entries[i].next = freeList; entries[i].key = default(TKey); entries[i].value = default(TValue); freeList = i; freeCount++; version++; return true; } } } return false; } public bool TryGetValue(TKey key, out TValue value) { int i = FindEntry(key); if (i >= 0) { value = entries[i].value; return true; } value = default(TValue); return false; } // This is a convenience method for the internal callers that were converted from using Hashtable. // Many were combining key doesn't exist and key exists but null value (for non-value types) checks. // This allows them to continue getting that behavior with minimal code delta. This is basically // TryGetValue without the out param internal TValue GetValueOrDefault(TKey key) { int i = FindEntry(key); if (i >= 0) { return entries[i].value; } return default(TValue); } bool ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly { get { return false; } } void ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[] array, int index) { CopyTo(array, index); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if( array.GetLowerBound(0) != 0 ) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey,TValue>[] pairs = array as KeyValuePair<TKey,TValue>[]; if (pairs != null) { CopyTo(pairs, index); } else if( array is DictionaryEntry[]) { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value); } } } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } try { int count = this.count; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { objects[index++] = new KeyValuePair<TKey,TValue>(entries[i].key, entries[i].value); } } } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } } } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if( _syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } bool IDictionary.IsFixedSize { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } ICollection IDictionary.Keys { get { return (ICollection)Keys; } } ICollection IDictionary.Values { get { return (ICollection)Values; } } object IDictionary.this[object key] { get { if( IsCompatibleKey(key)) { int i = FindEntry((TKey)key); if (i >= 0) { return entries[i].value; } } return null; } set { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } } private static bool IsCompatibleKey(object key) { if( key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } return (key is TKey); } void IDictionary.Add(object key, object value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { Add(tempKey, (TValue)value); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } bool IDictionary.Contains(object key) { if(IsCompatibleKey(key)) { return ContainsKey((TKey)key); } return false; } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator(this, Enumerator.DictEntry); } void IDictionary.Remove(object key) { if(IsCompatibleKey(key)) { Remove((TKey)key); } } [Serializable] public struct Enumerator: IEnumerator<KeyValuePair<TKey,TValue>>, IDictionaryEnumerator { private Dictionary<TKey,TValue> dictionary; private int version; private int index; private KeyValuePair<TKey,TValue> current; private int getEnumeratorRetType; // What should Enumerator.Current return? internal const int DictEntry = 1; internal const int KeyValuePair = 2; internal Enumerator(Dictionary<TKey,TValue> dictionary, int getEnumeratorRetType) { this.dictionary = dictionary; version = dictionary.version; index = 0; this.getEnumeratorRetType = getEnumeratorRetType; current = new KeyValuePair<TKey, TValue>(); } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends. // dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { current = new KeyValuePair<TKey, TValue>(dictionary.entries[index].key, dictionary.entries[index].value); index++; return true; } index++; } index = dictionary.count + 1; current = new KeyValuePair<TKey, TValue>(); return false; } public KeyValuePair<TKey,TValue> Current { get { return current; } } public void Dispose() { } object IEnumerator.Current { get { if( index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } if (getEnumeratorRetType == DictEntry) { return new System.Collections.DictionaryEntry(current.Key, current.Value); } else { return new KeyValuePair<TKey, TValue>(current.Key, current.Value); } } } void IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } index = 0; current = new KeyValuePair<TKey, TValue>(); } DictionaryEntry IDictionaryEnumerator.Entry { get { if( index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(current.Key, current.Value); } } object IDictionaryEnumerator.Key { get { if( index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return current.Key; } } object IDictionaryEnumerator.Value { get { if( index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return current.Value; } } } [DebuggerTypeProxy(typeof(Mscorlib_DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public sealed class KeyCollection: ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private Dictionary<TKey,TValue> dictionary; public KeyCollection(Dictionary<TKey,TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } this.dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(dictionary); } public void CopyTo(TKey[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = dictionary.count; Entry[] entries = dictionary.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) array[index++] = entries[i].key; } } public int Count { get { return dictionary.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } void ICollection<TKey>.Add(TKey item){ ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); } void ICollection<TKey>.Clear(){ ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); } bool ICollection<TKey>.Contains(TKey item){ return dictionary.ContainsKey(item); } bool ICollection<TKey>.Remove(TKey item){ ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); return false; } IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() { return new Enumerator(dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(dictionary); } void ICollection.CopyTo(Array array, int index) { if (array==null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if( array.GetLowerBound(0) != 0 ) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } TKey[] keys = array as TKey[]; if (keys != null) { CopyTo(keys, index); } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } int count = dictionary.count; Entry[] entries = dictionary.entries; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) objects[index++] = entries[i].key; } } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)dictionary).SyncRoot; } } [Serializable] public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> dictionary; private int index; private int version; private TKey currentKey; internal Enumerator(Dictionary<TKey, TValue> dictionary) { this.dictionary = dictionary; version = dictionary.version; index = 0; currentKey = default(TKey); } public void Dispose() { } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { currentKey = dictionary.entries[index].key; index++; return true; } index++; } index = dictionary.count + 1; currentKey = default(TKey); return false; } public TKey Current { get { return currentKey; } } Object System.Collections.IEnumerator.Current { get { if( index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return currentKey; } } void System.Collections.IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } index = 0; currentKey = default(TKey); } } } [DebuggerTypeProxy(typeof(Mscorlib_DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public sealed class ValueCollection: ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private Dictionary<TKey,TValue> dictionary; public ValueCollection(Dictionary<TKey,TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } this.dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(dictionary); } public void CopyTo(TValue[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = dictionary.count; Entry[] entries = dictionary.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) array[index++] = entries[i].value; } } public int Count { get { return dictionary.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } void ICollection<TValue>.Add(TValue item){ ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Remove(TValue item){ ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); return false; } void ICollection<TValue>.Clear(){ ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Contains(TValue item){ return dictionary.ContainsValue(item); } IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() { return new Enumerator(dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if( array.GetLowerBound(0) != 0 ) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < dictionary.Count) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); TValue[] values = array as TValue[]; if (values != null) { CopyTo(values, index); } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } int count = dictionary.count; Entry[] entries = dictionary.entries; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) objects[index++] = entries[i].value; } } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)dictionary).SyncRoot; } } [Serializable] public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> dictionary; private int index; private int version; private TValue currentValue; internal Enumerator(Dictionary<TKey, TValue> dictionary) { this.dictionary = dictionary; version = dictionary.version; index = 0; currentValue = default(TValue); } public void Dispose() { } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { currentValue = dictionary.entries[index].value; index++; return true; } index++; } index = dictionary.count + 1; currentValue = default(TValue); return false; } public TValue Current { get { return currentValue; } } Object System.Collections.IEnumerator.Current { get { if( index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return currentValue; } } void System.Collections.IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } index = 0; currentValue = default(TValue); } } } } }
// 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. // ---------------------------------------------------------------------------------- // Interop library code // // COM Marshalling helpers used by MCG // // NOTE: // These source code are being published to InternalAPIs and consumed by RH builds // Use PublishInteropAPI.bat to keep the InternalAPI copies in sync // ---------------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices; using System.Threading; using System.Text; using System.Runtime; using Internal.NativeFormat; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices { internal static unsafe class McgComHelpers { /// <summary> /// Returns runtime class name for a specific object /// </summary> internal static string GetRuntimeClassName(Object obj) { #if ENABLE_WINRT System.IntPtr pWinRTItf = default(IntPtr); try { pWinRTItf = McgMarshal.ObjectToIInspectable(obj); if (pWinRTItf == default(IntPtr)) return String.Empty; else return GetRuntimeClassName(pWinRTItf); } finally { if (pWinRTItf != default(IntPtr)) McgMarshal.ComRelease(pWinRTItf); } #else return string.Empty; #endif } /// <summary> /// Returns runtime class name for a specific WinRT interface /// </summary> internal static string GetRuntimeClassName(IntPtr pWinRTItf) { #if ENABLE_WINRT void* unsafe_hstring = null; try { int hr = CalliIntrinsics.StdCall__int( ((__com_IInspectable*)(void*)pWinRTItf)->pVtable->pfnGetRuntimeClassName, pWinRTItf, &unsafe_hstring); // Don't throw if the call fails if (hr < 0) return String.Empty; return McgMarshal.HStringToString(new IntPtr(unsafe_hstring)); } finally { if (unsafe_hstring != null) McgMarshal.FreeHString(new IntPtr(unsafe_hstring)); } #else throw new PlatformNotSupportedException("GetRuntimeClassName(IntPtr)"); #endif } /// <summary> /// Given a IStream*, seek to its beginning /// </summary> internal static unsafe bool SeekStreamToBeginning(IntPtr pStream) { Interop.COM.__IStream* pStreamNativePtr = (Interop.COM.__IStream*)(void*)pStream; UInt64 newPosition; int hr = CalliIntrinsics.StdCall<int>( pStreamNativePtr->vtbl->pfnSeek, pStreamNativePtr, 0UL, (uint)Interop.COM.STREAM_SEEK.STREAM_SEEK_SET, &newPosition); return (hr >= 0); } /// <summary> /// Given a IStream*, change its size /// </summary> internal static unsafe bool SetStreamSize(IntPtr pStream, ulong lSize) { Interop.COM.__IStream* pStreamNativePtr = (Interop.COM.__IStream*)(void*)pStream; UInt64 newPosition; int hr = CalliIntrinsics.StdCall<int>( pStreamNativePtr->vtbl->pfnSetSize, pStreamNativePtr, lSize, (uint)Interop.COM.STREAM_SEEK.STREAM_SEEK_SET, &newPosition); return (hr >= 0); } /// <summary> /// Release a IStream that has marshalled data in it /// </summary> internal static void SafeReleaseStream(IntPtr pStream) { #if ENABLE_WINRT if (pStream != default(IntPtr)) { // Release marshalled data and ignore any error ExternalInterop.CoReleaseMarshalData(pStream); McgMarshal.ComRelease(pStream); } #else throw new PlatformNotSupportedException("SafeReleaseStream"); #endif } /// <summary> /// Returns whether the IUnknown* is a free-threaded COM object /// </summary> /// <param name="pUnknown"></param> internal static unsafe bool IsFreeThreaded(IntPtr pUnknown) { // // Does it support IAgileObject? // IntPtr pAgileObject = McgMarshal.ComQueryInterfaceNoThrow(pUnknown, ref Interop.COM.IID_IAgileObject); if (pAgileObject != default(IntPtr)) { // Anything that implements IAgileObject is considered to be free-threaded // NOTE: This doesn't necessarily mean that the object is free-threaded - it only means // we BELIEVE it is free-threaded McgMarshal.ComRelease_StdCall(pAgileObject); return true; } IntPtr pMarshal = McgMarshal.ComQueryInterfaceNoThrow(pUnknown, ref Interop.COM.IID_IMarshal); if (pMarshal == default(IntPtr)) return false; try { // // Check the un-marshaler // Interop.COM.__IMarshal* pIMarshalNativePtr = (Interop.COM.__IMarshal*)(void*)pMarshal; fixed (Guid* pGuid = &Interop.COM.IID_IUnknown) { Guid clsid; int hr = CalliIntrinsics.StdCall__int( pIMarshalNativePtr->vtbl->pfnGetUnmarshalClass, new IntPtr(pIMarshalNativePtr), pGuid, default(IntPtr), (uint)Interop.COM.MSHCTX.MSHCTX_INPROC, default(IntPtr), (uint)Interop.COM.MSHLFLAGS.MSHLFLAGS_NORMAL, &clsid); if (hr >= 0 && InteropExtensions.GuidEquals(ref clsid, ref Interop.COM.CLSID_InProcFreeMarshaler)) { // The un-marshaller is indeed the unmarshaler for the FTM so this object // is free threaded. return true; } } return false; } finally { McgMarshal.ComRelease_StdCall(pMarshal); } } /// <summary> /// Get from cache if available, else allocate from heap /// </summary> #if !RHTESTCL [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] #endif internal static void* CachedAlloc(int size, ref IntPtr cache) { // Read cache, clear it void* pBlock = (void*)Interlocked.Exchange(ref cache, default(IntPtr)); if (pBlock == null) { pBlock =(void*) ExternalInterop.MemAlloc(new UIntPtr((uint)size)); } return pBlock; } /// <summary> /// Return to cache if empty, else free to heap /// </summary> #if !RHTESTCL [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] #endif internal static void CachedFree(void* block, ref IntPtr cache) { if ((void*)Interlocked.CompareExchange(ref cache, new IntPtr(block), default(IntPtr)) != null) { ExternalInterop.MemFree((IntPtr)block); } } /// <summary> /// Return true if the object is a RCW. False otherwise /// </summary> internal static bool IsComObject(object obj) { return (obj is __ComObject); } /// <summary> /// Unwrap if this is a managed wrapper /// Typically used in data binding /// For example, you don't want to data bind against a KeyValuePairImpl<K, V> - you want the real /// KeyValuePair<K, V> /// </summary> /// <param name="target">The object you want to unwrap</param> /// <returns>The original object or the unwrapped object</returns> internal static object UnboxManagedWrapperIfBoxed(object target) { // // If the target is boxed by managed code: // 1. BoxedValue // 2. BoxedKeyValuePair // 3. StandardCustomPropertyProviderProxy/EnumerableCustomPropertyProviderProxy/ListCustomPropertyProviderProxy // // we should use its value for data binding // if (InteropExtensions.AreTypesAssignable(target.GetTypeHandle(), typeof(IManagedWrapper).TypeHandle)) { target = ((IManagedWrapper)target).GetTarget(); Debug.Assert(!(target is IManagedWrapper)); } return target; } [Flags] internal enum CreateComObjectFlags { None = 0, IsWinRTObject, /// <summary> /// Don't attempt to find out the actual type (whether it is IInspectable nor IProvideClassInfo) /// of the incoming interface and do not attempt to unbox them using WinRT rules /// </summary> SkipTypeResolutionAndUnboxing } /// <summary> /// Returns the existing RCW or create a new RCW from the COM interface pointer /// NOTE: Don't use this overload if you already have the identity IUnknown /// </summary> /// <param name="expectedContext"> /// The current context of this thread. If it is passed and is not Default, we'll check whether the /// returned RCW from cache matches this expected context. If it is not a match (from a different /// context, and is not free threaded), we'll go ahead ignoring the cached entry, and create a new /// RCW instead - which will always end up in the current context /// We'll skip the check if current == ContextCookie.Default. /// </param> internal static object ComInterfaceToComObject( IntPtr pComItf, RuntimeTypeHandle interfaceType, RuntimeTypeHandle classTypeInSigature, ContextCookie expectedContext, CreateComObjectFlags flags ) { Debug.Assert(expectedContext.IsDefault || expectedContext.IsCurrent); // // Get identity IUnknown for lookup // IntPtr pComIdentityIUnknown = McgMarshal.ComQueryInterfaceNoThrow(pComItf, ref Interop.COM.IID_IUnknown); if (pComIdentityIUnknown == default(IntPtr)) throw new InvalidCastException(); try { object obj = ComInterfaceToComObjectInternal( pComItf, pComIdentityIUnknown, interfaceType, classTypeInSigature, expectedContext, flags ); return obj; } finally { McgMarshal.ComRelease(pComIdentityIUnknown); } } /// <summary> /// Returns the existing RCW or create a new RCW from the COM interface pointer /// NOTE: This does unboxing unless CreateComObjectFlags.SkipTypeResolutionAndUnboxing is specified /// </summary> /// <param name="expectedContext"> /// The current context of this thread. If it is passed and is not Default, we'll check whether the /// returned RCW from cache matches this expected context. If it is not a match (from a different /// context, and is not free threaded), we'll go ahead ignoring the cached entry, and create a new /// RCW instead - which will always end up in the current context /// We'll skip the check if current == ContextCookie.Default. /// </param> internal static object ComInterfaceToComObjectInternal( IntPtr pComItf, IntPtr pComIdentityIUnknown, RuntimeTypeHandle interfaceType, RuntimeTypeHandle classTypeInSignature, ContextCookie expectedContext, CreateComObjectFlags flags ) { string className; object obj = ComInterfaceToComObjectInternal_NoCache( pComItf, pComIdentityIUnknown, interfaceType, classTypeInSignature, expectedContext, flags, out className ); // // The assumption here is that if the classInfoInSignature is null and interfaceTypeInfo // is either IUnknow and IInspectable we need to try unboxing. // bool doUnboxingCheck = (flags & CreateComObjectFlags.SkipTypeResolutionAndUnboxing) == 0 && obj != null && classTypeInSignature.IsNull() && (interfaceType.Equals(InternalTypes.IUnknown) || interfaceType.IsIInspectable()); if (doUnboxingCheck) { // // Try unboxing // Even though this might just be a IUnknown * from the signature, we still attempt to unbox // if it implements IInspectable // // @TODO - We might need to optimize this by pre-checking the names to see if they // potentially represents a boxed type, but for now let's keep it simple and I also don't // want to replicate the knowledge here // @TODO2- We probably should skip the creating the COM object in the first place. // // NOTE: the RCW here could be a cached one (for a brief time if GC doesn't kick in. as there // is nothing to hold the RCW alive for IReference<T> RCWs), so this could save us a RCW // creation cost potentially. Desktop CLR doesn't do this. But we also paying for unnecessary // cache management cost, and it is difficult to say which way is better without proper // measuring // object unboxedObj = McgMarshal.UnboxIfBoxed(obj, className); if (unboxedObj != null) return unboxedObj; } // // In order for variance to work, we save the incoming interface pointer as specified in the // signature into the cache, so that we know this RCW does support this interface and variance // can take advantage of that later // NOTE: In some cases, native might pass a WinRT object as a 'compatible' interface, for example, // pass IVector<IFoo> as IVector<Object> because they are 'compatible', but QI for IVector<object> // won't succeed. In this case, we'll just believe it implements IVector<Object> as in the // signature while the underlying interface pointer is actually IVector<IFoo> // __ComObject comObject = obj as __ComObject; if (comObject != null) { McgMarshal.ComAddRef(pComItf); try { comObject.InsertIntoCache(interfaceType, ContextCookie.Current, ref pComItf, true); } finally { // // Only release when a exception is thrown or we didn't 'swallow' the ref count by // inserting it into the cache // McgMarshal.ComSafeRelease(pComItf); } } return obj; } /// <summary> /// Returns the existing RCW or create a new RCW from the COM interface pointer /// NOTE: This does not do any unboxing at all. /// </summary> /// <param name="expectedContext"> /// The current context of this thread. If it is passed and is not Default, we'll check whether the /// returned RCW from cache matches this expected context. If it is not a match (from a different /// context, and is not free threaded), we'll go ahead ignoring the cached entry, and create a new /// RCW instead - which will always end up in the current context /// We'll skip the check if current == ContextCookie.Default. /// </param> private static object ComInterfaceToComObjectInternal_NoCache( IntPtr pComItf, IntPtr pComIdentityIUnknown, RuntimeTypeHandle interfaceType, RuntimeTypeHandle classTypeInSignature, ContextCookie expectedContext, CreateComObjectFlags flags, out string className ) { className = null; // // Lookup RCW in global RCW cache based on the identity IUnknown // __ComObject comObject = ComObjectCache.Lookup(pComIdentityIUnknown); if (comObject != null) { bool useThisComObject = true; if (!expectedContext.IsDefault) { // // Make sure the returned RCW matches the context we specify (if any) // if (!comObject.IsFreeThreaded && !comObject.ContextCookie.Equals(expectedContext)) { // // This is a mismatch. // We only care about context for WinRT factory RCWs (which is the only place we are // passing in the context right now). // When we get back a WinRT factory RCW created in a different context. This means the // factory is a singleton, and the returned IActivationFactory could be either one of // the following: // 1) A raw pointer, and it acts like a free threaded object // 2) A proxy that is used across different contexts. It might maintain a list of contexts // that it is marshaled to, and will fail to be called if it is not marshaled to this // context yet. // // In this case, it is unsafe to use this RCW in this context and we should proceed // to create a duplicated one instead. It might make sense to have a context-sensitive // RCW cache but I don't think this case will be common enough to justify it // // @TODO: Check for DCOM proxy as well useThisComObject = false; } } if (useThisComObject) { // // We found one - AddRef and return // comObject.AddRef(); return comObject; } } string winrtClassName = null; bool isSealed = false; if (!classTypeInSignature.IsNull()) { isSealed = classTypeInSignature.IsSealed(); } // // Only look at runtime class name if the class type in signature is not sealed // NOTE: In the case of System.Uri, we are not pass the class type, only the interface // if (!isSealed && (flags & CreateComObjectFlags.SkipTypeResolutionAndUnboxing) == 0) { IntPtr pInspectable; bool needRelease = false; if (interfaceType.IsSupportIInspectable()) { // // Use the interface pointer as IInspectable as we know it is indeed a WinRT interface that // derives from IInspectable // pInspectable = pComItf; } else if ((flags & CreateComObjectFlags.IsWinRTObject) != 0) { // // Otherwise, if someone tells us that this is a WinRT object, but we don't have a // IInspectable interface at hand, we'll QI for it // pInspectable = McgMarshal.ComQueryInterfaceNoThrow(pComItf, ref Interop.COM.IID_IInspectable); needRelease = true; } else { pInspectable = default(IntPtr); } try { if (pInspectable != default(IntPtr)) { className = McgComHelpers.GetRuntimeClassName(pInspectable); winrtClassName = className; } } finally { if (needRelease && pInspectable != default(IntPtr)) { McgMarshal.ComRelease(pInspectable); pInspectable = default(IntPtr); } } } // // 1. Prefer using the class returned from GetRuntimeClassName // 2. Otherwise use the class (if there) in the signature // 3. Out of options - create __ComObject // RuntimeTypeHandle classTypeToCreateRCW = default(RuntimeTypeHandle); RuntimeTypeHandle interfaceTypeFromName = default(RuntimeTypeHandle); if (!String.IsNullOrEmpty(className)) { if (!McgModuleManager.TryGetClassTypeFromName(className, out classTypeToCreateRCW)) { // // If we can't find the class name in our map, try interface as well // Such as IVector<Int32> // This apparently won't work if we haven't seen the interface type in MCG // McgModuleManager.TryGetInterfaceTypeFromName(className, out interfaceTypeFromName); } } if (classTypeToCreateRCW.IsNull()) classTypeToCreateRCW = classTypeInSignature; // Use identity IUnknown to create the new RCW // @TODO: Transfer the ownership of ref count to the RCW if (classTypeToCreateRCW.IsNull()) { // // Create a weakly typed RCW because we have no information about this particular RCW // @TODO - what if this RCW is not seen by MCG but actually exists in WinMD and therefore we // are missing GCPressure and ComMarshallingType information for this object? // comObject = new __ComObject(pComIdentityIUnknown, default(RuntimeTypeHandle)); } else { // // Create a strongly typed RCW based on RuntimeTypeHandle // comObject = CreateComObjectInternal(classTypeToCreateRCW, pComIdentityIUnknown); // Use identity IUnknown to create the new RCW } #if DEBUG // // Remember the runtime class name for debugging purpose // This way you can tell what the class name is, even when we failed to create a strongly typed // RCW for it // comObject.m_runtimeClassName = className; #endif // // Make sure we QI for that interface // if (!interfaceType.IsNull()) { comObject.QueryInterface_NoAddRef_Internal(interfaceType, /* cacheOnly= */ false, /* throwOnQueryInterfaceFailure= */ false); } return comObject; } internal static __ComGenericInterfaceDispatcher CreateGenericComDispatcher(RuntimeTypeHandle genericDispatcherDef, RuntimeTypeHandle[] genericArguments, __ComObject comThisPointer) { #if !RHTESTCL && !CORECLR && !CORERT Debug.Assert(genericDispatcherDef.IsGenericTypeDefinition()); Debug.Assert(genericArguments != null && genericArguments.Length > 0); RuntimeTypeHandle instantiatedDispatcherType; if (!Internal.Runtime.TypeLoader.TypeLoaderEnvironment.Instance.TryGetConstructedGenericTypeForComponents(genericDispatcherDef, genericArguments, out instantiatedDispatcherType)) return null; // ERROR __ComGenericInterfaceDispatcher dispatcher = (__ComGenericInterfaceDispatcher)InteropExtensions.RuntimeNewObject(instantiatedDispatcherType); dispatcher.m_comObject = comThisPointer; return dispatcher; #else return null; #endif } private static __ComObject CreateComObjectInternal(RuntimeTypeHandle classType, IntPtr pComItf) { Debug.Assert(!classType.IsNull()); if (classType.Equals(McgModule.s_DependencyReductionTypeRemovedTypeHandle)) { // We should filter out the strongly typed RCW in TryGetClassInfoFromName step #if !RHTESTCL Environment.FailFast(McgTypeHelpers.GetDiagnosticMessageForMissingType(classType)); #else Environment.FailFast("We should never see strongly typed RCW discarded here"); #endif } //Note that this doesn't run the constructor in RH but probably do in your reflection based implementation. //If this were a real RCW, you would actually 'new' the RCW which is wrong. Fortunately in CoreCLR we don't have //this scenario so we are OK, but we should figure out a way to fix this by having a runtime API. object newClass = InteropExtensions.RuntimeNewObject(classType); Debug.Assert(newClass is __ComObject); __ComObject newObj = InteropExtensions.UncheckedCast<__ComObject>(newClass); IntPtr pfnCtor = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfAttachingCtor>(__ComObject.AttachingCtor); CalliIntrinsics.Call<int>(pfnCtor, newObj, pComItf, classType); return newObj; } /// <summary> /// Converts a COM interface pointer to a managed object /// This either gets back a existing CCW, or a existing RCW, or create a new RCW /// </summary> internal static object ComInterfaceToObjectInternal( IntPtr pComItf, RuntimeTypeHandle interfaceType, RuntimeTypeHandle classTypeInSignature, CreateComObjectFlags flags) { bool needUnboxing = (flags & CreateComObjectFlags.SkipTypeResolutionAndUnboxing) == 0; object ret = ComInterfaceToObjectInternal_NoManagedUnboxing(pComItf, interfaceType, classTypeInSignature, flags); if (ret != null && needUnboxing) { return UnboxManagedWrapperIfBoxed(ret); } return ret; } static object ComInterfaceToObjectInternal_NoManagedUnboxing( IntPtr pComItf, RuntimeTypeHandle interfaceType, RuntimeTypeHandle classTypeInSignature, CreateComObjectFlags flags) { if (pComItf == default(IntPtr)) return null; // // Is this a CCW? // ComCallableObject ccw; if (ComCallableObject.TryGetCCW(pComItf, out ccw)) { return ccw.TargetObject; } // // This pointer is not a CCW, but we need to do one additional check here for aggregation // In case the COM pointer is a interface implementation from native, but the outer object is a // managed object // IntPtr pComIdentityIUnknown = McgMarshal.ComQueryInterfaceNoThrow(pComItf, ref Interop.COM.IID_IUnknown); if (pComIdentityIUnknown == default(IntPtr)) throw new InvalidCastException(); try { // // Check whether the identity COM pointer to see if it is a aggregating CCW // if (ComCallableObject.TryGetCCW(pComIdentityIUnknown, out ccw)) { return ccw.TargetObject; } // // Nope, not a CCW - let's go down our RCW creation code path // return ComInterfaceToComObjectInternal( pComItf, pComIdentityIUnknown, interfaceType, classTypeInSignature, ContextCookie.Default, flags ); } finally { McgMarshal.ComRelease(pComIdentityIUnknown); } } internal static unsafe IntPtr ObjectToComInterfaceInternal(Object obj, RuntimeTypeHandle typeHnd) { if (obj == null) return default(IntPtr); #if ENABLE_WINRT // // Try boxing if this is a WinRT object // if (typeHnd.Equals(InternalTypes.IInspectable)) { object unboxed = McgMarshal.BoxIfBoxable(obj); // // Marshal ReferenceImpl<T> to WinRT as IInspectable // if (unboxed != null) { obj = unboxed; } else { // // Anything that can be casted to object[] will be boxed as object[] // object[] objArray = obj as object[]; if (objArray != null) { unboxed = McgMarshal.BoxIfBoxable(obj, typeof(object[]).TypeHandle); if (unboxed != null) obj = unboxed; } } } #endif //ENABLE_WINRT // // If this is a RCW, and the RCW is not a base class (managed class deriving from RCW class), // QI on the RCW // __ComObject comObject = obj as __ComObject; if (comObject != null && !comObject.ExtendsComObject) { IntPtr pComPtr = comObject.QueryInterface_NoAddRef_Internal(typeHnd, /* cacheOnly= */ false, /* throwOnQueryInterfaceFailure= */ false); if (pComPtr == default(IntPtr)) return default(IntPtr); McgMarshal.ComAddRef(pComPtr); GC.KeepAlive(comObject); // make sure we don't collect the object before adding a refcount. return pComPtr; } // // Otherwise, go down the CCW code path // return ManagedObjectToComInterface(obj, typeHnd); } internal static unsafe IntPtr ManagedObjectToComInterface(Object obj, RuntimeTypeHandle interfaceType) { Guid iid = interfaceType.GetInterfaceGuid(); return ManagedObjectToComInterfaceInternal(obj, ref iid, interfaceType); } internal static unsafe IntPtr ManagedObjectToComInterface(Object obj, ref Guid iid) { return ManagedObjectToComInterfaceInternal(obj, ref iid, default(RuntimeTypeHandle)); } private static unsafe IntPtr ManagedObjectToComInterfaceInternal(Object obj, ref Guid iid, RuntimeTypeHandle interfaceType) { if (obj == null) { return default(IntPtr); } // // Look up ComCallableObject from the cache // If couldn't find one, create a new one // ComCallableObject ccw = null; try { // // Either return existing one or create a new one // In either case, the returned CCW is addref-ed to avoid race condition // IntPtr dummy; ccw = CCWLookupMap.GetOrCreateCCW(obj, interfaceType, out dummy); Debug.Assert(ccw != null); return ccw.GetComInterfaceForIID(ref iid, interfaceType); } finally { // // Free the extra ref count added by GetOrCreateCCW (to protect the CCW from being collected) // if (ccw != null) ccw.Release(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OrchardCore.Abstractions.Setup; using OrchardCore.Data; using OrchardCore.Email; using OrchardCore.Environment.Shell; using OrchardCore.Modules; using OrchardCore.Recipes.Models; using OrchardCore.Setup.Services; using OrchardCore.Setup.ViewModels; namespace OrchardCore.Setup.Controllers { public class SetupController : Controller { private readonly IClock _clock; private readonly ISetupService _setupService; private readonly ShellSettings _shellSettings; private readonly IShellHost _shellHost; private IdentityOptions _identityOptions; private readonly IEmailAddressValidator _emailAddressValidator; private readonly IEnumerable<DatabaseProvider> _databaseProviders; private readonly ILogger _logger; private readonly IStringLocalizer S; public SetupController( IClock clock, ISetupService setupService, ShellSettings shellSettings, IShellHost shellHost, IOptions<IdentityOptions> identityOptions, IEmailAddressValidator emailAddressValidator, IEnumerable<DatabaseProvider> databaseProviders, IStringLocalizer<SetupController> localizer, ILogger<SetupController> logger) { _clock = clock; _setupService = setupService; _shellSettings = shellSettings; _shellHost = shellHost; _identityOptions = identityOptions.Value; _emailAddressValidator = emailAddressValidator; _databaseProviders = databaseProviders; _logger = logger; S = localizer; } public async Task<ActionResult> Index(string token) { var recipes = await _setupService.GetSetupRecipesAsync(); var defaultRecipe = recipes.FirstOrDefault(x => x.Tags.Contains("default")) ?? recipes.FirstOrDefault(); if (!string.IsNullOrWhiteSpace(_shellSettings["Secret"])) { if (string.IsNullOrEmpty(token) || !await IsTokenValid(token)) { _logger.LogWarning("An attempt to access '{TenantName}' without providing a secret was made", _shellSettings.Name); return StatusCode(404); } } var model = new SetupViewModel { DatabaseProviders = _databaseProviders, Recipes = recipes, RecipeName = defaultRecipe?.Name, Secret = token }; CopyShellSettingsValues(model); if (!String.IsNullOrEmpty(_shellSettings["TablePrefix"])) { model.DatabaseConfigurationPreset = true; model.TablePrefix = _shellSettings["TablePrefix"]; } return View(model); } [HttpPost, ActionName("Index")] public async Task<ActionResult> IndexPOST(SetupViewModel model) { if (!string.IsNullOrWhiteSpace(_shellSettings["Secret"])) { if (string.IsNullOrEmpty(model.Secret) || !await IsTokenValid(model.Secret)) { _logger.LogWarning("An attempt to access '{TenantName}' without providing a valid secret was made", _shellSettings.Name); return StatusCode(404); } } model.DatabaseProviders = _databaseProviders; model.Recipes = await _setupService.GetSetupRecipesAsync(); var selectedProvider = model.DatabaseProviders.FirstOrDefault(x => x.Value == model.DatabaseProvider); if (!model.DatabaseConfigurationPreset) { if (selectedProvider != null && selectedProvider.HasConnectionString && String.IsNullOrWhiteSpace(model.ConnectionString)) { ModelState.AddModelError(nameof(model.ConnectionString), S["The connection string is mandatory for this provider."]); } } if (String.IsNullOrEmpty(model.Password)) { ModelState.AddModelError(nameof(model.Password), S["The password is required."]); } if (model.Password != model.PasswordConfirmation) { ModelState.AddModelError(nameof(model.PasswordConfirmation), S["The password confirmation doesn't match the password."]); } RecipeDescriptor selectedRecipe = null; if (!string.IsNullOrEmpty(_shellSettings["RecipeName"])) { selectedRecipe = model.Recipes.FirstOrDefault(x => x.Name == _shellSettings["RecipeName"]); if (selectedRecipe == null) { ModelState.AddModelError(nameof(model.RecipeName), S["Invalid recipe."]); } } else if (String.IsNullOrEmpty(model.RecipeName) || (selectedRecipe = model.Recipes.FirstOrDefault(x => x.Name == model.RecipeName)) == null) { ModelState.AddModelError(nameof(model.RecipeName), S["Invalid recipe."]); } // Only add additional errors if attribute validation has passed. if (!String.IsNullOrEmpty(model.Email) && !_emailAddressValidator.Validate(model.Email)) { ModelState.AddModelError(nameof(model.Email), S["The email is invalid."]); } if (!String.IsNullOrEmpty(model.UserName) && model.UserName.Any(c => !_identityOptions.User.AllowedUserNameCharacters.Contains(c))) { ModelState.AddModelError(nameof(model.UserName), S["User name '{0}' is invalid, can only contain letters or digits.", model.UserName]); } if (!ModelState.IsValid) { CopyShellSettingsValues(model); return View(model); } var setupContext = new SetupContext { ShellSettings = _shellSettings, EnabledFeatures = null, // default list, Errors = new Dictionary<string, string>(), Recipe = selectedRecipe, Properties = new Dictionary<string, object> { { SetupConstants.SiteName, model.SiteName }, { SetupConstants.AdminUsername, model.UserName }, { SetupConstants.AdminEmail, model.Email }, { SetupConstants.AdminPassword, model.Password }, { SetupConstants.SiteTimeZone, model.SiteTimeZone }, } }; if (!string.IsNullOrEmpty(_shellSettings["ConnectionString"])) { setupContext.Properties[SetupConstants.DatabaseProvider] = _shellSettings["DatabaseProvider"]; setupContext.Properties[SetupConstants.DatabaseConnectionString] = _shellSettings["ConnectionString"]; setupContext.Properties[SetupConstants.DatabaseTablePrefix] = _shellSettings["TablePrefix"]; } else { setupContext.Properties[SetupConstants.DatabaseProvider] = model.DatabaseProvider; setupContext.Properties[SetupConstants.DatabaseConnectionString] = model.ConnectionString; setupContext.Properties[SetupConstants.DatabaseTablePrefix] = model.TablePrefix; } var executionId = await _setupService.SetupAsync(setupContext); // Check if a component in the Setup failed if (setupContext.Errors.Any()) { foreach (var error in setupContext.Errors) { ModelState.AddModelError(error.Key, error.Value); } return View(model); } return Redirect("~/"); } private void CopyShellSettingsValues(SetupViewModel model) { if (!String.IsNullOrEmpty(_shellSettings["ConnectionString"])) { model.DatabaseConfigurationPreset = true; model.ConnectionString = _shellSettings["ConnectionString"]; } if (!String.IsNullOrEmpty(_shellSettings["RecipeName"])) { model.RecipeNamePreset = true; model.RecipeName = _shellSettings["RecipeName"]; } if (!String.IsNullOrEmpty(_shellSettings["DatabaseProvider"])) { model.DatabaseConfigurationPreset = true; model.DatabaseProvider = _shellSettings["DatabaseProvider"]; } else { model.DatabaseProvider = model.DatabaseProviders.FirstOrDefault(p => p.IsDefault)?.Value; } if (!String.IsNullOrEmpty(_shellSettings["Description"])) { model.Description = _shellSettings["Description"]; } } private async Task<bool> IsTokenValid(string token) { try { var result = false; var shellScope = await _shellHost.GetScopeAsync(ShellHelper.DefaultShellName); await shellScope.UsingAsync(scope => { var dataProtectionProvider = scope.ServiceProvider.GetRequiredService<IDataProtectionProvider>(); var dataProtector = dataProtectionProvider.CreateProtector("Tokens").ToTimeLimitedDataProtector(); var tokenValue = dataProtector.Unprotect(token, out var expiration); if (_clock.UtcNow < expiration.ToUniversalTime()) { if (_shellSettings["Secret"] == tokenValue) { result = true; } } return Task.CompletedTask; }); return result; } catch (Exception ex) { _logger.LogError(ex, "Error in decrypting the token"); } return false; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data.OleDb; using FileHelpers.DataLink; using NUnit.Framework; namespace FileHelpers.Tests.DataLink { [TestFixture] [Explicit] [Category("Advanced")] public class DataLinks { private FileDataLink mLink; #region " FillRecordOrders " protected void FillRecordOrders(object rec, object[] fields) { var record = (OrdersFixed) rec; record.OrderID = (int) fields[0]; record.CustomerID = (string) fields[1]; record.EmployeeID = (int) fields[2]; record.OrderDate = (DateTime) fields[3]; record.RequiredDate = (DateTime) fields[4]; if (fields[5] != DBNull.Value) record.ShippedDate = (DateTime) fields[5]; else record.ShippedDate = DateTime.MinValue; record.ShipVia = (int) fields[6]; record.Freight = (decimal) fields[7]; } #endregion [Test] public void OrdersDbToFile() { var storage = new AccessStorage(typeof (OrdersFixed), @"..\data\TestData.mdb"); storage.SelectSql = "SELECT * FROM Orders"; storage.FillRecordCallback = new FillRecordHandler(FillRecordOrders); mLink = new FileDataLink(storage); mLink.ExtractToFile(@"..\data\temp.txt"); int extractNum = mLink.LastExtractedRecords.Length; var records = (OrdersFixed[]) mLink.FileHelperEngine.ReadFile(@"..\data\temp.txt"); Assert.AreEqual(extractNum, records.Length); } [Test] public void OrdersDbToFileEasy() { var storage = new AccessStorage(typeof (OrdersFixed), @"..\data\TestData.mdb"); storage.SelectSql = "SELECT * FROM Orders"; storage.FillRecordCallback = new FillRecordHandler(FillRecordOrders); var records = (OrdersFixed[]) FileDataLink.EasyExtractToFile(storage, @"..\data\temp.txt"); int extractNum = records.Length; records = (OrdersFixed[]) CommonEngine.ReadFile(typeof (OrdersFixed), @"..\data\temp.txt"); Assert.AreEqual(extractNum, records.Length); } private void FillRecordCustomers(object rec, object[] fields) { var record = (CustomersVerticalBar) rec; record.CustomerID = (string) fields[0]; record.CompanyName = (string) fields[1]; record.ContactName = (string) fields[2]; record.ContactTitle = (string) fields[3]; record.Address = (string) fields[4]; record.City = (string) fields[5]; record.Country = (string) fields[6]; } [Test] public void CustomersDbToFile() { var storage = new AccessStorage(typeof (CustomersVerticalBar), @"..\data\TestData.mdb"); storage.SelectSql = "SELECT * FROM Customers"; storage.FillRecordCallback = new FillRecordHandler(FillRecordCustomers); mLink = new FileDataLink(storage); mLink.ExtractToFile(@"..\data\temp.txt"); int extractNum = mLink.LastExtractedRecords.Length; var records = (CustomersVerticalBar[]) mLink.FileHelperEngine.ReadFile(@"..\data\temp.txt"); Assert.AreEqual(extractNum, records.Length); } private object FillRecord(object[] fields) { var record = new CustomersVerticalBar(); record.CustomerID = (string) fields[0]; record.CompanyName = (string) fields[1]; record.ContactName = (string) fields[2]; record.ContactTitle = (string) fields[3]; record.Address = (string) fields[4]; record.City = (string) fields[5]; record.Country = (string) fields[6]; return record; } #region " GetInsertSql " protected string GetInsertSqlCust(object record) { var obj = (CustomersVerticalBar) record; return String.Format( "INSERT INTO CustomersTemp (Address, City, CompanyName, ContactName, ContactTitle, Country, CustomerID) " + " VALUES ( \"{0}\" , \"{1}\" , \"{2}\" , \"{3}\" , \"{4}\" , \"{5}\" , \"{6}\" ); ", obj.Address, obj.City, obj.CompanyName, obj.ContactName, obj.ContactTitle, obj.Country, obj.CustomerID ); } #endregion [Test] public void CustomersFileToDb() { var storage = new AccessStorage(typeof (CustomersVerticalBar), @"..\data\TestData.mdb"); storage.InsertSqlCallback = new InsertSqlHandler(GetInsertSqlCust); mLink = new FileDataLink(storage); ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp"); int count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp"); Assert.AreEqual(0, count); mLink.InsertFromFile(@"..\data\UpLoadCustomers.txt"); count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp"); Assert.AreEqual(91, count); ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "CustomersTemp"); } protected object FillRecordOrder(object[] fields) { var record = new OrdersFixed(); record.OrderID = (int) fields[0]; record.CustomerID = (string) fields[1]; record.EmployeeID = (int) fields[2]; record.OrderDate = (DateTime) fields[3]; record.RequiredDate = (DateTime) fields[4]; if (fields[5] != DBNull.Value) record.ShippedDate = (DateTime) fields[5]; else record.ShippedDate = DateTime.MinValue; record.ShipVia = (int) fields[6]; record.Freight = (decimal) fields[7]; return record; } #region " GetInsertSql " protected string GetInsertSqlOrder(object record) { var obj = (OrdersFixed) record; return String.Format( "INSERT INTO OrdersTemp (CustomerID, EmployeeID, Freight, OrderDate, OrderID, RequiredDate, ShippedDate, ShipVia) " + " VALUES ( \"{0}\" , \"{1}\" , \"{2}\" , \"{3}\" , \"{4}\" , \"{5}\" , \"{6}\" , \"{7}\" ) ", obj.CustomerID, obj.EmployeeID, obj.Freight, obj.OrderDate, obj.OrderID, obj.RequiredDate, obj.ShippedDate, obj.ShipVia ); } #endregion [Test] [Ignore("Needs Access Installed")] public void OrdersFileToDb() { var storage = new AccessStorage(typeof (OrdersFixed), @"..\data\TestData.mdb"); storage.InsertSqlCallback = new InsertSqlHandler(GetInsertSqlOrder); mLink = new FileDataLink(storage); ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp"); int count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp"); Assert.AreEqual(0, count); mLink.InsertFromFile(@"..\data\UpLoadOrders.txt"); count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp"); Assert.AreEqual(830, count); ClearData(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp"); } private const string AccessConnStr = @"Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Database Password=;Data Source=""<BASE>"";Password=;Jet OLEDB:Engine Type=5;Jet OLEDB:Global Bulk Transactions=1;Provider=""Microsoft.Jet.OLEDB.4.0"";Jet OLEDB:System database=;Jet OLEDB:SFP=False;Extended Properties=;Mode=Share Deny None;Jet OLEDB:New Database Password=;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;User ID=Admin;Jet OLEDB:Encrypt Database=False"; public void ClearData(string fileName, string table) { string conString = AccessConnStr.Replace("<BASE>", fileName); var conn = new OleDbConnection(conString); var cmd = new OleDbCommand("DELETE FROM " + table, conn); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); int count = Count(((AccessStorage) mLink.DataStorage).AccessFileName, "OrdersTemp"); } public int Count(string fileName, string table) { string conString = AccessConnStr.Replace("<BASE>", fileName); var conn = new OleDbConnection(conString); var cmd = new OleDbCommand("SELECT COUNT (*) FROM " + table, conn); conn.Open(); var res = (int) cmd.ExecuteScalar(); conn.Close(); return res; } } }
//----------------------------------------------------------------------- // <copyright file="Transfer.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.Actor; using Akka.Pattern; namespace Akka.Streams.Implementation { /// <summary> /// TBD /// </summary> public class SubReceive { private Receive _currentReceive; /// <summary> /// TBD /// </summary> /// <param name="initial">TBD</param> public SubReceive(Receive initial) { _currentReceive = initial; } /// <summary> /// TBD /// </summary> public Receive CurrentReceive => _currentReceive; /// <summary> /// TBD /// </summary> /// <param name="receive">TBD</param> public void Become(Receive receive) => _currentReceive = receive; } /// <summary> /// TBD /// </summary> internal interface IInputs { /// <summary> /// TBD /// </summary> TransferState NeedsInput { get; } /// <summary> /// TBD /// </summary> TransferState NeedsInputOrComplete { get; } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> object DequeueInputElement(); /// <summary> /// TBD /// </summary> SubReceive SubReceive { get; } /// <summary> /// TBD /// </summary> void Cancel(); /// <summary> /// TBD /// </summary> bool IsClosed { get; } /// <summary> /// TBD /// </summary> bool IsOpen { get; } /// <summary> /// TBD /// </summary> bool AreInputsDepleted { get; } /// <summary> /// TBD /// </summary> bool AreInputsAvailable { get; } } /// <summary> /// TBD /// </summary> internal static class DefaultInputTransferStates { /// <summary> /// TBD /// </summary> /// <param name="inputs">TBD</param> /// <returns>TBD</returns> public static TransferState NeedsInput(IInputs inputs) => new LambdaTransferState(() => inputs.AreInputsAvailable, () => inputs.AreInputsDepleted); /// <summary> /// TBD /// </summary> /// <param name="inputs">TBD</param> /// <returns>TBD</returns> public static TransferState NeedsInputOrComplete(IInputs inputs) => new LambdaTransferState(() => inputs.AreInputsAvailable || inputs.AreInputsDepleted, () => false); } /// <summary> /// TBD /// </summary> internal interface IOutputs { /// <summary> /// TBD /// </summary> SubReceive SubReceive { get; } /// <summary> /// TBD /// </summary> TransferState NeedsDemand { get; } /// <summary> /// TBD /// </summary> TransferState NeedsDemandOrCancel { get; } /// <summary> /// TBD /// </summary> long DemandCount { get; } /// <summary> /// TBD /// </summary> bool IsDemandAvailable { get; } /// <summary> /// TBD /// </summary> /// <param name="element">TBD</param> void EnqueueOutputElement(object element); /// <summary> /// TBD /// </summary> void Complete(); /// <summary> /// TBD /// </summary> void Cancel(); /// <summary> /// TBD /// </summary> /// <param name="e">TBD</param> void Error(Exception e); /// <summary> /// TBD /// </summary> bool IsClosed { get; } /// <summary> /// TBD /// </summary> bool IsOpen { get; } } /// <summary> /// TBD /// </summary> internal static class DefaultOutputTransferStates { /// <summary> /// TBD /// </summary> /// <param name="outputs">TBD</param> /// <returns>TBD</returns> public static TransferState NeedsDemand(IOutputs outputs) => new LambdaTransferState(() => outputs.IsDemandAvailable, () => outputs.IsClosed); /// <summary> /// TBD /// </summary> /// <param name="outputs">TBD</param> /// <returns>TBD</returns> public static TransferState NeedsDemandOrCancel(IOutputs outputs) => new LambdaTransferState(() => outputs.IsDemandAvailable || outputs.IsClosed, () => false); } /// <summary> /// TBD /// </summary> public abstract class TransferState { /// <summary> /// TBD /// </summary> public abstract bool IsReady { get; } /// <summary> /// TBD /// </summary> public abstract bool IsCompleted { get; } /// <summary> /// TBD /// </summary> public bool IsExecutable => IsReady && !IsCompleted; /// <summary> /// TBD /// </summary> /// <param name="other">TBD</param> /// <returns>TBD</returns> public TransferState Or(TransferState other) => new LambdaTransferState(() => IsReady || other.IsReady, () => IsCompleted && other.IsCompleted); /// <summary> /// TBD /// </summary> /// <param name="other">TBD</param> /// <returns>TBD</returns> public TransferState And(TransferState other) => new LambdaTransferState(() => IsReady && other.IsReady, () => IsCompleted || other.IsCompleted); } /// <summary> /// TBD /// </summary> internal sealed class LambdaTransferState : TransferState { private readonly Func<bool> _isReady; private readonly Func<bool> _isCompleted; /// <summary> /// TBD /// </summary> public override bool IsReady => _isReady(); /// <summary> /// TBD /// </summary> public override bool IsCompleted => _isCompleted(); /// <summary> /// TBD /// </summary> /// <param name="isReady">TBD</param> /// <param name="isCompleted">TBD</param> public LambdaTransferState(Func<bool> isReady, Func<bool> isCompleted) { _isReady = isReady; _isCompleted = isCompleted; } } /// <summary> /// TBD /// </summary> internal sealed class Completed : TransferState { /// <summary> /// TBD /// </summary> public static readonly Completed Instance = new Completed(); private Completed() { } /// <summary> /// TBD /// </summary> public override bool IsReady => false; /// <summary> /// TBD /// </summary> public override bool IsCompleted => true; } /// <summary> /// TBD /// </summary> internal sealed class NotInitialized : TransferState { /// <summary> /// TBD /// </summary> public static readonly NotInitialized Instance = new NotInitialized(); private NotInitialized() { } /// <summary> /// TBD /// </summary> public override bool IsReady => false; /// <summary> /// TBD /// </summary> public override bool IsCompleted => false; } /// <summary> /// TBD /// </summary> internal class WaitingForUpstreamSubscription : TransferState { /// <summary> /// TBD /// </summary> public readonly int Remaining; /// <summary> /// TBD /// </summary> public readonly TransferPhase AndThen; /// <summary> /// TBD /// </summary> /// <param name="remaining">TBD</param> /// <param name="andThen">TBD</param> public WaitingForUpstreamSubscription(int remaining, TransferPhase andThen) { Remaining = remaining; AndThen = andThen; } /// <summary> /// TBD /// </summary> public override bool IsReady => false; /// <summary> /// TBD /// </summary> public override bool IsCompleted => false; } /// <summary> /// TBD /// </summary> internal sealed class Always : TransferState { /// <summary> /// TBD /// </summary> public static readonly Always Instance = new Always(); private Always() { } /// <summary> /// TBD /// </summary> public override bool IsReady => true; /// <summary> /// TBD /// </summary> public override bool IsCompleted => false; } /// <summary> /// TBD /// </summary> public struct TransferPhase { /// <summary> /// TBD /// </summary> public readonly TransferState Precondition; /// <summary> /// TBD /// </summary> public readonly Action Action; /// <summary> /// TBD /// </summary> /// <param name="precondition">TBD</param> /// <param name="action">TBD</param> public TransferPhase(TransferState precondition, Action action) : this() { Precondition = precondition; Action = action; } } /// <summary> /// TBD /// </summary> public interface IPump { /// <summary> /// TBD /// </summary> TransferState TransferState { get; set; } /// <summary> /// TBD /// </summary> Action CurrentAction { get; set; } /// <summary> /// TBD /// </summary> bool IsPumpFinished { get; } /// <summary> /// TBD /// </summary> /// <param name="waitForUpstream">TBD</param> /// <param name="andThen">TBD</param> void InitialPhase(int waitForUpstream, TransferPhase andThen); /// <summary> /// TBD /// </summary> /// <param name="waitForUpstream">TBD</param> void WaitForUpstream(int waitForUpstream); /// <summary> /// TBD /// </summary> void GotUpstreamSubscription(); /// <summary> /// TBD /// </summary> /// <param name="phase">TBD</param> void NextPhase(TransferPhase phase); // Exchange input buffer elements and output buffer "requests" until one of them becomes empty. // Generate upstream requestMore for every Nth consumed input element /// <summary> /// TBD /// </summary> void Pump(); /// <summary> /// TBD /// </summary> /// <param name="e">TBD</param> void PumpFailed(Exception e); /// <summary> /// TBD /// </summary> void PumpFinished(); } /// <summary> /// TBD /// </summary> internal abstract class PumpBase : IPump { /// <summary> /// Initializes a new instance of the <see cref="PumpBase" /> class. /// </summary> /// <exception cref="IllegalStateException"> /// This exception is thrown when the pump has not been initialized with a phase. /// </exception> protected PumpBase() { TransferState = NotInitialized.Instance; CurrentAction = () => { throw new IllegalStateException("Pump has not been initialized with a phase"); }; } /// <summary> /// TBD /// </summary> public TransferState TransferState { get; set; } /// <summary> /// TBD /// </summary> public Action CurrentAction { get; set; } /// <summary> /// TBD /// </summary> public bool IsPumpFinished => TransferState.IsCompleted; /// <summary> /// TBD /// </summary> /// <param name="waitForUpstream">TBD</param> /// <param name="andThen">TBD</param> public void InitialPhase(int waitForUpstream, TransferPhase andThen) => Pumps.InitialPhase(this, waitForUpstream, andThen); /// <summary> /// TBD /// </summary> /// <param name="waitForUpstream">TBD</param> public void WaitForUpstream(int waitForUpstream) => Pumps.WaitForUpstream(this, waitForUpstream); /// <summary> /// TBD /// </summary> public void GotUpstreamSubscription() => Pumps.GotUpstreamSubscription(this); /// <summary> /// TBD /// </summary> /// <param name="phase">TBD</param> public void NextPhase(TransferPhase phase) => Pumps.NextPhase(this, phase); /// <summary> /// TBD /// </summary> public void Pump() => Pumps.Pump(this); /// <summary> /// TBD /// </summary> /// <param name="e">TBD</param> public abstract void PumpFailed(Exception e); /// <summary> /// TBD /// </summary> public abstract void PumpFinished(); } /// <summary> /// TBD /// </summary> internal static class Pumps { /// <summary> /// TBD /// </summary> /// <param name="self">TBD</param> /// <exception cref="IllegalStateException"> /// This exception is thrown when the pump has not been initialized with a phase. /// </exception> public static void Init(this IPump self) { self.TransferState = NotInitialized.Instance; self.CurrentAction = () => { throw new IllegalStateException("Pump has not been initialized with a phase"); }; } /// <summary> /// TBD /// </summary> /// <exception cref="IllegalStateException"> /// This exception is thrown when the action of the completed phase tried to execute. /// </exception> public static readonly TransferPhase CompletedPhase = new TransferPhase(Completed.Instance, () => { throw new IllegalStateException("The action of completed phase must never be executed"); }); /// <summary> /// TBD /// </summary> /// <param name="self">TBD</param> /// <param name="waitForUpstream">TBD</param> /// <param name="andThen">TBD</param> /// <exception cref="ArgumentException"> /// This exception is thrown when the specified <paramref name="waitForUpstream"/> is less than one. /// </exception> /// <exception cref="IllegalStateException"> /// This exception is thrown when the initial state is not <see cref="NotInitialized.Instance"/>. /// </exception> public static void InitialPhase(this IPump self, int waitForUpstream, TransferPhase andThen) { if (waitForUpstream < 1) throw new ArgumentException($"WaitForUpstream must be >= 1 (was {waitForUpstream})"); if(self.TransferState != NotInitialized.Instance) throw new IllegalStateException($"Initial state expected NotInitialized, but got {self.TransferState}"); self.TransferState = new WaitingForUpstreamSubscription(waitForUpstream, andThen); } /// <summary> /// TBD /// </summary> /// <param name="self">TBD</param> /// <param name="waitForUpstream">TBD</param> /// <exception cref="ArgumentException"> /// This exception is thrown when the specified <paramref name="waitForUpstream"/> is less than one. /// </exception> public static void WaitForUpstream(this IPump self, int waitForUpstream) { if(waitForUpstream < 1) throw new ArgumentException($"WaitForUpstream must be >= 1 (was {waitForUpstream})"); self.TransferState = new WaitingForUpstreamSubscription(waitForUpstream, new TransferPhase(self.TransferState, self.CurrentAction)); } /// <summary> /// TBD /// </summary> /// <param name="self">TBD</param> public static void GotUpstreamSubscription(this IPump self) { if (self.TransferState is WaitingForUpstreamSubscription) { var t = (WaitingForUpstreamSubscription) self.TransferState; if (t.Remaining == 1) { self.TransferState = t.AndThen.Precondition; self.CurrentAction = t.AndThen.Action; } else self.TransferState = new WaitingForUpstreamSubscription(t.Remaining - 1, t.AndThen); } self.Pump(); } /// <summary> /// TBD /// </summary> /// <param name="self">TBD</param> /// <param name="phase">TBD</param> public static void NextPhase(this IPump self, TransferPhase phase) { if (self.TransferState is WaitingForUpstreamSubscription) { var w = (WaitingForUpstreamSubscription) self.TransferState; self.TransferState = new WaitingForUpstreamSubscription(w.Remaining, phase); } else { self.TransferState = phase.Precondition; self.CurrentAction = phase.Action; } } /// <summary> /// TBD /// </summary> /// <param name="self">TBD</param> /// <returns>TBD</returns> public static bool IsPumpFinished(this IPump self) => self.TransferState.IsCompleted; /// <summary> /// TBD /// </summary> /// <param name="self">TBD</param> public static void Pump(this IPump self) { try { while (self.TransferState.IsExecutable) self.CurrentAction(); } catch (Exception e) { self.PumpFailed(e); } if(self.IsPumpFinished) self.PumpFinished(); } } }
/* * Copyright (C) 2012, 2013 OUYA, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; using Debug = UnityEngine.Debug; public class OuyaMenuAdmin : MonoBehaviour { private static Vector3 m_pos = Vector3.zero; private static Vector3 m_euler = Vector3.zero; [MenuItem("OUYA/Export Core Package", priority = 100)] public static void MenuPackageCore() { string[] paths = { "ProjectSettings/InputManager.asset", "Assets/Litjson", "Assets/Ouya/SDK", "Assets/Plugins", }; AssetDatabase.ExportPackage(paths, "OuyaSDK-Core.unitypackage", ExportPackageOptions.IncludeDependencies | ExportPackageOptions.Recurse | ExportPackageOptions.Interactive); Debug.Log(string.Format("Export OuyaSDK-Core.unitypackage success in: {0}", Directory.GetCurrentDirectory())); } [MenuItem("OUYA/Export Examples Package", priority = 110)] public static void MenuPackageExamples() { string[] paths = { "Assets/Ouya/Examples", }; AssetDatabase.ExportPackage(paths, "OuyaSDK-Examples.unitypackage", ExportPackageOptions.IncludeDependencies | ExportPackageOptions.Recurse | ExportPackageOptions.Interactive); Debug.Log(string.Format("Export OuyaSDK-Examples.unitypackage success in: {0}", Directory.GetCurrentDirectory())); } [MenuItem("OUYA/Export StarterKit Package", priority = 120)] public static void MenuPackageStarterKit() { string[] paths = { "Assets/Ouya/StarterKit", }; AssetDatabase.ExportPackage(paths, "OuyaSDK-StarterKit.unitypackage", ExportPackageOptions.IncludeDependencies | ExportPackageOptions.Recurse | ExportPackageOptions.Interactive); Debug.Log(string.Format("Export OuyaSDK-StarterKit.unitypackage success in: {0}", Directory.GetCurrentDirectory())); } [MenuItem("OUYA/Copy Object Transform", priority=1000)] public static void MenuCopyObjectTransform() { if (Selection.activeGameObject) { m_pos = Selection.activeGameObject.transform.position; m_euler = Selection.activeGameObject.transform.rotation.eulerAngles; } } [MenuItem("OUYA/Copy Scene Transform", priority = 1000)] public static void MenuCopySceneTransform() { if (SceneView.currentDrawingSceneView && SceneView.currentDrawingSceneView.camera && SceneView.currentDrawingSceneView.camera.transform) { m_pos = SceneView.currentDrawingSceneView.camera.transform.position; m_euler = SceneView.currentDrawingSceneView.camera.transform.rotation.eulerAngles; } } [MenuItem("OUYA/Paste Stored Transform", priority = 1000)] public static void MenuSetTransform() { if (Selection.activeGameObject) { Selection.activeGameObject.transform.position = m_pos; Selection.activeGameObject.transform.rotation = Quaternion.Euler(m_euler); } } public static void MenuGeneratePluginJar() { UpdatePaths(); if (CompileApplicationClasses()) { BuildApplicationJar(); AssetDatabase.Refresh(); } } private static string m_pathUnityProject = string.Empty; private static string m_pathUnityEditor = string.Empty; private static string m_pathUnityJar = string.Empty; private static string m_pathJDK = string.Empty; private static string m_pathToolsJar = string.Empty; private static string m_pathJar = string.Empty; private static string m_pathJavaC = string.Empty; private static string m_pathJavaP = string.Empty; private static string m_pathSrc = string.Empty; private static string m_pathSDK = string.Empty; private static string m_pathOuyaSDKJar = string.Empty; private static string m_pathGsonJar = string.Empty; private static void UpdatePaths() { m_pathUnityProject = new DirectoryInfo(Directory.GetCurrentDirectory()).FullName; switch (Application.platform) { case RuntimePlatform.OSXEditor: m_pathUnityEditor = EditorApplication.applicationPath; m_pathUnityJar = string.Format("{0}/{1}", m_pathUnityEditor, OuyaPanel.PATH_UNITY_JAR_MAC); break; case RuntimePlatform.WindowsEditor: m_pathUnityEditor = new FileInfo(EditorApplication.applicationPath).Directory.FullName; m_pathUnityJar = string.Format("{0}/{1}", m_pathUnityEditor, OuyaPanel.PATH_UNITY_JAR_WIN); break; } m_pathSrc = string.Format("{0}/Assets/Plugins/Android/src", m_pathUnityProject); m_pathSDK = EditorPrefs.GetString(OuyaPanel.KEY_PATH_ANDROID_SDK); m_pathJDK = EditorPrefs.GetString(OuyaPanel.KEY_PATH_JAVA_JDK); switch (Application.platform) { case RuntimePlatform.OSXEditor: m_pathToolsJar = string.Format("{0}/Contents/Classes/classes.jar", m_pathJDK); m_pathJar = string.Format("{0}/Contents/Commands/{1}", m_pathJDK, OuyaPanel.FILE_JAR_MAC); m_pathJavaC = string.Format("{0}/Contents/Commands/{1}", m_pathJDK, OuyaPanel.FILE_JAVAC_MAC); m_pathJavaP = string.Format("{0}/Contents/Commands/{1}", m_pathJDK, OuyaPanel.FILE_JAVAP_MAC); break; case RuntimePlatform.WindowsEditor: m_pathToolsJar = string.Format("{0}/lib/tools.jar", m_pathJDK); m_pathJar = string.Format("{0}/{1}/{2}", m_pathJDK, OuyaPanel.REL_JAVA_PLATFORM_TOOLS, OuyaPanel.FILE_JAR_WIN); m_pathJavaC = string.Format("{0}/{1}/{2}", m_pathJDK, OuyaPanel.REL_JAVA_PLATFORM_TOOLS, OuyaPanel.FILE_JAVAC_WIN); m_pathJavaP = string.Format("{0}/{1}/{2}", m_pathJDK, OuyaPanel.REL_JAVA_PLATFORM_TOOLS, OuyaPanel.FILE_JAVAP_WIN); break; } m_pathOuyaSDKJar = string.Format("{0}/Assets/Plugins/Android/libs/ouya-sdk.jar", m_pathUnityProject); m_pathGsonJar = string.Format("{0}/Assets/Plugins/Android/libs/gson-2.2.2.jar", m_pathUnityProject); } private static string GetPathAndroidJar() { return string.Format("{0}/platforms/android-{1}/android.jar", m_pathSDK, (int)PlayerSettings.Android.minSdkVersion); } static bool CompileApplicationClasses() { string pathClasses = string.Format("{0}/Assets/Plugins/Android/Classes", m_pathUnityProject); if (!Directory.Exists(pathClasses)) { Directory.CreateDirectory(pathClasses); } string includeFiles = string.Format("\"{0}/OuyaUnityPlugin.java\" \"{0}/IOuyaActivity.java\" \"{0}/TestOuyaFacade.java\"", m_pathSrc); string jars = string.Empty; if (File.Exists(m_pathToolsJar)) { Debug.Log(string.Format("Found Java tools jar: {0}", m_pathToolsJar)); } else { Debug.LogError(string.Format("Failed to find Java tools jar: {0}", m_pathToolsJar)); return false; } if (File.Exists(GetPathAndroidJar())) { Debug.Log(string.Format("Found Android jar: {0}", GetPathAndroidJar())); } else { Debug.LogError(string.Format("Failed to find Android jar: {0}", GetPathAndroidJar())); return false; } if (File.Exists(m_pathGsonJar)) { Debug.Log(string.Format("Found GJON jar: {0}", m_pathGsonJar)); } else { Debug.LogError(string.Format("Failed to find GSON jar: {0}", m_pathGsonJar)); return false; } if (File.Exists(m_pathUnityJar)) { Debug.Log(string.Format("Found Unity jar: {0}", m_pathUnityJar)); } else { Debug.LogError(string.Format("Failed to find Unity jar: {0}", m_pathUnityJar)); return false; } string output = string.Empty; string error = string.Empty; switch (Application.platform) { case RuntimePlatform.OSXEditor: jars = string.Format("\"{0}:{1}:{2}:{3}:{4}\"", m_pathToolsJar, GetPathAndroidJar(), m_pathGsonJar, m_pathUnityJar, m_pathOuyaSDKJar); OuyaPanel.RunProcess(m_pathJavaC, string.Empty, string.Format("-g -source 1.6 -target 1.6 {0} -classpath {1} -bootclasspath {1} -d \"{2}\"", includeFiles, jars, pathClasses), ref output, ref error); break; case RuntimePlatform.WindowsEditor: jars = string.Format("\"{0}\";\"{1}\";\"{2}\";\"{3}\";\"{4}\"", m_pathToolsJar, GetPathAndroidJar(), m_pathGsonJar, m_pathUnityJar, m_pathOuyaSDKJar); OuyaPanel.RunProcess(m_pathJavaC, string.Empty, string.Format("-Xlint:deprecation -g -source 1.6 -target 1.6 {0} -classpath {1} -bootclasspath {1} -d \"{2}\"", includeFiles, jars, pathClasses), ref output, ref error); break; default: return false; } if (!string.IsNullOrEmpty(error)) { Debug.LogError(error); if (OuyaPanel.StopOnErrors) { return false; } } return true; } static void BuildApplicationJar() { string pathClasses = string.Format("{0}/Assets/Plugins/Android/Classes", m_pathUnityProject); OuyaPanel.RunProcess(m_pathJar, pathClasses, string.Format("cvfM OuyaUnityPlugin.jar tv/")); OuyaPanel.RunProcess(m_pathJavaP, pathClasses, "-s tv.ouya.sdk.OuyaUnityPlugin"); OuyaPanel.RunProcess(m_pathJavaP, pathClasses, "-s tv.ouya.sdk.TestOuyaFacade"); OuyaPanel.RunProcess(m_pathJavaP, pathClasses, "-s tv.ouya.sdk.IOuyaActivity"); string pathAppJar = string.Format("{0}/OuyaUnityPlugin.jar", pathClasses); string pathDest = string.Format("{0}/Assets/Plugins/Android/OuyaUnityPlugin.jar", m_pathUnityProject); if (File.Exists(pathDest)) { File.Delete(pathDest); } if (File.Exists(pathAppJar)) { File.Move(pathAppJar, pathDest); } if (Directory.Exists(pathClasses)) { Directory.Delete(pathClasses, true); } } }
using System; using System.IO; using System.Collections.ObjectModel; namespace SteamBot { /// <summary> /// A interpreter for the bot manager so a user can control bots. /// </summary> /// <remarks> /// There is currently a small set of commands this can interpret. They /// are limited by the functionality the <see cref="BotManager"/> class /// exposes. /// </remarks> public class BotManagerInterpreter { private readonly BotManager manager; private CommandSet p; private string start = String.Empty; private string stop = String.Empty; private bool showHelp; private bool clearConsole; public BotManagerInterpreter(BotManager manager) { this.manager = manager; p = new CommandSet { new BotManagerOption("stop", "stop (X) where X = the username or index of the configured bot", s => stop = s), new BotManagerOption("start", "start (X) where X = the username or index of the configured bot", s => start = s), new BotManagerOption("help", "shows this help text", s => showHelp = s != null), new BotManagerOption("show", "show (x) where x is one of the following: index, \"bots\", or empty", param => ShowCommand(param)), new BotManagerOption("clear", "clears this console", s => clearConsole = s != null), new BotManagerOption("auth", "auth (X)=(Y) where X = the username or index of the configured bot and Y = the steamguard code", AuthSet), new BotManagerOption("exec", "exec (X) (Y) where X = the username or index of the bot and Y = your custom command to execute", ExecCommand), new BotManagerOption("input", "input (X) (Y) where X = the username or index of the bot and Y = your input", InputCommand) }; } void AuthSet(string auth) { string[] xy = auth.Split('='); if (xy.Length == 2) { int index; string code = xy[1].Trim(); if (int.TryParse(xy[0], out index) && (index < manager.ConfigObject.Bots.Length)) { // Console.WriteLine("Authing bot with '" + code + "'"); manager.AuthBot(index, code); } else if (!String.IsNullOrEmpty(xy[0])) { for (index = 0; index < manager.ConfigObject.Bots.Length; index++) { if (manager.ConfigObject.Bots[index].Username.Equals(xy[0], StringComparison.CurrentCultureIgnoreCase)) { // Console.WriteLine("Authing bot with '" + code + "'"); manager.AuthBot(index, code); } } } } } /// <summary> /// This interprets the given command string. /// </summary> /// <param name="command">The entire command string.</param> public void CommandInterpreter(string command) { showHelp = false; start = null; stop = null; p.Parse(command); if (showHelp) { // Console.WriteLine(""); p.WriteOptionDescriptions(Console.Out); } if (!String.IsNullOrEmpty(stop)) { int index; if (int.TryParse(stop, out index) && (index < manager.ConfigObject.Bots.Length)) { manager.StopBot(index); } else { manager.StopBot(stop); } } if (!String.IsNullOrEmpty(start)) { int index; if (int.TryParse(start, out index) && (index < manager.ConfigObject.Bots.Length)) { manager.StartBot(index); } else { manager.StartBot(start); } } if (clearConsole) { clearConsole = false; Console.Clear(); } } private void ShowCommand(string param) { param = param.Trim(); int i; if (int.TryParse(param, out i)) { // spit out the bots config at index. if (manager.ConfigObject.Bots.Length > i) { Console.WriteLine(); Console.WriteLine(manager.ConfigObject.Bots[i].ToString()); } } else if (!String.IsNullOrEmpty(param)) { if (param.Equals("bots")) { // print out the config.Bots array foreach (var b in manager.ConfigObject.Bots) { Console.WriteLine(); Console.WriteLine(b.ToString()); Console.WriteLine(); } } } else { // print out entire config. // the bots array does not get printed. Console.WriteLine(); Console.WriteLine(manager.ConfigObject.ToString()); } } private void ExecCommand(string cmd) { cmd = cmd.Trim(); var cs = cmd.Split(' '); if (cs.Length < 2) { Console.WriteLine("Error: No command given to be executed."); return; } // Take the rest of the input as is var command = cmd.Remove(0, cs[0].Length + 1); int index; // Try index first then search usernames if (int.TryParse(cs[0], out index) && (index < manager.ConfigObject.Bots.Length)) { if (manager.ConfigObject.Bots.Length > index) { manager.SendCommand(index, command); return; } } else if (!String.IsNullOrEmpty(cs[0])) { for (index = 0; index < manager.ConfigObject.Bots.Length; index++) { if (manager.ConfigObject.Bots[index].Username.Equals(cs[0], StringComparison.CurrentCultureIgnoreCase)) { manager.SendCommand(index, command); return; } } } // Print error Console.WriteLine("Error: Bot " + cs[0] + " not found."); } private void InputCommand(string inpt) { inpt = inpt.Trim(); var cs = inpt.Split(' '); if (cs.Length < 2) { Console.WriteLine("Error: No input given."); return; } // Take the rest of the input as is var input = inpt.Remove(0, cs[0].Length + 1); int index; // Try index first then search usernames if (int.TryParse(cs[0], out index) && (index < manager.ConfigObject.Bots.Length)) { if (manager.ConfigObject.Bots.Length > index) { manager.SendInput(index, input); return; } } else if (!String.IsNullOrEmpty(cs[0])) { for (index = 0; index < manager.ConfigObject.Bots.Length; index++) { if (manager.ConfigObject.Bots[index].Username.Equals(cs[0], StringComparison.CurrentCultureIgnoreCase)) { manager.SendInput(index, input); return; } } } // Print error Console.WriteLine("Error: Bot " + cs[0] + " not found."); } #region Nested Options classes // these are very much like the NDesk.Options but without the // maturity, features or need for command seprators like "-" or "/" private class BotManagerOption { public string Name { get; set; } public string Help { get; set; } public Action<string> Func { get; set; } public BotManagerOption(string name, string help, Action<string> func) { Name = name; Help = help; Func = func; } } private class CommandSet : KeyedCollection<string, BotManagerOption> { protected override string GetKeyForItem(BotManagerOption item) { return item.Name; } public void Parse(string commandLine) { var c = commandLine.Trim(); var cs = c.Split(' '); foreach (var option in this) { if (cs[0].Equals(option.Name, StringComparison.CurrentCultureIgnoreCase)) { if (cs.Length > 2) { option.Func(c.Remove(0, cs[0].Length + 1)); } else if (cs.Length > 1) { option.Func(cs[1]); } else { option.Func(String.Empty); } } } } public void WriteOptionDescriptions(TextWriter o) { foreach (BotManagerOption p in this) { o.Write('\t'); o.WriteLine(p.Name + '\t' + p.Help); } } } #endregion Nested Options classes } }
// <copyright file="RetrieveMultiplePlugin.cs" company=""> // Copyright (c) 2014 All Rights Reserved // </copyright> // <author></author> // <date>10/23/2014 7:09:08 PM</date> // <summary>Implements the RetrieveMultiplePlugin Plugin.</summary> // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // </auto-generated> namespace SparkleXrm.Plugins.MetadataWebresourceServer { using System; using System.ServiceModel; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Query; using System.Text.RegularExpressions; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.Xrm.Sdk.Metadata.Query; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Metadata; using System.Runtime.Serialization.Json; using System.IO; using Microsoft.Crm.Sdk.Messages; /// <summary> /// RetrieveMultiplePlugin Plugin. /// </summary> public class MetadataServerPlugin: Plugin { private string _unsecureconfig; private string _secureconfig; /// <summary> /// Initializes a new instance of the <see cref="MetadataServerPlugin"/> class. /// </summary> public MetadataServerPlugin(string unsecure, string secure) : base(typeof(MetadataServerPlugin)) { _unsecureconfig = unsecure; _secureconfig = secure; base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "RetrieveMultiple", "webresource", new Action<LocalPluginContext>(ExecuteRetrieveMultiplePlugin))); // Note : you can register for more events here if this plugin is not specific to an individual entity and message combination. // You may also need to update your RegisterFile.crmregister plug-in registration file to reflect any change. } /// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecuteRetrieveMultiplePlugin(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } try { var service = localContext.OrganizationService; var trace = localContext.TracingService; // Check the depth - we don't want to run on child queries if (localContext.PluginExecutionContext.Depth > 1) return; // Exract the search criteria QueryBase query = (QueryBase)localContext.PluginExecutionContext.InputParameters["Query"]; Type queryType = query.GetType(); if (queryType == typeof(QueryExpression)) { var queryExpression = (QueryExpression)query; var webresourceName = GetMetadataRequestWebresourceName(queryExpression); if (webresourceName==null) return; // Get the requested LCID var lcidString = webresourceName.Substring(webresourceName.Length - 7, 4); int lcid = 0; if (!int.TryParse(lcidString, out lcid)) return; // Is there a webresource with this LCID in the system? var outputCollection = (EntityCollection)localContext.PluginExecutionContext.OutputParameters["BusinessEntityCollection"]; var templateEntity = outputCollection; if (outputCollection.Entities.Count==0) { // No webresource found, so get the template resource file for the base language queryExpression.Criteria.Conditions[0].Values[0] = webresourceName.Replace("_" + lcid.ToString(), "_" + GetDefaultLCID(service).ToString()); templateEntity = service.RetrieveMultiple(query); if (templateEntity.Entities.Count != 1) return; } var templateData = System.Convert.FromBase64String(templateEntity.Entities[0].GetAttributeValue<string>("content")); var templateText = System.Text.Encoding.UTF8.GetString(templateData); var outputText = ParseTemplate(templateText, lcid, service); var scriptBytes = System.Text.Encoding.UTF8.GetBytes(outputText); Entity output = new Entity("webresource"); output["name"] = webresourceName; output["content"] = System.Convert.ToBase64String(scriptBytes); output["webresourcetype"] = new OptionSetValue(3); outputCollection.Entities.Clear(); outputCollection.Entities.Add(output); } } catch (Exception ex) { if (_unsecureconfig == "Debug") { throw new InvalidPluginExecutionException("Could not create metadata webresouces : " + ex.Message, ex); } } } /// <summary> /// Determine if this is a request for a metadata resource. /// </summary> /// <param name="queryExpression"></param> /// <returns>Name of requested webresource or null if not a metadata request</returns> private static string GetMetadataRequestWebresourceName(QueryExpression queryExpression) { // Get condition string webresourceName = null; if (queryExpression.EntityName != "webresource") { return webresourceName; } if (queryExpression.Criteria == null || queryExpression.Criteria.Conditions.Count != 1 || queryExpression.Criteria.Conditions[0].AttributeName != "name") { return webresourceName; } webresourceName = (string)queryExpression.Criteria.Conditions[0].Values[0]; // Is this a request for a metadata server page int length = webresourceName.Length; // Metadata server webresources must have the name 'SomeName.metadata_xxxx.js' where xxxx is in the language LCID var isMetadataRequest = webresourceName.EndsWith(".js") && length > 17 && webresourceName.Substring(length - 17, 10) == ".metadata_"; if (!isMetadataRequest) return null; return webresourceName; } /// <summary> /// Check that the requested LCID is a provisioned language - otherwise return the default LCID /// </summary> /// <param name="service"></param> /// <param name="lcid"></param> /// <returns></returns> private static int CheckLcid(IOrganizationService service, int lcid) { // Find the provisioned languages and check that we are requesting one - otherwise fallback to the default language RetrieveAvailableLanguagesRequest langRequest = new RetrieveAvailableLanguagesRequest(); var langResponse = (RetrieveAvailableLanguagesResponse)service.Execute(langRequest); if (!langResponse.LocaleIds.Contains(lcid)) { lcid = GetDefaultLCID(service); } return lcid; } private static int GetDefaultLCID(IOrganizationService service) { // Get the orgs default language FetchExpression languageQuery = new FetchExpression(@"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"" count=""1"" > <entity name=""organization"" > <attribute name=""languagecode"" /> </entity> </fetch>"); var orgSettings = service.RetrieveMultiple(languageQuery); var lcid = orgSettings.Entities[0].GetAttributeValue<int>("languagecode"); return lcid; } /// <summary> /// Get a list of tokens in the template webresource and set the values based on the LCID /// </summary> /// <param name="template"></param> /// <param name="lcid"></param> /// <param name="service"></param> /// <returns></returns> public string ParseTemplate(string template, int lcid, IOrganizationService service) { lcid = CheckLcid(service, lcid); // Remove the comment start and end tags template = template.Replace("/*metadata", ""); template = template.Replace("metadata*/", ""); Dictionary<string, Dictionary<string, HashSet<string>>> entities; // Get a list of tokens and a consolidated list of metadata that is requested List<MetadataExpression> expressions = ExtractTokens(template, out entities); // Get the metadata var metadataResponse = GetEntityMetadata(service, entities, lcid); // Set the token values in the template based on the requested metadata SetValues(expressions, metadataResponse, service); return CreateOutput(template, expressions); } /// <summary> /// Add the expression values into the template to create the output webresource that will be cached on the client /// </summary> /// <param name="template"></param> /// <param name="expressions"></param> /// <returns></returns> private static string CreateOutput(string template, List<MetadataExpression> expressions) { // Replace the values in the template StringBuilder output = new StringBuilder(); int sourcePosition = 0; foreach (MetadataExpression match in expressions) { output.Append(template.Substring(sourcePosition, match.StartIndex - sourcePosition)); output.Append(match.Value); sourcePosition = match.StartIndex + match.Length; } // Add the final text output.Append(template.Substring(sourcePosition)); StringWriter writer = new StringWriter(); output.Append(writer.ToString()); return output.ToString(); } /// <summary> /// Extract all the tokens in the template that need replacing with actual values /// </summary> /// <param name="template"></param> /// <param name="entities"></param> /// <returns></returns> private static List<MetadataExpression> ExtractTokens(string template, out Dictionary<string, Dictionary<string, HashSet<string>>> entities) { List<MetadataExpression> expressions = new List<MetadataExpression>(); Regex expression = new Regex(@"\<@([\w\.\>\<\/\-\=\""\'\s\{\}]+)@\>"); var matches = expression.Matches(template); foreach (Match match in matches) { // Get a list of entities, attributes and metatadata to retrieve MetadataExpression expr = new MetadataExpression(match.Groups[1].Value, match.Index, match.Length); expressions.Add(expr); } // Analysis of the expressions entities = new Dictionary<string, Dictionary<string, HashSet<string>>>(); foreach (var expr in expressions) { switch (expr.ExpressionType) { case TokenExpressionType.EntityMetadata: if (!entities.ContainsKey(expr.Entity)) { entities.Add(expr.Entity, new Dictionary<string, HashSet<string>>()); } var attributes = entities[expr.Entity]; if (!attributes.ContainsKey(expr.Attribute)) { attributes.Add(expr.Attribute, new HashSet<string>()); } var properties = attributes[expr.Attribute]; if (!properties.Contains(expr.PropertyName)) properties.Add(expr.PropertyName); break; } } return expressions; } /// <summary> /// Evaluate the expressions and set their values based on the metadata response /// </summary> /// <param name="expressions"></param> /// <param name="metadataResponse"></param> /// <param name="service"></param> private static void SetValues(List<MetadataExpression> expressions, RetrieveMetadataChangesResponse metadataResponse, IOrganizationService service) { string formatString = ""; foreach (var expr in expressions) { if (expr.ExpressionType == TokenExpressionType.EntityMetadata) { var entityMetadata = metadataResponse.EntityMetadata.Where(m => m.LogicalName == expr.Entity).FirstOrDefault(); if (entityMetadata == null) continue; string propertyName = expr.PropertyName; try { if (expr.Attribute == MetadataExpression.EntityProperties) { // Get properties from entity object value = entityMetadata.GetType().GetProperty(expr.PropertyName).GetValue(entityMetadata); expr.SerialiseValue(value); } else { // Get property from attribute var attributeMetadata = entityMetadata.Attributes.Where(m => m.LogicalName == expr.Attribute).FirstOrDefault(); object value = attributeMetadata.GetType().GetProperty(expr.PropertyName).GetValue(attributeMetadata); expr.SerialiseValue(value); } if (!string.IsNullOrWhiteSpace(formatString)) expr.Value = String.Format(formatString, expr.Value, expr.Entity, expr.Attribute, expr.PropertyName); } catch (Exception ex) { expr.SerialiseValue(ex.ToString()); } } else if (expr.ExpressionType==TokenExpressionType.Function) { switch (expr.FunctionName.ToLower()) { case "fetch": try { // Execute the fetchxml FetchExpression query = new FetchExpression(expr.Paramaters); var response = service.RetrieveMultiple(query); expr.SerialiseValue(response); } catch (Exception ex) { expr.SerialiseValue(ex.Message); } break; case "format": // Use a format string formatString = expr.Paramaters; break; } } } } private RetrieveMetadataChangesResponse GetEntityMetadata(IOrganizationService service, Dictionary<string, Dictionary<string, HashSet<string>>> entities, int lcid) { MetadataFilterExpression entityFilter = new MetadataFilterExpression(LogicalOperator.Or); MetadataPropertiesExpression entityProperties = new MetadataPropertiesExpression{AllProperties = false}; entityProperties.PropertyNames.Add("Attributes"); // By default query the properties that match the query MetadataFilterExpression attributesFilter = new MetadataFilterExpression(LogicalOperator.Or); MetadataPropertiesExpression attributeProperties = new MetadataPropertiesExpression{AllProperties = false}; LabelQueryExpression labelQuery = new LabelQueryExpression(); labelQuery.MissingLabelBehavior = 1; labelQuery.FilterLanguages.Add(lcid); HashSet<string> attributePropertyNamesAdded = new HashSet<string>(); HashSet<string> entityPropertyNamesAdded = new HashSet<string>(); foreach (var entity in entities.Keys) { entityFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entity)); var attributes = entities[entity]; foreach (var attribute in attributes.Keys) { if (attribute != MetadataExpression.EntityProperties) { // Query attribute properties MetadataFilterExpression attributeFilter = new MetadataFilterExpression(LogicalOperator.And); attributesFilter.Filters.Add(attributeFilter); attributeFilter.Conditions.Add(new MetadataConditionExpression("EntityLogicalName", MetadataConditionOperator.Equals, entity)); attributeFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, attribute)); var properties = attributes[attribute]; foreach (var property in properties) { if (!attributePropertyNamesAdded.Contains(property)) { attributeProperties.PropertyNames.Add(property); attributePropertyNamesAdded.Add(property); } } } else { // Query entity properties var properties = attributes[attribute]; foreach (var property in properties) { if (!entityPropertyNamesAdded.Contains(property)) { entityProperties.PropertyNames.Add(property); entityPropertyNamesAdded.Add(property); } } } } } EntityQueryExpression entityQueryExpression = new EntityQueryExpression() { Criteria = entityFilter, Properties = entityProperties, AttributeQuery = new AttributeQueryExpression() { Criteria = attributesFilter, Properties = attributeProperties }, LabelQuery = labelQuery }; RetrieveMetadataChangesRequest retrieveMetadataChangesRequest = new RetrieveMetadataChangesRequest() { Query = entityQueryExpression }; var response = (RetrieveMetadataChangesResponse)service.Execute(retrieveMetadataChangesRequest); return response; } } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using FlatRedBall; using FlatRedBall.Input; using FlatRedBall.Instructions; using FlatRedBall.AI.Pathfinding; using FlatRedBall.Graphics.Animation; using FlatRedBall.Graphics.Particle; using FlatRedBall.Math.Collision; using FlatRedBall.Math.Geometry; using FlatRedBall.Math.Splines; using Cursor = FlatRedBall.Gui.Cursor; using GuiManager = FlatRedBall.Gui.GuiManager; using FlatRedBall.Localization; using Keys = Microsoft.Xna.Framework.Input.Keys; using Vector3 = Microsoft.Xna.Framework.Vector3; using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D; using GlueTestProject.TestFramework; namespace GlueTestProject.Screens { public partial class CollisionScreen { void CustomInitialize() { MovableRectangle.X = 1; MovableRectangle.CollideAgainstMove(ImmovableRectangle, 0, 1); if(MovableRectangle.X == 1) { throw new Exception("CollideAgainstMove didn't move the movable rectangle"); } if(ImmovableRectangle.X != 0) { throw new Exception("CollideAgainstMove moved an object when colliding against a 0 mass object"); } // try positive infinity: MovableRectangle.X = 1; MovableRectangle.CollideAgainstMove(ImmovableRectangle, 1, float.PositiveInfinity); if (MovableRectangle.X == 1) { throw new Exception("CollideAgainstMove didn't move the movable rectangle"); } if (ImmovableRectangle.X != 0) { throw new Exception("CollideAgainstMove moved an object with positive infinity"); } // Try positive infinity, call with the immovable: MovableRectangle.X = 1; ImmovableRectangle.CollideAgainstMove(MovableRectangle, float.PositiveInfinity, 1); if (MovableRectangle.X == 1) { throw new Exception("CollideAgainstMove didn't move the movable rectangle"); } if (ImmovableRectangle.X != 0) { throw new Exception("CollideAgainstMove moved an object with positive infinity"); } Test_L_RepositonDirection(); CreateCollisionRelationships(); TestEntityListVsShapeCollection(); TestEntityVsShapeCollection(); TestNullSubcollision(); TestCollidedThisFrame(); } private void TestCollidedThisFrame() { var firstEntity = new Entities.CollidableEntity(); var secondEntity = new Entities.CollidableEntity(); var relationship = CollisionManager.Self.CreateRelationship(firstEntity, secondEntity); relationship.CollidedThisFrame.ShouldBe(false); var collided = relationship.DoCollisions(); collided.ShouldBe(true); relationship.CollidedThisFrame.ShouldBe(true); firstEntity.X += 10000; firstEntity.ForceUpdateDependenciesDeep(); collided = relationship.DoCollisions(); collided.ShouldBe(false); relationship.CollidedThisFrame.ShouldBe(false); firstEntity.Destroy(); secondEntity.Destroy(); } private void TestEntityVsShapeCollection() { var singleEntity = new Entities.CollidableEntity(); // for now just testing that the method exists: var relationship = CollisionManager.Self.CreateRelationship(singleEntity, ShapeCollectionInstance); CollisionManager.Self.Relationships.Remove(relationship); singleEntity.Destroy(); } private void TestNullSubcollision() { CollisionEntityList[0].Collision.ShouldNotBe(null); // event collision, both null var relationship = CollisionManager.Self.CreateRelationship(CollisionEntityList, CollisionEntityList); relationship.SetFirstSubCollision(item => item.NullCollidableEntityInstance); relationship.SetSecondSubCollision(item => item.NullCollidableEntityInstance); relationship.CollisionOccurred += (first, second) => { }; relationship.DoCollisions(); // Move collision, both null relationship = CollisionManager.Self.CreateRelationship(CollisionEntityList, CollisionEntityList); relationship.SetFirstSubCollision(item => item.NullCollidableEntityInstance); relationship.SetSecondSubCollision(item => item.NullCollidableEntityInstance); relationship.SetMoveCollision(1, 1); relationship.DoCollisions(); // Bounce collision, both null relationship = CollisionManager.Self.CreateRelationship(CollisionEntityList, CollisionEntityList); relationship.SetFirstSubCollision(item => item.NullCollidableEntityInstance); relationship.SetSecondSubCollision(item => item.NullCollidableEntityInstance); relationship.SetBounceCollision(1, 1, 1); relationship.DoCollisions(); // event collision, second null relationship = CollisionManager.Self.CreateRelationship(CollisionEntityList, CollisionEntityList); relationship.SetSecondSubCollision(item => item.NullCollidableEntityInstance); relationship.CollisionOccurred += (first, second) => { }; relationship.DoCollisions(); // Move collision, second null relationship = CollisionManager.Self.CreateRelationship(CollisionEntityList, CollisionEntityList); relationship.SetSecondSubCollision(item => item.NullCollidableEntityInstance); relationship.SetMoveCollision(1, 1); relationship.DoCollisions(); // Bounce collision, second null relationship = CollisionManager.Self.CreateRelationship(CollisionEntityList, CollisionEntityList); relationship.SetSecondSubCollision(item => item.NullCollidableEntityInstance); relationship.SetBounceCollision(1, 1, 1); relationship.DoCollisions(); } private void CreateCollisionRelationships() { var subcollision = CollisionManager.Self.CreateRelationship(PlayerList, ShipList); var selfCollidingRelationship = CollisionManager.Self.CreateRelationship(SelfCollisionList, SelfCollisionList); selfCollidingRelationship.SetMoveCollision(1, 1); var fullVsEmptyRelationship = CollisionManager.Self.CreateRelationship(PlayerList, EmptyList1); var emptyVsFullRelationship = CollisionManager.Self.CreateRelationship(EmptyList1, PlayerList); var emptyVsEmptyRelationship = CollisionManager.Self.CreateRelationship(EmptyList1, EmptyList2); var emptyVsSameEmptyRelationship = CollisionManager.Self.CreateRelationship(EmptyList1, EmptyList1); } private void TestEntityListVsShapeCollection() { var entityVsShapeCollection = CollisionManager.Self.CreateRelationship(CollidableList, ShapeCollectionInstance); List<Entities.CollidableEntity> collidedEntities = new List<Entities.CollidableEntity>(); entityVsShapeCollection.CollisionOccurred += (entity, shapeCollection) => { collidedEntities.Add(entity); }; entityVsShapeCollection.DoCollisions(); collidedEntities.Contains(At0).ShouldBe(true); collidedEntities.Contains(At100).ShouldBe(true); collidedEntities.Contains(At200).ShouldBe(true); collidedEntities.Contains(At400).ShouldBe(false); } private void Test_L_RepositonDirection() { ShapeCollection rectangles = new ShapeCollection(); // This tests the following bug: // https://trello.com/c/twwOTKFz/411-l-shaped-corners-can-cause-entities-to-teleport-through-despite-using-proper-reposition-directions // make corner first so it is tested first var corner = new AxisAlignedRectangle(); corner.X = 0; corner.Y = 0; corner.Width = 32; corner.Height = 32; corner.RepositionDirections = RepositionDirections.Left | RepositionDirections.Down; rectangles.AxisAlignedRectangles.Add(corner); var top = new AxisAlignedRectangle(); top.X = 0; top.Y = 32; top.Width = 32; top.Height = 32; top.RepositionDirections = RepositionDirections.Left | RepositionDirections.Right; rectangles.AxisAlignedRectangles.Add(top); var right = new AxisAlignedRectangle(); right.X = 32; right.Y = 0; right.Width = 32; right.Height = 32; right.RepositionDirections = RepositionDirections.Up | RepositionDirections.Down; rectangles.AxisAlignedRectangles.Add(right); var movable = new AxisAlignedRectangle(); movable.X = 32 - 1; movable.Y = 32 - 1; movable.Width = 32; movable.Height = 32; movable.CollideAgainstMove(rectangles, 0, 1); movable.X.ShouldBeGreaterThan(31); movable.Y.ShouldBeGreaterThan(31); } void CustomActivity(bool firstTimeCalled) { var shouldContinue = this.ActivityCallCount > 5; // give the screen a chance to call if(!firstTimeCalled) { var areAllDifferent = C1.X != C2.X && C2.X != C3.X && C3.X != C4.X; areAllDifferent.ShouldBe(true, "because all items in this list should self move collide"); } if (shouldContinue) { IsActivityFinished = true; } } void CustomDestroy() { CollisionManager.Self.Relationships.Count.ShouldBe(0); } static void CustomLoadStaticContent(string contentManagerName) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; namespace System { // Represents a Globally Unique Identifier. [StructLayout(LayoutKind.Sequential)] public partial struct Guid : IFormattable, IComparable, IComparable<Guid>, IEquatable<Guid> { public static readonly Guid Empty = new Guid(); //////////////////////////////////////////////////////////////////////////////// // Member variables //////////////////////////////////////////////////////////////////////////////// private int _a; private short _b; private short _c; private byte _d; private byte _e; private byte _f; private byte _g; private byte _h; private byte _i; private byte _j; private byte _k; //////////////////////////////////////////////////////////////////////////////// // Constructors //////////////////////////////////////////////////////////////////////////////// // Creates a new guid from an array of bytes. // public Guid(byte[] b) { if (b == null) throw new ArgumentNullException(nameof(b)); if (b.Length != 16) throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "16"), nameof(b)); Contract.EndContractBlock(); _a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0]; _b = (short)(((int)b[5] << 8) | b[4]); _c = (short)(((int)b[7] << 8) | b[6]); _d = b[8]; _e = b[9]; _f = b[10]; _g = b[11]; _h = b[12]; _i = b[13]; _j = b[14]; _k = b[15]; } [CLSCompliant(false)] public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = (int)a; _b = (short)b; _c = (short)c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } // Creates a new GUID initialized to the value represented by the arguments. // public Guid(int a, short b, short c, byte[] d) { if (d == null) throw new ArgumentNullException(nameof(d)); // Check that array is not too big if (d.Length != 8) throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), nameof(d)); Contract.EndContractBlock(); _a = a; _b = b; _c = c; _d = d[0]; _e = d[1]; _f = d[2]; _g = d[3]; _h = d[4]; _i = d[5]; _j = d[6]; _k = d[7]; } // Creates a new GUID initialized to the value represented by the // arguments. The bytes are specified like this to avoid endianness issues. // public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = a; _b = b; _c = c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } [Flags] private enum GuidStyles { None = 0x00000000, AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces AllowDashes = 0x00000004, //Allow the guid to contain dash group separators AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd} RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens RequireBraces = 0x00000020, //Require the guid to be enclosed in braces RequireDashes = 0x00000040, //Require the guid to contain dash group separators RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd} HexFormat = RequireBraces | RequireHexPrefix, /* X */ NumberFormat = None, /* N */ DigitFormat = RequireDashes, /* D */ BraceFormat = RequireBraces | RequireDashes, /* B */ ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */ Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix, } private enum GuidParseThrowStyle { None = 0, All = 1, AllButOverflow = 2 } private enum ParseFailureKind { None = 0, ArgumentNull = 1, Format = 2, FormatWithParameter = 3, NativeException = 4, FormatWithInnerException = 5 } // This will store the result of the parsing. And it will eventually be used to construct a Guid instance. private struct GuidResult { internal Guid parsedGuid; internal GuidParseThrowStyle throwStyle; internal ParseFailureKind m_failure; internal string m_resourceMessageFormat; internal object m_failureMessageFormatArgument; internal string m_failureArgumentName; internal Exception m_innerException; internal void Init(GuidParseThrowStyle canThrow) { parsedGuid = Guid.Empty; throwStyle = canThrow; } internal void SetFailure(Exception nativeException) { m_failure = ParseFailureKind.NativeException; m_innerException = nativeException; } internal void SetFailure(ParseFailureKind failure, string failureMessageID) { SetFailure(failure, failureMessageID, null, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null); } internal void SetFailure(ParseFailureKind failure, string failureMessageFormat, object failureMessageFormatArgument, string failureArgumentName, Exception innerException) { Debug.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload"); m_failure = failure; m_resourceMessageFormat = failureMessageFormat; m_failureMessageFormatArgument = failureMessageFormatArgument; m_failureArgumentName = failureArgumentName; m_innerException = innerException; if (throwStyle != GuidParseThrowStyle.None) { throw GetGuidParseException(); } } internal Exception GetGuidParseException() { switch (m_failure) { case ParseFailureKind.ArgumentNull: return new ArgumentNullException(m_failureArgumentName, m_resourceMessageFormat); case ParseFailureKind.FormatWithInnerException: return new FormatException(m_resourceMessageFormat, m_innerException); case ParseFailureKind.FormatWithParameter: return new FormatException(SR.Format(m_resourceMessageFormat, m_failureMessageFormatArgument)); case ParseFailureKind.Format: return new FormatException(m_resourceMessageFormat); case ParseFailureKind.NativeException: return m_innerException; default: Debug.Assert(false, "Unknown GuidParseFailure: " + m_failure); return new FormatException(SR.Format_GuidUnrecognized); } } } // Creates a new guid based on the value in the string. The value is made up // of hex digits speared by the dash ("-"). The string may begin and end with // brackets ("{", "}"). // // The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where // d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4, // then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223" // public Guid(String g) { if (g == null) { throw new ArgumentNullException(nameof(g)); } Contract.EndContractBlock(); this = Guid.Empty; GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.All); if (TryParseGuid(g, GuidStyles.Any, ref result)) { this = result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static Guid Parse(String input) { if (input == null) { throw new ArgumentNullException(nameof(input)); } Contract.EndContractBlock(); GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, GuidStyles.Any, ref result)) { return result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParse(String input, out Guid result) { GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, GuidStyles.Any, ref parseResult)) { result = parseResult.parsedGuid; return true; } else { result = Guid.Empty; return false; } } public static Guid ParseExact(String input, String format) { if (input == null) throw new ArgumentNullException(nameof(input)); if (format == null) throw new ArgumentNullException(nameof(format)); if (format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } GuidStyles style; char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { style = GuidStyles.DigitFormat; } else if (formatCh == 'N' || formatCh == 'n') { style = GuidStyles.NumberFormat; } else if (formatCh == 'B' || formatCh == 'b') { style = GuidStyles.BraceFormat; } else if (formatCh == 'P' || formatCh == 'p') { style = GuidStyles.ParenthesisFormat; } else if (formatCh == 'X' || formatCh == 'x') { style = GuidStyles.HexFormat; } else { throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } GuidResult result = new GuidResult(); result.Init(GuidParseThrowStyle.AllButOverflow); if (TryParseGuid(input, style, ref result)) { return result.parsedGuid; } else { throw result.GetGuidParseException(); } } public static bool TryParseExact(String input, String format, out Guid result) { if (format == null || format.Length != 1) { result = Guid.Empty; return false; } GuidStyles style; char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { style = GuidStyles.DigitFormat; } else if (formatCh == 'N' || formatCh == 'n') { style = GuidStyles.NumberFormat; } else if (formatCh == 'B' || formatCh == 'b') { style = GuidStyles.BraceFormat; } else if (formatCh == 'P' || formatCh == 'p') { style = GuidStyles.ParenthesisFormat; } else if (formatCh == 'X' || formatCh == 'x') { style = GuidStyles.HexFormat; } else { // invalid guid format specification result = Guid.Empty; return false; } GuidResult parseResult = new GuidResult(); parseResult.Init(GuidParseThrowStyle.None); if (TryParseGuid(input, style, ref parseResult)) { result = parseResult.parsedGuid; return true; } else { result = Guid.Empty; return false; } } private static bool TryParseGuid(String g, GuidStyles flags, ref GuidResult result) { if (g == null) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized); return false; } String guidString = g.Trim(); //Remove Whitespace if (guidString.Length == 0) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized); return false; } // Check for dashes bool dashesExistInString = (guidString.IndexOf('-', 0) >= 0); if (dashesExistInString) { if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0) { // dashes are not allowed result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized); return false; } } else { if ((flags & GuidStyles.RequireDashes) != 0) { // dashes are required result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized); return false; } } // Check for braces bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0); if (bracesExistInString) { if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0) { // braces are not allowed result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized); return false; } } else { if ((flags & GuidStyles.RequireBraces) != 0) { // braces are required result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized); return false; } } // Check for parenthesis bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0); if (parenthesisExistInString) { if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0) { // parenthesis are not allowed result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized); return false; } } else { if ((flags & GuidStyles.RequireParenthesis) != 0) { // parenthesis are required result.SetFailure(ParseFailureKind.Format, SR.Format_GuidUnrecognized); return false; } } try { // let's get on with the parsing if (dashesExistInString) { // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] return TryParseGuidWithDashes(guidString, ref result); } else if (bracesExistInString) { // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} return TryParseGuidWithHexPrefix(guidString, ref result); } else { // Check if it's of the form dddddddddddddddddddddddddddddddd return TryParseGuidWithNoStyle(guidString, ref result); } } catch (IndexOutOfRangeException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, SR.Format_GuidUnrecognized, null, null, ex); return false; } catch (ArgumentException ex) { result.SetFailure(ParseFailureKind.FormatWithInnerException, SR.Format_GuidUnrecognized, null, null, ex); return false; } } // Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} private static bool TryParseGuidWithHexPrefix(String guidString, ref GuidResult result) { int numStart = 0; int numLen = 0; // Eat all of the whitespace guidString = EatAllWhitespace(guidString); // Check for leading '{' if (String.IsNullOrEmpty(guidString) || guidString[0] != '{') { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidBrace); return false; } // Check for '0x' if (!IsHexPrefix(guidString, 1)) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidHexPrefix, "{0xdddddddd, etc}"); return false; } // Find the end of this hex number (since it is not fixed length) numStart = 3; numLen = guidString.IndexOf(',', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidComma); return false; } if (!StringToInt(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result)) return false; // Check for '0x' if (!IsHexPrefix(guidString, numStart + numLen + 1)) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidHexPrefix, "{0xdddddddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidComma); return false; } // Read in the number if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result)) return false; // Check for '0x' if (!IsHexPrefix(guidString, numStart + numLen + 1)) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidHexPrefix, "{0xdddddddd, 0xdddd, 0xdddd, etc}"); return false; } // +3 to get by ',0x' numStart = numStart + numLen + 3; numLen = guidString.IndexOf(',', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidComma); return false; } // Read in the number if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result)) return false; // Check for '{' if (guidString.Length <= numStart + numLen + 1 || guidString[numStart + numLen + 1] != '{') { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidBrace); return false; } // Prepare for loop numLen++; byte[] bytes = new byte[8]; for (int i = 0; i < 8; i++) { // Check for '0x' if (!IsHexPrefix(guidString, numStart + numLen + 1)) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidHexPrefix, "{... { ... 0xdd, ...}}"); return false; } // +3 to get by ',0x' or '{0x' for first case numStart = numStart + numLen + 3; // Calculate number length if (i < 7) // first 7 cases { numLen = guidString.IndexOf(',', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidComma); return false; } } else // last case ends with '}', not ',' { numLen = guidString.IndexOf('}', numStart) - numStart; if (numLen <= 0) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidBraceAfterLastNumber); return false; } } // Read in the number uint number = (uint)ParseNumbers.StringToInt(guidString.Substring(numStart, numLen), 16, ParseNumbers.IsTight); // check for overflow if (number > 255) { result.SetFailure(ParseFailureKind.Format, SR.Overflow_Byte); return false; } bytes[i] = (byte)number; } result.parsedGuid._d = bytes[0]; result.parsedGuid._e = bytes[1]; result.parsedGuid._f = bytes[2]; result.parsedGuid._g = bytes[3]; result.parsedGuid._h = bytes[4]; result.parsedGuid._i = bytes[5]; result.parsedGuid._j = bytes[6]; result.parsedGuid._k = bytes[7]; // Check for last '}' if (numStart + numLen + 1 >= guidString.Length || guidString[numStart + numLen + 1] != '}') { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidEndBrace); return false; } // Check if we have extra characters at the end if (numStart + numLen + 1 != guidString.Length - 1) { result.SetFailure(ParseFailureKind.Format, SR.Format_ExtraJunkAtEnd); return false; } return true; } // Check if it's of the form dddddddddddddddddddddddddddddddd private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result) { int startPos = 0; int temp; long templ; int currentPos = 0; if (guidString.Length != 32) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvLen); return false; } for (int i = 0; i < guidString.Length; i++) { char ch = guidString[i]; if (ch >= '0' && ch <= '9') { continue; } else { char upperCaseCh = Char.ToUpperInvariant(ch); if (upperCaseCh >= 'A' && upperCaseCh <= 'F') { continue; } } result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvalidChar); return false; } if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result)) return false; startPos += 8; if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result)) return false; startPos += 4; if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result)) return false; startPos += 4; if (!StringToInt(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out temp, ref result)) return false; startPos += 4; currentPos = startPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos != 12) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvLen); return false; } result.parsedGuid._d = (byte)(temp >> 8); result.parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result.parsedGuid._f = (byte)(temp >> 8); result.parsedGuid._g = (byte)(temp); temp = (int)(templ); result.parsedGuid._h = (byte)(temp >> 24); result.parsedGuid._i = (byte)(temp >> 16); result.parsedGuid._j = (byte)(temp >> 8); result.parsedGuid._k = (byte)(temp); return true; } // Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)] private static bool TryParseGuidWithDashes(String guidString, ref GuidResult result) { int startPos = 0; int temp; long templ; int currentPos = 0; // check to see that it's the proper length if (guidString[0] == '{') { if (guidString.Length != 38 || guidString[37] != '}') { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvLen); return false; } startPos = 1; } else if (guidString[0] == '(') { if (guidString.Length != 38 || guidString[37] != ')') { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvLen); return false; } startPos = 1; } else if (guidString.Length != 36) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvLen); return false; } if (guidString[8 + startPos] != '-' || guidString[13 + startPos] != '-' || guidString[18 + startPos] != '-' || guidString[23 + startPos] != '-') { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidDashes); return false; } currentPos = startPos; if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._a = temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._b = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; result.parsedGuid._c = (short)temp; ++currentPos; //Increment past the '-'; if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result)) return false; ++currentPos; //Increment past the '-'; startPos = currentPos; if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result)) return false; if (currentPos - startPos != 12) { result.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvLen); return false; } result.parsedGuid._d = (byte)(temp >> 8); result.parsedGuid._e = (byte)(temp); temp = (int)(templ >> 32); result.parsedGuid._f = (byte)(temp >> 8); result.parsedGuid._g = (byte)(temp); temp = (int)(templ); result.parsedGuid._h = (byte)(temp >> 24); result.parsedGuid._i = (byte)(temp >> 16); result.parsedGuid._j = (byte)(temp >> 8); result.parsedGuid._k = (byte)(temp); return true; } // // StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines; // private static bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult) { int parsePos = 0; return StringToShort(str, ref parsePos, requiredLength, flags, out result, ref parseResult); } private static bool StringToShort(String str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) { result = 0; int x; bool retValue = StringToInt(str, ref parsePos, requiredLength, flags, out x, ref parseResult); result = (short)x; return retValue; } private static bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult) { int parsePos = 0; return StringToInt(str, ref parsePos, requiredLength, flags, out result, ref parseResult); } private static bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) { result = 0; int currStart = parsePos; try { result = ParseNumbers.StringToInt(str, 16, flags, ref parsePos); } catch (OverflowException ex) { if (parseResult.throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(SR.Format_GuidUnrecognized, ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult.throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } //If we didn't parse enough characters, there's clearly an error. if (requiredLength != -1 && parsePos - currStart != requiredLength) { parseResult.SetFailure(ParseFailureKind.Format, SR.Format_GuidInvalidChar); return false; } return true; } private static bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult) { result = 0; try { result = ParseNumbers.StringToLong(str, 16, flags, ref parsePos); } catch (OverflowException ex) { if (parseResult.throwStyle == GuidParseThrowStyle.All) { throw; } else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) { throw new FormatException(SR.Format_GuidUnrecognized, ex); } else { parseResult.SetFailure(ex); return false; } } catch (Exception ex) { if (parseResult.throwStyle == GuidParseThrowStyle.None) { parseResult.SetFailure(ex); return false; } else { throw; } } return true; } private static String EatAllWhitespace(String str) { int newLength = 0; char[] chArr = new char[str.Length]; char curChar; // Now get each char from str and if it is not whitespace add it to chArr for (int i = 0; i < str.Length; i++) { curChar = str[i]; if (!Char.IsWhiteSpace(curChar)) { chArr[newLength++] = curChar; } } // Return a new string based on chArr return new String(chArr, 0, newLength); } private static bool IsHexPrefix(String str, int i) { if (str.Length > i + 1 && str[i] == '0' && (Char.ToLowerInvariant(str[i + 1]) == 'x')) return true; else return false; } // Returns an unsigned byte array containing the GUID. public byte[] ToByteArray() { byte[] g = new byte[16]; g[0] = (byte)(_a); g[1] = (byte)(_a >> 8); g[2] = (byte)(_a >> 16); g[3] = (byte)(_a >> 24); g[4] = (byte)(_b); g[5] = (byte)(_b >> 8); g[6] = (byte)(_c); g[7] = (byte)(_c >> 8); g[8] = _d; g[9] = _e; g[10] = _f; g[11] = _g; g[12] = _h; g[13] = _i; g[14] = _j; g[15] = _k; return g; } // Returns the guid in "registry" format. public override String ToString() { return ToString("D", null); } public unsafe override int GetHashCode() { // Simply XOR all the bits of the GUID 32 bits at a time. fixed (int* ptr = &_a) return ptr[0] ^ ptr[1] ^ ptr[2] ^ ptr[3]; } // Returns true if and only if the guid represented // by o is the same as this instance. public override bool Equals(Object o) { Guid g; // Check that o is a Guid first if (o == null || !(o is Guid)) return false; else g = (Guid)o; // Now compare each of the elements if (g._a != _a) return false; if (g._b != _b) return false; if (g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } public bool Equals(Guid g) { // Now compare each of the elements if (g._a != _a) return false; if (g._b != _b) return false; if (g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } internal bool Equals(ref Guid g) { // Now compare each of the elements if (g._a != _a) return false; if (g._b != _b) return false; if (g._c != _c) return false; if (g._d != _d) return false; if (g._e != _e) return false; if (g._f != _f) return false; if (g._g != _g) return false; if (g._h != _h) return false; if (g._i != _i) return false; if (g._j != _j) return false; if (g._k != _k) return false; return true; } private int GetResult(uint me, uint them) { if (me < them) { return -1; } return 1; } public int CompareTo(Object value) { if (value == null) { return 1; } if (!(value is Guid)) { throw new ArgumentException(SR.Arg_MustBeGuid, nameof(value)); } Guid g = (Guid)value; if (g._a != _a) { return GetResult((uint)_a, (uint)g._a); } if (g._b != _b) { return GetResult((uint)_b, (uint)g._b); } if (g._c != _c) { return GetResult((uint)_c, (uint)g._c); } if (g._d != _d) { return GetResult((uint)_d, (uint)g._d); } if (g._e != _e) { return GetResult((uint)_e, (uint)g._e); } if (g._f != _f) { return GetResult((uint)_f, (uint)g._f); } if (g._g != _g) { return GetResult((uint)_g, (uint)g._g); } if (g._h != _h) { return GetResult((uint)_h, (uint)g._h); } if (g._i != _i) { return GetResult((uint)_i, (uint)g._i); } if (g._j != _j) { return GetResult((uint)_j, (uint)g._j); } if (g._k != _k) { return GetResult((uint)_k, (uint)g._k); } return 0; } public int CompareTo(Guid value) { if (value._a != _a) { return GetResult((uint)_a, (uint)value._a); } if (value._b != _b) { return GetResult((uint)_b, (uint)value._b); } if (value._c != _c) { return GetResult((uint)_c, (uint)value._c); } if (value._d != _d) { return GetResult((uint)_d, (uint)value._d); } if (value._e != _e) { return GetResult((uint)_e, (uint)value._e); } if (value._f != _f) { return GetResult((uint)_f, (uint)value._f); } if (value._g != _g) { return GetResult((uint)_g, (uint)value._g); } if (value._h != _h) { return GetResult((uint)_h, (uint)value._h); } if (value._i != _i) { return GetResult((uint)_i, (uint)value._i); } if (value._j != _j) { return GetResult((uint)_j, (uint)value._j); } if (value._k != _k) { return GetResult((uint)_k, (uint)value._k); } return 0; } public static bool operator ==(Guid a, Guid b) { // Now compare each of the elements if (a._a != b._a) return false; if (a._b != b._b) return false; if (a._c != b._c) return false; if (a._d != b._d) return false; if (a._e != b._e) return false; if (a._f != b._f) return false; if (a._g != b._g) return false; if (a._h != b._h) return false; if (a._i != b._i) return false; if (a._j != b._j) return false; if (a._k != b._k) return false; return true; } public static bool operator !=(Guid a, Guid b) { return !(a == b); } public String ToString(String format) { return ToString(format, null); } private static char HexToChar(int a) { a = a & 0xf; return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30); } unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b) { return HexsToChars(guidChars, offset, a, b, false); } unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex) { if (hex) { guidChars[offset++] = '0'; guidChars[offset++] = 'x'; } guidChars[offset++] = HexToChar(a >> 4); guidChars[offset++] = HexToChar(a); if (hex) { guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; } guidChars[offset++] = HexToChar(b >> 4); guidChars[offset++] = HexToChar(b); return offset; } // IFormattable interface // We currently ignore provider public String ToString(String format, IFormatProvider provider) { if (format == null || format.Length == 0) format = "D"; string guidString; int offset = 0; bool dash = true; bool hex = false; if (format.Length != 1) { // all acceptable format strings are of length 1 throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { guidString = string.FastAllocateString(36); } else if (formatCh == 'N' || formatCh == 'n') { guidString = string.FastAllocateString(32); dash = false; } else if (formatCh == 'B' || formatCh == 'b') { guidString = string.FastAllocateString(38); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '{'; guidChars[37] = '}'; } } } else if (formatCh == 'P' || formatCh == 'p') { guidString = string.FastAllocateString(38); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '('; guidChars[37] = ')'; } } } else if (formatCh == 'X' || formatCh == 'x') { guidString = string.FastAllocateString(68); unsafe { fixed (char* guidChars = guidString) { guidChars[offset++] = '{'; guidChars[67] = '}'; } } dash = false; hex = true; } else { throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } unsafe { fixed (char* guidChars = guidString) { if (hex) { // {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}} guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16); offset = HexsToChars(guidChars, offset, _a >> 8, _a); guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _b >> 8, _b); guidChars[offset++] = ','; guidChars[offset++] = '0'; guidChars[offset++] = 'x'; offset = HexsToChars(guidChars, offset, _c >> 8, _c); guidChars[offset++] = ','; guidChars[offset++] = '{'; offset = HexsToChars(guidChars, offset, _d, _e, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _f, _g, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _h, _i, true); guidChars[offset++] = ','; offset = HexsToChars(guidChars, offset, _j, _k, true); guidChars[offset++] = '}'; } else { // [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)] offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16); offset = HexsToChars(guidChars, offset, _a >> 8, _a); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _b >> 8, _b); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _c >> 8, _c); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _d, _e); if (dash) guidChars[offset++] = '-'; offset = HexsToChars(guidChars, offset, _f, _g); offset = HexsToChars(guidChars, offset, _h, _i); offset = HexsToChars(guidChars, offset, _j, _k); } } } return guidString; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Codecs.Redis { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Text; using DotNetty.Buffers; using DotNetty.Codecs.Redis.Messages; using DotNetty.Common.Utilities; using DotNetty.Transport.Channels; public sealed class RedisDecoder : ByteToMessageDecoder { readonly IRedisMessagePool messagePool; readonly int maximumInlineMessageLength; readonly ToPositiveLongProcessor toPositiveLongProcessor = new ToPositiveLongProcessor(); enum State { DecodeType, DecodeInline, // SIMPLE_STRING, ERROR, INTEGER DecodeLength, // BULK_STRING, ARRAY_HEADER DecodeBulkStringEndOfLine, DecodeBulkStringContent, } // current decoding states State state = State.DecodeType; RedisMessageType messageType; int remainingBulkLength; public RedisDecoder() : this(RedisConstants.MaximumInlineMessageLength, FixedRedisMessagePool.Default) { } public RedisDecoder(int maximumInlineMessageLength, IRedisMessagePool messagePool) { Contract.Requires(maximumInlineMessageLength > 0 && maximumInlineMessageLength <= RedisConstants.MaximumMessageLength); Contract.Requires(messagePool != null); this.maximumInlineMessageLength = maximumInlineMessageLength; this.messagePool = messagePool; } protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output) { Contract.Requires(context != null); Contract.Requires(input != null); Contract.Requires(output != null); try { while (true) { switch (this.state) { case State.DecodeType: if (!this.DecodeType(input)) { return; } break; case State.DecodeInline: if (!this.DecodeInline(input, output)) { return; } break; case State.DecodeLength: if (!this.DecodeLength(input, output)) { return; } break; case State.DecodeBulkStringEndOfLine: if (!this.DecodeBulkStringEndOfLine(input, output)) { return; } break; case State.DecodeBulkStringContent: if (!this.DecodeBulkStringContent(input, output)) { return; } break; default: throw new RedisCodecException($"Unknown state: {this.state}"); } } } catch (RedisCodecException) { this.ResetDecoder(); throw; } catch (Exception exception) { this.ResetDecoder(); throw new RedisCodecException(exception); } } IRedisMessage ReadInlineMessage(RedisMessageType redisMessageType, IByteBuffer byteBuffer) { Contract.Requires(byteBuffer != null); switch (redisMessageType) { case RedisMessageType.SimpleString: return this.GetSimpleStringMessage(byteBuffer); case RedisMessageType.Error: return this.GetErrorMessage(byteBuffer); case RedisMessageType.Integer: return this.GetIntegerMessage(byteBuffer); default: throw new RedisCodecException( $"Message type {redisMessageType} must be inline messageType of SimpleString, Error or Integer"); } } SimpleStringRedisMessage GetSimpleStringMessage(IByteBuffer byteBuffer) { Contract.Requires(byteBuffer != null); SimpleStringRedisMessage message; if (!this.messagePool.TryGetMessage(byteBuffer, out message)) { message = new SimpleStringRedisMessage(byteBuffer.ToString(Encoding.UTF8)); } return message; } ErrorRedisMessage GetErrorMessage(IByteBuffer byteBuffer) { Contract.Requires(byteBuffer != null); ErrorRedisMessage message; if (!this.messagePool.TryGetMessage(byteBuffer, out message)) { message = new ErrorRedisMessage(byteBuffer.ToString(Encoding.UTF8)); } return message; } IntegerRedisMessage GetIntegerMessage(IByteBuffer byteBuffer) { IntegerRedisMessage message; if (!this.messagePool.TryGetMessage(byteBuffer, out message)) { message = new IntegerRedisMessage(this.ParseNumber(byteBuffer)); } return message; } bool DecodeType(IByteBuffer byteBuffer) { Contract.Requires(byteBuffer != null); if (!byteBuffer.IsReadable()) { return false; } RedisMessageType redisMessageType = RedisCodecUtil.ParseMessageType(byteBuffer.ReadByte()); this.state = IsInline(redisMessageType) ? State.DecodeInline : State.DecodeLength; this.messageType = redisMessageType; return true; } static bool IsInline(RedisMessageType messageType) => messageType == RedisMessageType.SimpleString || messageType == RedisMessageType.Error || messageType == RedisMessageType.Integer; bool DecodeInline(IByteBuffer byteBuffer, ICollection<object> output) { Contract.Requires(byteBuffer != null); Contract.Requires(output != null); IByteBuffer buffer = ReadLine(byteBuffer); if (buffer == null) { if (byteBuffer.ReadableBytes > this.maximumInlineMessageLength) { throw new RedisCodecException( $"Length: {byteBuffer.ReadableBytes} (expected: <= {this.maximumInlineMessageLength})"); } return false; } IRedisMessage message = this.ReadInlineMessage(this.messageType, buffer); output.Add(message); this.ResetDecoder(); return true; } bool DecodeLength(IByteBuffer byteBuffer, ICollection<object> output) { Contract.Requires(byteBuffer != null); Contract.Requires(output != null); IByteBuffer lineByteBuffer = ReadLine(byteBuffer); if (lineByteBuffer == null) { return false; } long length = this.ParseNumber(lineByteBuffer); if (length < RedisConstants.NullValue) { throw new RedisCodecException( $"Length: {length} (expected: >= {RedisConstants.NullValue})"); } switch (this.messageType) { case RedisMessageType.ArrayHeader: output.Add(new ArrayHeaderRedisMessage(length)); this.ResetDecoder(); return true; case RedisMessageType.BulkString: if (length > RedisConstants.MaximumMessageLength) { throw new RedisCodecException( $"Length: {length} (expected: <= {RedisConstants.MaximumMessageLength})"); } this.remainingBulkLength = (int)length; // range(int) is already checked. return this.DecodeBulkString(byteBuffer, output); default: throw new RedisCodecException( $"Bad messageType: {this.messageType}, expecting ArrayHeader or BulkString."); } } bool DecodeBulkString(IByteBuffer byteBuffer, ICollection<object> output) { Contract.Requires(byteBuffer != null); Contract.Requires(output != null); if (this.remainingBulkLength == RedisConstants.NullValue) // $-1\r\n { output.Add(FullBulkStringRedisMessage.Null); this.ResetDecoder(); return true; } if (this.remainingBulkLength == 0) { this.state = State.DecodeBulkStringEndOfLine; return this.DecodeBulkStringEndOfLine(byteBuffer, output); } // expectedBulkLength is always positive. output.Add(new BulkStringHeaderRedisMessage(this.remainingBulkLength)); this.state = State.DecodeBulkStringContent; return this.DecodeBulkStringContent(byteBuffer, output); } bool DecodeBulkStringContent(IByteBuffer byteBuffer, ICollection<object> output) { Contract.Requires(byteBuffer != null); Contract.Requires(output != null); int readableBytes = byteBuffer.ReadableBytes; if (readableBytes == 0) { return false; } // if this is last frame. if (readableBytes >= this.remainingBulkLength + RedisConstants.EndOfLineLength) { IByteBuffer content = byteBuffer.ReadSlice(this.remainingBulkLength); ReadEndOfLine(byteBuffer); // Only call retain after readEndOfLine(...) as the method may throw an exception. output.Add(new LastBulkStringRedisContent((IByteBuffer)content.Retain())); this.ResetDecoder(); return true; } // chunked write. int toRead = Math.Min(this.remainingBulkLength, readableBytes); this.remainingBulkLength -= toRead; IByteBuffer buffer = byteBuffer.ReadSlice(toRead); output.Add(new BulkStringRedisContent((IByteBuffer)buffer.Retain())); return true; } // $0\r\n <here> \r\n bool DecodeBulkStringEndOfLine(IByteBuffer byteBuffer, ICollection<object> output) { Contract.Requires(byteBuffer != null); Contract.Requires(output != null); if (byteBuffer.ReadableBytes < RedisConstants.EndOfLineLength) { return false; } ReadEndOfLine(byteBuffer); output.Add(FullBulkStringRedisMessage.Empty); this.ResetDecoder(); return true; } static IByteBuffer ReadLine(IByteBuffer byteBuffer) { Contract.Requires(byteBuffer != null); if (!byteBuffer.IsReadable(RedisConstants.EndOfLineLength)) { return null; } int lfIndex = byteBuffer.ForEachByte(ByteProcessor.FIND_LF); if (lfIndex < 0) { return null; } IByteBuffer buffer = byteBuffer.ReadSlice(lfIndex - byteBuffer.ReaderIndex - 1); ReadEndOfLine(byteBuffer); return buffer; } static void ReadEndOfLine(IByteBuffer byteBuffer) { Contract.Requires(byteBuffer != null); short delim = byteBuffer.ReadShort(); if (RedisConstants.EndOfLine == delim) { return; } byte[] bytes = RedisCodecUtil.GetBytes(delim); throw new RedisCodecException($"delimiter: [{bytes[0]},{bytes[1]}] (expected: \\r\\n)"); } void ResetDecoder() { this.state = State.DecodeType; this.remainingBulkLength = 0; } long ParseNumber(IByteBuffer byteBuffer) { int readableBytes = byteBuffer.ReadableBytes; bool negative = readableBytes > 0 && byteBuffer.GetByte(byteBuffer.ReaderIndex) == '-'; int extraOneByteForNegative = negative ? 1 : 0; if (readableBytes <= extraOneByteForNegative) { throw new RedisCodecException( $"No number to parse: {byteBuffer.ToString(Encoding.ASCII)}"); } if (readableBytes > RedisConstants.PositiveLongValueMaximumLength + extraOneByteForNegative) { throw new RedisCodecException( $"Too many characters to be a valid RESP Integer: {byteBuffer.ToString(Encoding.ASCII)}"); } if (negative) { return -this.ParsePositiveNumber(byteBuffer.SkipBytes(extraOneByteForNegative)); } return this.ParsePositiveNumber(byteBuffer); } long ParsePositiveNumber(IByteBuffer byteBuffer) { this.toPositiveLongProcessor.Reset(); byteBuffer.ForEachByte(this.toPositiveLongProcessor); return this.toPositiveLongProcessor.Content; } class ToPositiveLongProcessor : ByteProcessor { public override bool Process(byte value) { if (!char.IsDigit((char)value)) { throw new RedisCodecException($"Bad byte in number: {value}, expecting digits from 0 to 9"); } this.Content = this.Content * 10 + (value - '0'); return true; } public long Content { get; private set; } public void Reset() => this.Content = 0; } } }
using System; using NUnit.Framework; using StructureMap.Testing.Widget; namespace StructureMap.Testing.Pipeline { [TestFixture] public class OptionalSetterInjectionTester { [Test] public void AutoFill_a_property() { var container = new Container(r => { r.ForConcreteType<ClassWithDependency>().Configure .Setter<Rule>().IsTheDefault(); r.For<Rule>().Use(new ColorRule("Green")); }); container.GetInstance<ClassWithDependency>().Rule.ShouldBeOfType(typeof (ColorRule)); } [Test] public void one_optional_child_array_setter() { var container = new Container(x => { x.For<ClassWithDependency>().Use<ClassWithDependency>() .EnumerableOf<Rule>().Contains(arr => { arr.IsThis(new ColorRule("Red")); }); }); container.GetInstance<ClassWithDependency>().Rules.Length.ShouldEqual(1); } [Test] public void one_optional_child_setter2() { var container = new Container(r => { r.ForConcreteType<ClassWithDependency>().Configure .Setter<Rule>().Is(new ColorRule("Red")); }); container.GetInstance<ClassWithDependency>().Rule.ShouldBeOfType(typeof (ColorRule)); } [Test] public void one_optional_child_setter_with_the_setter_property_defined() { var container = new Container(r => { r.ForConcreteType<ClassWithDependency>().Configure .Setter<Rule>().Is(new ColorRule("Red")); }); container.GetInstance<ClassWithDependency>().Rule.ShouldBeOfType(typeof (ColorRule)); } [Test] public void one_optional_child_setter_without_the_setter_property_defined() { var container = new Container(r => { r.ForConcreteType<ClassWithDependency>(); }); container.GetInstance<ClassWithDependency>().Rule.ShouldBeNull(); } [Test] public void one_optional_enum_setter() { var container = new Container(r => { r.ForConcreteType<ClassWithOneEnum>().Configure .Setter(x => x.Color).Is(ColorEnum.Red); }); container.GetInstance<ClassWithOneEnum>().Color.ShouldEqual(ColorEnum.Red); } [Test] public void one_optional_long_and_one_bool_setter() { var container = new Container(r => { r.ForConcreteType<ClassWithOneLongAndOneBool>().Configure .Setter(x => x.Age).Is(34) .Setter(x => x.Active).Is(true); }); var instance = container.GetInstance<ClassWithOneLongAndOneBool>(); instance.Age.ShouldEqual(34); instance.Active.ShouldBeTrue(); } [Test] public void one_optional_setter_injection_with_string() { var container = new Container(r => { r.ForConcreteType<ClassWithOneSetter>().Configure .Setter(x => x.Name).Is("Jeremy"); }); container.GetInstance<ClassWithOneSetter>().Name.ShouldEqual("Jeremy"); } [Test] public void optional_setter_injection_with_string() { var container = new Container(r => { // The "Name" property is not configured for this instance r.For<OptionalSetterTarget>().Use<OptionalSetterTarget>().Named("NoName"); // The "Name" property is configured for this instance r.ForConcreteType<OptionalSetterTarget>().Configure .Setter(x => x.Name).Is("Jeremy"); }); container.GetInstance<OptionalSetterTarget>().Name.ShouldEqual("Jeremy"); container.GetInstance<OptionalSetterTarget>("NoName").Name.ShouldBeNull(); } [Test] public void optional_setter_with_Action() { var container = new Container(r => { // The "Name" property is not configured for this instance r.For<OptionalSetterTarget>().Use<OptionalSetterTarget>().Named("NoName"); // The "Name" property is configured for this instance r.ForConcreteType<OptionalSetterTarget>().Configure .Setter(x => x.Name).Is("Jeremy"); }); container.GetInstance<OptionalSetterTarget>().Name.ShouldEqual("Jeremy"); container.GetInstance<OptionalSetterTarget>("NoName").Name.ShouldBeNull(); } [Test] public void using_the_FillAllPropertiesOf() { var container = new Container(r => r.Policies.FillAllPropertiesOfType<Rule>().Use(new ColorRule("Red"))); container.GetInstance<ClassWithDependency>().Rule.ShouldBeOfType(typeof (ColorRule)); } } public class ClassWithClassWithLogger { private readonly ClassWithLogger _classWithLogger; public ClassWithClassWithLogger(ClassWithLogger classWithLogger) { _classWithLogger = classWithLogger; } public ClassWithLogger ClassWithLogger { get { return _classWithLogger; } } } public interface ILogger { void LogMessage(string message); } public class Logger : ILogger { private readonly Type _type; public Logger(Type type) { _type = type; } public Type Type { get { return _type; } } public void LogMessage(string message) { } } public class ClassWithLogger { public ILogger Logger { get; set; } } public class ClassWithLogger2 { public ILogger Logger { get; set; } } public enum ColorEnum { Red, Blue, Green } public class OptionalSetterTarget { public string Name { get; set; } public string Name2 { get; set; } } public class NoSettersTarget { } public class ClassWithOneSetter { public string Name { get; set; } } public class ClassWithOneEnum { public ColorEnum Color { get; set; } } public class ClassWithOneLongAndOneBool { public bool Active { get; set; } public int Age { get; set; } } public class ClassWithDependency { public Rule Rule { get; set; } public Rule[] Rules { get; set; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcav = Google.Cloud.AIPlatform.V1; using sys = System; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Resource name for the <c>Feature</c> resource.</summary> public sealed partial class FeatureName : gax::IResourceName, sys::IEquatable<FeatureName> { /// <summary>The possible contents of <see cref="FeatureName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c> /// projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}</c> /// . /// </summary> ProjectLocationFeaturestoreEntityTypeFeature = 1, } private static gax::PathTemplate s_projectLocationFeaturestoreEntityTypeFeature = new gax::PathTemplate("projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}"); /// <summary>Creates a <see cref="FeatureName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="FeatureName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static FeatureName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new FeatureName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="FeatureName"/> with the pattern /// <c> /// projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="featurestoreId">The <c>Featurestore</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="featureId">The <c>Feature</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="FeatureName"/> constructed from the provided ids.</returns> public static FeatureName FromProjectLocationFeaturestoreEntityTypeFeature(string projectId, string locationId, string featurestoreId, string entityTypeId, string featureId) => new FeatureName(ResourceNameType.ProjectLocationFeaturestoreEntityTypeFeature, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), featurestoreId: gax::GaxPreconditions.CheckNotNullOrEmpty(featurestoreId, nameof(featurestoreId)), entityTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(entityTypeId, nameof(entityTypeId)), featureId: gax::GaxPreconditions.CheckNotNullOrEmpty(featureId, nameof(featureId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeatureName"/> with pattern /// <c> /// projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="featurestoreId">The <c>Featurestore</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="featureId">The <c>Feature</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeatureName"/> with pattern /// <c> /// projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}</c> /// . /// </returns> public static string Format(string projectId, string locationId, string featurestoreId, string entityTypeId, string featureId) => FormatProjectLocationFeaturestoreEntityTypeFeature(projectId, locationId, featurestoreId, entityTypeId, featureId); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeatureName"/> with pattern /// <c> /// projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="featurestoreId">The <c>Featurestore</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="featureId">The <c>Feature</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeatureName"/> with pattern /// <c> /// projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}</c> /// . /// </returns> public static string FormatProjectLocationFeaturestoreEntityTypeFeature(string projectId, string locationId, string featurestoreId, string entityTypeId, string featureId) => s_projectLocationFeaturestoreEntityTypeFeature.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(featurestoreId, nameof(featurestoreId)), gax::GaxPreconditions.CheckNotNullOrEmpty(entityTypeId, nameof(entityTypeId)), gax::GaxPreconditions.CheckNotNullOrEmpty(featureId, nameof(featureId))); /// <summary>Parses the given resource name string into a new <see cref="FeatureName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="featureName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="FeatureName"/> if successful.</returns> public static FeatureName Parse(string featureName) => Parse(featureName, false); /// <summary> /// Parses the given resource name string into a new <see cref="FeatureName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="featureName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="FeatureName"/> if successful.</returns> public static FeatureName Parse(string featureName, bool allowUnparsed) => TryParse(featureName, allowUnparsed, out FeatureName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="FeatureName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="featureName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="FeatureName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string featureName, out FeatureName result) => TryParse(featureName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="FeatureName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="featureName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="FeatureName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string featureName, bool allowUnparsed, out FeatureName result) { gax::GaxPreconditions.CheckNotNull(featureName, nameof(featureName)); gax::TemplatedResourceName resourceName; if (s_projectLocationFeaturestoreEntityTypeFeature.TryParseName(featureName, out resourceName)) { result = FromProjectLocationFeaturestoreEntityTypeFeature(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(featureName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private FeatureName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string entityTypeId = null, string featureId = null, string featurestoreId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; EntityTypeId = entityTypeId; FeatureId = featureId; FeaturestoreId = featurestoreId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="FeatureName"/> class from the component parts of pattern /// <c> /// projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}/features/{feature}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="featurestoreId">The <c>Featurestore</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="featureId">The <c>Feature</c> ID. Must not be <c>null</c> or empty.</param> public FeatureName(string projectId, string locationId, string featurestoreId, string entityTypeId, string featureId) : this(ResourceNameType.ProjectLocationFeaturestoreEntityTypeFeature, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), featurestoreId: gax::GaxPreconditions.CheckNotNullOrEmpty(featurestoreId, nameof(featurestoreId)), entityTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(entityTypeId, nameof(entityTypeId)), featureId: gax::GaxPreconditions.CheckNotNullOrEmpty(featureId, nameof(featureId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>EntityType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string EntityTypeId { get; } /// <summary> /// The <c>Feature</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeatureId { get; } /// <summary> /// The <c>Featurestore</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string FeaturestoreId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationFeaturestoreEntityTypeFeature: return s_projectLocationFeaturestoreEntityTypeFeature.Expand(ProjectId, LocationId, FeaturestoreId, EntityTypeId, FeatureId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as FeatureName); /// <inheritdoc/> public bool Equals(FeatureName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(FeatureName a, FeatureName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(FeatureName a, FeatureName b) => !(a == b); } public partial class Feature { /// <summary> /// <see cref="gcav::FeatureName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::FeatureName FeatureName { get => string.IsNullOrEmpty(Name) ? null : gcav::FeatureName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Hatfield.AnalyteManagement.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2017 Leandro F. Vieira (leandromoh). 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. #endregion namespace MoreLinq.Test { using System.Collections.Generic; using System.Collections; using NUnit.Framework; [TestFixture] public class FlattenTest { // Flatten(this IEnumerable source) [Test] public void Flatten() { var source = new object[] { 1, 2, new object[] { 3, new object[] { 4, "foo" }, 5, true, }, "bar", 6, new[] { 7, 8, 9, 10 }, }; var result = source.Flatten(); var expectations = new object[] { 1, 2, 3, 4, "foo", 5, true, "bar", 6, 7, 8, 9, 10 }; Assert.That(result, Is.EqualTo(expectations)); } [Test] public void FlattenCast() { var source = new object[] { 1, 2, 3, 4, 5, new object[] { 6, 7, new object[] { 8, 9, new object[] { 10, 11, 12, }, 13, 14, 15, }, 16, 17, }, 18, 19, 20, }; var result = source.Flatten().Cast<int>(); var expectations = Enumerable.Range(1, 20); Assert.That(result, Is.EqualTo(expectations)); } [Test] public void FlattenIsLazy() { new BreakingSequence<int>().Flatten(); } // Flatten(this IEnumerable source, Func<IEnumerable, bool> predicate) [Test] public void FlattenPredicate() { var source = new object[] { 1, 2, 3, "bar", new object[] { 4, new[] { true, false }, 5, }, 6, 7, }; var result = source.Flatten(obj => !(obj is IEnumerable<bool>)); var expectations = new object[] { 1, 2, 3, 'b', 'a', 'r', 4, new[] { true, false }, 5, 6, 7, }; Assert.That(result, Is.EqualTo(expectations)); } [Test] public void FlattenPredicateAlwaysFalse() { var source = new object[] { 1, 2, 3, "bar", new[] { true, false, }, 6 }; var result = source.Flatten(_ => false); Assert.That(result, Is.EqualTo(source)); } [Test] public void FlattenPredicateAlwaysTrue() { var source = new object[] { 1, 2, "bar", 3, new[] { 4, 5, }, 6 }; var result = source.Flatten(_ => true); var expectations = new object[] { 1, 2, 'b', 'a', 'r', 3, 4, 5, 6 }; Assert.That(result, Is.EqualTo(expectations)); } [Test] public void FlattenPredicateIsLazy() { new BreakingSequence<int>().Flatten(BreakingFunc.Of<object, bool>()); } [Test] public void FlattenFullIteratedDisposesInnerSequences() { var expectations = new object[] { 4, 5, 6, true, false, 7, }; using var inner1 = TestingSequence.Of(4, 5); using var inner2 = TestingSequence.Of(true, false); using var inner3 = TestingSequence.Of<object>(6, inner2, 7); using var source = TestingSequence.Of<object>(inner1, inner3); Assert.That(source.Flatten(), Is.EqualTo(expectations)); } [Test] public void FlattenInterruptedIterationDisposesInnerSequences() { using var inner1 = TestingSequence.Of(4, 5); using var inner2 = MoreEnumerable.From(() => true, () => false, () => throw new TestException()) .AsTestingSequence(); using var inner3 = TestingSequence.Of<object>(6, inner2, 7); using var source = TestingSequence.Of<object>(inner1, inner3); Assert.Throws<TestException>(() => source.Flatten().Consume()); } [Test] public void FlattenEvaluatesInnerSequencesLazily() { var source = new object[] { 1, 2, 3, 4, 5, new object[] { 6, 7, new object[] { 8, 9, MoreEnumerable.From ( () => 10, () => throw new TestException(), () => 12 ), 13, 14, 15, }, 16, 17, }, 18, 19, 20, }; var result = source.Flatten().Cast<int>(); var expectations = Enumerable.Range(1, 10); Assert.That(result.Take(10), Is.EqualTo(expectations)); Assert.Throws<TestException>(() => source.Flatten().ElementAt(11)); } // Flatten(this IEnumerable source, Func<object, IEnumerable> selector) [Test] public void FlattenSelectorIsLazy() { new BreakingSequence<int>().Flatten(BreakingFunc.Of<object, IEnumerable>()); } [Test] public void FlattenSelector() { var source = new[] { new Series { Name = "series1", Attributes = new[] { new Attribute { Values = new[] { 1, 2 } }, new Attribute { Values = new[] { 3, 4 } }, } }, new Series { Name = "series2", Attributes = new[] { new Attribute { Values = new[] { 5, 6 } }, } } }; var result = source.Flatten(obj => { switch (obj) { case string: return null; case IEnumerable inner: return inner; case Series s: return new object[] { s.Name, s.Attributes }; case Attribute a: return a.Values; default: return null; } }); var expectations = new object[] { "series1", 1, 2, 3, 4, "series2", 5, 6 }; Assert.That(result, Is.EqualTo(expectations)); } [Test] public void FlattenSelectorFilteringOnlyIntegers() { var source = new object[] { true, false, 1, "bar", new object[] { 2, new[] { 3, }, }, 'c', 4, }; var result = source.Flatten(obj => { switch (obj) { case int: return null; case IEnumerable inner: return inner; default: return Enumerable.Empty<object>(); } }); var expectations = new object[] { 1, 2, 3, 4 }; Assert.That(result, Is.EqualTo(expectations)); } [Test] public void FlattenSelectorWithTree() { var source = new Tree<int> ( new Tree<int> ( new Tree<int>(1), 2, new Tree<int>(3) ), 4, new Tree<int> ( new Tree<int>(5), 6, new Tree<int>(7) ) ); var result = new [] { source }.Flatten(obj => { switch (obj) { case int: return null; case Tree<int> tree: return new object[] { tree.Left, tree.Value, tree.Right }; case IEnumerable inner: return inner; default: return Enumerable.Empty<object>(); } }); var expectations = Enumerable.Range(1, 7); Assert.That(result, Is.EqualTo(expectations)); } class Series { public string Name; public Attribute[] Attributes; } class Attribute { public int[] Values; } class Tree<T> { public readonly T Value; public readonly Tree<T> Left; public readonly Tree<T> Right; public Tree(T value) : this(null, value, null) {} public Tree(Tree<T> left, T value, Tree<T> right) { Left = left; Value = value; Right = right; } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // // // HashAlgorithm.cs // namespace System.Security.Cryptography { using System.IO; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public abstract class HashAlgorithm : IDisposable, ICryptoTransform { protected int HashSizeValue; protected internal byte[] HashValue; protected int State = 0; private bool m_bDisposed = false; protected HashAlgorithm() {} // // public properties // public virtual int HashSize { get { return HashSizeValue; } } public virtual byte[] Hash { get { if (m_bDisposed) throw new ObjectDisposedException(null); if (State != 0) throw new CryptographicUnexpectedOperationException(Environment.GetResourceString("Cryptography_HashNotYetFinalized")); return (byte[]) HashValue.Clone(); } } // // public methods // static public HashAlgorithm Create() { #if FULL_AOT_RUNTIME return new System.Security.Cryptography.SHA1CryptoServiceProvider (); #else return Create("System.Security.Cryptography.HashAlgorithm"); #endif } static public HashAlgorithm Create(String hashName) { return (HashAlgorithm) CryptoConfig.CreateFromName(hashName); } public byte[] ComputeHash(Stream inputStream) { if (m_bDisposed) throw new ObjectDisposedException(null); // Default the buffer size to 4K. byte[] buffer = new byte[4096]; int bytesRead; do { bytesRead = inputStream.Read(buffer, 0, 4096); if (bytesRead > 0) { HashCore(buffer, 0, bytesRead); } } while (bytesRead > 0); HashValue = HashFinal(); byte[] Tmp = (byte[]) HashValue.Clone(); Initialize(); return(Tmp); } public byte[] ComputeHash(byte[] buffer) { if (m_bDisposed) throw new ObjectDisposedException(null); // Do some validation if (buffer == null) throw new ArgumentNullException("buffer"); HashCore(buffer, 0, buffer.Length); HashValue = HashFinal(); byte[] Tmp = (byte[]) HashValue.Clone(); Initialize(); return(Tmp); } public byte[] ComputeHash(byte[] buffer, int offset, int count) { // Do some validation if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0 || (count > buffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); if ((buffer.Length - count) < offset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (m_bDisposed) throw new ObjectDisposedException(null); HashCore(buffer, offset, count); HashValue = HashFinal(); byte[] Tmp = (byte[]) HashValue.Clone(); Initialize(); return(Tmp); } // ICryptoTransform methods // we assume any HashAlgorithm can take input a byte at a time public virtual int InputBlockSize { get { return(1); } } public virtual int OutputBlockSize { get { return(1); } } public virtual bool CanTransformMultipleBlocks { get { return(true); } } public virtual bool CanReuseTransform { get { return(true); } } // We implement TransformBlock and TransformFinalBlock here public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { // Do some validation, we let BlockCopy do the destination array validation if (inputBuffer == null) throw new ArgumentNullException("inputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (inputCount < 0 || (inputCount > inputBuffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (m_bDisposed) throw new ObjectDisposedException(null); // Change the State value State = 1; HashCore(inputBuffer, inputOffset, inputCount); if ((outputBuffer != null) && ((inputBuffer != outputBuffer) || (inputOffset != outputOffset))) Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount); return inputCount; } public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { // Do some validation if (inputBuffer == null) throw new ArgumentNullException("inputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (inputCount < 0 || (inputCount > inputBuffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (m_bDisposed) throw new ObjectDisposedException(null); HashCore(inputBuffer, inputOffset, inputCount); HashValue = HashFinal(); byte[] outputBytes; if (inputCount != 0) { outputBytes = new byte[inputCount]; Buffer.InternalBlockCopy(inputBuffer, inputOffset, outputBytes, 0, inputCount); } else { outputBytes = EmptyArray<Byte>.Value; } // reset the State value State = 0; return outputBytes; } // IDisposable methods // To keep mscorlib compatibility with Orcas, CoreCLR's HashAlgorithm has an explicit IDisposable // implementation. Post-Orcas the desktop has an implicit IDispoable implementation. #if FEATURE_CORECLR void IDisposable.Dispose() { Dispose(); } #endif // FEATURE_CORECLR public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Clear() { (this as IDisposable).Dispose(); } protected virtual void Dispose(bool disposing) { if (disposing) { if (HashValue != null) Array.Clear(HashValue, 0, HashValue.Length); HashValue = null; m_bDisposed = true; } } // // abstract public methods // public abstract void Initialize(); protected abstract void HashCore(byte[] array, int ibStart, int cbSize); protected abstract byte[] HashFinal(); } }
// 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: The boolean class serves as a wrapper for the primitive ** type boolean. ** ** ===========================================================*/ using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Versioning; namespace System { [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Boolean : IComparable, IConvertible, IComparable<Boolean>, IEquatable<Boolean> { // // Member Variables // private bool m_value; // Do not rename (binary serialization) // The true value. // internal const int True = 1; // The false value. // internal const int False = 0; // // Internal Constants are real consts for performance. // // The internal string representation of true. // internal const String TrueLiteral = "True"; // The internal string representation of false. // internal const String FalseLiteral = "False"; // // Public Constants // // The public string representation of true. // public static readonly String TrueString = TrueLiteral; // The public string representation of false. // public static readonly String FalseString = FalseLiteral; // // Overriden Instance Methods // /*=================================GetHashCode================================== **Args: None **Returns: 1 or 0 depending on whether this instance represents true or false. **Exceptions: None **Overriden From: Value ==============================================================================*/ // Provides a hash code for this instance. public override int GetHashCode() { return (m_value) ? True : False; } /*===================================ToString=================================== **Args: None **Returns: "True" or "False" depending on the state of the boolean. **Exceptions: None. ==============================================================================*/ // Converts the boolean value of this instance to a String. public override String ToString() { if (false == m_value) { return FalseLiteral; } return TrueLiteral; } public String ToString(IFormatProvider provider) { return ToString(); } // Determines whether two Boolean objects are equal. public override bool Equals(Object obj) { //If it's not a boolean, we're definitely not equal if (!(obj is Boolean)) { return false; } return (m_value == ((Boolean)obj).m_value); } [NonVersionable] public bool Equals(Boolean obj) { return m_value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. For booleans, false sorts before true. // null is considered to be less than any instance. // If object is not of type boolean, this method throws an ArgumentException. // // Returns a value less than zero if this object // public int CompareTo(Object obj) { if (obj == null) { return 1; } if (!(obj is Boolean)) { throw new ArgumentException(SR.Arg_MustBeBoolean); } if (m_value == ((Boolean)obj).m_value) { return 0; } else if (m_value == false) { return -1; } return 1; } public int CompareTo(Boolean value) { if (m_value == value) { return 0; } else if (m_value == false) { return -1; } return 1; } // // Static Methods // // Determines whether a String represents true or false. // public static Boolean Parse(String value) { if (value == null) throw new ArgumentNullException(nameof(value)); return Parse(value.AsReadOnlySpan()); } public static bool Parse(ReadOnlySpan<char> value) => TryParse(value, out bool result) ? result : throw new FormatException(SR.Format_BadBoolean); // Determines whether a String represents true or false. // public static Boolean TryParse(String value, out Boolean result) { if (value == null) { result = false; return false; } return TryParse(value.AsReadOnlySpan(), out result); } public static bool TryParse(ReadOnlySpan<char> value, out bool result) { ReadOnlySpan<char> trueSpan = TrueLiteral.AsReadOnlySpan(); if (StringSpanHelpers.Equals(trueSpan, value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } ReadOnlySpan<char> falseSpan = FalseLiteral.AsReadOnlySpan(); if (StringSpanHelpers.Equals(falseSpan, value, StringComparison.OrdinalIgnoreCase)) { result = false; return true; } // Special case: Trim whitespace as well as null characters. value = TrimWhiteSpaceAndNull(value); if (StringSpanHelpers.Equals(trueSpan, value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (StringSpanHelpers.Equals(falseSpan, value, StringComparison.OrdinalIgnoreCase)) { result = false; return true; } result = false; return false; } private static ReadOnlySpan<char> TrimWhiteSpaceAndNull(ReadOnlySpan<char> value) { const char nullChar = (char)0x0000; int start = 0; while (start < value.Length) { if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar) { break; } start++; } int end = value.Length - 1; while (end >= start) { if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar) { break; } end--; } return value.Slice(start, end - start + 1); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Boolean; } bool IConvertible.ToBoolean(IFormatProvider provider) { return m_value; } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal partial class Session { public void ComputeModel( IList<ISignatureHelpProvider> providers, SignatureHelpTriggerInfo triggerInfo) { ComputeModel(providers, SpecializedCollections.EmptyList<ISignatureHelpProvider>(), triggerInfo); } public void ComputeModel( IList<ISignatureHelpProvider> matchedProviders, IList<ISignatureHelpProvider> unmatchedProviders, SignatureHelpTriggerInfo triggerInfo) { AssertIsForeground(); var caretPosition = Controller.TextView.GetCaretPoint(Controller.SubjectBuffer).Value; var disconnectedBufferGraph = new DisconnectedBufferGraph(Controller.SubjectBuffer, Controller.TextView.TextBuffer); // If we've already computed a model, then just use that. Otherwise, actually // compute a new model and send that along. Computation.ChainTaskAndNotifyControllerWhenFinished( (model, cancellationToken) => ComputeModelInBackgroundAsync(model, matchedProviders, unmatchedProviders, caretPosition, disconnectedBufferGraph, triggerInfo, cancellationToken)); } private async Task<Model> ComputeModelInBackgroundAsync( Model currentModel, IList<ISignatureHelpProvider> matchedProviders, IList<ISignatureHelpProvider> unmatchedProviders, SnapshotPoint caretPosition, DisconnectedBufferGraph disconnectedBufferGraph, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.SignatureHelp_ModelComputation_ComputeModelInBackground, cancellationToken)) { AssertIsBackground(); cancellationToken.ThrowIfCancellationRequested(); var document = await Controller.DocumentProvider.GetDocumentAsync(caretPosition.Snapshot, cancellationToken).ConfigureAwait(false); if (document == null) { return currentModel; } if (triggerInfo.TriggerReason == SignatureHelpTriggerReason.RetriggerCommand) { if (currentModel == null || (triggerInfo.TriggerCharacter.HasValue && !currentModel.Provider.IsRetriggerCharacter(triggerInfo.TriggerCharacter.Value))) { return currentModel; } } // first try to query the providers that can trigger on the specified character var result = await ComputeItemsAsync(matchedProviders, caretPosition, triggerInfo, document, cancellationToken).ConfigureAwait(false); var provider = result.Item1; var items = result.Item2; if (provider == null) { // no match, so now query the other providers result = await ComputeItemsAsync(unmatchedProviders, caretPosition, triggerInfo, document, cancellationToken).ConfigureAwait(false); provider = result.Item1; items = result.Item2; if (provider == null) { // the other providers didn't produce items either, so we don't produce a model return null; } } if (currentModel != null && currentModel.Provider == provider && currentModel.GetCurrentSpanInSubjectBuffer(disconnectedBufferGraph.SubjectBufferSnapshot).Span.Start == items.ApplicableSpan.Start && currentModel.ArgumentIndex == items.ArgumentIndex && currentModel.ArgumentCount == items.ArgumentCount && currentModel.ArgumentName == items.ArgumentName) { // The new model is the same as the current model. Return the currentModel // so we keep the active selection. return currentModel; } var selectedItem = GetSelectedItem(currentModel, items, provider); var model = new Model(disconnectedBufferGraph, items.ApplicableSpan, provider, items.Items, selectedItem, items.ArgumentIndex, items.ArgumentCount, items.ArgumentName, selectedParameter: 0); var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var isCaseSensitive = syntaxFactsService == null || syntaxFactsService.IsCaseSensitive; var selection = DefaultSignatureHelpSelector.GetSelection(model.Items, model.SelectedItem, model.ArgumentIndex, model.ArgumentCount, model.ArgumentName, isCaseSensitive); return model.WithSelectedItem(selection.SelectedItem) .WithSelectedParameter(selection.SelectedParameter); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private static bool SequenceEquals(IEnumerable<string> s1, IEnumerable<string> s2) { if (s1 == s2) { return true; } return s1 != null && s2 != null && s1.SequenceEqual(s2); } private static SignatureHelpItem GetSelectedItem(Model currentModel, SignatureHelpItems items, ISignatureHelpProvider provider) { // Try to find the most appropriate item in the list to select by default. // If the provider specified one a selected item, then always stick with that one. if (items.SelectedItemIndex.HasValue) { return items.Items[items.SelectedItemIndex.Value]; } // If teh provider did not pick a default, and it's hte same provider as the previous // model we have, then try to return the same item that we had before. if (currentModel != null && currentModel.Provider == provider) { return items.Items.FirstOrDefault(i => DisplayPartsMatch(i, currentModel.SelectedItem)) ?? items.Items.First(); } // Otherwise, just pick the first item we have. return items.Items.First(); } private static bool DisplayPartsMatch(SignatureHelpItem i1, SignatureHelpItem i2) { return i1.GetAllParts().SequenceEqual(i2.GetAllParts(), CompareParts); } private static bool CompareParts(SymbolDisplayPart p1, SymbolDisplayPart p2) { return p1.ToString() == p2.ToString(); } private async Task<Tuple<ISignatureHelpProvider, SignatureHelpItems>> ComputeItemsAsync( IList<ISignatureHelpProvider> providers, SnapshotPoint caretPosition, SignatureHelpTriggerInfo triggerInfo, Document document, CancellationToken cancellationToken) { try { ISignatureHelpProvider bestProvider = null; SignatureHelpItems bestItems = null; // TODO(cyrusn): We're calling into extensions, we need to make ourselves resilient // to the extension crashing. foreach (var provider in providers) { cancellationToken.ThrowIfCancellationRequested(); var currentItems = await provider.GetItemsAsync(document, caretPosition, triggerInfo, cancellationToken).ConfigureAwait(false); if (currentItems != null && currentItems.ApplicableSpan.IntersectsWith(caretPosition.Position)) { // If another provider provides sig help items, then only take them if they // start after the last batch of items. i.e. we want the set of items that // conceptually are closer to where the caret position is. This way if you have: // // Foo(new Bar($$ // // Then invoking sig help will only show the items for "new Bar(" and not also // the items for "Foo(..." if (IsBetter(bestItems, currentItems.ApplicableSpan)) { bestItems = currentItems; bestProvider = provider; } } } return Tuple.Create(bestProvider, bestItems); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private bool IsBetter(SignatureHelpItems bestItems, TextSpan? currentTextSpan) { // If we have no best text span, then this span is definitely better. if (bestItems == null) { return true; } // Otherwise we want the one that is conceptually the innermost signature. So it's // only better if the distance from it to the caret position is less than the best // one so far. return currentTextSpan.Value.Start > bestItems.ApplicableSpan.Start; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using Devsense.PHP.Syntax.Ast; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Pchp.CodeAnalysis; using Pchp.CodeAnalysis.FlowAnalysis; using Pchp.CodeAnalysis.Semantics; using Pchp.CodeAnalysis.Symbols; using Peachpie.Library.Scripting; using Xunit; using Xunit.Abstractions; namespace Peachpie.DiagnosticTests { /// <summary> /// Test class. /// </summary> public class DiagnosticTest { private readonly ITestOutputHelper _output; private static readonly PhpCompilation EmptyCompilation = CreateEmptyCompilation(); private static readonly Regex DiagnosticAnnotationRegex = new Regex(@"/\*!([A-Z]*[0-9]*)!\*/"); private static readonly Regex TypeAnnotationRegex = new Regex(@"/\*\|([^/]*)\|\*/"); private static readonly Regex RoutinePropertiesRegex = new Regex(@"/\*{version:([0-9]+)}\*/"); private static readonly Regex ParameterPropertiesRegex = new Regex(@"/\*{skipPass:([01])}\*/"); private static readonly Regex OperationPropertiesRegex = new Regex(@"/\*{skipCopy:([01])}\*/"); /// <summary> /// Init test class. /// </summary> public DiagnosticTest(ITestOutputHelper output) { _output = output; } /// <summary> /// Test runner. /// </summary> [Theory] [DiagnosticScriptsListData] public void DiagnosticRunTest(string dir, string fname) { var path = Path.Combine(dir, fname); _output.WriteLine("Analysing {0} ...", path); var code = File.ReadAllText(path); var syntaxTree = PhpSyntaxTree.ParseCode(SourceText.From(code, Encoding.UTF8), PhpParseOptions.Default, PhpParseOptions.Default, path); var compilation = (PhpCompilation)EmptyCompilation.AddSyntaxTrees(syntaxTree); bool isCorrect = true; // Gather and check diagnostics var expectedDiags = DiagnosticAnnotationRegex.Matches(code); var actualDiags = compilation.GetDiagnostics() .OrderBy(diag => diag.Location.SourceSpan.Start) .ToArray(); isCorrect &= CheckDiagnostics(syntaxTree, actualDiags, expectedDiags); // Gather and check types and parameter properties if there are any annotations var expectedTypes = TypeAnnotationRegex.Matches(code); var expectedParamProps = ParameterPropertiesRegex.Matches(code); if (expectedTypes.Count > 0 || expectedParamProps.Count > 0) { var symbolsInfo = compilation.UserDeclaredRoutines .Where(routine => routine.ControlFlowGraph != null) .Select(routine => SymbolsSelector.Select(routine.ControlFlowGraph)) .Concat(compilation.UserDeclaredRoutines.Select(routine => SymbolsSelector.Select(routine))) // routine declarations .Concat(compilation.UserDeclaredTypes.Select(type => SymbolsSelector.Select(type))) // type declarations .SelectMany(enumerators => enumerators) // IEnumerable<IEnumerable<T>> => IEnumerable<T> .ToArray(); // Cache results isCorrect &= CheckTypes(syntaxTree, symbolsInfo, expectedTypes); isCorrect &= CheckParameterProperties(syntaxTree, symbolsInfo, expectedParamProps); } // Gather and check routine properties if there are any annotations var expectedRoutineProps = RoutinePropertiesRegex.Matches(code); if (expectedRoutineProps.Count > 0) { isCorrect &= CheckRoutineProperties(syntaxTree, compilation.SourceSymbolCollection.AllRoutines, expectedRoutineProps); } // Gather and check operation properties if there are any annotations var expectedOpProps = OperationPropertiesRegex.Matches(code); if (expectedOpProps.Count > 0) { var interestingOps = compilation.UserDeclaredRoutines .OfType<SourceRoutineSymbol>() .SelectMany(r => OperationSelector.Select(r)) .ToArray(); isCorrect &= CheckOperationProperties(syntaxTree, interestingOps, expectedOpProps); } Assert.True(isCorrect); } private bool CheckDiagnostics(PhpSyntaxTree syntaxTree, Diagnostic[] actual, MatchCollection expected) { // Compare in ascending order to systematically find all discrepancies bool isCorrect = true; int iActual = 0; int iExpected = 0; while (iActual < actual.Length && iExpected < expected.Count) { // The comment is right after the expected diagnostic int posActual = actual[iActual].Location.SourceSpan.End; int posExpected = expected[iExpected].Index; if (posActual < posExpected) { isCorrect = false; ReportUnexpectedDiagnostic(actual[iActual]); iActual++; } else if (posActual > posExpected) { isCorrect = false; ReportMissingDiagnostic(syntaxTree, expected[iExpected]); iExpected++; } else { string idActual = actual[iActual].Id; string idExpected = expected[iExpected].Groups[1].Value; if (idActual != idExpected) { isCorrect = false; ReportWrongDiagnosticId(actual[iActual], idActual, idExpected); } iActual++; iExpected++; } } // Process the remainder if present if (iActual < actual.Length) { isCorrect = false; for (; iActual < actual.Length; iActual++) { ReportUnexpectedDiagnostic(actual[iActual]); } } else if (iExpected < expected.Count) { isCorrect = false; for (; iExpected < expected.Count; iExpected++) { ReportMissingDiagnostic(syntaxTree, expected[iExpected]); } } return isCorrect; } private void ReportUnexpectedDiagnostic(Diagnostic diagnostic) { var position = GetLinePosition(diagnostic.Location.GetLineSpan()); _output.WriteLine($"Unexpected diagnostic {diagnostic.Id} on {position.Line},{position.Character}"); } private void ReportMissingDiagnostic(PhpSyntaxTree syntaxTree, Match expectedMatch) { string idExpected = expectedMatch.Groups[1].Value; var span = new TextSpan(expectedMatch.Index, 0); var position = GetLinePosition(syntaxTree.GetLineSpan(span)); _output.WriteLine($"Missing diagnostic {idExpected} on {position.Line},{position.Character}"); } private void ReportWrongDiagnosticId(Diagnostic diagnostic, string idActual, string idExpected) { var position = GetLinePosition(diagnostic.Location.GetLineSpan()); _output.WriteLine($"Wrong diagnostic {idActual} instead of {idExpected} on {position.Line},{position.Character}"); } private static LinePosition GetLinePosition(FileLinePositionSpan span) { // It is zero-based both for line and character, therefore we must add 1 var originalPos = span.StartLinePosition; return new LinePosition(originalPos.Line + 1, originalPos.Character + 1); } private bool CheckTypes(PhpSyntaxTree syntaxTree, IEnumerable<SymbolsSelector.SymbolStat> symbolStats, MatchCollection expectedTypes) { var positionSymbolMap = new Dictionary<int, SymbolsSelector.SymbolStat>(); foreach (var stat in symbolStats) { positionSymbolMap.TryAdd(stat.Span.Start, stat); } // Type annotation is voluntary; therefore, check only the specified types bool isCorrect = true; foreach (Match match in expectedTypes) { // The text of symbol should start where the annotation ends int expectedPos = match.Index + match.Length; if (!positionSymbolMap.TryGetValue(expectedPos, out var symbolStat)) { var linePos = GetLinePosition(syntaxTree.GetLineSpan(match.GetTextSpan())); _output.WriteLine($"Cannot get type information for type annotation on {linePos.Line},{linePos.Character}"); isCorrect = false; continue; } // Obtain the type of the given symbol or expression string actualType = GetTypeString(symbolStat); if (string.IsNullOrEmpty(actualType)) { var linePos = GetLinePosition(syntaxTree.GetLineSpan(symbolStat.Span.ToTextSpan())); _output.WriteLine($"Unable to get the type of the symbol on {linePos.Line},{linePos.Character}"); isCorrect = false; continue; } // Reorder expected types alphabetically string expectedType = string.Join("|", match.Groups[1].Value.Split('|').OrderBy(s => s)); // Report any problem if (actualType != expectedType) { var linePos = GetLinePosition(syntaxTree.GetLineSpan(symbolStat.Span.ToTextSpan())); _output.WriteLine( $"Wrong type {actualType} instead of {expectedType} of the expression on {linePos.Line},{linePos.Character}"); isCorrect = false; } } return isCorrect; } private string GetTypeString(SymbolsSelector.SymbolStat symbolStat) { if (symbolStat.TypeCtx == null) { return null; } if (symbolStat.BoundExpression != null) { return symbolStat.TypeCtx.ToString(symbolStat.BoundExpression.TypeRefMask); } else if (symbolStat.Symbol is IPhpValue typedValue) { TypeRefMask typeMask = typedValue.GetResultType(symbolStat.TypeCtx); return symbolStat.TypeCtx.ToString(typeMask); } else { return null; } } private bool CheckRoutineProperties(PhpSyntaxTree syntaxTree, IEnumerable<SourceRoutineSymbol> userDeclaredRoutines, MatchCollection expectedRoutineProps) { var positionRoutineMap = new Dictionary<int, SourceRoutineSymbol>( from routine in userDeclaredRoutines let position = (routine.Syntax as FunctionDecl)?.ParametersSpan.End ?? (routine.Syntax as MethodDecl)?.ParametersSpan.End where position != null select new KeyValuePair<int, SourceRoutineSymbol>(position.Value, routine)); // Routine properties are voluntary; therefore, check only the specified ones bool isCorrect = true; foreach (Match match in expectedRoutineProps) { int expectedPos = match.Index; if (!positionRoutineMap.TryGetValue(expectedPos, out var routine)) { var linePos = GetLinePosition(syntaxTree.GetLineSpan(match.GetTextSpan())); _output.WriteLine($"Cannot get routine information for properties on {linePos.Line},{linePos.Character}"); isCorrect = false; continue; } int expectedVersion = int.Parse(match.Groups[1].Value); int actualVersion = routine.ControlFlowGraph.FlowContext.Version; if (expectedVersion != actualVersion) { var linePos = GetLinePosition(syntaxTree.GetLineSpan(match.GetTextSpan())); _output.WriteLine( $"Wrong final flow analysis version {actualVersion} instead of {expectedVersion} of the routine {routine.Name} on {linePos.Line},{linePos.Character}"); isCorrect = false; } } return isCorrect; } private bool CheckParameterProperties(PhpSyntaxTree syntaxTree, IEnumerable<SymbolsSelector.SymbolStat> symbolStats, MatchCollection expectedParamProps) { var positionParamMap = new Dictionary<int, SourceParameterSymbol>( from symbolStat in symbolStats let symbol = symbolStat.Symbol where symbol is SourceParameterSymbol select new KeyValuePair<int, SourceParameterSymbol>(symbolStat.Span.End, (SourceParameterSymbol)symbol)); bool isCorrect = true; foreach (Match match in expectedParamProps) { int expectedPos = match.Index; if (!positionParamMap.TryGetValue(expectedPos, out var param)) { var linePos = GetLinePosition(syntaxTree.GetLineSpan(match.GetTextSpan())); _output.WriteLine($"Cannot get parameter information for properties on {linePos.Line},{linePos.Character}"); isCorrect = false; continue; } bool expectedSkipPass = (int.Parse(match.Groups[1].Value) != 0); bool actualSkipPass = !param.CopyOnPass; if (expectedSkipPass != actualSkipPass) { var linePos = GetLinePosition(syntaxTree.GetLineSpan(match.GetTextSpan())); _output.WriteLine( $"Wrong value of SkipPass {actualSkipPass} instead of {expectedSkipPass} of the parameter {param.Name} in {param.Routine.Name} on {linePos.Line},{linePos.Character}"); isCorrect = false; } } return isCorrect; } private bool CheckOperationProperties(PhpSyntaxTree syntaxTree, IEnumerable<IPhpOperation> interestingOps, MatchCollection expectedOpProps) { var copyPositionSet = new HashSet<int>( interestingOps .OfType<BoundCopyValue>() .Select(c => c.Expression.PhpSyntax.Span.End)); bool isCorrect = true; foreach (Match match in expectedOpProps) { bool expectedSkipCopy = (int.Parse(match.Groups[1].Value) != 0); bool actualSkipCopy = !copyPositionSet.Contains(match.Index); if (expectedSkipCopy != actualSkipCopy) { var linePos = GetLinePosition(syntaxTree.GetLineSpan(match.GetTextSpan())); _output.WriteLine( $"Wrong value of copy skipping {actualSkipCopy} instead of {expectedSkipCopy} of the expression on {linePos.Line},{linePos.Character}"); isCorrect = false; } } return isCorrect; } private static PhpCompilation CreateEmptyCompilation() { var compilation = PhpCompilation.Create("project", references: MetadataReferences().Select((string path) => MetadataReference.CreateFromFile(path)), syntaxTrees: Array.Empty<PhpSyntaxTree>(), options: new PhpCompilationOptions( outputKind: OutputKind.DynamicallyLinkedLibrary, baseDirectory: System.IO.Directory.GetCurrentDirectory(), sdkDirectory: null, optimizationLevel: PhpOptimizationLevel.Release)); // bind reference manager, cache all references var assemblytmp = compilation.Assembly; return compilation; } /// <summary> /// Collect references we have to pass to the compilation. /// </summary> private static IEnumerable<string> MetadataReferences() { // implicit references var types = new List<Type>() { typeof(object), // mscorlib (or System.Runtime) typeof(Pchp.Core.Context), // Peachpie.Runtime typeof(Pchp.Library.Strings), // Peachpie.Library typeof(ScriptingProvider), // Peachpie.Library.Scripting }; var list = types.Distinct().Select(ass => ass.GetTypeInfo().Assembly).ToList(); var set = new HashSet<Assembly>(list); for (int i = 0; i < list.Count; i++) { var assembly = list[i]; var refs = assembly.GetReferencedAssemblies(); foreach (var refname in refs) { var refassembly = Assembly.Load(refname); if (refassembly != null && set.Add(refassembly)) { list.Add(refassembly); } } } return list.Select(ass => ass.Location); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Tests { /// <summary> /// Contains tests that ensure the correctness of any class that implements the generic /// IDictionary interface /// </summary> public abstract partial class IDictionary_Generic_Tests<TKey, TValue> : ICollection_Generic_Tests<KeyValuePair<TKey, TValue>> { #region IDictionary<TKey, TValue> Helper Methods /// <summary> /// Creates an instance of an IDictionary{TKey, TValue} that can be used for testing. /// </summary> /// <returns>An instance of an IDictionary{TKey, TValue} that can be used for testing.</returns> protected abstract IDictionary<TKey, TValue> GenericIDictionaryFactory(); /// <summary> /// Creates an instance of an IDictionary{TKey, TValue} that can be used for testing. /// </summary> /// <param name="count">The number of items that the returned IDictionary{TKey, TValue} contains.</param> /// <returns>An instance of an IDictionary{TKey, TValue} that can be used for testing.</returns> protected virtual IDictionary<TKey, TValue> GenericIDictionaryFactory(int count) { IDictionary<TKey, TValue> collection = GenericIDictionaryFactory(); AddToCollection(collection, count); return collection; } /// <summary> /// To be implemented in the concrete Dictionary test classes. Creates an instance of TKey that /// is dependent only on the seed passed as input and will return the same key on repeated /// calls with the same seed. /// </summary> protected abstract TKey CreateTKey(int seed); /// <summary> /// To be implemented in the concrete Dictionary test classes. Creates an instance of TValue that /// is dependent only on the seed passed as input and will return the same value on repeated /// calls with the same seed. /// </summary> protected abstract TValue CreateTValue(int seed); /// <summary> /// Helper method to get a key that doesn't already exist within the dictionary given /// </summary> protected TKey GetNewKey(IDictionary<TKey, TValue> dictionary) { int seed = 840; TKey missingKey = CreateTKey(seed++); while (dictionary.ContainsKey(missingKey) || missingKey.Equals(default(TKey))) missingKey = CreateTKey(seed++); return missingKey; } /// <summary> /// For a Dictionary, the key comparer is primarily important rather than the KeyValuePair. For this /// reason, we rely only on the KeyComparer methods instead of the GetIComparer methods. /// </summary> public virtual IEqualityComparer<TKey> GetKeyIEqualityComparer() { return EqualityComparer<TKey>.Default; } /// <summary> /// For a Dictionary, the key comparer is primarily important rather than the KeyValuePair. For this /// reason, we rely only on the KeyComparer methods instead of the GetIComparer methods. /// </summary> public virtual IComparer<TKey> GetKeyIComparer() { return Comparer<TKey>.Default; } /// <summary> /// Class to provide an indirection around a Key comparer. Allows us to use a key comparer as a KeyValuePair comparer /// by only looking at the key of a KeyValuePair. /// </summary> public class KVPComparer : IEqualityComparer<KeyValuePair<TKey, TValue>>, IComparer<KeyValuePair<TKey, TValue>> { private IComparer<TKey> _comparer; private IEqualityComparer<TKey> _equalityComparer; public KVPComparer(IComparer<TKey> comparer, IEqualityComparer<TKey> eq) { _comparer = comparer; _equalityComparer = eq; } public int Compare(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y) { return _comparer.Compare(x.Key, y.Key); } public bool Equals(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y) { return _equalityComparer.Equals(x.Key, y.Key); } public int GetHashCode(KeyValuePair<TKey, TValue> obj) { return _equalityComparer.GetHashCode(obj.Key); } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Helper Methods protected override ICollection<KeyValuePair<TKey, TValue>> GenericICollectionFactory() { return GenericIDictionaryFactory(); } protected override ICollection<KeyValuePair<TKey, TValue>> GenericICollectionFactory(int count) { return GenericIDictionaryFactory(count); } protected override bool DefaultValueAllowed => false; protected override bool DuplicateValuesAllowed => false; protected override void AddToCollection(ICollection<KeyValuePair<TKey, TValue>> collection, int numberOfItemsToAdd) { Assert.False(IsReadOnly); int seed = 12353; IDictionary<TKey, TValue> casted = (IDictionary<TKey, TValue>)collection; int initialCount = casted.Count; while ((casted.Count - initialCount) < numberOfItemsToAdd) { KeyValuePair<TKey, TValue> toAdd = CreateT(seed++); while (casted.ContainsKey(toAdd.Key) || Enumerable.Contains(InvalidValues, toAdd)) toAdd = CreateT(seed++); collection.Add(toAdd); } } protected override IEqualityComparer<KeyValuePair<TKey, TValue>> GetIEqualityComparer() { return new KVPComparer(GetKeyIComparer(), GetKeyIEqualityComparer()); } protected override IComparer<KeyValuePair<TKey, TValue>> GetIComparer() { return new KVPComparer(GetKeyIComparer(), GetKeyIEqualityComparer()); } /// <summary> /// Returns a set of ModifyEnumerable delegates that modify the enumerable passed to them. /// </summary> protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) { if ((operations & ModifyOperation.Add) == ModifyOperation.Add) { yield return (IEnumerable<KeyValuePair<TKey, TValue>> enumerable) => { IDictionary<TKey, TValue> casted = ((IDictionary<TKey, TValue>)enumerable); casted.Add(CreateTKey(12), CreateTValue(5123)); return true; }; } if ((operations & ModifyOperation.Insert) == ModifyOperation.Insert) { yield return (IEnumerable<KeyValuePair<TKey, TValue>> enumerable) => { IDictionary<TKey, TValue> casted = ((IDictionary<TKey, TValue>)enumerable); casted[CreateTKey(541)] = CreateTValue(12); return true; }; } if ((operations & ModifyOperation.Remove) == ModifyOperation.Remove) { yield return (IEnumerable<KeyValuePair<TKey, TValue>> enumerable) => { IDictionary<TKey, TValue> casted = ((IDictionary<TKey, TValue>)enumerable); if (casted.Count() > 0) { var keys = casted.Keys.GetEnumerator(); keys.MoveNext(); casted.Remove(keys.Current); return true; } return false; }; } if ((operations & ModifyOperation.Clear) == ModifyOperation.Clear) { yield return (IEnumerable<KeyValuePair<TKey, TValue>> enumerable) => { IDictionary<TKey, TValue> casted = ((IDictionary<TKey, TValue>)enumerable); if (casted.Count() > 0) { casted.Clear(); return true; } return false; }; } //throw new InvalidOperationException(string.Format("{0:G}", operations)); } /// <summary> /// Used in IDictionary_Generic_Values_Enumeration_ParentDictionaryModifiedInvalidates and /// IDictionary_Generic_Keys_Enumeration_ParentDictionaryModifiedInvalidates. /// Some collections (e.g. ConcurrentDictionary) do not throw an InvalidOperationException /// when enumerating the Keys or Values property and the parent is modified. /// </summary> protected virtual bool IDictionary_Generic_Keys_Values_Enumeration_ThrowsInvalidOperation_WhenParentModified => true; /// <summary> /// Used in IDictionary_Generic_Values_ModifyingTheDictionaryUpdatesTheCollection and /// IDictionary_Generic_Keys_ModifyingTheDictionaryUpdatesTheCollection. /// Some collections (e.g ConcurrentDictionary) use iterators in the Keys and Values properties, /// and do not respond to updates in the base collection. /// </summary> protected virtual bool IDictionary_Generic_Keys_Values_ModifyingTheDictionaryUpdatesTheCollection => true; /// <summary> /// Used in IDictionary_Generic_Keys_Enumeration_Reset and IDictionary_Generic_Values_Enumeration_Reset. /// Typically, the support for Reset in enumerators for the Keys and Values depend on the support for it /// in the parent dictionary. However, some collections (e.g. ConcurrentDictionary) don't. /// </summary> protected virtual bool IDictionary_Generic_Keys_Values_Enumeration_ResetImplemented => ResetImplemented; #endregion #region Item Getter [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_ItemGet_DefaultKey(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); if (!DefaultValueAllowed) { Assert.Throws<ArgumentNullException>(() => dictionary[default(TKey)]); } else { TValue value = CreateTValue(3452); dictionary[default(TKey)] = value; Assert.Equal(value, dictionary[default(TKey)]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_ItemGet_MissingNonDefaultKey_ThrowsKeyNotFoundException(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); Assert.Throws<KeyNotFoundException>(() => dictionary[missingKey]); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_ItemGet_MissingDefaultKey_ThrowsKeyNotFoundException(int count) { if (DefaultValueAllowed) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = default(TKey); while (dictionary.ContainsKey(missingKey)) dictionary.Remove(missingKey); Assert.Throws<KeyNotFoundException>(() => dictionary[missingKey]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_ItemGet_PresentKeyReturnsCorrectValue(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); foreach (KeyValuePair<TKey, TValue> pair in dictionary) { Assert.Equal(pair.Value, dictionary[pair.Key]); } } #endregion #region Item Setter [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_ItemSet_DefaultKey(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); if (!DefaultValueAllowed) { Assert.Throws<ArgumentNullException>(() => dictionary[default(TKey)] = CreateTValue(3)); } else { TValue value = CreateTValue(3452); dictionary[default(TKey)] = value; Assert.Equal(value, dictionary[default(TKey)]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_ItemSet_OnReadOnlyDictionary_ThrowsNotSupportedException(int count) { if (IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); Assert.Throws<NotSupportedException>(() => dictionary[missingKey] = CreateTValue(5312)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_ItemSet_AddsNewValueWhenNotPresent(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); dictionary[missingKey] = CreateTValue(543); Assert.Equal(count + 1, dictionary.Count); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_ItemSet_ReplacesExistingValueWhenPresent(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey existingKey = GetNewKey(dictionary); dictionary.Add(existingKey, CreateTValue(5342)); TValue newValue = CreateTValue(1234); dictionary[existingKey] = newValue; Assert.Equal(count + 1, dictionary.Count); Assert.Equal(newValue, dictionary[existingKey]); } #endregion #region Keys [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Keys_ContainsAllCorrectKeys(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); IEnumerable<TKey> expected = dictionary.Select((pair) => pair.Key); Assert.True(expected.SequenceEqual(dictionary.Keys)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Keys_ModifyingTheDictionaryUpdatesTheCollection(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); ICollection<TKey> keys = dictionary.Keys; int previousCount = keys.Count; if (count > 0) Assert.NotEmpty(keys); dictionary.Clear(); if (IDictionary_Generic_Keys_Values_ModifyingTheDictionaryUpdatesTheCollection) { Assert.Empty(keys); } else { Assert.Equal(previousCount, keys.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Keys_Enumeration_ParentDictionaryModifiedInvalidates(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); ICollection<TKey> keys = dictionary.Keys; IEnumerator<TKey> keysEnum = keys.GetEnumerator(); dictionary.Add(GetNewKey(dictionary), CreateTValue(3432)); if (IDictionary_Generic_Keys_Values_Enumeration_ThrowsInvalidOperation_WhenParentModified) { Assert.Throws<InvalidOperationException>(() => keysEnum.MoveNext()); Assert.Throws<InvalidOperationException>(() => keysEnum.Reset()); } else { keysEnum.MoveNext(); keysEnum.Reset(); } var cur = keysEnum.Current; } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Keys_IsReadOnly(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); ICollection<TKey> keys = dictionary.Keys; Assert.True(keys.IsReadOnly); Assert.Throws<NotSupportedException>(() => keys.Add(CreateTKey(11))); Assert.Throws<NotSupportedException>(() => keys.Clear()); Assert.Throws<NotSupportedException>(() => keys.Remove(CreateTKey(11))); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Keys_Enumeration_Reset(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); ICollection<TKey> keys = dictionary.Keys; var enumerator = keys.GetEnumerator(); if (IDictionary_Generic_Keys_Values_Enumeration_ResetImplemented) enumerator.Reset(); else Assert.Throws<NotSupportedException>(() => enumerator.Reset()); } #endregion #region Values [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Values_ContainsAllCorrectValues(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); IEnumerable<TValue> expected = dictionary.Select((pair) => pair.Value); Assert.True(expected.SequenceEqual(dictionary.Values)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Values_IncludeDuplicatesMultipleTimes(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); int seed = 431; foreach (KeyValuePair<TKey, TValue> pair in dictionary.ToList()) { TKey missingKey = CreateTKey(seed++); while (dictionary.ContainsKey(missingKey)) missingKey = CreateTKey(seed++); dictionary.Add(missingKey, pair.Value); } Assert.Equal(count * 2, dictionary.Values.Count); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Values_ModifyingTheDictionaryUpdatesTheCollection(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); ICollection<TValue> values = dictionary.Values; int previousCount = values.Count; if (count > 0) Assert.NotEmpty(values); dictionary.Clear(); if (IDictionary_Generic_Keys_Values_ModifyingTheDictionaryUpdatesTheCollection) { Assert.Empty(values); } else { Assert.Equal(previousCount, values.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Values_Enumeration_ParentDictionaryModifiedInvalidates(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); ICollection<TValue> values = dictionary.Values; IEnumerator<TValue> valuesEnum = values.GetEnumerator(); dictionary.Add(GetNewKey(dictionary), CreateTValue(3432)); if (IDictionary_Generic_Keys_Values_Enumeration_ThrowsInvalidOperation_WhenParentModified) { Assert.Throws<InvalidOperationException>(() => valuesEnum.MoveNext()); Assert.Throws<InvalidOperationException>(() => valuesEnum.Reset()); } else { valuesEnum.MoveNext(); valuesEnum.Reset(); } var cur = valuesEnum.Current; } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Values_IsReadOnly(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); ICollection<TValue> values = dictionary.Values; Assert.True(values.IsReadOnly); Assert.Throws<NotSupportedException>(() => values.Add(CreateTValue(11))); Assert.Throws<NotSupportedException>(() => values.Clear()); Assert.Throws<NotSupportedException>(() => values.Remove(CreateTValue(11))); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Values_Enumeration_Reset(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); ICollection<TValue> values = dictionary.Values; var enumerator = values.GetEnumerator(); if (IDictionary_Generic_Keys_Values_Enumeration_ResetImplemented) enumerator.Reset(); else Assert.Throws<NotSupportedException>(() => enumerator.Reset()); } #endregion #region Add(TKey, TValue) [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Add_OnReadOnlyDictionary_ThrowsNotSupportedException(int count) { if (IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); Assert.Throws<NotSupportedException>(() => dictionary.Add(CreateTKey(0), CreateTValue(0))); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Add_DefaultKey_DefaultValue(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = default(TKey); TValue value = default(TValue); if (DefaultValueAllowed && !IsReadOnly) { dictionary.Add(missingKey, value); Assert.Equal(count + 1, dictionary.Count); Assert.Equal(value, dictionary[missingKey]); } else if (!IsReadOnly) { Assert.Throws<ArgumentNullException>(() => dictionary.Add(missingKey, value)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Add_DefaultKey_NonDefaultValue(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = default(TKey); TValue value = CreateTValue(1456); if (DefaultValueAllowed && !IsReadOnly) { dictionary.Add(missingKey, value); Assert.Equal(count + 1, dictionary.Count); Assert.Equal(value, dictionary[missingKey]); } else if (!IsReadOnly) { Assert.Throws<ArgumentNullException>(() => dictionary.Add(missingKey, value)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Add_NonDefaultKey_DefaultValue(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); TValue value = default(TValue); dictionary.Add(missingKey, value); Assert.Equal(count + 1, dictionary.Count); Assert.Equal(value, dictionary[missingKey]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Add_NonDefaultKey_NonDefaultValue(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); TValue value = CreateTValue(1342); dictionary.Add(missingKey, value); Assert.Equal(count + 1, dictionary.Count); Assert.Equal(value, dictionary[missingKey]); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Add_DuplicateValue(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); int seed = 321; TValue duplicate = CreateTValue(seed++); while (dictionary.Values.Contains(duplicate)) duplicate = CreateTValue(seed++); dictionary.Add(GetNewKey(dictionary), duplicate); dictionary.Add(GetNewKey(dictionary), duplicate); Assert.Equal(2, dictionary.Values.Count((value) => value.Equals(duplicate))); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_Add_DuplicateKey(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); dictionary.Add(missingKey, CreateTValue(34251)); Assert.Throws<ArgumentException>(() => dictionary.Add(missingKey, CreateTValue(134))); } } #endregion #region ContainsKey [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_ContainsKey_ValidKeyNotContainedInDictionary(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); Assert.False(dictionary.ContainsKey(missingKey)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_ContainsKey_ValidKeyContainedInDictionary(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); dictionary.Add(missingKey, CreateTValue(34251)); Assert.True(dictionary.ContainsKey(missingKey)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_ContainsKey_DefaultKeyNotContainedInDictionary(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); if (DefaultValueAllowed) { // returns false TKey missingKey = default(TKey); while (dictionary.ContainsKey(missingKey)) dictionary.Remove(missingKey); Assert.False(dictionary.ContainsKey(missingKey)); } else { // throws ArgumentNullException Assert.Throws<ArgumentNullException>(() => dictionary.ContainsKey(default(TKey))); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_ContainsKey_DefaultKeyContainedInDictionary(int count) { if (DefaultValueAllowed && !IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = default(TKey); if (!dictionary.ContainsKey(missingKey)) dictionary.Add(missingKey, CreateTValue(5341)); Assert.True(dictionary.ContainsKey(missingKey)); } } #endregion #region Remove(TKey) [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_RemoveKey_OnReadOnlyDictionary_ThrowsNotSupportedException(int count) { if (IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); Assert.Throws<NotSupportedException>(() => dictionary.Remove(CreateTKey(0))); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_RemoveKey_EveryKey(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); Assert.All(dictionary.Keys.ToList(), key => { Assert.True(dictionary.Remove(key)); }); Assert.Empty(dictionary); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_RemoveKey_ValidKeyNotContainedInDictionary(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); Assert.False(dictionary.Remove(missingKey)); Assert.Equal(count, dictionary.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_RemoveKey_ValidKeyContainedInDictionary(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); dictionary.Add(missingKey, CreateTValue(34251)); Assert.True(dictionary.Remove(missingKey)); Assert.Equal(count, dictionary.Count); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_RemoveKey_DefaultKeyNotContainedInDictionary(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); if (DefaultValueAllowed) { TKey missingKey = default(TKey); while (dictionary.ContainsKey(missingKey)) dictionary.Remove(missingKey); Assert.False(dictionary.Remove(missingKey)); } else { Assert.Throws<ArgumentNullException>(() => dictionary.Remove(default(TKey))); } } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_RemoveKey_DefaultKeyContainedInDictionary(int count) { if (DefaultValueAllowed && !IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = default(TKey); dictionary.TryAdd(missingKey, CreateTValue(5341)); Assert.True(dictionary.Remove(missingKey)); } } #endregion #region TryGetValue [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_TryGetValue_ValidKeyNotContainedInDictionary(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); TValue value = CreateTValue(5123); TValue outValue; Assert.False(dictionary.TryGetValue(missingKey, out outValue)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_TryGetValue_ValidKeyContainedInDictionary(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); TValue value = CreateTValue(5123); TValue outValue; dictionary.TryAdd(missingKey, value); Assert.True(dictionary.TryGetValue(missingKey, out outValue)); Assert.Equal(value, outValue); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_TryGetValue_DefaultKeyNotContainedInDictionary(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TValue outValue; if (DefaultValueAllowed) { TKey missingKey = default(TKey); while (dictionary.ContainsKey(missingKey)) dictionary.Remove(missingKey); Assert.False(dictionary.TryGetValue(missingKey, out outValue)); } else { Assert.Throws<ArgumentNullException>(() => dictionary.TryGetValue(default(TKey), out outValue)); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IDictionary_Generic_TryGetValue_DefaultKeyContainedInDictionary(int count) { if (DefaultValueAllowed && !IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = default(TKey); TValue value = CreateTValue(5123); TValue outValue; dictionary.TryAdd(missingKey, value); Assert.True(dictionary.TryGetValue(missingKey, out outValue)); Assert.Equal(value, outValue); } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Contains_ValidPresentKeyWithDefaultValue(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); dictionary.Add(missingKey, default(TValue)); Assert.True(dictionary.Contains(new KeyValuePair<TKey, TValue>(missingKey, default(TValue)))); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Remove_ValidPresentKeyWithDifferentValue(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); TValue present = CreateTValue(324); TValue missing = CreateTValue(5612); while (present.Equals(missing)) missing = CreateTValue(5612); dictionary.Add(missingKey, present); Assert.False(dictionary.Remove(new KeyValuePair<TKey, TValue>(missingKey, missing))); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_Generic_Contains_ValidPresentKeyWithDifferentValue(int count) { if (!IsReadOnly) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); TKey missingKey = GetNewKey(dictionary); TValue present = CreateTValue(324); TValue missing = CreateTValue(5612); while (present.Equals(missing)) missing = CreateTValue(5612); dictionary.Add(missingKey, present); Assert.False(dictionary.Contains(new KeyValuePair<TKey, TValue>(missingKey, missing))); } } #endregion #region ICollection [Theory] [MemberData(nameof(ValidCollectionSizes))] public void ICollection_NonGeneric_CopyTo(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[count]; object[] objarray = new object[count]; dictionary.CopyTo(array, 0); ((ICollection)dictionary).CopyTo(objarray, 0); for (int i = 0; i < count; i++) Assert.Equal(array[i], (KeyValuePair<TKey, TValue>)(objarray[i])); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public override void ICollection_Generic_Contains_DefaultValueWhenNotAllowed(int count) { ICollection<KeyValuePair<TKey, TValue>> collection = GenericIDictionaryFactory(count); if (!DefaultValueAllowed && !IsReadOnly) { if (DefaultValueWhenNotAllowed_Throws) Assert.Throws<ArgumentNullException>(() => collection.Contains(default(KeyValuePair<TKey, TValue>))); else Assert.False(collection.Remove(default(KeyValuePair<TKey, TValue>))); } } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcov = Google.Cloud.OsConfig.V1; using sys = System; namespace Google.Cloud.OsConfig.V1 { /// <summary>Resource name for the <c>OSPolicyAssignment</c> resource.</summary> public sealed partial class OSPolicyAssignmentName : gax::IResourceName, sys::IEquatable<OSPolicyAssignmentName> { /// <summary>The possible contents of <see cref="OSPolicyAssignmentName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}</c>. /// </summary> ProjectLocationOsPolicyAssignment = 1, } private static gax::PathTemplate s_projectLocationOsPolicyAssignment = new gax::PathTemplate("projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}"); /// <summary>Creates a <see cref="OSPolicyAssignmentName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="OSPolicyAssignmentName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static OSPolicyAssignmentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new OSPolicyAssignmentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="OSPolicyAssignmentName"/> with the pattern /// <c>projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="osPolicyAssignmentId"> /// The <c>OsPolicyAssignment</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns>A new instance of <see cref="OSPolicyAssignmentName"/> constructed from the provided ids.</returns> public static OSPolicyAssignmentName FromProjectLocationOsPolicyAssignment(string projectId, string locationId, string osPolicyAssignmentId) => new OSPolicyAssignmentName(ResourceNameType.ProjectLocationOsPolicyAssignment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), osPolicyAssignmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(osPolicyAssignmentId, nameof(osPolicyAssignmentId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="OSPolicyAssignmentName"/> with pattern /// <c>projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="osPolicyAssignmentId"> /// The <c>OsPolicyAssignment</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="OSPolicyAssignmentName"/> with pattern /// <c>projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}</c>. /// </returns> public static string Format(string projectId, string locationId, string osPolicyAssignmentId) => FormatProjectLocationOsPolicyAssignment(projectId, locationId, osPolicyAssignmentId); /// <summary> /// Formats the IDs into the string representation of this <see cref="OSPolicyAssignmentName"/> with pattern /// <c>projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="osPolicyAssignmentId"> /// The <c>OsPolicyAssignment</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="OSPolicyAssignmentName"/> with pattern /// <c>projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}</c>. /// </returns> public static string FormatProjectLocationOsPolicyAssignment(string projectId, string locationId, string osPolicyAssignmentId) => s_projectLocationOsPolicyAssignment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(osPolicyAssignmentId, nameof(osPolicyAssignmentId))); /// <summary> /// Parses the given resource name string into a new <see cref="OSPolicyAssignmentName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="oSPolicyAssignmentName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="OSPolicyAssignmentName"/> if successful.</returns> public static OSPolicyAssignmentName Parse(string oSPolicyAssignmentName) => Parse(oSPolicyAssignmentName, false); /// <summary> /// Parses the given resource name string into a new <see cref="OSPolicyAssignmentName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="oSPolicyAssignmentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="OSPolicyAssignmentName"/> if successful.</returns> public static OSPolicyAssignmentName Parse(string oSPolicyAssignmentName, bool allowUnparsed) => TryParse(oSPolicyAssignmentName, allowUnparsed, out OSPolicyAssignmentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="OSPolicyAssignmentName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="oSPolicyAssignmentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="OSPolicyAssignmentName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string oSPolicyAssignmentName, out OSPolicyAssignmentName result) => TryParse(oSPolicyAssignmentName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="OSPolicyAssignmentName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="oSPolicyAssignmentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="OSPolicyAssignmentName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string oSPolicyAssignmentName, bool allowUnparsed, out OSPolicyAssignmentName result) { gax::GaxPreconditions.CheckNotNull(oSPolicyAssignmentName, nameof(oSPolicyAssignmentName)); gax::TemplatedResourceName resourceName; if (s_projectLocationOsPolicyAssignment.TryParseName(oSPolicyAssignmentName, out resourceName)) { result = FromProjectLocationOsPolicyAssignment(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(oSPolicyAssignmentName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private OSPolicyAssignmentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string osPolicyAssignmentId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; OsPolicyAssignmentId = osPolicyAssignmentId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="OSPolicyAssignmentName"/> class from the component parts of /// pattern <c>projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="osPolicyAssignmentId"> /// The <c>OsPolicyAssignment</c> ID. Must not be <c>null</c> or empty. /// </param> public OSPolicyAssignmentName(string projectId, string locationId, string osPolicyAssignmentId) : this(ResourceNameType.ProjectLocationOsPolicyAssignment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), osPolicyAssignmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(osPolicyAssignmentId, nameof(osPolicyAssignmentId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>OsPolicyAssignment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed /// resource name. /// </summary> public string OsPolicyAssignmentId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationOsPolicyAssignment: return s_projectLocationOsPolicyAssignment.Expand(ProjectId, LocationId, OsPolicyAssignmentId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as OSPolicyAssignmentName); /// <inheritdoc/> public bool Equals(OSPolicyAssignmentName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(OSPolicyAssignmentName a, OSPolicyAssignmentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(OSPolicyAssignmentName a, OSPolicyAssignmentName b) => !(a == b); } public partial class OSPolicyAssignment { /// <summary> /// <see cref="gcov::OSPolicyAssignmentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcov::OSPolicyAssignmentName OSPolicyAssignmentName { get => string.IsNullOrEmpty(Name) ? null : gcov::OSPolicyAssignmentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class OSPolicyAssignmentOperationMetadata { /// <summary> /// <see cref="OSPolicyAssignmentName"/>-typed view over the <see cref="OsPolicyAssignment"/> resource name /// property. /// </summary> public OSPolicyAssignmentName OsPolicyAssignmentAsOSPolicyAssignmentName { get => string.IsNullOrEmpty(OsPolicyAssignment) ? null : OSPolicyAssignmentName.Parse(OsPolicyAssignment, allowUnparsed: true); set => OsPolicyAssignment = value?.ToString() ?? ""; } } public partial class CreateOSPolicyAssignmentRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetOSPolicyAssignmentRequest { /// <summary> /// <see cref="gcov::OSPolicyAssignmentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcov::OSPolicyAssignmentName OSPolicyAssignmentName { get => string.IsNullOrEmpty(Name) ? null : gcov::OSPolicyAssignmentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListOSPolicyAssignmentsRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListOSPolicyAssignmentRevisionsRequest { /// <summary> /// <see cref="gcov::OSPolicyAssignmentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcov::OSPolicyAssignmentName OSPolicyAssignmentName { get => string.IsNullOrEmpty(Name) ? null : gcov::OSPolicyAssignmentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeleteOSPolicyAssignmentRequest { /// <summary> /// <see cref="gcov::OSPolicyAssignmentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcov::OSPolicyAssignmentName OSPolicyAssignmentName { get => string.IsNullOrEmpty(Name) ? null : gcov::OSPolicyAssignmentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using OpenLiveWriter.Api; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.ApplicationFramework.ApplicationStyles; using OpenLiveWriter.CoreServices; namespace OpenLiveWriter.Extensibility.ImageEditing { /// <summary> /// The base class for building an editor for an image decorator. /// </summary> public class ImageDecoratorEditor : UserControl { /// <summary> /// Required designer variable. /// </summary> private Container components = null; public ImageDecoratorEditor() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region 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() { components = new System.ComponentModel.Container(); } #endregion protected enum ControlState { Uninitialized, Loading, Loaded }; protected ControlState EditorState { get { return _loadedState; } } private ControlState _loadedState = ControlState.Uninitialized; private IImageTargetEditor _imageTargetEditor; public void LoadEditor(ImageDecoratorEditorContext context, object state, IImageTargetEditor imageTargetEditor) { _loadedState = ControlState.Loading; _context = context; _state = state; _imageTargetEditor = imageTargetEditor; LoadEditor(); _loadedState = ControlState.Loaded; OnEditorLoaded(); } protected virtual void OnEditorLoaded() { } /// <summary> /// Signal the editor to save its settings and to apply the image decoration. /// </summary> /// <param name="forced">If true, the settings will be applied even if the editor is not fully loaded.</param> protected void SaveSettingsAndApplyDecorator(bool forced) { if (forced || EditorState == ControlState.Loaded) { using (new WaitCursor()) { using (IImageDecoratorUndoUnit undo = EditorContext.CreateUndoUnit()) { OnSaveSettings(); EditorContext.ApplyDecorator(); undo.Commit(); _imageTargetEditor.ImageEditFinished(); } } } } /// <summary> /// Signal the editor to save its settings and to apply the image decoration. /// Note: if the editor is not in Loaded state, this call is a no-op. /// </summary> protected void SaveSettingsAndApplyDecorator() { SaveSettingsAndApplyDecorator(false); } /// <summary> /// Signal the editor to save its settings. /// </summary> /// <param name="forced">If true, the settings will be applied even if the editor is not fully loaded.</param> protected void SaveSettings(bool forced) { if (forced || EditorState == ControlState.Loaded) { using (IImageDecoratorUndoUnit undo = EditorContext.CreateUndoUnit()) { OnSaveSettings(); undo.Commit(); _imageTargetEditor.ImageEditFinished(); } } } /// <summary> /// Signal the editor to save its settings. /// Note: if the editor is not in Loaded state, this call is a no-op. /// </summary> protected void SaveSettings() { SaveSettings(false); } /// <summary> /// Should be implemented by subclasses to save their settings. /// </summary> protected virtual void OnSaveSettings() { } protected virtual void LoadEditor() { } protected IProperties Settings { get { return _context.Settings; } } public virtual FormBorderStyle FormBorderStyle { get { return FormBorderStyle.FixedDialog; } } internal protected ImageDecoratorEditorContext EditorContext { get { return _context; } } private ImageDecoratorEditorContext _context; internal protected object State { get { return _state; } } private object _state; public virtual Size GetPreferredSize() { return new Size(ScaleX(100), ScaleX(100)); } #region High DPI Scaling protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { SaveScale(factor.Width, factor.Height); base.ScaleControl(factor, specified); } protected override void ScaleCore(float dx, float dy) { SaveScale(dx, dy); base.ScaleCore(dx, dy); } private void SaveScale(float dx, float dy) { scale = new PointF(scale.X * dx, scale.Y * dy); } private PointF scale = new PointF(1f, 1f); protected int ScaleX(int x) { return (int)(x * scale.X); } protected int ScaleY(int y) { return (int)(y * scale.Y); } #endregion } }
/* * 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.Data; using System.Reflection; using System.Threading; using log4net; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.MySQL { /// <summary> /// A MySQL Interface for the Grid Server /// </summary> public class MySQLGridData : GridDataBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// MySQL Database Manager /// </summary> private MySQLManager database; /// <summary> /// Better DB manager. Swap-in replacement too. /// </summary> public Dictionary<int, MySQLSuperManager> m_dbconnections = new Dictionary<int, MySQLSuperManager>(); public int m_maxConnections = 10; public int m_lastConnect; public MySQLSuperManager GetLockedConnection() { int lockedCons = 0; while (true) { m_lastConnect++; // Overflow protection if (m_lastConnect == int.MaxValue) m_lastConnect = 0; MySQLSuperManager x = m_dbconnections[m_lastConnect % m_maxConnections]; if (!x.Locked) { x.GetLock(); return x; } lockedCons++; if (lockedCons > m_maxConnections) { lockedCons = 0; Thread.Sleep(1000); // Wait some time before searching them again. m_log.Debug( "WARNING: All threads are in use. Probable cause: Something didnt release a mutex properly, or high volume of requests inbound."); } } } override public void Initialise() { m_log.Info("[MySQLGridData]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException (Name); } /// <summary> /// <para>Initialises Grid interface</para> /// <para> /// <list type="bullet"> /// <item>Loads and initialises the MySQL storage plugin</item> /// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item> /// <item>Check for migration</item> /// </list> /// </para> /// </summary> /// <param name="connect">connect string.</param> override public void Initialise(string connect) { if (connect != String.Empty) { database = new MySQLManager(connect); m_log.Info("Creating " + m_maxConnections + " DB connections..."); for (int i = 0; i < m_maxConnections; i++) { m_log.Info("Connecting to DB... [" + i + "]"); MySQLSuperManager msm = new MySQLSuperManager(); msm.Manager = new MySQLManager(connect); m_dbconnections.Add(i, msm); } } else { m_log.Warn("Using deprecated mysql_connection.ini. Please update database_connect in GridServer_Config.xml and we'll use that instead"); IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini"); string settingHostname = GridDataMySqlFile.ParseFileReadValue("hostname"); string settingDatabase = GridDataMySqlFile.ParseFileReadValue("database"); string settingUsername = GridDataMySqlFile.ParseFileReadValue("username"); string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); string settingPooling = GridDataMySqlFile.ParseFileReadValue("pooling"); string settingPort = GridDataMySqlFile.ParseFileReadValue("port"); database = new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, settingPooling, settingPort); m_log.Info("Creating " + m_maxConnections + " DB connections..."); for (int i = 0; i < m_maxConnections; i++) { m_log.Info("Connecting to DB... [" + i + "]"); MySQLSuperManager msm = new MySQLSuperManager(); msm.Manager = new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, settingPooling, settingPort); m_dbconnections.Add(i, msm); } } // This actually does the roll forward assembly stuff Assembly assem = GetType().Assembly; Migration m = new Migration(database.Connection, assem, "GridStore"); m.Update(); } /// <summary> /// Shuts down the grid interface /// </summary> override public void Dispose() { database.Close(); } /// <summary> /// Returns the plugin name /// </summary> /// <returns>Plugin name</returns> override public string Name { get { return "MySql OpenGridData"; } } /// <summary> /// Returns the plugin version /// </summary> /// <returns>Plugin version</returns> override public string Version { get { return "0.1"; } } /// <summary> /// Returns all the specified region profiles within coordates -- coordinates are inclusive /// </summary> /// <param name="xmin">Minimum X coordinate</param> /// <param name="ymin">Minimum Y coordinate</param> /// <param name="xmax">Maximum X coordinate</param> /// <param name="ymax">Maximum Y coordinate</param> /// <returns>Array of sim profiles</returns> override public RegionProfileData[] GetProfilesInRange(uint xmin, uint ymin, uint xmax, uint ymax) { MySQLSuperManager dbm = GetLockedConnection(); try { Dictionary<string, object> param = new Dictionary<string, object>(); param["?xmin"] = xmin.ToString(); param["?ymin"] = ymin.ToString(); param["?xmax"] = xmax.ToString(); param["?ymax"] = ymax.ToString(); using (IDbCommand result = dbm.Manager.Query( "SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax", param)) { using (IDataReader reader = result.ExecuteReader()) { RegionProfileData row; List<RegionProfileData> rows = new List<RegionProfileData>(); while ((row = dbm.Manager.readSimRow(reader)) != null) rows.Add(row); return rows.ToArray(); } } } catch (Exception e) { dbm.Manager.Reconnect(); m_log.Error(e.Message, e); return null; } finally { dbm.Release(); } } /// <summary> /// Returns up to maxNum profiles of regions that have a name starting with namePrefix /// </summary> /// <param name="name">The name to match against</param> /// <param name="maxNum">Maximum number of profiles to return</param> /// <returns>A list of sim profiles</returns> override public List<RegionProfileData> GetRegionsByName(string namePrefix, uint maxNum) { MySQLSuperManager dbm = GetLockedConnection(); try { Dictionary<string, object> param = new Dictionary<string, object>(); param["?name"] = namePrefix + "%"; using (IDbCommand result = dbm.Manager.Query( "SELECT * FROM regions WHERE regionName LIKE ?name", param)) { using (IDataReader reader = result.ExecuteReader()) { RegionProfileData row; List<RegionProfileData> rows = new List<RegionProfileData>(); while (rows.Count < maxNum && (row = dbm.Manager.readSimRow(reader)) != null) rows.Add(row); return rows; } } } catch (Exception e) { dbm.Manager.Reconnect(); m_log.Error(e.Message, e); return null; } finally { dbm.Release(); } } /// <summary> /// Returns a sim profile from it's location /// </summary> /// <param name="handle">Region location handle</param> /// <returns>Sim profile</returns> override public RegionProfileData GetProfileByHandle(ulong handle) { MySQLSuperManager dbm = GetLockedConnection(); try { Dictionary<string, object> param = new Dictionary<string, object>(); param["?handle"] = handle.ToString(); using (IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param)) { using (IDataReader reader = result.ExecuteReader()) { RegionProfileData row = dbm.Manager.readSimRow(reader); return row; } } } catch (Exception e) { dbm.Manager.Reconnect(); m_log.Error(e.Message, e); return null; } finally { dbm.Release(); } } /// <summary> /// Returns a sim profile from it's UUID /// </summary> /// <param name="uuid">The region UUID</param> /// <returns>The sim profile</returns> override public RegionProfileData GetProfileByUUID(UUID uuid) { MySQLSuperManager dbm = GetLockedConnection(); try { Dictionary<string, object> param = new Dictionary<string, object>(); param["?uuid"] = uuid.ToString(); using (IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE uuid = ?uuid", param)) { using (IDataReader reader = result.ExecuteReader()) { RegionProfileData row = dbm.Manager.readSimRow(reader); return row; } } } catch (Exception e) { dbm.Manager.Reconnect(); m_log.Error(e.Message, e); return null; } finally { dbm.Release(); } } /// <summary> /// Returns a sim profile from it's Region name string /// </summary> /// <returns>The sim profile</returns> override public RegionProfileData GetProfileByString(string regionName) { if (regionName.Length > 2) { MySQLSuperManager dbm = GetLockedConnection(); try { Dictionary<string, object> param = new Dictionary<string, object>(); // Add % because this is a like query. param["?regionName"] = regionName + "%"; // Order by statement will return shorter matches first. Only returns one record or no record. using (IDbCommand result = dbm.Manager.Query( "SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1", param)) { using (IDataReader reader = result.ExecuteReader()) { RegionProfileData row = dbm.Manager.readSimRow(reader); return row; } } } catch (Exception e) { dbm.Manager.Reconnect(); m_log.Error(e.Message, e); return null; } finally { dbm.Release(); } } m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters"); return null; } /// <summary> /// Adds a new profile to the database /// </summary> /// <param name="profile">The profile to add</param> /// <returns>Successful?</returns> override public DataResponse StoreProfile(RegionProfileData profile) { MySQLSuperManager dbm = GetLockedConnection(); try { if (dbm.Manager.insertRegion(profile)) return DataResponse.RESPONSE_OK; else return DataResponse.RESPONSE_ERROR; } finally { dbm.Release(); } } /// <summary> /// Deletes a sim profile from the database /// </summary> /// <param name="uuid">the sim UUID</param> /// <returns>Successful?</returns> //public DataResponse DeleteProfile(RegionProfileData profile) override public DataResponse DeleteProfile(string uuid) { MySQLSuperManager dbm = GetLockedConnection(); try { if (dbm.Manager.deleteRegion(uuid)) return DataResponse.RESPONSE_OK; else return DataResponse.RESPONSE_ERROR; } finally { dbm.Release(); } } /// <summary> /// DEPRECATED. Attempts to authenticate a region by comparing a shared secret. /// </summary> /// <param name="uuid">The UUID of the challenger</param> /// <param name="handle">The attempted regionHandle of the challenger</param> /// <param name="authkey">The secret</param> /// <returns>Whether the secret and regionhandle match the database entry for UUID</returns> override public bool AuthenticateSim(UUID uuid, ulong handle, string authkey) { bool throwHissyFit = false; // Should be true by 1.0 if (throwHissyFit) throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential."); RegionProfileData data = GetProfileByUUID(uuid); return (handle == data.regionHandle && authkey == data.regionSecret); } /// <summary> /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region /// </summary> /// <remarks>This requires a security audit.</remarks> /// <param name="uuid"></param> /// <param name="handle"></param> /// <param name="authhash"></param> /// <param name="challenge"></param> /// <returns></returns> public bool AuthenticateSim(UUID uuid, ulong handle, string authhash, string challenge) { // SHA512Managed HashProvider = new SHA512Managed(); // Encoding TextProvider = new UTF8Encoding(); // byte[] stream = TextProvider.GetBytes(uuid.ToString() + ":" + handle.ToString() + ":" + challenge); // byte[] hash = HashProvider.ComputeHash(stream); return false; } /// <summary> /// Adds a location reservation /// </summary> /// <param name="x">x coordinate</param> /// <param name="y">y coordinate</param> /// <returns></returns> override public ReservationData GetReservationAtPoint(uint x, uint y) { MySQLSuperManager dbm = GetLockedConnection(); try { Dictionary<string, object> param = new Dictionary<string, object>(); param["?x"] = x.ToString(); param["?y"] = y.ToString(); using (IDbCommand result = dbm.Manager.Query( "SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y", param)) { using (IDataReader reader = result.ExecuteReader()) { ReservationData row = dbm.Manager.readReservationRow(reader); return row; } } } catch (Exception e) { dbm.Manager.Reconnect(); m_log.Error(e.Message, e); return null; } finally { dbm.Release(); } } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Relational.Migrations.Infrastructure; using PrepOps.Models; namespace PrepOps.Migrations { [ContextType(typeof(PrepOpsContext))] partial class SecurityModelChanges { public override string Id { get { return "20150714190819_SecurityModelChanges"; } } public override string ProductVersion { get { return "7.0.0-beta5-13549"; } } public override void BuildTargetModel(ModelBuilder builder) { builder .Annotation("SqlServer:ValueGeneration", "Identity"); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id") .GenerateValueOnAdd(); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken(); b.Property<string>("Name"); b.Property<string>("NormalizedName"); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoles"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId"); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoleClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId"); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUserClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .GenerateValueOnAdd(); b.Property<string>("ProviderKey") .GenerateValueOnAdd(); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId"); b.Key("LoginProvider", "ProviderKey"); b.Annotation("Relational:TableName", "AspNetUserLogins"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.Key("UserId", "RoleId"); b.Annotation("Relational:TableName", "AspNetUserRoles"); }); builder.Entity("PrepOps.Models.Activity", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<int>("CampaignId"); b.Property<string>("Description"); b.Property<DateTime>("EndDateTimeUtc"); b.Property<int?>("LocationId"); b.Property<string>("Name"); b.Property<string>("OrganizerId"); b.Property<DateTime>("StartDateTimeUtc"); b.Property<int>("TenantId"); b.Key("Id"); }); builder.Entity("PrepOps.Models.ActivitySignup", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<int?>("ActivityId"); b.Property<DateTime?>("CheckinDateTime"); b.Property<DateTime>("SignupDateTime"); b.Property<string>("UserId"); b.Key("Id"); }); builder.Entity("PrepOps.Models.ApplicationUser", b => { b.Property<string>("Id") .GenerateValueOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken(); b.Property<string>("Email"); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail"); b.Property<string>("NormalizedUserName"); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName"); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUsers"); }); builder.Entity("PrepOps.Models.Campaign", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("Description"); b.Property<DateTime>("EndDateTimeUtc"); b.Property<string>("ImageUrl"); b.Property<int>("ManagingTenantId"); b.Property<string>("Name"); b.Property<string>("OrganizerId"); b.Property<DateTime>("StartDateTimeUtc"); b.Key("Id"); }); builder.Entity("PrepOps.Models.CampaignSponsors", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<int?>("CampaignId"); b.Property<int?>("TenantId"); b.Key("Id"); }); builder.Entity("PrepOps.Models.Location", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("Address1"); b.Property<string>("Address2"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Name"); b.Property<string>("PhoneNumber"); b.Property<string>("PostalCodePostalCode"); b.Property<string>("State"); b.Key("Id"); }); builder.Entity("PrepOps.Models.PostalCodeGeo", b => { b.Property<string>("PostalCode") .GenerateValueOnAdd(); b.Property<string>("City"); b.Property<string>("State"); b.Key("PostalCode"); }); builder.Entity("PrepOps.Models.PrepOpsTask", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<int?>("ActivityId"); b.Property<string>("Description"); b.Property<DateTime?>("EndDateTimeUtc"); b.Property<string>("Name"); b.Property<DateTime?>("StartDateTimeUtc"); b.Property<int?>("TenantId"); b.Key("Id"); }); builder.Entity("PrepOps.Models.TaskUsers", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("Status"); b.Property<DateTime>("StatusDateTimeUtc"); b.Property<string>("StatusDescription"); b.Property<int?>("TaskId"); b.Property<string>("UserId"); b.Key("Id"); }); builder.Entity("PrepOps.Models.Tenant", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("LogoUrl"); b.Property<string>("Name"); b.Property<string>("WebUrl"); b.Key("Id"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Reference("PrepOps.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Reference("PrepOps.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); b.Reference("PrepOps.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("PrepOps.Models.Activity", b => { b.Reference("PrepOps.Models.Campaign") .InverseCollection() .ForeignKey("CampaignId"); b.Reference("PrepOps.Models.Location") .InverseCollection() .ForeignKey("LocationId"); b.Reference("PrepOps.Models.ApplicationUser") .InverseCollection() .ForeignKey("OrganizerId"); b.Reference("PrepOps.Models.Tenant") .InverseCollection() .ForeignKey("TenantId"); }); builder.Entity("PrepOps.Models.ActivitySignup", b => { b.Reference("PrepOps.Models.Activity") .InverseCollection() .ForeignKey("ActivityId"); b.Reference("PrepOps.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("PrepOps.Models.Campaign", b => { b.Reference("PrepOps.Models.Tenant") .InverseCollection() .ForeignKey("ManagingTenantId"); b.Reference("PrepOps.Models.ApplicationUser") .InverseCollection() .ForeignKey("OrganizerId"); }); builder.Entity("PrepOps.Models.CampaignSponsors", b => { b.Reference("PrepOps.Models.Campaign") .InverseCollection() .ForeignKey("CampaignId"); b.Reference("PrepOps.Models.Tenant") .InverseCollection() .ForeignKey("TenantId"); }); builder.Entity("PrepOps.Models.Location", b => { b.Reference("PrepOps.Models.PostalCodeGeo") .InverseCollection() .ForeignKey("PostalCodePostalCode"); }); builder.Entity("PrepOps.Models.PrepOpsTask", b => { b.Reference("PrepOps.Models.Activity") .InverseCollection() .ForeignKey("ActivityId"); b.Reference("PrepOps.Models.Tenant") .InverseCollection() .ForeignKey("TenantId"); }); builder.Entity("PrepOps.Models.TaskUsers", b => { b.Reference("PrepOps.Models.PrepOpsTask") .InverseCollection() .ForeignKey("TaskId"); b.Reference("PrepOps.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using Moq; using Moq.Properties; using Moq.Protected; using Xunit; using System.Web.UI.HtmlControls; using System.Threading; using System.Threading.Tasks; #region #181 // NOTE class without namespace public class _181 { [Fact] public void ReproTest() { var mock = new Mock<IDisposable>(); mock.Object.Dispose(); mock.Verify(d => d.Dispose()); } } #endregion namespace Moq.Tests.Regressions { public class IssueReportsFixture { // @ GitHub #region #54 public class Issue54 { public interface IFoo { void Bar(); } [Fact] public void when_as_disposable_then_succeeds() { var mock = new Mock<IFoo>(); mock.Setup(x => x.Bar()); mock.As<IDisposable>().Setup(x => x.Dispose()); Action<IFoo> testMock = (IFoo foo) => { foo.Bar(); var disposable = foo as IDisposable; if (disposable != null) { disposable.Dispose(); } }; testMock(mock.Object); mock.VerifyAll(); } } #endregion #region 47 & 62 #if !SILVERLIGHT public class Issue47ClassToMock { AutoResetEvent reset = new AutoResetEvent(false); public virtual void M1() { //we're inside the interceptor's stack now //kick off a new thread to a method on ourselves, which will also go through the interceptor Thread th = new Thread(new ThreadStart(M2)); th.Start(); //ensure the thread has started Thread.Sleep(500); //release the thing the thread 'should' be waiting on reset.Set(); //wait for the thread to finish th.Join(); } public virtual void M2() { //this method will get called on the thread, via the interceptor //if the interceptor is locking then we won't get here until after the thread.Join above has //finished, which is blocked waiting on us. reset.WaitOne(); } } [Fact] public void CallsToExternalCodeNotLockedInInterceptor() { var testMock = new Mock<Issue47ClassToMock> { CallBase = true }; testMock.Object.M1(); // <-- This will never return if the interceptor is locking! testMock.Verify(x => x.M1()); testMock.Verify(x => x.M2()); } #endif #endregion #region #78 #if !NET3x && !SILVERLIGHT public interface IIssue78Interface { Issue78TypeOne GetTypeOne(); Issue78TypeTwo GetTypeTwo(); } public class Issue78TypeOne { } public class Issue78TypeTwo { } public class Issue78Sut { public void TestMethod(IIssue78Interface intOne) { Task<Issue78TypeOne> getTypeOneTask = Task<Issue78TypeOne>.Factory.StartNew(() => intOne.GetTypeOne()); Task<Issue78TypeTwo> getTypeTwoTask = Task<Issue78TypeTwo>.Factory.StartNew(() => intOne.GetTypeTwo()); Issue78TypeOne objOne = getTypeOneTask.Result; Issue78TypeTwo objTwo = getTypeTwoTask.Result; } } public class Issue78Tests { [Fact()] public void DoTest() { Mock<IIssue78Interface> mock = new Mock<IIssue78Interface>(); Issue78TypeOne expectedResOne = new Issue78TypeOne(); Issue78TypeTwo expectedResTwo = new Issue78TypeTwo(); mock.Setup(it => it.GetTypeOne()).Returns(expectedResOne); mock.Setup(it => it.GetTypeTwo()).Returns(expectedResTwo); Issue78Sut sut = new Issue78Sut(); sut.TestMethod(mock.Object); mock.VerifyAll(); } } #endif #endregion #region #176 public class Issue176 { public interface ISomeInterface { TResult DoSomething<TResult>(int anInt); int DoSomethingElse(int anInt); } [Fact] public void when_a_mock_doesnt_match_generic_parameters_exception_indicates_generic_parameters() { var mock = new Mock<ISomeInterface>(MockBehavior.Strict); mock.Setup(m => m.DoSomething<int>(0)).Returns(1); try { mock.Object.DoSomething<string>(0); } catch (MockException exception) { var genericTypesRE = new Regex(@"\<.*?\>"); var match = genericTypesRE.Match(exception.Message); Assert.True(match.Success); Assert.Equal("<string>", match.Captures[0].Value, StringComparer.OrdinalIgnoreCase); return; } Assert.True(false, "No exception was thrown when one should have been"); } [Fact] public void when_a_method_doesnt_have_generic_parameters_exception_doesnt_include_brackets() { var mock = new Mock<ISomeInterface>(MockBehavior.Strict); mock.Setup(m => m.DoSomething<int>(0)).Returns(1); try { mock.Object.DoSomethingElse(0); } catch (MockException exception) { var genericTypesRE = new Regex(@"\<.*?\>"); var match = genericTypesRE.Match(exception.Message); Assert.False(match.Success); return; } Assert.True(false, "No exception was thrown when one should have been"); } } #endregion // #176 #region #184 public class Issue184 { public interface ISimpleInterface { void Method(Guid? g); } [Fact] public void strict_mock_accepts_null_as_nullable_guid_value() { var mock = new Mock<ISimpleInterface>(MockBehavior.Strict); mock.Setup(x => x.Method(It.IsAny<Guid?>())); mock.Object.Method(null); mock.Verify(); } } #endregion // #184 #region #252 public class Issue252 { [Fact] public void SetupsWithSameArgumentsInDifferentOrderShouldNotOverwriteEachOther() { var mock = new Mock<ISimpleInterface>(); var a = new MyClass(); var b = new MyClass(); mock.Setup(m => m.Method(a, b)).Returns(1); mock.Setup(m => m.Method(b, a)).Returns(2); Assert.Equal(1, mock.Object.Method(a, b)); Assert.Equal(2, mock.Object.Method(b, a)); } public interface ISimpleInterface { int Method(MyClass a, MyClass b); } public class MyClass { } } #endregion // #252 // Old @ Google Code #region #47 [Fact] public void ShouldReturnListFromDateTimeArg() { var items = new List<string>() { "Foo", "Bar" }; var mock = new Mock<IMyClass>(MockBehavior.Strict); mock .Setup(m => m.GetValuesSince(It.IsAny<DateTime>())) .Returns(items); var actual = mock.Object.GetValuesSince(DateTime.Now).ToList(); Assert.Equal(items.Count, actual.Count); } public interface IMyClass { IEnumerable<string> GetValuesSince(DateTime since); } #endregion #region #48 public class Issue48 { [Fact] public void ExpectsOnIndexer() { var mock = new Mock<ISomeInterface>(); mock.Setup(m => m[0]).Returns("a"); mock.Setup(m => m[1]).Returns("b"); Assert.Equal("a", mock.Object[0]); Assert.Equal("b", mock.Object[1]); Assert.Equal(default(string), mock.Object[2]); } public interface ISomeInterface { string this[int index] { get; set; } } } #endregion #region #52 [Fact] public void ShouldNotOverridePreviousExpectation() { var ids = Enumerable.Range(1, 10); var mock = new Mock<IOverwritingMethod>(MockBehavior.Strict); foreach (var id in ids) { mock.Setup(x => x.DoSomething(id)); } var component = mock.Object; foreach (var id in ids) { component.DoSomething(id); } } public interface IOverwritingMethod { void DoSomething(int id); } #endregion #region #62 public interface ISomething<T> { void DoSomething<U>() where U : T; } [Fact] public void CreatesMockWithGenericsConstraints() { var mock = new Mock<ISomething<object>>(); } #endregion #region #60 public interface IFoo { void DoThings(object arg); } [Fact] public void TwoExpectations() { Mock<IFoo> mocked = new Mock<IFoo>(MockBehavior.Strict); object arg1 = new object(); object arg2 = new object(); mocked.Setup(m => m.DoThings(arg1)); mocked.Setup(m => m.DoThings(arg2)); mocked.Object.DoThings(arg1); mocked.Object.DoThings(arg2); mocked.VerifyAll(); } #endregion #region #21 [Fact] public void MatchesLatestExpectations() { var mock = new Mock<IEvaluateLatest>(); mock.Setup(m => m.Method(It.IsAny<int>())).Returns(0); mock.Setup(m => m.Method(It.IsInRange<int>(0, 20, Range.Inclusive))).Returns(1); mock.Setup(m => m.Method(5)).Returns(2); mock.Setup(m => m.Method(10)).Returns(3); Assert.Equal(3, mock.Object.Method(10)); Assert.Equal(2, mock.Object.Method(5)); Assert.Equal(1, mock.Object.Method(6)); Assert.Equal(0, mock.Object.Method(25)); } public interface IEvaluateLatest { int Method(int value); } #endregion #region #49 [Fact] public void UsesCustomMatchersWithGenerics() { var mock = new Mock<IEvaluateLatest>(); mock.Setup(e => e.Method(IsEqual.To(5))).Returns(1); mock.Setup(e => e.Method(IsEqual.To<int, string>(6, "foo"))).Returns(2); Assert.Equal(1, mock.Object.Method(5)); Assert.Equal(2, mock.Object.Method(6)); } public static class IsEqual { #pragma warning disable 618 [Matcher] public static T To<T>(T value) { return value; } #pragma warning restore 618 public static bool To<T>(T left, T right) { return left.Equals(right); } #pragma warning disable 618 [Matcher] public static T To<T, U>(T value, U value2) { return value; } #pragma warning restore 618 public static bool To<T, U>(T left, T right, U value) { return left.Equals(right); } } #endregion #region #68 [Fact] public void GetMockCastedToObjectThrows() { var mock = new Mock<IAsyncResult>(); object m = mock.Object; Assert.Throws<ArgumentException>(() => Mock.Get(m)); } #endregion #region #69 public interface IFooPtr { IntPtr Get(string input); } [Fact] public void ReturnsIntPtr() { Mock<IFooPtr> mock = new Mock<IFooPtr>(MockBehavior.Strict); IntPtr ret = new IntPtr(3); mock.Setup(m => m.Get("a")).Returns(ret); IntPtr ret3 = mock.Object.Get("a"); Assert.Equal(ret, mock.Object.Get("a")); } #endregion #region #85 public class Issue85 { [Fact] public void FooTest() { // Setup var fooMock = new Mock<Foo>(); fooMock.CallBase = true; fooMock.Setup(o => o.GetBar()).Returns(new Bar()); var bar = ((IFoolery)fooMock.Object).DoStuffToBar(); Assert.NotNull(bar); } public interface IFoolery { Bar DoStuffToBar(); } public class Foo : IFoolery { public virtual Bar GetBar() { return new Bar(); } Bar IFoolery.DoStuffToBar() { return DoWeirdStuffToBar(); } protected internal virtual Bar DoWeirdStuffToBar() { var bar = GetBar(); //Would do stuff here. return bar; } } public class Bar { } } #endregion #region #89 public class Issue89 { [Fact] public void That_last_expectation_should_win() { var mock = new Mock<ISample>(); mock.Setup(s => s.Get(1)).Returns("blah"); mock.Setup(s => s.Get(It.IsAny<int>())).Returns("foo"); mock.Setup(s => s.Get(1)).Returns("bar"); Assert.Equal("bar", mock.Object.Get(1)); } public interface ISample { string Get(int i); } } #endregion #region #128 public class Issue128 { [Fact] public void That_CallBase_on_interface_should_not_throw_exception() { var mock = new Mock<IDataServiceFactory>() { DefaultValue = DefaultValue.Mock, CallBase = true }; var service = mock.Object.GetDataService(); var data = service.GetData(); var result = data.Sum(); Assert.Equal( 0, result ); } public interface IDataServiceFactory { IDataService GetDataService(); } public interface IDataService { IList<int> GetData(); } } #endregion #region #134 public class Issue134 { [Fact] public void Test() { var target = new Mock<IFoo>(); target.Setup(t => t.Submit(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>())); var e = Assert.Throws<MockVerificationException>(() => target.VerifyAll()); Assert.Contains( "IFoo t => t.Submit(It.IsAny<String>(), It.IsAny<String>(), new[] { It.IsAny<Int32>() })", e.Message); } public interface IFoo { void Submit(string mailServer, string from, params int[] toRecipient); } } #endregion #region #136 public class _136 { // Fixed on PropertiesFixture.cs } #endregion #region #138 public class _138 { public interface SuperFoo { string Bar { get; set; } } public interface Foo : SuperFoo { string Baz { get; set; } } [Fact] public void superFooMockSetupAllProperties() { var repo = new MockRepository(MockBehavior.Default); var superFooMock = repo.Create<SuperFoo>(); superFooMock.SetupAllProperties(); var superFoo = superFooMock.Object; superFoo.Bar = "Bar"; Assert.Equal("Bar", superFoo.Bar); } } #endregion #region #145 public class _145 { public interface IResolver { string Resolve<T>(); } public class DataWriter<T> { } public class DataA { } public class DataB { } [Fact] public void ShouldDifferentiateBetweenGenericsParams() { var mock = new Mock<IResolver>(); mock.Setup(m => m.Resolve<DataWriter<DataA>>()).Returns("Success A"); Assert.Equal("Success A", mock.Object.Resolve<DataWriter<DataA>>()); mock.Setup(m => m.Resolve<DataWriter<DataB>>()).Returns("Success B"); Assert.Equal("Success B", mock.Object.Resolve<DataWriter<DataB>>()); Assert.Equal("Success A", mock.Object.Resolve<DataWriter<DataA>>()); } } #endregion #region #111 & #155 public class _111 { [Fact] public void TestTypedParamsWithNoParams() { var mock = new Mock<IParams>(MockBehavior.Strict); mock.Setup(p => p.Submit(It.IsAny<string>(), It.IsAny<int[]>())); mock.Object.Submit("foo"); mock.VerifyAll(); } [Fact] public void TestTypedParams() { var mock = new Mock<IParams>(MockBehavior.Strict); mock.Setup(p => p.Submit(It.IsAny<string>(), It.IsAny<int[]>())); mock.Object.Submit("foo", 0, 1, 2); mock.VerifyAll(); } [Fact] public void TestObjectParamsWithoutParams() { var mock = new Mock<IParams>(MockBehavior.Strict); mock.Setup(p => p.Execute(It.IsAny<int>(), It.IsAny<object[]>())); mock.Object.Execute(1); mock.VerifyAll(); } [Fact] public void TestObjectParams() { var mock = new Mock<IParams>(MockBehavior.Strict); mock.Setup(p => p.Execute(It.IsAny<int>(), It.IsAny<object[]>())); mock.Object.Execute(1, "0", "1", "2"); mock.VerifyAll(); } [Fact] public void TestObjectParamsWithExpectedValues() { var mock = new Mock<IParams>(MockBehavior.Strict); mock.Setup(p => p.Execute(5, "foo", "bar")); Assert.Throws<MockException>(() => mock.Object.Execute(5, "bar", "foo")); mock.Object.Execute(5, "foo", "bar"); mock.Verify(p => p.Execute(5, "foo", "bar")); } [Fact] public void TestObjectParamsWithArray() { var mock = new Mock<IParams>(); mock.Setup(p => p.Execute(It.IsAny<int>(), It.IsAny<string[]>(), It.IsAny<int>())); mock.Object.Execute(1, new string[] { "0", "1" }, 3); mock.Verify(p => p.Execute(It.IsAny<int>(), It.IsAny<object[]>())); mock.Verify(p => p.Execute(It.IsAny<int>(), It.IsAny<string[]>(), It.IsAny<int>())); mock.Verify(p => p.Execute(It.IsAny<int>(), It.IsAny<object[]>(), It.IsAny<int>())); } [Fact] public void TestTypedParamsInEachArgument() { var mock = new Mock<IParams>(MockBehavior.Strict); mock.Setup(p => p.Submit(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())); mock.Object.Submit("foo", 0, 1); mock.Verify(p => p.Submit(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())); mock.Verify(p => p.Submit(It.IsAny<string>(), It.Is<int[]>(a => a.Length == 2))); mock.VerifyAll(); } [Fact] public void TestParamsWithReturnValue() { var mock = new Mock<IParams>(); mock.Setup(x => x.GetValue("Matt")).Returns("SomeString"); var ret = mock.Object.GetValue("Matt"); Assert.Equal("SomeString", ret); } public interface IParams { void Submit(string name, params int[] values); void Execute(int value, params object[] values); string GetValue(string name, params object[] args); } } #endregion #region #159 public class _159 { [Fact] public void ImplicitIntToLong() { int id = 1; var mock = new Mock<IFoo>(); mock.Object.SetIt(id); mock.Verify(x => x.SetIt(id)); } [Fact] public void ImplicitInterface() { var barMock = new Mock<IBar>(); var baz = new Baz(barMock.Object); baz.DoBarFoo(new Foo()); barMock.Verify(x => x.DoFoo(It.IsAny<Foo>())); } public interface IFoo { long Id { get; set; } void SetIt(long it); } public class Foo : IFoo { public long Id { get; set; } public void SetIt(long it) { } } public interface IBar { void DoFoo(IFoo foo); } public class Baz { private readonly IBar _bar; public Baz(IBar bar) { _bar = bar; } public void DoBarFoo(IFoo foo) { _bar.DoFoo(foo); } } } #endregion #region #152 public class _152 { public enum MembershipCreateStatus { Created, Duplicated, Invalid } public interface IMembershipService { int MinPasswordLength { get; } bool ValidateUser(string userName, string password); MembershipCreateStatus CreateUser(string userName, string password, string email); bool ChangePassword(string userName, string oldPassword, string newPassword); } [Fact] public void ShouldReturnEnum() { var provider = new Mock<IMembershipService>(); // For some reason, this particular lambda doesn't let me specify // a method return value for the method even though it returns a // MembershipCreateStatus enum provider.Setup(p => p.CreateUser(string.Empty, string.Empty, string.Empty)).Returns(MembershipCreateStatus.Invalid); Assert.Equal(MembershipCreateStatus.Invalid, provider.Object.CreateUser("", "", "")); } } #endregion #region #153 public class _153 { public struct SomeClass<T> // Struct just to avoid having to implement Equals/GetHashCode { public static implicit operator SomeClass<T>(T t) { return new SomeClass<T>(); } public static SomeClass<T> From(T t) { return t; } } public interface IIfc { int Get(SomeClass<string> id); } public class ImplicitConversionProblem { [Fact] public void ImplicitSetupVerifyAll_Fails() { const string s = "XYZ"; var mock = new Mock<IIfc>(); mock.Setup(ifc => ifc.Get(s)).Returns(17); var result = mock.Object.Get(s); mock.VerifyAll(); // MockVerificationException here Assert.Equal(17, result); } [Fact] public void ExplicitSetupVerifyAll_Works() { const string s = "XYZ"; var mock = new Mock<IIfc>(); mock.Setup(ifc => ifc.Get(SomeClass<string>.From(s))).Returns(17); var result = mock.Object.Get(s); mock.VerifyAll(); Assert.Equal(17, result); } [Fact] public void ExplicitSetupImplicitVerification_Fails() { const string s = "XYZ"; var mock = new Mock<IIfc>(); mock.Setup(ifc => ifc.Get(SomeClass<string>.From(s))).Returns(17); var result = mock.Object.Get(s); // Here the problem can be seen even in the exception message: // Invocation was not performed on the mock: ifc => ifc.Get("XYZ") // -----------------------------------------------------------^ mock.Verify(ifc => ifc.Get(s)); Assert.Equal(17, result); } [Fact] public void ImplicitSetupExplicitVerification_Fails() { const string s = "XYZ"; var mock = new Mock<IIfc>(); mock.Setup(ifc => ifc.Get(s)).Returns(17); var result = mock.Object.Get(s); // This verification passes oddly enough mock.Verify(ifc => ifc.Get(SomeClass<string>.From(s))); // This assert fails, indicating that the setup was not used Assert.Equal(17, result); } } } #endregion #region #146 public class _146 { public interface IFoo { bool Property { get; set; } string StringProperty { get; set; } } [Fact] public void StrictMockPropertySet() { var mock = new Mock<IFoo>(MockBehavior.Strict); mock.SetupSet(v => v.Property = false); Assert.Throws<MockException>(() => mock.VerifySet(v => v.Property = false)); mock.Object.Property = false; mock.VerifySet(v => v.Property = false); } } #endregion #region #158 public class _158 { public class Foo { public virtual void Boo() { Bar(); Bar(); } protected virtual void Bar() { } } #pragma warning disable 618 [Fact(Skip = "This setup doesn't make sense, and xUnit does not provide this message checking capability.")] public void ShouldRenderCustomMessage() { var foo = new Mock<Foo> { CallBase = true }; foo.Protected().Setup("Bar").AtMostOnce().Verifiable("Hello"); foo.Object.Boo(); //Assert.Throws<MockException>("Hello", () => foo.Object.Boo()); } #pragma warning restore 618 } #endregion #region #160 #if !SILVERLIGHT public class _160 { [Fact] public void ShouldMockHtmlControl() { // CallBase was missing var htmlInputTextMock = new Mock<HtmlInputText>() { CallBase = true }; Assert.True(htmlInputTextMock.Object.Visible); } } #endif #endregion #region #161 public class _161 { [Fact] public void InvertEqualObjects() { var foo1 = new Foo { Id = "1" }; var foo = new Foo { Id = "2" }; var dependency = new Mock<IDependency>(); dependency.Setup(x => x.DoThis(foo, foo1)) .Returns(new Foo()); var f = dependency.Object.DoThis(foo, foo1); dependency.Verify(x => x.DoThis(foo, foo1)); dependency.Verify(x => x.DoThis(foo1, foo), Times.Never()); } [Fact(Skip = "Wrong Equals implemention in the report. Won't Fix")] public void ExampleFailingTest() { var foo1 = new Foo(); var foo = new Foo(); var sut = new Perfectly_fine_yet_failing_test(); var dependency = new Mock<IDependency>(); dependency.Setup(x => x.DoThis(foo, foo1)) .Returns(new Foo()); sut.Do(dependency.Object, foo, foo1); dependency.Verify(x => x.DoThis(foo, foo1)); dependency.Verify(x => x.DoThis(foo1, foo), Times.Never()); } public class Perfectly_fine_yet_failing_test { public void Do(IDependency dependency, Foo foo, Foo foo1) { var foo2 = dependency.DoThis(foo, foo1); if (foo2 == null) foo2 = dependency.DoThis(foo1, foo); } } public interface IDependency { Foo DoThis(Foo foo, Foo foo1); } public class Foo { public string Id { get; set; } public override bool Equals(object obj) { return obj is Foo && ((Foo)obj).Id == Id; } public override int GetHashCode() { return base.GetHashCode(); } } } #endregion #region #174 public class _174 { [Fact] public void Test() { var serviceNo1Mock = new Mock<IServiceNo1>(); var collaboratorMock = new Mock<ISomeCollaborator>(); collaboratorMock.Object.Collaborate(serviceNo1Mock.Object); collaboratorMock.Verify(o => o.Collaborate(serviceNo1Mock.Object)); } public interface ISomeCollaborator { void Collaborate(IServiceNo1 serviceNo1); } public interface IServiceNo1 : IEnumerable { } } #endregion #region #177 public class _177 { [Fact] public void Test() { var mock = new Mock<IMyInterface>(); Assert.NotNull(mock.Object); } public interface IMyInterface { void DoStuff<TFrom, TTo>() where TTo : TFrom; } } #endregion #region #184 public class _184 { [Fact] public void Test() { var fooRaised = false; var barRaised = false; var fooMock = new Mock<IFoo>(); var barMock = fooMock.As<IBar>(); fooMock.Object.FooEvent += (s, e) => fooRaised = true; barMock.Object.BarEvent += (s, e) => barRaised = true; fooMock.Raise(m => m.FooEvent += null, EventArgs.Empty); barMock.Raise(m => m.BarEvent += null, EventArgs.Empty); Assert.True(fooRaised); Assert.True(barRaised); } public interface IFoo { event EventHandler FooEvent; } public interface IBar { event EventHandler BarEvent; } } #endregion #region #185 public class _185 { [Fact] public void Test() { var mock = new Mock<IList<string>>(); Assert.Throws<NotSupportedException>(() => mock.Setup(l => l.FirstOrDefault()).Returns("Hello world")); } } #endregion #region #187 public class _187 { [Fact] public void Test() { var mock = new Mock<IGeneric>(); mock.Setup(r => r.Get<Foo.Inner>()).Returns(new Object()); mock.Setup(r => r.Get<Bar.Inner>()).Returns(new Object()); Assert.NotNull(mock.Object.Get<Foo.Inner>()); Assert.NotNull(mock.Object.Get<Bar.Inner>()); } public class Foo { public class Inner { } } public class Bar { public class Inner { } } public interface IGeneric { object Get<T>() where T : new(); } } #endregion #region #183 public class _183 { [Fact] public void Test() { var mock = new Mock<IFoo>(); mock.Setup(m => m.Execute(1)); mock.Setup(m => m.Execute(It.IsInRange(2, 20, Range.Exclusive))); mock.Setup(m => m.Execute(3, "Caption")); mock.Object.Execute(3); mock.Object.Execute(4); mock.Object.Execute(5); var e = Assert.Throws<MockException>(() => mock.Verify(m => m.Execute(0))); Assert.Contains( "\r\nConfigured setups:" + "\r\nm => m.Execute(1), Times.Never" + "\r\nm => m.Execute(It.IsInRange<Int32>(2, 20, Range.Exclusive)), Times.Exactly(3)", e.Message); } [Fact] public void TestGeneric() { var mock = new Mock<IFoo>(); mock.Setup(m => m.Execute<int>(1, 10)); mock.Setup(m => m.Execute<string>(1, "Foo")); mock.Object.Execute(1, 10); var e = Assert.Throws<MockException>(() => mock.Verify(m => m.Execute<int>(1, 1))); Assert.Contains( "\r\nConfigured setups:\r\nm => m.Execute<Int32>(1, 10), Times.Once", e.Message); } [Fact] public void TestNoSetups() { var mock = new Mock<IFoo>(); var e = Assert.Throws<MockException>(() => mock.Verify(m => m.Execute(1))); Assert.Contains("\r\nNo setups configured.", e.Message); } public interface IFoo { void Execute(int param); void Execute(int param, string caption); void Execute<T>(int p, T param); } } #endregion #region #186 public class _186 { [Fact] public void TestVerifyMessage() { var mock = new Mock<Foo>(); mock.Setup(m => m.OnExecute()); var e = Assert.Throws<NotSupportedException>(() => mock.Verify(m => m.Execute())); Assert.True(e.Message.StartsWith("Invalid verify")); } public class Foo { public void Execute() { this.OnExecute(); } public virtual void OnExecute() { throw new NotImplementedException(); } } } #endregion #region #190 public class _190 { [Fact] public void Test() { var mock = new Mock<IDisposable>().As<IComponent>(); mock.SetupAllProperties(); ISite site = new FooSite(); mock.Object.Site = site; Assert.Same(site, mock.Object.Site); } public class FooSite : ISite { public IComponent Component { get { throw new NotImplementedException(); } } public IContainer Container { get { throw new NotImplementedException(); } } public bool DesignMode { get { throw new NotImplementedException(); } } public string Name { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public object GetService(Type serviceType) { throw new NotImplementedException(); } } } #endregion #region #204 public class _204 { [Fact] public void Test() { var mock = new Mock<IRepository>(); mock.Setup(x => x.Select<User>(u => u.Id == 100)) .Returns(new User() { Id = 100 }); var user = mock.Object.Select<User>(usr => usr.Id == 100); Assert.Equal(100, user.Id); mock.Verify(x => x.Select<User>(usr => usr.Id == 100), Times.Once()); user = mock.Object.Select<User>(usr => usr.Id == 101); Assert.Null(user); mock.Verify(x => x.Select<User>(usr => usr.Id == 101), Times.Once()); mock.Verify(x => x.Select<User>(usr => usr.Id == 102), Times.Never()); mock.Verify(x => x.Select<User>(It.IsAny<Expression<Func<User, bool>>>()), Times.Exactly(2)); } public interface IRepository { T Select<T>(Expression<Func<T, bool>> filter) where T : class; } public class User { public int Id { get; set; } } } #endregion #region #205 public class _205 { [Fact] public void Test() { new Mock<IFoo>().SetupAllProperties(); } public interface IFoo { string Error { get; set; } string this[int index] { get; set; } } } #endregion #region #223 public class _223 { [Fact] public void TestSetup() { this.TestSetupHelper<Foo>(); } public void TestSetupHelper<T>() where T : class, IFoo<int> { var expected = 2; var target = new Mock<T>(); target.Setup(p => p.DoInt32(0)).Returns(expected); target.Setup(p => p.DoGeneric(0)).Returns(expected); Assert.Equal(expected, target.Object.DoInt32(0)); Assert.Equal(expected, target.Object.DoGeneric(0)); } public interface IFoo<T> { int DoInt32(int value); T DoGeneric(int value); } public class Foo : IFoo<int> { public virtual int DoInt32(int value) { return 4; } public virtual int DoGeneric(int value) { return 5; } } } #endregion #region #229 public class _229 { [Fact] public void Test() { var target = new Mock<Foo> { CallBase = true }; var raised = false; target.Object.MyEvent += (s, e) => raised = true; target.Object.RaiseMyEvent(); Assert.True(raised); } public class Foo { public virtual event EventHandler MyEvent; public void RaiseMyEvent() { if (this.MyEvent != null) { this.MyEvent(this, EventArgs.Empty); } } } } #endregion #region #230 public class _230 { [Fact] public void ByteArrayCallbackArgumentShouldNotBeNull() { var data = new byte[] { 2, 1, 2 }; var stream = new Mock<Stream>(); stream.SetupGet(m => m.Length) .Returns(data.Length); stream.Setup(m => m.Read(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>())) .Callback<byte[], int, int>((b, o, c) => data.CopyTo(b, 0)) .Returns(data.Length); var contents = new byte[stream.Object.Length]; stream.Object.Read(contents, 0, (int)stream.Object.Length); } } #endregion #region #232 public class _232 { [Fact] public void Test() { var repository = new Mock<IRepository>(); var svc = new Service(repository.Object); svc.Create(); repository.Verify(r => r.Insert(It.IsAny<Foo>()), Times.Once()); repository.Verify(r => r.Insert(It.IsAny<Bar>()), Times.Once()); repository.Verify(r => r.Insert(It.IsAny<IEntity>()), Times.Exactly(2)); } public interface IRepository { void Insert(IEntity entity); } public interface IEntity { } public class Foo : IEntity { } public class Bar : IEntity { } public class Service { private IRepository repository; public Service(IRepository repository) { this.repository = repository; } public void Create() { repository.Insert(new Foo()); repository.Insert(new Bar()); } } } #endregion #region #242 public class _242 { [Fact] public void PropertyChangedTest() { var mock = new Mock<PropertyChangedInherited>(); int callbacks = 0; mock.Object.PropertyChanged += (sender, args) => callbacks++; mock.Raise(m => m.PropertyChanged += null, new PropertyChangedEventArgs("Foo")); Assert.Equal(1, callbacks); } public class PropertyChangedBase : INotifyPropertyChanged { public virtual event PropertyChangedEventHandler PropertyChanged = (s, e) => { }; } public class PropertyChangedInherited : PropertyChangedBase { } } #endregion #region #245 public class _245 { [Fact] public void Test() { var mock = new Mock<ITest>(); ITest instance; instance = mock.Object; } public interface ITest { void Do<T1, T2>() where T2 : T1; } } #endregion #region #251 public class _251 { [Fact] public void Test() { var repositoryMock = new Mock<IRepository<string>>(); var repository = repositoryMock.Object; repository.Save("test"); repositoryMock.Verify(m => m.Save("test")); } public interface IRepository { void Save(string value); } public interface IRepository<T> : IRepository { void Save(T value); } } #endregion #region #256 public class _256 { [Fact] public void TestFinalizeNotMocked() { var mock = new Mock<ClassWithFinalizer>(MockBehavior.Strict); mock.Setup(m => m.Foo).Returns(10); mock.Setup(m => m.Bar).Returns("Hello mocked world!"); var instance = mock.Object; Assert.Equal(10, instance.Foo); } public class ClassWithFinalizer { public virtual int Foo { get; set; } public virtual string Bar { get; set; } ~ClassWithFinalizer() { } } } #endregion #region #261 public class _261 { [Fact] public void Test() { var mock = new Mock<Foo>(); mock.Protected().SetupSet<int>("Status", 42); mock.Object.SetStatus(42); mock.Protected().VerifySet<int>("Status", Times.Once(), 42); } public class Foo { public virtual int Status { get; protected set; } internal void SetStatus(int value) { this.Status = value; } } } #endregion #region #267 public class _267 { public interface IPerformOperation { string Operation(object input); } public class OperationUser { private readonly IPerformOperation m_OperationPerformer; public OperationUser(IPerformOperation operationPerformer) { m_OperationPerformer = operationPerformer; } public string DoOperation(object input) { return m_OperationPerformer.Operation(input); } } public class HelperSetup { private Mock<IPerformOperation> m_OperationStub; public HelperSetup() { m_OperationStub = new Mock<IPerformOperation>(); } [Fact] public void InlineSetupTest() { m_OperationStub.Setup(m => m.Operation(It.IsAny<string>())).Returns<string>(value => "test"); m_OperationStub.Setup(m => m.Operation(It.IsAny<int>())).Returns<int>(value => "25"); var operationUser = new OperationUser(m_OperationStub.Object); var intOperationResult = operationUser.DoOperation(9); var stringOperationResult = operationUser.DoOperation("Hello"); Assert.Equal("25", intOperationResult); Assert.Equal("test", stringOperationResult); } [Fact] public void HelperSetupTest() { SetupOperationStub<string>(value => "test"); SetupOperationStub<int>(value => "25"); var operationUser = new OperationUser(m_OperationStub.Object); var intOperationResult = operationUser.DoOperation(9); var stringOperationResult = operationUser.DoOperation("Hello"); Assert.Equal("25", intOperationResult); Assert.Equal("test", stringOperationResult); } private void SetupOperationStub<T>(Func<T, string> valueFunction) { m_OperationStub.Setup(m => m.Operation(It.IsAny<T>())).Returns<T>(valueFunction); } } } #endregion #region #273 #if !SILVERLIGHT public class _273 { [Fact] public void WhenMockingAnExternalInterface_ThenItWorks() { Assert.NotNull(new Mock<ClassLibrary1.IFoo>().Object); Assert.NotNull(Mock.Of<ClassLibrary1.IFoo>()); Assert.NotNull(new Mock<ClassLibrary1.Foo>().Object); Assert.NotNull(new Mock<ClassLibrary2.IBar>().Object); Assert.NotNull(Mock.Of<ClassLibrary2.IBar>()); Assert.NotNull(new Mock<ClassLibrary2.Bar>().Object); Assert.NotNull(new Mock<Baz>().Object); } public class Baz : ClassLibrary2.Bar { } } #endif #endregion #region #325 public class _325 { [Fact] public void SubscribingWorks() { var target = new Mock<Foo> { CallBase = true }; target.As<IBar>(); var bar = (IBar)target.Object; var raised = false; bar.SomeEvent += (sender, e) => raised = true; target.As<IBar>().Raise(b => b.SomeEvent += null, EventArgs.Empty); Assert.True(raised); } [Fact] public void UnsubscribingWorks() { var target = new Mock<Foo> { CallBase = true }; target.As<IBar>(); var bar = (IBar)target.Object; var raised = false; EventHandler handler = (sender, e) => raised = true; bar.SomeEvent += handler; bar.SomeEvent -= handler; target.As<IBar>().Raise(b => b.SomeEvent += null, EventArgs.Empty); Assert.False(raised); } public class Foo { } public interface IBar { event EventHandler SomeEvent; } } #endregion #region #326 #if !SILVERLIGHT public class _326 { [Fact] public void ShouldSupportMockingWinFormsControl() { var foo = new Mock<System.Windows.Forms.Control>(); var bar = foo.Object; } } #endif #endregion #region Recursive issue public class RecursiveFixture { [Fact] public void TestRecursive() { var mock = new Mock<ControllerContext>() { DefaultValue = DefaultValue.Mock }; mock.Setup(c => c.HttpContext.Response.Write("stuff")); mock.Object.HttpContext.Response.Write("stuff"); mock.Object.HttpContext.Response.ShouldEncode = true; Assert.Throws<MockException>(() => mock.VerifySet( c => c.HttpContext.Response.ShouldEncode = It.IsAny<bool>(), Times.Never())); } public class ControllerContext { public virtual HttpContext HttpContext { get; set; } } public abstract class HttpContext { protected HttpContext() { } public virtual HttpResponse Response { get { throw new NotImplementedException(); } } } public abstract class HttpResponse { protected HttpResponse() { } public virtual bool ShouldEncode { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public virtual void Write(string s) { throw new NotImplementedException(); } } } #endregion #region #250 /// <summary> /// Silverlight MethodInfo protected constructor is internal, unlike desktop .NET /// </summary> public class _250 { [Fact] public void Test() { var target = new Mock<MethodInfo>(); Assert.NotNull(target.Object); } } #endregion #region Matcher should work with Convert public class MatcherConvertFixture { public interface IFoo { string M(long l); } [Fact] public void MatcherDoesNotIgnoreConvert() { var mock = new Mock<IFoo>(MockBehavior.Strict); mock.Setup(x => x.M(int.Parse("2"))).Returns("OK"); Assert.Equal("OK", mock.Object.M(2L)); } } #endregion } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using NUnit.Framework.Internal; using NUnit.Compatibility; using System.Collections; using System; using System.Reflection; namespace NUnit.Framework.Constraints { /// <summary> /// Delegate used to delay evaluation of the actual value /// to be used in evaluating a constraint /// </summary> public delegate TActual ActualValueDelegate<TActual>(); /// <summary> /// The Constraint class is the base of all built-in constraints /// within NUnit. It provides the operator overloads used to combine /// constraints. /// </summary> public abstract class Constraint : IConstraint { Lazy<string> _displayName; #region Constructor /// <summary> /// Construct a constraint with optional arguments /// </summary> /// <param name="args">Arguments to be saved</param> protected Constraint(params object[] args) { Arguments = args; _displayName = new Lazy<string>(() => { var type = this.GetType(); var displayName = type.Name; if (type.GetTypeInfo().IsGenericType) displayName = displayName.Substring(0, displayName.Length - 2); if (displayName.EndsWith("Constraint", StringComparison.Ordinal)) displayName = displayName.Substring(0, displayName.Length - 10); return displayName; }); } #endregion #region Properties /// <summary> /// The display name of this Constraint for use by ToString(). /// The default value is the name of the constraint with /// trailing "Constraint" removed. Derived classes may set /// this to another name in their constructors. /// </summary> public virtual string DisplayName { get { return _displayName.Value; } } /// <summary> /// The Description of what this constraint tests, for /// use in messages and in the ConstraintResult. /// </summary> public virtual string Description { get; protected set; } /// <summary> /// Arguments provided to this Constraint, for use in /// formatting the description. /// </summary> public object[] Arguments { get; private set; } /// <summary> /// The ConstraintBuilder holding this constraint /// </summary> public ConstraintBuilder Builder { get; set; } #endregion #region Abstract and Virtual Methods /// <summary> /// Applies the constraint to an actual value, returning a ConstraintResult. /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>A ConstraintResult</returns> public abstract ConstraintResult ApplyTo<TActual>(TActual actual); /// <summary> /// Applies the constraint to an ActualValueDelegate that returns /// the value to be tested. The default implementation simply evaluates /// the delegate but derived classes may override it to provide for /// delayed processing. /// </summary> /// <param name="del">An ActualValueDelegate</param> /// <returns>A ConstraintResult</returns> public virtual ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del) { #if ASYNC if (AsyncInvocationRegion.IsAsyncOperation(del)) using (var region = AsyncInvocationRegion.Create(del)) return ApplyTo(region.WaitForPendingOperationsToComplete(del())); #endif return ApplyTo(GetTestObject(del)); } #pragma warning disable 3006 /// <summary> /// Test whether the constraint is satisfied by a given reference. /// The default implementation simply dereferences the value but /// derived classes may override it to provide for delayed processing. /// </summary> /// <param name="actual">A reference to the value to be tested</param> /// <returns>A ConstraintResult</returns> public virtual ConstraintResult ApplyTo<TActual>(ref TActual actual) { return ApplyTo(actual); } #pragma warning restore 3006 /// <summary> /// Retrieves the value to be tested from an ActualValueDelegate. /// The default implementation simply evaluates the delegate but derived /// classes may override it to provide for delayed processing. /// </summary> /// <param name="del">An ActualValueDelegate</param> /// <returns>Delegate evaluation result</returns> protected virtual object GetTestObject<TActual>(ActualValueDelegate<TActual> del) { return del(); } #endregion #region ToString Override /// <summary> /// Default override of ToString returns the constraint DisplayName /// followed by any arguments within angle brackets. /// </summary> /// <returns></returns> public override string ToString() { string rep = GetStringRepresentation(); return this.Builder == null ? rep : string.Format("<unresolved {0}>", rep); } /// <summary> /// Returns the string representation of this constraint /// </summary> protected virtual string GetStringRepresentation() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("<"); sb.Append(DisplayName.ToLower()); foreach (object arg in Arguments) { sb.Append(" "); sb.Append(_displayable(arg)); } sb.Append(">"); return sb.ToString(); } private static string _displayable(object o) { if (o == null) return "null"; string fmt = o is string ? "\"{0}\"" : "{0}"; return string.Format(System.Globalization.CultureInfo.InvariantCulture, fmt, o); } #endregion #region Operator Overloads /// <summary> /// This operator creates a constraint that is satisfied only if both /// argument constraints are satisfied. /// </summary> public static Constraint operator &(Constraint left, Constraint right) { IResolveConstraint l = (IResolveConstraint)left; IResolveConstraint r = (IResolveConstraint)right; return new AndConstraint(l.Resolve(), r.Resolve()); } /// <summary> /// This operator creates a constraint that is satisfied if either /// of the argument constraints is satisfied. /// </summary> public static Constraint operator |(Constraint left, Constraint right) { IResolveConstraint l = (IResolveConstraint)left; IResolveConstraint r = (IResolveConstraint)right; return new OrConstraint(l.Resolve(), r.Resolve()); } /// <summary> /// This operator creates a constraint that is satisfied if the /// argument constraint is not satisfied. /// </summary> public static Constraint operator !(Constraint constraint) { IResolveConstraint r = (IResolveConstraint)constraint; return new NotConstraint(r.Resolve()); } #endregion #region Binary Operators /// <summary> /// Returns a ConstraintExpression by appending And /// to the current constraint. /// </summary> public ConstraintExpression And { get { ConstraintBuilder builder = this.Builder; if (builder == null) { builder = new ConstraintBuilder(); builder.Append(this); } builder.Append(new AndOperator()); return new ConstraintExpression(builder); } } /// <summary> /// Returns a ConstraintExpression by appending And /// to the current constraint. /// </summary> public ConstraintExpression With { get { return this.And; } } /// <summary> /// Returns a ConstraintExpression by appending Or /// to the current constraint. /// </summary> public ConstraintExpression Or { get { ConstraintBuilder builder = this.Builder; if (builder == null) { builder = new ConstraintBuilder(); builder.Append(this); } builder.Append(new OrOperator()); return new ConstraintExpression(builder); } } #endregion #region After Modifier #if !PORTABLE /// <summary> /// Returns a DelayedConstraint.WithRawDelayInterval with the specified delay time. /// </summary> /// <param name="delay">The delay, which defaults to milliseconds.</param> /// <returns></returns> public DelayedConstraint.WithRawDelayInterval After(int delay) { return new DelayedConstraint.WithRawDelayInterval(new DelayedConstraint( Builder == null ? this : Builder.Resolve(), delay)); } /// <summary> /// Returns a DelayedConstraint with the specified delay time /// and polling interval. /// </summary> /// <param name="delayInMilliseconds">The delay in milliseconds.</param> /// <param name="pollingInterval">The interval at which to test the constraint.</param> /// <returns></returns> public DelayedConstraint After(int delayInMilliseconds, int pollingInterval) { return new DelayedConstraint( Builder == null ? this : Builder.Resolve(), delayInMilliseconds, pollingInterval); } #endif #endregion #region IResolveConstraint Members /// <summary> /// Resolves any pending operators and returns the resolved constraint. /// </summary> IConstraint IResolveConstraint.Resolve() { return Builder == null ? this : Builder.Resolve(); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using CodeSmith.Engine; using CslaGenerator.Metadata; using CslaGenerator.Util; using DBSchemaInfo.Base; namespace CslaGenerator.CodeGen { /// <summary> /// Summary description for SprocTemplateHelper. /// </summary> public class SprocTemplateHelper : CodeTemplate { #region Private fields private readonly ICatalog _catalog = GeneratorController.Catalog; private CslaObjectInfo _info; private Criteria _criteria = new Criteria(); private bool _criteriaDefined; private CslaObjectInfo _topLevelObject; private bool _topLevelCollectiontHasNoGetParams; private readonly List<DuplicateTables> _correlationNames = new List<DuplicateTables>(); private int _innerJoins; #endregion #region Private struct protected struct DuplicateTables { internal string PropertyName; internal string TableName; internal string ColumnName; internal int Order; } #endregion #region Public Properties public CslaGeneratorUnit CurrentUnit { get; set; } [Browsable(false)] public ICatalog Catalog { get { return _catalog; } } public CslaObjectInfo Info { get { return _info; } set { _info = value; } } /*public bool IncludeParentProperties { get { return _includeParentProperties; } set { _includeParentProperties = value; } }*/ protected bool CriteriaDefined { get { return _criteriaDefined; } } public Criteria Criteria { get { return _criteria; } set { _criteria = value; _criteriaDefined = true; } } #endregion public void Init(CslaObjectInfo info) { _topLevelObject = info; if (_topLevelObject.ObjectType.IsCollectionType()) { _topLevelCollectiontHasNoGetParams = true; foreach (var crit in info.CriteriaObjects) { if ((crit.GetOptions.DataPortal || crit.GetOptions.Factory || crit.GetOptions.Procedure) && crit.Properties.Count > 0) { _topLevelCollectiontHasNoGetParams = false; break; } } } } #region Accessories public string GetSchema(IResultObject table, bool fullSchema) { if (!Info.Parent.GenerationParams.GenerateQueriesWithSchema) return ""; if (fullSchema) return "[" + table.ObjectSchema + "]."; return table.ObjectSchema + "."; } private void StoreCorrelationNames(CslaObjectInfo info) { _correlationNames.Clear(); var writeCorr = new DuplicateTables(); var vpc = new ValuePropertyCollection(); /*if (IncludeParentProperties) vpc.AddRange(info.GetParentValueProperties());*/ vpc.AddRange(info.GetAllValueProperties()); for (var vp = 0; vp < vpc.Count; vp++) { var count = 1; for (var prop = 0; prop < vp; prop++) { var readCorr = _correlationNames[prop]; if (readCorr.PropertyName != vpc[vp].Name) { if (readCorr.TableName == vpc[vp].DbBindColumn.ObjectName && readCorr.ColumnName == vpc[vp].DbBindColumn.ColumnName) { if (readCorr.Order >= count) count = readCorr.Order + 1; } } } writeCorr.PropertyName = vpc[vp].Name; writeCorr.TableName = vpc[vp].DbBindColumn.ObjectName; writeCorr.ColumnName = vpc[vp].DbBindColumn.ColumnName; writeCorr.Order = count; _correlationNames.Add(writeCorr); } } private string GetCorrelationName(ValueProperty prop) { foreach (var correlationName in _correlationNames) { if (correlationName.PropertyName == prop.Name) { if (correlationName.Order > 1) return correlationName.TableName + correlationName.Order; return correlationName.TableName; } } MessageBox.Show(@"Property " + prop.Name + @" not found.", @"Error!"); return ""; } public string GetDataTypeString(CslaObjectInfo info, string propName) { var prop = GetValuePropertyByName(info,propName); if (prop == null) throw new ArgumentException("Parameter '" + propName + "' does not have a corresponding ValueProperty. Make sure a ValueProperty with the same name exists"); if (prop.DbBindColumn == null) throw new ArgumentException("Property '" + propName + "' does not have it's DbBindColumn initialized."); return GetDataTypeString(prop.DbBindColumn); } public string GetDataTypeString(CriteriaProperty col) { if (col.DbBindColumn.Column != null) return GetDataTypeString(col.DbBindColumn); var prop = Info.ValueProperties.Find(col.Name); if (prop != null) return GetDataTypeString(prop.DbBindColumn); throw new ArgumentException("No column information for this criteria property: " + col.Name); } public string GetDataTypeString(DbBindColumn col) { var nativeType = col.NativeType.ToLower(); var sb = new StringBuilder(); if (nativeType == "varchar" || nativeType == "nvarchar" || nativeType == "char" || nativeType == "nchar" || nativeType == "binary" || nativeType == "varbinary") { sb.Append(col.NativeType); sb.Append("("); sb.Append(col.Column.ColumnLength >= 0 ? col.Column.ColumnLength.ToString() : "MAX"); sb.Append(")"); } else if (nativeType == "decimal" || nativeType == "numeric") { sb.Append(col.NativeType); sb.Append("("); sb.Append(col.Column.ColumnLength.ToString()); sb.Append(", "); sb.Append(col.Column.ColumnScale.ToString()); sb.Append(")"); } else sb.Append(col.NativeType); return sb.ToString(); } public string GetColumnString(CriteriaProperty param) { if (param.DbBindColumn.Column != null) return GetColumnString(param.DbBindColumn); var prop = Info.ValueProperties.Find(param.Name); if (prop != null) return GetColumnString(prop.DbBindColumn); throw new ArgumentException("No column information for this criteria property: " + param.Name); } public string GetColumnString(DbBindColumn col) { return col.ColumnName; } public string GetTableString(CriteriaProperty param) { if (param.DbBindColumn.Column != null) return GetTableString(param.DbBindColumn); var prop = Info.ValueProperties.Find(param.Name); if (prop != null) return GetTableString(prop.DbBindColumn); throw new ArgumentException("No table information for this criteria property: " + param.Name); } public string GetTableString(DbBindColumn col) { return col.ObjectName; } #endregion #region SELECT core public string GetSelect(CslaObjectInfo info, Criteria crit, bool includeParentObjects, bool isCollectionSearchWhereClause, int level, bool dontInnerJoinUp) { var collType = info.ObjectType.IsCollectionType(); if (collType) info = FindChildInfo(info, info.ItemType); var dataOrigin = "table"; // find out where the data come from foreach (var prop in info.GetAllValueProperties()) { if (!prop.IsDatabaseBound || prop.DbBindColumn.Column == null) continue; if (prop.DbBindColumn.ColumnOriginType == ColumnOriginType.View) { dataOrigin = "view"; break; } } StoreCorrelationNames(info); var sb = new StringBuilder(); sb.Append(Environment.NewLine); sb.Append(Indent(2) + "/* Get " + info.ObjectName + " from " + dataOrigin + " */" + Environment.NewLine); sb.Append(GetSelectFields(info, level)); if (dontInnerJoinUp) sb.Append(GetFromClause(crit, info, false)); else sb.Append(isCollectionSearchWhereClause ? GetFromClause(crit, info, true) : GetFromClause(crit, info, includeParentObjects)); sb.Append(isCollectionSearchWhereClause ? GetSearchWhereClause(_topLevelObject, info, crit) : GetWhereClause(info, crit, includeParentObjects)); return NormalizeNewLineAtEndOfFile(sb.ToString()); } private static string NormalizeNewLineAtEndOfFile(string statement) { var uni = Environment.NewLine.ToCharArray(); statement = statement.TrimEnd(uni); statement = statement.TrimEnd(uni); statement = statement.TrimEnd(uni); statement = statement.Replace(Environment.NewLine + Environment.NewLine + Environment.NewLine, Environment.NewLine + Environment.NewLine); return statement; } public string GetChildSelects(CslaObjectInfo info, Criteria crit, bool isCollectionSearchWhereClause, int level, bool dontInnerJoinUp) { level++; if (info.ObjectType.IsCollectionType()) info = FindChildInfo(info, info.ItemType); var sb = new StringBuilder(); var first = true; foreach (var childProp in info.GetAllChildProperties()) { var childInfo = FindChildInfo(info, childProp.TypeName); if (childInfo != null && childProp.LoadingScheme == LoadingScheme.ParentLoad) { if (!first) sb.Append(Environment.NewLine); else first = false; if (level > 2) sb.Append(Environment.NewLine); sb.Append(GetSelect(childInfo, crit, true, isCollectionSearchWhereClause, level, dontInnerJoinUp)); sb.Append(GetChildSelects(childInfo, crit, isCollectionSearchWhereClause, level, dontInnerJoinUp)); } } return NormalizeNewLineAtEndOfFile(sb.ToString()); } public string MissingForeignKeys(Criteria crit, CslaObjectInfo info, int level, bool dontInnerJoinUp) { var result = string.Empty; level++; if (info.ObjectType.IsCollectionType()) info = FindChildInfo(info, info.ItemType); foreach (var childProp in info.GetAllChildProperties()) { var childInfo = FindChildInfo(info, childProp.TypeName); if (childInfo != null && childProp.LoadingScheme == LoadingScheme.ParentLoad) { var temp = MissingForeignKeys(crit, childInfo, level, dontInnerJoinUp); if (temp != string.Empty) { if (result != string.Empty) result += ", "; result += temp; } } } if (level > 2) { var tables = GetTables(crit, info, true); if (tables.Count > 1) { var problemTables = new List<IResultObject>(); var parentTables = GetTablesParent(crit, info); foreach (var table in tables) { if (parentTables.Contains(table)) continue; var fkFound = false; var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(table); SortKeys(fKeys, parentTables); fKeys = FilterDuplicateConstraintTables(fKeys, info.GetDatabaseBoundValueProperties()); foreach (var key in fKeys) { if (tables.IndexOf(key.PKTable) >= 0) { fkFound = true; break; } } if (!fkFound) { problemTables.Add(table); } } foreach (var table in tables) { if (parentTables.Contains(table)) continue; var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(table); SortKeys(fKeys, parentTables); fKeys = FilterDuplicateConstraintTables(fKeys, info.GetDatabaseBoundValueProperties()); foreach (var key in fKeys) { for (var index = 0; index < problemTables.Count; index++) { var problemTable = problemTables[index]; if (table == problemTable) continue; if (key.PKTable.ObjectName == problemTable.ObjectName) { problemTables.Remove(problemTable); if (problemTables.Count == 0) break; } } if (problemTables.Count == 0) break; } if (problemTables.Count == 0) break; } foreach (var problemTable in problemTables) { if (result != string.Empty) result += ", "; result += problemTable.ObjectName; } } } return result; } private string GetFromClause(Criteria crit, CslaObjectInfo info, bool includeParentObjects) { _innerJoins = 0; var tables = GetTables(crit, info, includeParentObjects); SortTables(tables); CheckTableJoins(tables); var sb = new StringBuilder(); sb.Append(Indent(2) + "FROM "); if (tables.Count == 1) { sb.AppendFormat("{0}[{1}]", GetSchema(tables[0], true), tables[0].ObjectName); sb.Append(Environment.NewLine); return sb.ToString(); } if (tables.Count > 1) { var usedTables = new List<IResultObject>(); var firstJoin = true; var parentTables = GetTablesParent(crit, info); foreach (var table in tables) { var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(table); // sort key.PKTable so key.PKTable that reference the parent table come before other keys // and // Primary keys come before other constraint references to the parent object SortKeys(fKeys, parentTables); fKeys = FilterDuplicateConstraintTables(fKeys, info.GetDatabaseBoundValueProperties()); foreach (var key in fKeys) { // check if this key is needed in the join if (tables.IndexOf(key.PKTable) >= 0) { if (key.PKTable != key.ConstraintTable) { if (firstJoin) { sb.AppendFormat("{0}[{1}]", GetSchema(key.ConstraintTable, true), key.ConstraintTable.ObjectName); sb.Append(Environment.NewLine + Indent(3)); sb.Append("INNER JOIN "); sb.AppendFormat("{0}[{1}]", GetSchema(key.PKTable, true), key.PKTable.ObjectName); sb.Append(" ON "); var firstKeyColl = true; foreach (var kcPair in key.Columns) { if (firstKeyColl) firstKeyColl = false; else { sb.Append(" AND"); sb.Append(Environment.NewLine + Indent(6)); } sb.Append(GetAliasedFieldString(key.ConstraintTable, kcPair.FKColumn)); sb.Append(" = "); sb.Append(GetAliasedFieldString(key.PKTable, kcPair.PKColumn)); _innerJoins++; } usedTables.Add(key.PKTable); usedTables.Add(key.ConstraintTable); firstJoin = false; } else { if (usedTables.Contains(key.PKTable) && usedTables.Contains(key.ConstraintTable)) { sb.Append(" AND"); sb.Append(Environment.NewLine + Indent(6)); } else { sb.Append(Environment.NewLine + Indent(3)); sb.Append("INNER JOIN "); sb.AppendFormat("{0}[{1}]", GetSchema(key.PKTable, true), key.PKTable.ObjectName); sb.Append(" ON "); usedTables.Add(key.PKTable); } var firstKeyColl = true; foreach (var kcPair in key.Columns) { if (firstKeyColl) firstKeyColl = false; else { sb.Append(" AND"); sb.Append(Environment.NewLine + Indent(6)); } sb.Append(GetAliasedFieldString(key.ConstraintTable, kcPair.FKColumn)); sb.Append(" = "); sb.Append(GetAliasedFieldString(key.PKTable, kcPair.PKColumn)); _innerJoins++; } } } } } } sb.Append(Environment.NewLine); return sb.ToString(); } return String.Empty; } private string InjectParentPropertiesOnResultSet(CslaObjectInfo info, ref bool first, ref List<IColumnInfo> usedByParentProperties) { var tables = GetTables(new Criteria(info), info, false); var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(tables[0]); fKeys = FilterDuplicateConstraintTables(fKeys, info.GetDatabaseBoundValueProperties()); var sb = new StringBuilder(); var parentProperties = info.GetParentValueProperties(); foreach (var key in fKeys) { if (key.PKTable != key.ConstraintTable) { foreach (var prop in parentProperties) { if (!prop.IsDatabaseBound || prop.DbBindColumn.Column == null) continue; if (prop.DbBindColumn.ObjectName == key.PKTable.ObjectName) { foreach (var t in key.Columns) { if (prop.DbBindColumn.ColumnName == t.PKColumn.ColumnName) { usedByParentProperties.Add(t.FKColumn); if (!first) sb.Append("," + Environment.NewLine); else first = false; sb.Append(Indent(3)); if (t.FKColumn.DbType == DbType.StringFixedLength) { sb.Append("RTRIM("); sb.Append(GetAliasedFieldString(key.ConstraintTable, t.FKColumn) + ")"); } else { sb.Append(GetAliasedFieldString(key.ConstraintTable, t.FKColumn)); } } } } } } } return sb.ToString(); } private string GetSelectFields(CslaObjectInfo info, int level) { var sb = new StringBuilder(); sb.Append(Indent(2) + "SELECT" + Environment.NewLine); var first = true; var usedByParentProperties = new List<IColumnInfo>(); if (level > 2 || (_topLevelCollectiontHasNoGetParams && level > 1)) sb.Append(InjectParentPropertiesOnResultSet(info, ref first, ref usedByParentProperties)); var vpc = new ValuePropertyCollection(); /*if (IncludeParentProperties) vpc.AddRange(info.GetParentValueProperties());*/ //t.FKColumn vpc.AddRange(info.GetAllValueProperties()); foreach (var prop in vpc) { if (!prop.IsDatabaseBound || prop.DbBindColumn.Column == null) continue; if (prop.DataAccess != ValueProperty.DataAccessBehaviour.WriteOnly) { var duplicatedColumn = false; foreach (var parentProperty in usedByParentProperties) { if (parentProperty == prop.DbBindColumn.Column) { duplicatedColumn = true; break; } } if (duplicatedColumn) continue; if (!first) sb.Append("," + Environment.NewLine); else first = false; sb.Append(Indent(3)); if (prop.DbBindColumn.DataType.ToString() == "StringFixedLength") { sb.Append("RTRIM("); sb.Append("[" + GetCorrelationName(prop) + "].[" + prop.DbBindColumn.ColumnName + "]" + ")"); sb.Append(String.Format(" AS [{0}]", prop.ParameterName)); } else { sb.Append("[" + GetCorrelationName(prop) + "].[" + prop.DbBindColumn.ColumnName + "]"); if (prop.DbBindColumn.ColumnName != prop.ParameterName) { sb.Append(String.Format(" AS [{0}]", prop.ParameterName)); } } } } sb.Append(Environment.NewLine); return sb.ToString(); } private static string GetAliasedFieldString(DbBindColumn col) { return "[" + col.ObjectName + "].[" + col.ColumnName + "]"; } public static string GetAliasedFieldString(IResultObject table, IColumnInfo col) { return "[" + table.ObjectName + "].[" + col.ColumnName + "]"; } public static ValueProperty GetValuePropertyByName(CslaObjectInfo info, string propName) { var prop = info.ValueProperties.Find(propName); if (prop == null) prop = info.InheritedValueProperties.Find(propName); // check itemType to see if this is collection if (prop == null && info.ItemType != String.Empty) { var itemInfo = info.Parent.CslaObjects.Find(info.ItemType); if (itemInfo != null) prop = GetValuePropertyByName(itemInfo, propName); } return prop; } private string GetWhereClause(CslaObjectInfo info, Criteria crit, bool includeParentObjects) { var originalInfo = info; var parentInfo = info.FindParentObject(); if (parentInfo != null) { var temp = parentInfo; while (temp != null) { temp = temp.FindParentObject(); if (temp != null) { parentInfo = temp; } } info = parentInfo; } var chidParamDBC = new List<DbBindColumn>(); if (includeParentObjects) { var collType = info.Parent.CslaObjects.Find(originalInfo.ParentType); foreach (var childCrit in collType.CriteriaObjects) { if (crit.GetOptions.Procedure && crit.GetOptions.ProcedureName != string.Empty) { foreach (var param in childCrit.Properties) { chidParamDBC.Add(param.DbBindColumn); } } } } var sb = new StringBuilder(); var first = true; var parmCounter = 0; foreach (var parm in crit.Properties) { parmCounter++; var dbc = parm.DbBindColumn; if (dbc == null || dbc.Column == null) { var prop = GetValuePropertyByName(info, parm.Name); if (prop != null) dbc = prop.DbBindColumn; } if (dbc != null && dbc.Column != null) { if (first) { sb.Append(Indent(2) + "WHERE" + Environment.NewLine); first = false; } else sb.Append(" AND" + Environment.NewLine); if (includeParentObjects && chidParamDBC.Count >= parmCounter) sb.Append(Indent(3) + GetAliasedFieldString(chidParamDBC[parmCounter - 1])); else sb.Append(Indent(3) + GetAliasedFieldString(dbc)); sb.Append(" = @"); sb.Append(parm.ParameterName); } } sb.Append(SoftDeleteWhereClause(originalInfo, crit, first)); return sb.ToString(); } private string GetSearchWhereClause(CslaObjectInfo info, CslaObjectInfo originalInfo, Criteria crit) { var sb = new StringBuilder(); var first = true; foreach (CriteriaProperty parm in crit.Properties) { var dbc = parm.DbBindColumn; if (dbc == null) { var prop = GetValuePropertyByName(info, parm.Name); dbc = prop.DbBindColumn; } if (dbc != null) { if (first) { sb.Append(Indent(2) + "WHERE" + Environment.NewLine); first = false; } else sb.Append(" AND" + Environment.NewLine); sb.Append(Indent(3)); if (!parm.Nullable) { sb.Append(GetAliasedFieldString(dbc)); sb.Append(" = @"); sb.Append(parm.ParameterName); } else { if (IsStringType(dbc.DataType)) { sb.Append("ISNULL("); sb.Append(GetAliasedFieldString(dbc)); sb.Append(", '')"); if (dbc.DataType.ToString() == "StringFixedLength") { sb.Append(" LIKE RTRIM(@"); sb.Append(parm.ParameterName); sb.Append(")"); } else { sb.Append(" LIKE @"); sb.Append(parm.ParameterName); } } else { sb.Append(GetAliasedFieldString(dbc)); sb.Append(" = ISNULL(@"); sb.Append(parm.ParameterName); sb.Append(", "); sb.Append(GetAliasedFieldString(dbc)); sb.Append(")"); } } } } sb.Append(SoftDeleteWhereClause(originalInfo, crit, first)); sb.Append(Environment.NewLine); return sb.ToString(); } #endregion #region Tables public List<IResultObject> GetTablesSelect(CslaObjectInfo info) { var tables = new List<IResultObject>(); var allValueProps = new ValuePropertyCollection(); if (!info.ObjectType.IsCollectionType()) allValueProps = info.GetAllValueProperties(); else { var item = info.Parent.CslaObjects.Find(info.ItemType); allValueProps = item.GetAllValueProperties(); } foreach (var prop in allValueProps) { if (!prop.IsDatabaseBound || prop.DbBindColumn.Column == null) continue; if ((prop.DataAccess != ValueProperty.DataAccessBehaviour.WriteOnly || prop.PrimaryKey != ValueProperty.UserDefinedKeyBehaviour.Default) && (prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table || prop.DbBindColumn.ColumnOriginType == ColumnOriginType.View)) { var table = (IResultObject) prop.DbBindColumn.DatabaseObject; if (!tables.Contains(table)) tables.Add(table); } } return tables; } // patch for using SProcs as source of RO/NVL public string GetSprocSchemaSelect(CslaObjectInfo info) { var result = string.Empty; //var tables = new List<IResultObject>(); var allValueProps = new ValuePropertyCollection(); if (!info.ObjectType.IsCollectionType()) allValueProps = info.GetAllValueProperties(); else { var item = info.Parent.CslaObjects.Find(info.ItemType); allValueProps = item.GetAllValueProperties(); } foreach (var prop in allValueProps) { if (!prop.IsDatabaseBound || prop.DbBindColumn.Column == null) continue; result = prop.DbBindColumn.SchemaName; break; } return result; } public List<IResultObject> GetTablesInsert(CslaObjectInfo info) { var tables = new List<IResultObject>(); foreach (var prop in info.GetAllValueProperties()) { if (!prop.IsDatabaseBound || prop.DbBindColumn.Column == null) continue; if (prop.DataAccess != ValueProperty.DataAccessBehaviour.ReadOnly && prop.DataAccess != ValueProperty.DataAccessBehaviour.UpdateOnly && prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table) { var table = (IResultObject)prop.DbBindColumn.DatabaseObject; if (!tables.Contains(table)) { tables.Add(table); } } } return tables; } public List<IResultObject> GetTablesUpdate(CslaObjectInfo info) { var tables = new List<IResultObject>(); foreach (var prop in info.GetAllValueProperties()) { if (!prop.IsDatabaseBound || prop.DbBindColumn.Column == null) continue; if (prop.DataAccess != ValueProperty.DataAccessBehaviour.ReadOnly && prop.DataAccess != ValueProperty.DataAccessBehaviour.CreateOnly && prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table) { var table = (IResultObject)prop.DbBindColumn.DatabaseObject; if (!tables.Contains(table)) tables.Add(table); } } return tables; } public List<IResultObject> GetTablesDelete(CslaObjectInfo info) { var tablesCol = new List<IResultObject>(); foreach (var prop in info.GetAllValueProperties()) { if (!prop.IsDatabaseBound || prop.DbBindColumn.Column == null) continue; if (prop.DataAccess != ValueProperty.DataAccessBehaviour.ReadOnly && prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table) { var table = (IResultObject)prop.DbBindColumn.DatabaseObject; if (!tablesCol.Contains(table)) tablesCol.Add(table); } } return tablesCol; } private static List<IResultObject> GetTables(Criteria crit) { var tablesCol = new List<IResultObject>(); foreach (var parm in crit.Properties) { if (parm.DbBindColumn.ColumnOriginType == ColumnOriginType.Table || parm.DbBindColumn.ColumnOriginType == ColumnOriginType.View) { var table = (IResultObject)parm.DbBindColumn.DatabaseObject; if (table != null && !tablesCol.Contains(table)) tablesCol.Add(table); } } return tablesCol; } public static List<IResultObject> GetTablesParent(Criteria crit, CslaObjectInfo info) { var tablesCol = new List<IResultObject>(); var parent = info.FindParentObject(); if (parent != null) tablesCol.AddRange(GetTables(crit, parent, true)); return tablesCol; } public static List<IResultObject> GetTables(Criteria crit, CslaObjectInfo info, bool includeParentObjects) { return GetTables(crit, info, includeParentObjects, true); } public static List<IResultObject> GetTables(Criteria crit, CslaObjectInfo info, bool includeParentObjects, bool includeCriteria) { return GetTables(crit, info, includeParentObjects, includeCriteria, true); } public static List<IResultObject> GetTables(Criteria crit, CslaObjectInfo info, bool includeParentObjects, bool includeCriteria, bool includeAllValueProperties) { var tablesCol = new List<IResultObject>(); if (includeParentObjects) { var parent = info.FindParentObject(); if (parent != null) tablesCol.AddRange(GetTables(crit, parent, true, includeCriteria, includeAllValueProperties)); } foreach (var prop in info.GetAllValueProperties()) { if (!prop.IsDatabaseBound || prop.DbBindColumn.Column == null) continue; if (includeAllValueProperties) { if (prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table || prop.DbBindColumn.ColumnOriginType == ColumnOriginType.View) { var table = (IResultObject) prop.DbBindColumn.DatabaseObject; if (!tablesCol.Contains(table)) tablesCol.Add(table); } } else { if (prop.PrimaryKey != ValueProperty.UserDefinedKeyBehaviour.Default) { var table = (IResultObject) prop.DbBindColumn.DatabaseObject; if (!tablesCol.Contains(table)) tablesCol.Add(table); } } } if (includeCriteria) { foreach (var table in GetTables(crit)) { if (!tablesCol.Contains(table)) tablesCol.Add(table); } } return tablesCol; } public List<IResultObject> GetTablesParentProperties(Criteria crit, CslaObjectInfo childInfo, CslaObjectInfo topObjectInfo, bool parentFound) { return GetTablesParentProperties(crit, childInfo, topObjectInfo, parentFound, false); } public List<IResultObject> GetTablesParentProperties(Criteria crit, CslaObjectInfo childInfo, CslaObjectInfo topObjectInfo, bool parentFound, bool excludeCriteria) { var isRootOrRootItem = childInfo.IsRootOrRootItem(); var parentInsertOnly = false; if (childInfo.CanHaveParentProperties()) parentInsertOnly = childInfo.ParentInsertOnly; var tablesCol = new List<IResultObject>(); if (!parentFound) { var parentInfo = childInfo.FindParentObject(); if (parentInfo != null) { tablesCol.AddRange(GetTablesParentProperties(crit, parentInfo, topObjectInfo, ReferenceEquals(parentInfo, topObjectInfo))); } if (!isRootOrRootItem) { parentInfo = topObjectInfo.Parent.CslaObjects.Find(topObjectInfo.ParentType); if (parentInfo != null) isRootOrRootItem = parentInfo.IsRootType(); } } foreach (var prop in childInfo.GetAllValueProperties()) { if (!prop.IsDatabaseBound || prop.DbBindColumn.Column == null) continue; if (parentInsertOnly && prop.PrimaryKey == ValueProperty.UserDefinedKeyBehaviour.Default) continue; if (prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table || prop.DbBindColumn.ColumnOriginType == ColumnOriginType.View) { var table = (IResultObject) prop.DbBindColumn.DatabaseObject; if (parentInsertOnly || isRootOrRootItem) { if (!tablesCol.Contains(table)) tablesCol.Add(table); } else { foreach (var parentProp in childInfo.GetParentValueProperties()) { if (!parentProp.IsDatabaseBound || parentProp.DbBindColumn.Column == null) continue; if (prop.DbBindColumn.ColumnOriginType == ColumnOriginType.Table && parentProp.DbBindColumn.ColumnOriginType == ColumnOriginType.Table) { table = GetFKTableObjectForParentProperty(parentProp, table); if (table != null) if (!tablesCol.Contains(table)) tablesCol.Add(table); } } } } } if (!excludeCriteria) { foreach (var table in GetTables(crit)) { if (!tablesCol.Contains(table)) tablesCol.Add(table); } } return tablesCol; } public void SortTables(List<IResultObject> tables) { var tArray = tables.ToArray(); //Sort collection so that tables that reference others come after reference tables for (var i = 0; i < tArray.Length - 1; i++) { var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(tArray[i]); if (fKeys.Count > 0) { for (var j = i + 1; j < tArray.Length; j++) { var table = tArray[i]; if (!ReferencesTable(fKeys, tArray[j])) { tArray[i] = tArray[j]; tArray[j] = table; } } } } tables.Clear(); tables.AddRange(tArray); } public static void SortKeys(List<IForeignKeyConstraint> fKeys, List<IResultObject> parentTables) { if (parentTables.Count == 0) return; var sorted = false; var parentTable = parentTables[0].ObjectName; var fkArray = fKeys.ToArray(); // sort collection so that keys that reference the parent table come before other keys for (var i = 0; i < fkArray.Length; i++) { if (parentTable == fkArray[i].PKTable.ObjectName) { var fkey = fkArray[i]; for (var j = i; j > 0; j--) { fkArray[j] = fkArray[j- 1]; } fkArray[0] = fkey; sorted = true; } } if (sorted) { fKeys.Clear(); fKeys.AddRange(fkArray); } // sort collection so that Primary Keys that reference the parent table come before other non-primary keys sorted = false; for (var i = 0; i < fkArray.Length; i++) { if (parentTable == fkArray[i].PKTable.ObjectName && fkArray[i].Columns[0].PKColumn.IsPrimaryKey) { var fkey = fkArray[i]; for (var j = i; j > 0; j--) { fkArray[j] = fkArray[j- 1]; } fkArray[0] = fkey; sorted = true; } } if (sorted) { fKeys.Clear(); fKeys.AddRange(fkArray); } } /* // debugging only private void ShowKeys(string header, List<IForeignKeyConstraint> fKeys1, List<IForeignKeyConstraint> fKeys2) { var msg = "Original\r\n"; foreach (var fKey in fKeys1) { msg += fKey.ConstraintName + ": "; msg += fKey.ConstraintTable.ObjectName + " - "; msg += fKey.Columns[0].FKColumn.ColumnName+ " / "; msg += fKey.PKTable.ObjectName + " - "; msg += fKey.Columns[0].PKColumn.ColumnName + Environment.NewLine; } msg += "\r\nRefactored\r\n"; foreach (var fKey in fKeys2) { msg += fKey.ConstraintName + ": "; msg += fKey.ConstraintTable.ObjectName + " - "; msg += fKey.Columns[0].FKColumn.ColumnName+ " / "; msg += fKey.PKTable.ObjectName + " - "; msg += fKey.Columns[0].PKColumn.ColumnName + Environment.NewLine; } MessageBox.Show(msg, header); } */ public static List<IForeignKeyConstraint> FilterDuplicateConstraintTables(List<IForeignKeyConstraint> fKeys, ValuePropertyCollection vpc) { var filteredKeys = new List<IForeignKeyConstraint>(); if (fKeys.Count == 0) return filteredKeys; var fkArray = fKeys.ToArray(); // filter constraint table references not included by ValueProperty.FKConstraint foreach (var key in fkArray) { var match = false; foreach (var vp in vpc) { if (vp.FKConstraint == key.ConstraintName) { match = true; break; } } if (match) filteredKeys.Add(key); } // filter duplicate references to the same constraint table foreach (var t in fkArray) { var exists = false; foreach (var key in filteredKeys) { if (t.ConstraintTable.ObjectName == key.ConstraintTable.ObjectName && t.PKTable.ObjectName == key.PKTable.ObjectName) exists = true; } if (!exists) filteredKeys.Add(t); } return filteredKeys; } private static bool ReferencesTable(List<IForeignKeyConstraint> constraints, IResultObject pkTable) { foreach (var fkc in constraints) { if (fkc.PKTable == pkTable) return true; } return false; } public void CheckTableJoins(List<IResultObject> tables) { if (tables.Count < 2) { return; } var tablesMissingJoins = new List<IResultObject>(); foreach (var t in tables) { if (!HasJoin(t, tables)) tablesMissingJoins.Add(t); } if (tablesMissingJoins.Count > 0) AddJoinTables(tables, tablesMissingJoins); } private void AddJoinTables(List<IResultObject> tables, List<IResultObject> tablesMissingJoins) { var joinTables = FindJoinTables(tables, tablesMissingJoins); foreach (var t in joinTables) { if (!tables.Contains(t)) tables.Add(t); } } private List<IResultObject> FindJoinTables(List<IResultObject> tables, List<IResultObject> missingTables) { var joinTables = new List<IResultObject>(); foreach (var t in Catalog.Tables) { var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(t); if (fKeys.Count > 1) { var tableCount = 0; var missingTableCount = 0; foreach (var key in fKeys) { if (missingTables.Contains(key.PKTable)) missingTableCount++; else if (tables.Contains(key.PKTable)) tableCount++; } if (missingTableCount > 1 || (tableCount > 0 && missingTableCount > 0)) { joinTables.Add(t); } } } return joinTables; } private bool HasJoin(IResultObject table, List<IResultObject> tables) { foreach (var key in Catalog.ForeignKeyConstraints.GetConstraintsFor(table)) { if (tables.Contains(key.PKTable)) return true; } foreach (var t in tables) { if (t != table) { foreach (var key in Catalog.ForeignKeyConstraints.GetConstraintsFor(t)) { if (key.PKTable == table) return true; } } } return false; } #endregion #region Helpers public bool IsCollectionType(CslaObjectType cslaType) { if (cslaType.IsEditableRootCollection() || cslaType.IsEditableChildCollection() || cslaType.IsDynamicEditableRootCollection() || cslaType.IsReadOnlyCollection()) return true; return false; } public CslaObjectInfo FindChildInfo(CslaObjectInfo info, string name) { return info.Parent.CslaObjects.Find(name); } /// <summary> /// Gets all child objects of a CslaObjectInfo. /// Gets all child properties: collection and non-collection, including inherited. /// </summary> /// <param name="info">The CslaOnjectInfo.</param> /// <returns>A CslaObjectInfo array holding the objects for all child properties.</returns> public CslaObjectInfo[] GetAllChildItems(CslaObjectInfo info) { var list = new List<CslaObjectInfo>(); foreach (var cp in info.GetAllChildProperties()) { var childInfo = FindChildInfo(info, cp.TypeName); if (childInfo.ObjectType.IsCollectionType()) { var ci = FindChildInfo(info, cp.TypeName); if (ci != null) { ci = FindChildInfo(info, ci.ItemType); if (ci != null) list.Add(ci); } } else { list.Add(childInfo); } } return list.ToArray(); } /// <summary> /// Gets the full hierarchy of all child object names of a CslaObjectInfo. /// </summary> /// <param name="info">The CslaOnjectInfo.</param> /// <returns>A string array holding the objects for the hierarchy of all child properties.</returns> public string[] GetAllChildItemsInHierarchy(CslaObjectInfo info) { var list = new List<string>(); foreach (var obj in GetAllChildItems(info)) { list.Add(obj.ObjectName); list.AddRange(GetAllChildItemsInHierarchy(obj)); } return list.ToArray(); } public static bool IsStringType(DbType dbType) { if (dbType == DbType.String || dbType == DbType.StringFixedLength || dbType == DbType.AnsiString || dbType == DbType.AnsiStringFixedLength) return true; return false; } public static string Indent(int len) { return new string(' ', len * 4); } public string GetFKColumnForParentProperty(ValueProperty parentProp, IResultObject childTable) { if (parentProp.DbBindColumn.ColumnOriginType != ColumnOriginType.Table) return parentProp.ParameterName; var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(childTable); foreach (var tks in fKeys) { if (tks.PKTable == parentProp.DbBindColumn.DatabaseObject) { foreach (var colPair in tks.Columns) { if (colPair.PKColumn == parentProp.DbBindColumn.Column) return colPair.FKColumn.ColumnName; } } } return string.Empty; } public string GetFKTableForParentProperty(ValueProperty parentProp, IResultObject childTable) { if (parentProp.DbBindColumn.ColumnOriginType != ColumnOriginType.Table) return parentProp.ParameterName; var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(childTable); foreach (var fKey in fKeys) { if (fKey.PKTable == parentProp.DbBindColumn.DatabaseObject) { foreach (var colPair in fKey.Columns) { if (colPair.PKColumn == parentProp.DbBindColumn.Column) return colPair.FKColumn.FKConstraint.ConstraintTable.ObjectName; } } } return string.Empty; } public IResultObject GetFKTableObjectForParentProperty(ValueProperty parentProp, IResultObject childTable) { if (parentProp.DbBindColumn.ColumnOriginType != ColumnOriginType.Table) return null; var fKeys = Catalog.ForeignKeyConstraints.GetConstraintsFor(childTable); foreach (var fKey in fKeys) { if (fKey.PKTable == parentProp.DbBindColumn.DatabaseObject) { foreach (var colPair in fKey.Columns) { if (colPair.PKColumn == parentProp.DbBindColumn.Column) return colPair.FKColumn.FKConstraint.ConstraintTable; } } } return null; } public static bool IsChildSelfLoaded(CslaObjectInfo info) { var selfLoad = false; var parent = info.Parent.CslaObjects.Find(info.ParentType); if (parent != null) { foreach (var childProp in parent.GetAllChildProperties()) { if (childProp.TypeName == info.ObjectName) { selfLoad = childProp.LoadingScheme == LoadingScheme.SelfLoad; break; } } } return selfLoad; } #endregion #region SoftDelete methods private bool IgnoreFilterCriteria(Criteria crit) { foreach (var prop in crit.Properties) { if (prop.DbBindColumn.ColumnName == Info.Parent.Params.SpBoolSoftDeleteColumn && prop.DbBindColumn.Column.DbType == DbType.Boolean) return true; if (prop.DbBindColumn.ColumnName == Info.Parent.Params.SpIntSoftDeleteColumn && (prop.DbBindColumn.Column.DbType == DbType.Int16 || prop.DbBindColumn.Column.DbType == DbType.Int32 || prop.DbBindColumn.Column.DbType == DbType.Int64)) return true; } return false; } private string SoftDeleteWhereClause(CslaObjectInfo info, Criteria crit, bool first) { if (IgnoreFilterCriteria(crit)) return ""; var sb = new StringBuilder(); List<IResultObject> tablesCol; if (info.CanHaveParentProperties() && !info.ParentInsertOnly) tablesCol = GetTablesParentProperties(crit, info, info, true, true); else tablesCol = GetTables(crit, info, false, false, false); SortTables(tablesCol); CheckTableJoins(tablesCol); foreach (var table in tablesCol) { sb.Append(AppendSoftDeleteWhereClause(info, table, first)); first = false; } return sb.ToString(); } private string AppendSoftDeleteWhereClause(CslaObjectInfo info, IResultObject table, bool first) { var sb = new StringBuilder(); if (UseBoolSoftDelete(table, IgnoreFilter(info))) { if (!first) sb.Append(" AND" + Environment.NewLine); else { sb.Append(Indent(2) + "WHERE" + Environment.NewLine); } sb.Append(Indent(3)); sb.Append("[" + table.ObjectName + "].[" + Info.Parent.Params.SpBoolSoftDeleteColumn + "] = 'true'"); } return sb.ToString(); } public bool IgnoreFilter(CslaObjectInfo info) { if (Info.Parent.Params.SpIgnoreFilterWhenSoftDeleteIsParam) { foreach (var prop in info.GetAllValueProperties()) { if (!prop.IsDatabaseBound || prop.DbBindColumn.Column == null) continue; if (prop.Name == Info.Parent.Params.SpBoolSoftDeleteColumn) return true; } } return false; } /// <summary> /// Uses the bool soft delete. /// </summary> /// <param name="tables">The tables to check.</param> /// <param name="ignoreFilterEnabled">if set to <c>true</c> [ignore filter enabled].</param> /// <returns></returns> public bool UseBoolSoftDelete(List<IResultObject> tables, bool ignoreFilterEnabled) { if (!string.IsNullOrEmpty(Info.Parent.Params.SpBoolSoftDeleteColumn) && !ignoreFilterEnabled) { foreach (var table in tables) { if (!UseBoolSoftDelete(table, ignoreFilterEnabled)) return false; } return true; } return false; } private bool UseBoolSoftDelete(IResultObject table, bool ignoreFilterEnabled) { if (!string.IsNullOrEmpty(Info.Parent.Params.SpBoolSoftDeleteColumn) && !ignoreFilterEnabled) { /*for (var col = 0; col < table.Columns.Count; col++) { if (table.Columns[col].ColumnName == Info.Parent.Params.SpBoolSoftDeleteColumn && table.Columns[col].DbType == DbType.Boolean) { return true; } }*/ return table.Columns.Any(t => t.ColumnName == Info.Parent.Params.SpBoolSoftDeleteColumn && t.DbType == DbType.Boolean); } return false; } public bool UseIntSoftDelete(List<IResultObject> tables, bool ignoreFilterEnabled) { if (!string.IsNullOrEmpty(Info.Parent.Params.SpIntSoftDeleteColumn) && !ignoreFilterEnabled) { foreach (var table in tables) { if (!UseIntSoftDelete(table)) return false; } return true; } return false; } private bool UseIntSoftDelete(IResultObject table) { /*for (var col = 0; col < table.Columns.Count; col++) { if (table.Columns[col].ColumnName == Info.Parent.Params.SpIntSoftDeleteColumn && (table.Columns[col].DbType == DbType.Int16 || table.Columns[col].DbType == DbType.Int32 || table.Columns[col].DbType == DbType.Int64)) return true; } return false;*/ return table.Columns.Any(t => t.ColumnName == Info.Parent.Params.SpIntSoftDeleteColumn && (t.DbType == DbType.Int16 || t.DbType == DbType.Int32 || t.DbType == DbType.Int64)); } #endregion } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using Microsoft.Win32; using HtmlHelp; using HtmlHelp.UIComponents; using HtmlHelp.ChmDecoding; using AxSHDocVw; namespace HtmlHelpViewer { /// <summary> /// This class implements the main form for the htmlhelp viewer /// </summary> public class Viewer : System.Windows.Forms.Form, IHelpViewer { private static Viewer _current = null; private string LM_Key = @"Software\Klaus Weisser\HtmlHelpViewer\"; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Splitter splitter1; private System.Windows.Forms.Panel panel3; private AxSHDocVw.AxWebBrowser axWebBrowser1; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabContents; private System.Windows.Forms.TabPage tabIndex; private System.Windows.Forms.TabPage tabSearch; private HtmlHelp.UIComponents.TocTree tocTree1; private HtmlHelp.UIComponents.helpIndex helpIndex1; private HtmlHelp.UIComponents.helpSearch helpSearch2; private System.ComponentModel.IContainer components; private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem miFile; private System.Windows.Forms.MenuItem miOpen; private System.Windows.Forms.MenuItem miMerge; private System.Windows.Forms.MenuItem miSep1; private System.Windows.Forms.MenuItem miPrint; private System.Windows.Forms.MenuItem miSep2; private System.Windows.Forms.MenuItem miExit; private System.Windows.Forms.ToolBar toolBar1; private System.Windows.Forms.ImageList imgToolBar; private System.Windows.Forms.ToolBarButton btnBack; private System.Windows.Forms.ToolBarButton btnNext; private System.Windows.Forms.ToolBarButton btnStop; private System.Windows.Forms.ToolBarButton btnRefresh; private System.Windows.Forms.ToolBarButton btnHome; private System.Windows.Forms.ToolBarButton btnSep1; private System.Windows.Forms.ToolBarButton btnContents; private System.Windows.Forms.ToolBarButton btnIndex; private System.Windows.Forms.ToolBarButton btnSearch; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.MenuItem miPageSetup; private System.Windows.Forms.MenuItem miPrintPreview; private System.Windows.Forms.MenuItem miView; private System.Windows.Forms.MenuItem miBrowser; private System.Windows.Forms.MenuItem miBack; private System.Windows.Forms.MenuItem miForward; private System.Windows.Forms.MenuItem miSep4; private System.Windows.Forms.MenuItem miHome; private System.Windows.Forms.MenuItem miNav; private System.Windows.Forms.MenuItem miContents; private System.Windows.Forms.MenuItem miIndex; private System.Windows.Forms.MenuItem miSearch; private System.Windows.Forms.MenuItem miHelp; private System.Windows.Forms.MenuItem miContents1; private System.Windows.Forms.MenuItem miIndex1; private System.Windows.Forms.MenuItem miSearch1; private System.Windows.Forms.MenuItem miSep5; private System.Windows.Forms.MenuItem miAbout; private System.Windows.Forms.MenuItem miTools; private System.Windows.Forms.MenuItem miDmpConfig; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem miPreferences; private System.Windows.Forms.MenuItem miCloseFile; private System.Windows.Forms.MenuItem miCustomize; private System.Windows.Forms.ToolBarButton btnSynch; HtmlHelpSystem _reader = null; DumpingInfo _dmpInfo=null; InfoTypeCategoryFilter _filter = new InfoTypeCategoryFilter(); string _prefDumpOutput=""; DumpCompression _prefDumpCompression = DumpCompression.Medium; DumpingFlags _prefDumpFlags = DumpingFlags.DumpBinaryTOC | DumpingFlags.DumpTextTOC | DumpingFlags.DumpTextIndex | DumpingFlags.DumpBinaryIndex | DumpingFlags.DumpUrlStr | DumpingFlags.DumpStrings; string _prefURLPrefix = "mk:@MSITStore:"; bool _prefUseHH2TreePics = false; /// <summary> /// Gets the current viewer window /// </summary> public static Viewer Current { get { return _current; } } /// <summary> /// Constructor of the class /// </summary> public Viewer() { Viewer._current = this; // create a new instance of the classlibrary's main class _reader = new HtmlHelpSystem(); HtmlHelpSystem.UrlPrefix = "mk:@MSITStore:"; // use temporary folder for data dumping string sTemp = System.Environment.GetEnvironmentVariable("TEMP"); if(sTemp.Length <= 0) sTemp = System.Environment.GetEnvironmentVariable("TMP"); _prefDumpOutput = sTemp; // create a dump info instance used for dumping data _dmpInfo = new DumpingInfo(DumpingFlags.DumpBinaryTOC | DumpingFlags.DumpTextTOC | DumpingFlags.DumpTextIndex | DumpingFlags.DumpBinaryIndex | DumpingFlags.DumpUrlStr | DumpingFlags.DumpStrings, sTemp, DumpCompression.Medium); LoadRegistryPreferences(); HtmlHelpSystem.UrlPrefix = _prefURLPrefix; HtmlHelpSystem.UseHH2TreePics = _prefUseHH2TreePics; InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Viewer)); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.panel1 = new System.Windows.Forms.Panel(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.panel2 = new System.Windows.Forms.Panel(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabContents = new System.Windows.Forms.TabPage(); this.tocTree1 = new HtmlHelp.UIComponents.TocTree(); this.tabIndex = new System.Windows.Forms.TabPage(); this.helpIndex1 = new HtmlHelp.UIComponents.helpIndex(); this.tabSearch = new System.Windows.Forms.TabPage(); this.helpSearch2 = new HtmlHelp.UIComponents.helpSearch(); this.splitter1 = new System.Windows.Forms.Splitter(); this.panel3 = new System.Windows.Forms.Panel(); this.axWebBrowser1 = new AxSHDocVw.AxWebBrowser(); this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components); this.miFile = new System.Windows.Forms.MenuItem(); this.miOpen = new System.Windows.Forms.MenuItem(); this.miMerge = new System.Windows.Forms.MenuItem(); this.miCloseFile = new System.Windows.Forms.MenuItem(); this.miSep1 = new System.Windows.Forms.MenuItem(); this.miPageSetup = new System.Windows.Forms.MenuItem(); this.miPrintPreview = new System.Windows.Forms.MenuItem(); this.miPrint = new System.Windows.Forms.MenuItem(); this.miSep2 = new System.Windows.Forms.MenuItem(); this.miExit = new System.Windows.Forms.MenuItem(); this.miView = new System.Windows.Forms.MenuItem(); this.miBrowser = new System.Windows.Forms.MenuItem(); this.miBack = new System.Windows.Forms.MenuItem(); this.miForward = new System.Windows.Forms.MenuItem(); this.miSep4 = new System.Windows.Forms.MenuItem(); this.miHome = new System.Windows.Forms.MenuItem(); this.miNav = new System.Windows.Forms.MenuItem(); this.miContents = new System.Windows.Forms.MenuItem(); this.miIndex = new System.Windows.Forms.MenuItem(); this.miSearch = new System.Windows.Forms.MenuItem(); this.miTools = new System.Windows.Forms.MenuItem(); this.miDmpConfig = new System.Windows.Forms.MenuItem(); this.miCustomize = new System.Windows.Forms.MenuItem(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.miPreferences = new System.Windows.Forms.MenuItem(); this.miHelp = new System.Windows.Forms.MenuItem(); this.miContents1 = new System.Windows.Forms.MenuItem(); this.miIndex1 = new System.Windows.Forms.MenuItem(); this.miSearch1 = new System.Windows.Forms.MenuItem(); this.miSep5 = new System.Windows.Forms.MenuItem(); this.miAbout = new System.Windows.Forms.MenuItem(); this.toolBar1 = new System.Windows.Forms.ToolBar(); this.btnBack = new System.Windows.Forms.ToolBarButton(); this.btnNext = new System.Windows.Forms.ToolBarButton(); this.btnStop = new System.Windows.Forms.ToolBarButton(); this.btnRefresh = new System.Windows.Forms.ToolBarButton(); this.btnHome = new System.Windows.Forms.ToolBarButton(); this.btnSynch = new System.Windows.Forms.ToolBarButton(); this.btnSep1 = new System.Windows.Forms.ToolBarButton(); this.btnContents = new System.Windows.Forms.ToolBarButton(); this.btnIndex = new System.Windows.Forms.ToolBarButton(); this.btnSearch = new System.Windows.Forms.ToolBarButton(); this.imgToolBar = new System.Windows.Forms.ImageList(this.components); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.panel2.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabContents.SuspendLayout(); this.tabIndex.SuspendLayout(); this.tabSearch.SuspendLayout(); this.panel3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).BeginInit(); this.SuspendLayout(); // // openFileDialog1 // this.openFileDialog1.DefaultExt = "chm"; this.openFileDialog1.Filter = "Compiled HTML-Help files (*.chm)|*.chm|All files|*.*"; this.openFileDialog1.Title = "Open HTML-Help files"; // // panel1 // this.panel1.Controls.Add(this.pictureBox1); this.panel1.Dock = System.Windows.Forms.DockStyle.Top; this.panel1.Location = new System.Drawing.Point(0, 28); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(759, 4); this.panel1.TabIndex = 5; // // pictureBox1 // this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Top; this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(0, 0); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(759, 2); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // panel2 // this.panel2.Controls.Add(this.tabControl1); this.panel2.Dock = System.Windows.Forms.DockStyle.Left; this.panel2.Location = new System.Drawing.Point(0, 32); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(300, 468); this.panel2.TabIndex = 7; // // tabControl1 // this.tabControl1.Controls.Add(this.tabContents); this.tabControl1.Controls.Add(this.tabIndex); this.tabControl1.Controls.Add(this.tabSearch); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(300, 468); this.tabControl1.TabIndex = 8; // // tabContents // this.tabContents.Controls.Add(this.tocTree1); this.tabContents.Location = new System.Drawing.Point(4, 22); this.tabContents.Name = "tabContents"; this.tabContents.Size = new System.Drawing.Size(292, 442); this.tabContents.TabIndex = 0; this.tabContents.Text = "Contents"; // // tocTree1 // this.tocTree1.Dock = System.Windows.Forms.DockStyle.Fill; this.tocTree1.Location = new System.Drawing.Point(0, 0); this.tocTree1.Name = "tocTree1"; this.tocTree1.Padding = new System.Windows.Forms.Padding(2); this.tocTree1.Size = new System.Drawing.Size(292, 442); this.tocTree1.TabIndex = 0; this.tocTree1.TocSelected += new HtmlHelp.UIComponents.TocSelectedEventHandler(this.tocTree1_TocSelected); // // tabIndex // this.tabIndex.Controls.Add(this.helpIndex1); this.tabIndex.Location = new System.Drawing.Point(4, 22); this.tabIndex.Name = "tabIndex"; this.tabIndex.Size = new System.Drawing.Size(292, 442); this.tabIndex.TabIndex = 1; this.tabIndex.Text = "Index"; // // helpIndex1 // this.helpIndex1.Dock = System.Windows.Forms.DockStyle.Fill; this.helpIndex1.Location = new System.Drawing.Point(0, 0); this.helpIndex1.Name = "helpIndex1"; this.helpIndex1.Size = new System.Drawing.Size(292, 442); this.helpIndex1.TabIndex = 0; this.helpIndex1.IndexSelected += new HtmlHelp.UIComponents.IndexSelectedEventHandler(this.helpIndex1_IndexSelected); // // tabSearch // this.tabSearch.Controls.Add(this.helpSearch2); this.tabSearch.Location = new System.Drawing.Point(4, 22); this.tabSearch.Name = "tabSearch"; this.tabSearch.Size = new System.Drawing.Size(292, 442); this.tabSearch.TabIndex = 2; this.tabSearch.Text = "Search"; // // helpSearch2 // this.helpSearch2.Dock = System.Windows.Forms.DockStyle.Fill; this.helpSearch2.Location = new System.Drawing.Point(0, 0); this.helpSearch2.Name = "helpSearch2"; this.helpSearch2.Size = new System.Drawing.Size(292, 442); this.helpSearch2.TabIndex = 0; this.helpSearch2.FTSearch += new HtmlHelp.UIComponents.FTSearchEventHandler(this.helpSearch2_FTSearch); this.helpSearch2.HitSelected += new HtmlHelp.UIComponents.HitSelectedEventHandler(this.helpSearch2_HitSelected); this.helpSearch2.Load += new System.EventHandler(this.helpSearch2_Load); // // splitter1 // this.splitter1.Location = new System.Drawing.Point(300, 32); this.splitter1.Name = "splitter1"; this.splitter1.Size = new System.Drawing.Size(3, 468); this.splitter1.TabIndex = 9; this.splitter1.TabStop = false; // // panel3 // this.panel3.BackColor = System.Drawing.SystemColors.Control; this.panel3.Controls.Add(this.axWebBrowser1); this.panel3.Dock = System.Windows.Forms.DockStyle.Fill; this.panel3.Location = new System.Drawing.Point(303, 32); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size(456, 468); this.panel3.TabIndex = 10; // // axWebBrowser1 // this.axWebBrowser1.Dock = System.Windows.Forms.DockStyle.Fill; this.axWebBrowser1.Enabled = true; this.axWebBrowser1.Location = new System.Drawing.Point(0, 0); this.axWebBrowser1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axWebBrowser1.OcxState"))); this.axWebBrowser1.Size = new System.Drawing.Size(456, 468); this.axWebBrowser1.TabIndex = 0; this.axWebBrowser1.DownloadComplete += new System.EventHandler(this.axWebBrowser1_DownloadComplete); this.axWebBrowser1.DownloadBegin += new System.EventHandler(this.axWebBrowser1_DownloadBegin); this.axWebBrowser1.CommandStateChange += new AxSHDocVw.DWebBrowserEvents2_CommandStateChangeEventHandler(this.axWebBrowser1_CommandStateChanged); this.axWebBrowser1.ProgressChange += new AxSHDocVw.DWebBrowserEvents2_ProgressChangeEventHandler(this.axWebBrowser1_ProgressChanged); // // mainMenu1 // this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miFile, this.miView, this.miTools, this.miHelp}); // // miFile // this.miFile.Index = 0; this.miFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miOpen, this.miMerge, this.miCloseFile, this.miSep1, this.miPageSetup, this.miPrintPreview, this.miPrint, this.miSep2, this.miExit}); this.miFile.Text = "&File"; // // miOpen // this.miOpen.Index = 0; this.miOpen.Text = "&Open ..."; this.miOpen.Click += new System.EventHandler(this.miOpen_Click); // // miMerge // this.miMerge.Index = 1; this.miMerge.Text = "&Merge ..."; this.miMerge.Click += new System.EventHandler(this.miMerge_Click); // // miCloseFile // this.miCloseFile.Index = 2; this.miCloseFile.Text = "&Close file(s)"; this.miCloseFile.Click += new System.EventHandler(this.miCloseFile_Click); // // miSep1 // this.miSep1.Index = 3; this.miSep1.Text = "-"; // // miPageSetup // this.miPageSetup.Index = 4; this.miPageSetup.Text = "Page &setup ..."; this.miPageSetup.Click += new System.EventHandler(this.miPageSetup_Click); // // miPrintPreview // this.miPrintPreview.Index = 5; this.miPrintPreview.Text = "Print p&review ..."; this.miPrintPreview.Click += new System.EventHandler(this.miPrintPreview_Click); // // miPrint // this.miPrint.Index = 6; this.miPrint.Text = "&Print ..."; this.miPrint.Click += new System.EventHandler(this.miPrint_Click); // // miSep2 // this.miSep2.Index = 7; this.miSep2.Text = "-"; // // miExit // this.miExit.Index = 8; this.miExit.Text = "&Exit"; this.miExit.Click += new System.EventHandler(this.miExit_Click); // // miView // this.miView.Index = 1; this.miView.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miBrowser, this.miNav}); this.miView.Text = "&View"; // // miBrowser // this.miBrowser.Index = 0; this.miBrowser.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miBack, this.miForward, this.miSep4, this.miHome}); this.miBrowser.Text = "Web brow&ser"; // // miBack // this.miBack.Index = 0; this.miBack.Text = "&Back"; this.miBack.Click += new System.EventHandler(this.miBack_Click); // // miForward // this.miForward.Index = 1; this.miForward.Text = "&Forward"; this.miForward.Click += new System.EventHandler(this.miForward_Click); // // miSep4 // this.miSep4.Index = 2; this.miSep4.Text = "-"; // // miHome // this.miHome.Index = 3; this.miHome.Text = "&Home"; this.miHome.Click += new System.EventHandler(this.miHome_Click); // // miNav // this.miNav.Index = 1; this.miNav.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miContents, this.miIndex, this.miSearch}); this.miNav.Text = "&Navigation"; // // miContents // this.miContents.Index = 0; this.miContents.Text = "&Contents"; this.miContents.Click += new System.EventHandler(this.miContents_Click); // // miIndex // this.miIndex.Index = 1; this.miIndex.Text = "&Index"; this.miIndex.Click += new System.EventHandler(this.miIndex_Click); // // miSearch // this.miSearch.Index = 2; this.miSearch.Text = "&Search"; this.miSearch.Click += new System.EventHandler(this.miSearch_Click); // // miTools // this.miTools.Index = 2; this.miTools.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miDmpConfig, this.miCustomize, this.menuItem1, this.miPreferences}); this.miTools.Text = "&Tools"; // // miDmpConfig // this.miDmpConfig.Index = 0; this.miDmpConfig.Text = "&Configure data dumping ..."; this.miDmpConfig.Click += new System.EventHandler(this.miDmpConfig_Click); // // miCustomize // this.miCustomize.Index = 1; this.miCustomize.Text = "Customize &help contents ..."; this.miCustomize.Click += new System.EventHandler(this.miCustomize_Click); // // menuItem1 // this.menuItem1.Index = 2; this.menuItem1.Text = "-"; // // miPreferences // this.miPreferences.Index = 3; this.miPreferences.Text = "&Preferences ..."; this.miPreferences.Click += new System.EventHandler(this.miPreferences_Click); // // miHelp // this.miHelp.Index = 3; this.miHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.miContents1, this.miIndex1, this.miSearch1, this.miSep5, this.miAbout}); this.miHelp.Text = "&Help"; // // miContents1 // this.miContents1.Index = 0; this.miContents1.Text = "&Contents"; this.miContents1.Click += new System.EventHandler(this.miContents1_Click); // // miIndex1 // this.miIndex1.Index = 1; this.miIndex1.Text = "&Index"; this.miIndex1.Click += new System.EventHandler(this.miIndex1_Click); // // miSearch1 // this.miSearch1.Index = 2; this.miSearch1.Text = "&Search"; this.miSearch1.Click += new System.EventHandler(this.miSearch1_Click); // // miSep5 // this.miSep5.Index = 3; this.miSep5.Text = "-"; // // miAbout // this.miAbout.Index = 4; this.miAbout.Text = "&About ..."; this.miAbout.Click += new System.EventHandler(this.miAbout_Click); // // toolBar1 // this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat; this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] { this.btnBack, this.btnNext, this.btnStop, this.btnRefresh, this.btnHome, this.btnSynch, this.btnSep1, this.btnContents, this.btnIndex, this.btnSearch}); this.toolBar1.DropDownArrows = true; this.toolBar1.ImageList = this.imgToolBar; this.toolBar1.Location = new System.Drawing.Point(0, 0); this.toolBar1.Name = "toolBar1"; this.toolBar1.ShowToolTips = true; this.toolBar1.Size = new System.Drawing.Size(759, 28); this.toolBar1.TabIndex = 0; this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick); // // btnBack // this.btnBack.ImageIndex = 0; this.btnBack.Name = "btnBack"; this.btnBack.ToolTipText = "Back"; // // btnNext // this.btnNext.ImageIndex = 1; this.btnNext.Name = "btnNext"; this.btnNext.ToolTipText = "Forward"; // // btnStop // this.btnStop.ImageIndex = 2; this.btnStop.Name = "btnStop"; this.btnStop.ToolTipText = "Stop"; // // btnRefresh // this.btnRefresh.ImageIndex = 3; this.btnRefresh.Name = "btnRefresh"; this.btnRefresh.ToolTipText = "Refresh"; // // btnHome // this.btnHome.ImageIndex = 4; this.btnHome.Name = "btnHome"; this.btnHome.ToolTipText = "Default topic"; // // btnSynch // this.btnSynch.ImageIndex = 8; this.btnSynch.Name = "btnSynch"; this.btnSynch.ToolTipText = "Snychronize contents"; // // btnSep1 // this.btnSep1.Name = "btnSep1"; this.btnSep1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator; // // btnContents // this.btnContents.ImageIndex = 5; this.btnContents.Name = "btnContents"; this.btnContents.ToolTipText = "Show help contents"; // // btnIndex // this.btnIndex.ImageIndex = 6; this.btnIndex.Name = "btnIndex"; this.btnIndex.ToolTipText = "Show help index"; // // btnSearch // this.btnSearch.ImageIndex = 7; this.btnSearch.Name = "btnSearch"; this.btnSearch.ToolTipText = "Fulltext search"; // // imgToolBar // this.imgToolBar.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgToolBar.ImageStream"))); this.imgToolBar.TransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(214)))), ((int)(((byte)(211)))), ((int)(((byte)(206))))); this.imgToolBar.Images.SetKeyName(0, ""); this.imgToolBar.Images.SetKeyName(1, ""); this.imgToolBar.Images.SetKeyName(2, ""); this.imgToolBar.Images.SetKeyName(3, ""); this.imgToolBar.Images.SetKeyName(4, ""); this.imgToolBar.Images.SetKeyName(5, ""); this.imgToolBar.Images.SetKeyName(6, ""); this.imgToolBar.Images.SetKeyName(7, ""); this.imgToolBar.Images.SetKeyName(8, ""); // // Viewer // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(759, 500); this.Controls.Add(this.panel3); this.Controls.Add(this.splitter1); this.Controls.Add(this.panel2); this.Controls.Add(this.panel1); this.Controls.Add(this.toolBar1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Menu = this.mainMenu1; this.Name = "Viewer"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "HtmlHelp - Viewer"; this.Closing += new System.ComponentModel.CancelEventHandler(this.Viewer_Closing); this.Load += new System.EventHandler(this.Form1_Load); this.panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.panel2.ResumeLayout(false); this.tabControl1.ResumeLayout(false); this.tabContents.ResumeLayout(false); this.tabIndex.ResumeLayout(false); this.tabSearch.ResumeLayout(false); this.panel3.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Viewer()); } /// <summary> /// Navigates the embedded browser to the specified url /// </summary> /// <param name="url">url to navigate</param> private void NavigateBrowser(string url) { object flags = 0; object targetFrame = String.Empty; object postData = String.Empty; object headers = String.Empty; object oUrl = url; //axWebBrowser1.Navigate(url, ref flags, ref targetFrame, ref postData, ref headers); axWebBrowser1.Navigate2(ref oUrl, ref flags, ref targetFrame, ref postData, ref headers); } #region Registry preferences /// <summary> /// Loads viewer preferences from registry /// </summary> private void LoadRegistryPreferences() { /* RegistryKey regKey = Registry.LocalMachine.CreateSubKey(LM_Key); bool bEnable = bool.Parse(regKey.GetValue("EnableDumping", true).ToString()); _prefDumpOutput = (string) regKey.GetValue("DumpOutputDir", _prefDumpOutput); _prefDumpCompression = (DumpCompression) ((int)regKey.GetValue("CompressionLevel", _prefDumpCompression)); _prefDumpFlags = (DumpingFlags) ((int)regKey.GetValue("DumpingFlags", _prefDumpFlags)); if(bEnable) _dmpInfo = new DumpingInfo(_prefDumpFlags, _prefDumpOutput, _prefDumpCompression); else _dmpInfo = null; _prefURLPrefix = (string) regKey.GetValue("ITSUrlPrefix", _prefURLPrefix); _prefUseHH2TreePics = bool.Parse(regKey.GetValue("UseHH2TreePics", _prefUseHH2TreePics).ToString()); * */ } /// <summary> /// Saves viewer preferences to registry /// </summary> private void SaveRegistryPreferences() { RegistryKey regKey = Registry.LocalMachine.CreateSubKey(LM_Key); regKey.SetValue("EnableDumping", (_dmpInfo!=null)); regKey.SetValue("DumpOutputDir", _prefDumpOutput); regKey.SetValue("CompressionLevel", (int)_prefDumpCompression); regKey.SetValue("DumpingFlags", (int)_prefDumpFlags); regKey.SetValue("ITSUrlPrefix", _prefURLPrefix); regKey.SetValue("UseHH2TreePics", _prefUseHH2TreePics); } #endregion #region Eventhandlers for library usercontrols /// <summary> /// Called if the user hits the "Search" button on the full-text search pane /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameters</param> private void helpSearch2_FTSearch(object sender, SearchEventArgs e) { this.Cursor = Cursors.WaitCursor; try { DataTable dtResults = _reader.PerformSearch( e.Words, 500, e.PartialWords, e.TitlesOnly); helpSearch2.SetResults(dtResults); } finally { this.Cursor = Cursors.Arrow; } } /// <summary> /// Called if the user selects an entry from the search results. /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameters</param> private void helpSearch2_HitSelected(object sender, HitEventArgs e) { if( e.URL.Length > 0) { NavigateBrowser(e.URL); } } /// <summary> /// Called if the user selects a new table of contents item /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameters</param> private void tocTree1_TocSelected(object sender, TocEventArgs e) { if( e.Item.Local.Length > 0) { NavigateBrowser(e.Item.Url); } } /// <summary> /// Called if the user selects an index topic /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameters</param> private void helpIndex1_IndexSelected(object sender, IndexEventArgs e) { if(e.URL.Length > 0) NavigateBrowser(e.URL); } #endregion #region IHelpViewer interface implementation /// <summary> /// Navigates the helpviewer to a specific help url /// </summary> /// <param name="url">url</param> void IHelpViewer.NavigateTo(string url) { NavigateBrowser(url); } /// <summary> /// Shows help for a specific url /// </summary> /// <param name="namespaceFilter">namespace filter (used for merged files)</param> /// <param name="hlpNavigator">navigator value</param> /// <param name="keyword">keyword</param> void IHelpViewer.ShowHelp(string namespaceFilter, HelpNavigator hlpNavigator, string keyword) { ((IHelpViewer)this).ShowHelp(namespaceFilter, hlpNavigator, keyword, ""); } /// <summary> /// Shows help for a specific keyword /// </summary> /// <param name="namespaceFilter">namespace filter (used for merged files)</param> /// <param name="hlpNavigator">navigator value</param> /// <param name="keyword">keyword</param> /// <param name="url">url</param> void IHelpViewer.ShowHelp(string namespaceFilter, HelpNavigator hlpNavigator, string keyword, string url) { switch(hlpNavigator) { case HelpNavigator.AssociateIndex: { IndexItem foundIdx = _reader.Index.SearchIndex(keyword, IndexType.AssiciativeLinks); if(foundIdx != null) { if(foundIdx.Topics.Count > 0) { IndexTopic topic = foundIdx.Topics[0] as IndexTopic; if(topic.Local.Length>0) NavigateBrowser(topic.URL); } } };break; case HelpNavigator.Find: { this.Cursor = Cursors.WaitCursor; this.helpSearch2.SetSearchText(keyword); DataTable dtResults = _reader.PerformSearch(keyword, 500, true, false); this.helpSearch2.SetResults(dtResults); this.Cursor = Cursors.Arrow; this.helpSearch2.Focus(); };break; case HelpNavigator.Index: { ((IHelpViewer)this).ShowHelpIndex(url); };break; case HelpNavigator.KeywordIndex: { IndexItem foundIdx = _reader.Index.SearchIndex(keyword, IndexType.KeywordLinks); if(foundIdx != null) { if(foundIdx.Topics.Count == 1) { IndexTopic topic = foundIdx.Topics[0] as IndexTopic; if(topic.Local.Length>0) NavigateBrowser(topic.URL); } else if(foundIdx.Topics.Count>1) { this.helpIndex1.SelectText(foundIdx.IndentKeyWord); } } this.helpIndex1.Focus(); };break; case HelpNavigator.TableOfContents: { TOCItem foundTOC = _reader.TableOfContents.SearchTopic(keyword); if(foundTOC != null) { if(foundTOC.Local.Length>0) NavigateBrowser(foundTOC.Url); } this.tocTree1.Focus(); };break; case HelpNavigator.Topic: { TOCItem foundTOC = _reader.TableOfContents.SearchTopic(keyword); if(foundTOC != null) { if(foundTOC.Local.Length>0) NavigateBrowser(foundTOC.Url); } };break; } } /// <summary> /// Shows the help index /// </summary> /// <param name="url">url</param> void IHelpViewer.ShowHelpIndex(string url) { if( url.Length == 0) url = HtmlHelpSystem.Current.DefaultTopic; NavigateBrowser(url); } /// <summary> /// Shows a help popup window /// </summary> /// <param name="parent">the parent control for the popup window</param> /// <param name="text">help text</param> /// <param name="location">display location</param> void IHelpViewer.ShowPopup(Control parent, string text, Point location) { // Display a native toolwindow and display the help string HelpToolTipWindow hlpTTip = new HelpToolTipWindow(); hlpTTip.Location = location; hlpTTip.Text = text; hlpTTip.ShowShadow = true; hlpTTip.MaximumDuration = 300; // duration before hiding (after focus lost) hlpTTip.Show(); } #endregion /// <summary> /// Called if the form loads /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void Form1_Load(object sender, System.EventArgs e) { tocTree1.Enabled = false; helpIndex1.Enabled = false; helpSearch2.Enabled = false; btnContents.Enabled = false; btnIndex.Enabled = false; btnSearch.Enabled = false; miContents.Enabled = false; miContents1.Enabled = false; miIndex.Enabled = false; miIndex1.Enabled = false; miSearch.Enabled = false; miSearch1.Enabled = false; btnBack.Enabled = false; miBack.Enabled = false; btnNext.Enabled = false; miForward.Enabled = false; btnStop.Enabled = false; btnRefresh.Enabled = false; btnHome.Enabled = false; miHome.Enabled = false; btnSynch.Enabled = false; miMerge.Enabled = false; miCloseFile.Enabled = false; miCustomize.Enabled = false; miPageSetup.Enabled = false; miPrint.Enabled = false; miPrintPreview.Enabled = false; } /// <summary> /// Called if the viewer is closing /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void Viewer_Closing(object sender, System.ComponentModel.CancelEventArgs e) { SaveRegistryPreferences(); } /// <summary> /// Called if the browser changes its command state (forward/back button) /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void axWebBrowser1_CommandStateChanged(object sender, AxSHDocVw.DWebBrowserEvents2_CommandStateChangeEvent e) { switch(e.command) { case 1: // forward command update { btnNext.Enabled = e.enable; miForward.Enabled = e.enable; };break; case 2: case 3: // back command update { btnBack.Enabled = e.enable; miBack.Enabled = e.enable; };break; } } /// <summary> /// Called wenn the download progress of the browser changes /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void axWebBrowser1_ProgressChanged(object sender, AxSHDocVw.DWebBrowserEvents2_ProgressChangeEvent e) { double dPercent = ((double)e.progress * 100.0)/(double)e.progressMax; dPercent = Math.Round(dPercent); //((IStatusBar)base.ServiceProvider.GetService(typeof(IStatusBar))).SetProgress((int)dPercent); } /// <summary> /// Called if the browser begins to download content /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void axWebBrowser1_DownloadBegin(object sender, System.EventArgs e) { btnStop.Enabled = true; btnHome.Enabled = false; miHome.Enabled = false; btnBack.Enabled = false; miBack.Enabled = false; btnNext.Enabled = false; miForward.Enabled = false; } /// <summary> /// Called if the browser has finished downloading content /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void axWebBrowser1_DownloadComplete(object sender, System.EventArgs e) { btnStop.Enabled = false; btnHome.Enabled = true; miHome.Enabled = true; miPageSetup.Enabled = true; miPrint.Enabled = true; miPrintPreview.Enabled = true; } /// <summary> /// Called if the user clicks the File-Exit menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miExit_Click(object sender, System.EventArgs e) { this.Close(); } /// <summary> /// Called if the user clicks the File-Open menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miOpen_Click(object sender, System.EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK ) { this.Cursor = Cursors.WaitCursor; try { // clear current items tocTree1.ClearContents(); helpIndex1.ClearContents(); helpSearch2.ClearContents(); // open the chm-file selected in the OpenFileDialog _reader.OpenFile( openFileDialog1.FileName, _dmpInfo ); // Enable the toc-tree pane if the opened file has a table of contents tocTree1.Enabled = _reader.HasTableOfContents; // Enable the index pane if the opened file has an index helpIndex1.Enabled = _reader.HasIndex; // Enable the full-text search pane if the opened file supports full-text searching helpSearch2.Enabled = _reader.FullTextSearch; btnContents.Enabled = _reader.HasTableOfContents; btnIndex.Enabled = _reader.HasIndex; btnSearch.Enabled = _reader.FullTextSearch; miContents.Enabled = _reader.HasTableOfContents; miContents1.Enabled = _reader.HasTableOfContents; miIndex.Enabled = _reader.HasIndex; miIndex1.Enabled = _reader.HasIndex; miSearch.Enabled = _reader.FullTextSearch; miSearch1.Enabled = _reader.FullTextSearch; btnSynch.Enabled = _reader.HasTableOfContents; tabControl1.SelectedIndex = 0; btnRefresh.Enabled = true; if( _reader.DefaultTopic.Length > 0) { btnHome.Enabled = true; miHome.Enabled = true; } // Build the table of contents tree view in the classlibrary control tocTree1.BuildTOC( _reader.TableOfContents, _filter ); // Build the index entries in the classlibrary control if( _reader.HasKLinks ) helpIndex1.BuildIndex( _reader.Index, IndexType.KeywordLinks, _filter ); else if( _reader.HasALinks ) helpIndex1.BuildIndex( _reader.Index, IndexType.AssiciativeLinks, _filter ); // Navigate the embedded browser to the default help topic NavigateBrowser( _reader.DefaultTopic ); miMerge.Enabled = true; miCloseFile.Enabled = true; this.Text = _reader.FileList[0].FileInfo.HelpWindowTitle + " - HtmlHelp - Viewer"; miCustomize.Enabled = ( _reader.HasInformationTypes || _reader.HasCategories); // Force garbage collection to free memory GC.Collect(); } finally { this.Cursor = Cursors.Arrow; } this.Cursor = Cursors.Arrow; } } /// <summary> /// Called if the user clicks the File-Merge menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miMerge_Click(object sender, System.EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK ) { this.Cursor = Cursors.WaitCursor; try { // clear current items tocTree1.ClearContents(); helpIndex1.ClearContents(); helpSearch2.ClearContents(); // merge the chm file selected in the OpenFileDialog to the existing one // in the HtmlHelpSystem class _reader.MergeFile( openFileDialog1.FileName, _dmpInfo ); // Enable the toc-tree pane if the opened file has a table of contents tocTree1.Enabled = _reader.HasTableOfContents; // Enable the index pane if the opened file has an index helpIndex1.Enabled = _reader.HasIndex; // Enable the full-text search pane if the opened file supports full-text searching helpSearch2.Enabled = _reader.FullTextSearch; btnContents.Enabled = _reader.HasTableOfContents; btnIndex.Enabled = _reader.HasIndex; btnSearch.Enabled = _reader.FullTextSearch; miContents.Enabled = _reader.HasTableOfContents; miContents1.Enabled = _reader.HasTableOfContents; miIndex.Enabled = _reader.HasIndex; miIndex1.Enabled = _reader.HasIndex; miSearch.Enabled = _reader.FullTextSearch; miSearch1.Enabled = _reader.FullTextSearch; btnSynch.Enabled = _reader.HasTableOfContents; tabControl1.SelectedIndex = 0; btnRefresh.Enabled = true; if( _reader.DefaultTopic.Length > 0) { btnHome.Enabled = true; miHome.Enabled = true; } // Rebuild the table of contents tree view in the classlibrary control // using the new merged table of contents tocTree1.BuildTOC( _reader.TableOfContents, _filter ); // Rebuild the index entries in the classlibrary control // using the new merged index if( _reader.HasKLinks ) helpIndex1.BuildIndex( _reader.Index, IndexType.KeywordLinks, _filter ); else if( _reader.HasALinks ) helpIndex1.BuildIndex( _reader.Index, IndexType.AssiciativeLinks, _filter ); // Navigate the embedded browser to the default help topic NavigateBrowser( _reader.DefaultTopic ); miCustomize.Enabled = ( _reader.HasInformationTypes || _reader.HasCategories); // Force garbage collection to free memory GC.Collect(); } catch(Exception ex) { this.Cursor = Cursors.Arrow; throw ex; } this.Cursor = Cursors.Arrow; } } /// <summary> /// Called if the user clicks the File-close file(s) menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param>> private void miCloseFile_Click(object sender, System.EventArgs e) { this.Cursor = Cursors.WaitCursor; // clear current items tocTree1.ClearContents(); helpIndex1.ClearContents(); helpSearch2.ClearContents(); _reader.CloseAllFiles(); // Navigate the embedded browser to the default help topic NavigateBrowser( "about:blank" ); // Force garbage collection to free memory GC.Collect(); this.Cursor = Cursors.Arrow; } /// <summary> /// Called if the user clicks the File-Page setup menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miPageSetup_Click(object sender, System.EventArgs e) { object pvaIn = String.Empty; object pvaOut = String.Empty; axWebBrowser1.ExecWB(SHDocVw.OLECMDID.OLECMDID_PAGESETUP, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref pvaIn, ref pvaOut); } /// <summary> /// Called if the user clicks the File-Print preview menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miPrintPreview_Click(object sender, System.EventArgs e) { object pvaIn = String.Empty; object pvaOut = String.Empty; axWebBrowser1.ExecWB(SHDocVw.OLECMDID.OLECMDID_PRINTPREVIEW, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref pvaIn, ref pvaOut); } /// <summary> /// Called if the user clicks the File-Print menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miPrint_Click(object sender, System.EventArgs e) { object pvaIn = String.Empty; object pvaOut = String.Empty; axWebBrowser1.ExecWB(SHDocVw.OLECMDID.OLECMDID_PRINT, SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref pvaIn, ref pvaOut); } /// <summary> /// Called if the user clicks a toolbar button /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e) { if( e.Button == btnContents ) // show help contents clicked { tabControl1.SelectedIndex = 0; tocTree1.Focus(); } if( e.Button == btnIndex ) // show help index clicked { tabControl1.SelectedIndex = 1; helpIndex1.Focus(); } if( e.Button == btnSearch ) // show help search clicked { tabControl1.SelectedIndex = 2; helpSearch2.Focus(); } if( e.Button == btnRefresh ) // refresh clicked { try { axWebBrowser1.Refresh(); } catch(Exception) { } } if( e.Button == btnNext ) // next/forward clicked { try { axWebBrowser1.GoForward(); } catch(Exception) { } } if( e.Button == btnBack ) // back clicked { try { axWebBrowser1.GoBack(); } catch(Exception) { } } if( e.Button == btnHome ) // home clicked { NavigateBrowser( _reader.DefaultTopic ); } if( e.Button == btnStop ) // stop clicked { try { axWebBrowser1.Stop(); } catch(Exception) { } } if( e.Button == btnSynch ) { this.Cursor = Cursors.WaitCursor; tocTree1.Synchronize(axWebBrowser1.LocationURL); this.Cursor = Cursors.Arrow; } } /// <summary> /// Called if the user clicks the Web browser-Back menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miBack_Click(object sender, System.EventArgs e) { try { axWebBrowser1.GoBack(); } catch(Exception) { } } /// <summary> /// Called if the user clicks the Web browser-Forward menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miForward_Click(object sender, System.EventArgs e) { try { axWebBrowser1.GoForward(); } catch(Exception) { } } /// <summary> /// Called if the user clicks the Web browser - home menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miHome_Click(object sender, System.EventArgs e) { NavigateBrowser( _reader.DefaultTopic ); } /// <summary> /// Called if the user clicks the Navigation-contents menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miContents_Click(object sender, System.EventArgs e) { tabControl1.SelectedIndex = 0; tocTree1.Focus(); } /// <summary> /// Called if the user clicks the Navigation-index menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miIndex_Click(object sender, System.EventArgs e) { tabControl1.SelectedIndex = 1; helpIndex1.Focus(); } /// <summary> /// Called if the user clicks the Navigation-search /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miSearch_Click(object sender, System.EventArgs e) { tabControl1.SelectedIndex = 2; helpSearch2.Focus(); } /// <summary> /// Called if the user clicks on the Help-Contents menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miContents1_Click(object sender, System.EventArgs e) { tabControl1.SelectedIndex = 0; tocTree1.Focus(); } /// <summary> /// Called if the user clicks on the Help-Index menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miIndex1_Click(object sender, System.EventArgs e) { tabControl1.SelectedIndex = 1; helpIndex1.Focus(); } /// <summary> /// Called if the user clicks on the Help-Search menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miSearch1_Click(object sender, System.EventArgs e) { tabControl1.SelectedIndex = 2; helpSearch2.Focus(); } /// <summary> /// Called if the user clicks the Help-About menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miAbout_Click(object sender, System.EventArgs e) { AboutDlg dlgA = new AboutDlg(_reader); dlgA.ShowDialog(); } /// <summary> /// Called if the user clicks the Tools-Configure data dumping menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miDmpConfig_Click(object sender, System.EventArgs e) { DumpCfg dmpCfg = new DumpCfg(); dmpCfg.DumpingInfo = _dmpInfo; dmpCfg.PreferencesOutput = _prefDumpOutput; dmpCfg.PrefencesCompression = _prefDumpCompression; dmpCfg.PreferencesFlags = _prefDumpFlags; if(dmpCfg.ShowDialog() == DialogResult.OK) { _dmpInfo = dmpCfg.DumpingInfo; _prefDumpOutput = dmpCfg.PreferencesOutput; _prefDumpCompression = dmpCfg.PrefencesCompression; _prefDumpFlags = dmpCfg.PreferencesFlags; } } /// <summary> /// Called if the user clicks the Tools-Preferences menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miPreferences_Click(object sender, System.EventArgs e) { Preferences prefDlg = new Preferences(); prefDlg.UrlPrefixPreference = _prefURLPrefix; prefDlg.UseHH2TreePicsPreference = _prefUseHH2TreePics; if( prefDlg.ShowDialog() == DialogResult.OK) { _prefURLPrefix = prefDlg.UrlPrefixPreference; HtmlHelpSystem.UrlPrefix = _prefURLPrefix; if( _prefUseHH2TreePics != prefDlg.UseHH2TreePicsPreference) { bool bChangeSetting = false; if(_reader.FileList.Length <= 0) { bChangeSetting = true; } else { if( MessageBox.Show("Changing the image list preference requires to close all documents !\n \nShould the new setting should be applied ?", "Warning",MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { bChangeSetting = true; } } if(bChangeSetting) { miCloseFile_Click(sender,e); _prefUseHH2TreePics = prefDlg.UseHH2TreePicsPreference; HtmlHelpSystem.UseHH2TreePics = _prefUseHH2TreePics; tocTree1.ReloadImageList(); } } } } /// <summary> /// Called if the user clicks the Tools-customize help contents menu /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void miCustomize_Click(object sender, System.EventArgs e) { CustomizeContent custDlg = new CustomizeContent(); custDlg.Filter = _filter; if( custDlg.ShowDialog() == DialogResult.OK) { this.Cursor = Cursors.WaitCursor; _filter = custDlg.Filter; // clear current items tocTree1.ClearContents(); helpIndex1.ClearContents(); helpSearch2.ClearContents(); // Rebuild the table of contents tree view in the classlibrary control // applying the new filter tocTree1.BuildTOC( _reader.TableOfContents, _filter ); // Rebuild the index entries in the classlibrary control // applying the new filter if( _reader.HasKLinks ) helpIndex1.BuildIndex( _reader.Index, IndexType.KeywordLinks, _filter ); else if( _reader.HasALinks ) helpIndex1.BuildIndex( _reader.Index, IndexType.AssiciativeLinks, _filter ); // Navigate the embedded browser to the default help topic NavigateBrowser( _reader.DefaultTopic ); GC.Collect(); this.Cursor = Cursors.Arrow; } } private void helpSearch2_Load(object sender, EventArgs e) { } } }
using Microsoft.Build.Framework; using Newtonsoft.Json; using System.Collections.Generic; using System.IO; using System.Linq; using System; using System.Text.RegularExpressions; using System.Diagnostics; namespace Microsoft.DotNet.Build.Tasks { public class CleanupVSTSAgent : Microsoft.Build.Utilities.Task { public bool Clean { get; set; } public bool Report { get; set; } [Required] public string AgentDirectory { get; set; } [Required] public double RetentionDays { get; set; } public int? Retries { get; set; } public int? SleepTimeInMilliseconds { get; set; } public ITaskItem[] ProcessNamesToKill { get; set; } private static readonly int s_DefaultRetries = 3; private static readonly int s_DefaultSleepTime = 2000; public override bool Execute() { KillStaleProcesses(); if (!Directory.Exists(AgentDirectory)) { Console.WriteLine($"Agent directory specified: '{AgentDirectory}' does not exist."); return false; } if(!Retries.HasValue) { Retries = s_DefaultRetries; } if(!SleepTimeInMilliseconds.HasValue) { SleepTimeInMilliseconds = s_DefaultSleepTime; } bool returnValue = true; if(Report) { ReportDiskUsage(); } if(Clean) { returnValue &= CleanupAgentsAsync().Result; // If report and clean are both 'true', then report disk usage both before and after cleanup. if (Report) { Console.WriteLine("Disk usage after 'Clean'."); ReportDiskUsage(); } } return returnValue; } private void KillStaleProcesses() { foreach (string imageName in ProcessNamesToKill.Select(t => t.ItemSpec)) { Process[] allInstances = Process.GetProcessesByName(imageName); foreach (Process proc in allInstances) { try { if (!proc.HasExited) { proc.Kill(); Console.WriteLine($"Killed process {imageName} ({proc.Id})"); } } catch (Exception e) { Console.WriteLine($"Hit {e.GetType().ToString()} trying to kill process {imageName} ({proc.Id})"); } } } } private void ReportDiskUsage() { string drive = Path.GetPathRoot(AgentDirectory); DriveInfo driveInfo = new DriveInfo(drive); Console.WriteLine("Disk Usage Report"); Console.WriteLine($" Agent directory: {AgentDirectory}"); Console.WriteLine($" Drive letter: {drive}"); Console.WriteLine($" Total disk size: {string.Format("{0:N0}", driveInfo.TotalSize)} bytes"); Console.WriteLine($" Total disk free space: {string.Format("{0:N0}", driveInfo.TotalFreeSpace)} bytes"); var workingDirectories = Directory.GetDirectories(Path.Combine(AgentDirectory, "_work")); var totalWorkingDirectories = workingDirectories != null ? workingDirectories.Length : 0; Console.WriteLine(" Agent info"); Console.WriteLine($" Total size of agent directory: {string.Format("{0:N0}", GetDirectoryAttributes(AgentDirectory).Item1)} bytes"); Console.WriteLine($" Total agent working directories: {totalWorkingDirectories}"); if (totalWorkingDirectories > 0) { int nameLength = 0; foreach(string directoryName in workingDirectories) { nameLength = directoryName.Length > nameLength ? directoryName.Length : nameLength; } int sizeLength = string.Format("{0:N0}", driveInfo.TotalSize).Length; string columnFormat = " {0,-" + nameLength.ToString() + "} {1," + sizeLength.ToString() + ":N0} {2}"; Console.WriteLine(string.Format(columnFormat, "Folder name", "Size (bytes)", "Last Modified DateTime")); foreach (var workingDirectory in workingDirectories) { Tuple<long, DateTime> directoryAttributes = GetDirectoryAttributes(workingDirectory); Console.WriteLine(string.Format(columnFormat, workingDirectory, directoryAttributes.Item1, directoryAttributes.Item2)); } } } private Tuple<long, DateTime> GetDirectoryAttributes(string directory) { DirectoryInfo directoryInfo = new DirectoryInfo(directory); FileInfo[] fileInfos = directoryInfo.GetFiles(); long totalSize = 0; DateTime lastModifiedDateTime = directoryInfo.LastWriteTime; foreach(FileInfo fileInfo in fileInfos) { totalSize += fileInfo.Length; lastModifiedDateTime = fileInfo.LastWriteTime > lastModifiedDateTime ? fileInfo.LastWriteTime : lastModifiedDateTime; } string[] directories = Directory.GetDirectories(directory); foreach(string dir in directories) { Tuple<long, DateTime> directoryAttributes = GetDirectoryAttributes(dir); totalSize += directoryAttributes.Item1; lastModifiedDateTime = directoryAttributes.Item2 > lastModifiedDateTime ? directoryAttributes.Item2 : lastModifiedDateTime; } return Tuple.Create(totalSize, lastModifiedDateTime); } private async System.Threading.Tasks.Task<bool> CleanupAgentsAsync() { bool returnStatus = true; DateTime now = DateTime.Now; // Cleanup the agents that the VSTS agent is tracking string[] sourceFolderJsons = Directory.GetFiles(Path.Combine(AgentDirectory, "_work", "SourceRootMapping"), "SourceFolder.json", SearchOption.AllDirectories); HashSet<string> knownDirectories = new HashSet<string>(); List<System.Threading.Tasks.Task<bool>> cleanupTasks = new List<System.Threading.Tasks.Task<bool>>(); Console.WriteLine($"Found {sourceFolderJsons.Length} known agent working directories. "); foreach (var sourceFolderJson in sourceFolderJsons) { Console.WriteLine($"Examining {sourceFolderJson} ..."); Tuple<string, string, DateTime> agentInfo = await GetAgentInfoAsync(sourceFolderJson); string workDirectory = Path.Combine(AgentDirectory, "_work", agentInfo.Item2); knownDirectories.Add(workDirectory); TimeSpan span = new TimeSpan(now.Ticks - agentInfo.Item3.Ticks); if (span.TotalDays > RetentionDays) { cleanupTasks.Add(CleanupAgentAsync(workDirectory, Path.GetDirectoryName(agentInfo.Item1))); } else { Console.WriteLine($"Skipping cleanup for {sourceFolderJson}, it is newer than {RetentionDays} days old, last run date is '{agentInfo.Item3.ToString()}'"); } } System.Threading.Tasks.Task.WaitAll(cleanupTasks.ToArray()); foreach(var cleanupTask in cleanupTasks) { returnStatus &= cleanupTask.Result; } // Attempt to cleanup any working folders which the VSTS agent doesn't know about. Console.WriteLine("Looking for additional '_work' directories which are unknown to the agent."); cleanupTasks.Clear(); Regex workingDirectoryRegex = new Regex(@"\\\d+$"); var workingDirectories = Directory.GetDirectories(Path.Combine(AgentDirectory, "_work"), "*", SearchOption.TopDirectoryOnly).Where(w => workingDirectoryRegex.IsMatch(w)); foreach (var workingDirectory in workingDirectories) { if (!knownDirectories.Contains(workingDirectory)) { cleanupTasks.Add(CleanupAgentDirectoryAsync(workingDirectory)); } } System.Threading.Tasks.Task.WaitAll(cleanupTasks.ToArray()); foreach (var cleanupTask in cleanupTasks) { returnStatus &= cleanupTask.Result; } return returnStatus; } private async System.Threading.Tasks.Task<bool> CleanupAgentAsync(string workDirectory, string sourceFolderJson) { bool returnStatus = await CleanupAgentDirectoryAsync(workDirectory); returnStatus &= await CleanupAgentDirectoryAsync(sourceFolderJson).ConfigureAwait(false); return returnStatus; } private async System.Threading.Tasks.Task<bool> CleanupAgentDirectoryAsync(string directory, int attempts = 0) { try { if (Directory.Exists(directory)) { Console.Write($"Attempting to cleanup {directory} ... "); Directory.Delete(directory, true); Console.WriteLine("Success"); } else { Console.WriteLine($"Specified directory, {directory}, does not exist"); } return true; } catch (Exception e) { attempts++; Console.WriteLine($"Failed in cleanup attempt... {Retries - attempts} retries left."); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); if(attempts < Retries) { Console.WriteLine($"Will retry again in {SleepTimeInMilliseconds} ms"); await System.Threading.Tasks.Task.Delay(SleepTimeInMilliseconds.Value); return await CleanupAgentDirectoryAsync(directory, attempts).ConfigureAwait(false); } } Console.WriteLine("Failed to cleanup agent"); return false; } private async System.Threading.Tasks.Task<Tuple<string, string, DateTime>> GetAgentInfoAsync(string sourceFolderJson) { Regex getValueRegex = new Regex(".*\": \"(?<value>[^\"]+)\""); DateTime lastRunOn = DateTime.Now; string agentBuildDirectory = null; using (Stream stream = File.OpenRead(sourceFolderJson)) using (StreamReader reader = new StreamReader(stream)) { while(!reader.EndOfStream) { string line = await reader.ReadLineAsync(); if(line.Contains("lastRunOn")) { lastRunOn = DateTime.Parse(getValueRegex.Match(line).Groups["value"].Value.ToString()); } else if(line.Contains("agent_builddirectory")) { agentBuildDirectory = getValueRegex.Match(line).Groups["value"].Value.ToString(); } } } return new Tuple<string, string, DateTime>(sourceFolderJson, agentBuildDirectory, lastRunOn); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // TargetCore.cs // // // The core implementation of a standard ITargetBlock<TInput>. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; namespace System.Threading.Tasks.Dataflow.Internal { // LOCK-LEVELING SCHEME // -------------------- // TargetCore employs a single lock: IncomingLock. This lock must not be used when calling out to any targets, // which TargetCore should not have, anyway. It also must not be held when calling back to any sources, except // during calls to OfferMessage from that same source. /// <summary>Options used to configure a target core.</summary> [Flags] internal enum TargetCoreOptions : byte { /// <summary>Synchronous completion, both a target and a source, etc.</summary> None = 0x0, /// <summary>Whether the block relies on the delegate to signal when an async operation has completed.</summary> UsesAsyncCompletion = 0x1, /// <summary> /// Whether the block containing this target core is just a target or also has a source side. /// If it's just a target, then this target core's completion represents the entire block's completion. /// </summary> RepresentsBlockCompletion = 0x2 } /// <summary> /// Provides a core implementation of <see cref="ITargetBlock{TInput}"/>.</summary> /// <typeparam name="TInput">Specifies the type of data accepted by the <see cref="TargetCore{TInput}"/>.</typeparam> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] [DebuggerDisplay("{DebuggerDisplayContent,nq}")] internal sealed class TargetCore<TInput> { // *** These fields are readonly and are initialized at AppDomain startup. /// <summary>Caching the keep alive predicate.</summary> private static readonly Common.KeepAlivePredicate<TargetCore<TInput>, KeyValuePair<TInput, long>> _keepAlivePredicate = (TargetCore<TInput> thisTargetCore, out KeyValuePair<TInput, long> messageWithId) => thisTargetCore.TryGetNextAvailableOrPostponedMessage(out messageWithId); // *** These fields are readonly and are initialized to new instances at construction. /// <summary>A task representing the completion of the block.</summary> private readonly TaskCompletionSource<VoidResult> _completionSource = new TaskCompletionSource<VoidResult>(); // *** These fields are readonly and are initialized by arguments to the constructor. /// <summary>The target block using this helper.</summary> private readonly ITargetBlock<TInput> _owningTarget; /// <summary>The messages in this target.</summary> /// <remarks>This field doubles as the IncomingLock.</remarks> private readonly IProducerConsumerQueue<KeyValuePair<TInput, long>> _messages; /// <summary>The options associated with this block.</summary> private readonly ExecutionDataflowBlockOptions _dataflowBlockOptions; /// <summary>An action to invoke for every accepted message.</summary> private readonly Action<KeyValuePair<TInput, long>> _callAction; /// <summary>Whether the block relies on the delegate to signal when an async operation has completed.</summary> private readonly TargetCoreOptions _targetCoreOptions; /// <summary>Bounding state for when the block is executing in bounded mode.</summary> private readonly BoundingStateWithPostponed<TInput> _boundingState; /// <summary>The reordering buffer used by the owner. May be null.</summary> private readonly IReorderingBuffer _reorderingBuffer; /// <summary>Gets the object used as the incoming lock.</summary> private object IncomingLock { get { return _messages; } } // *** These fields are mutated during execution. /// <summary>Exceptions that may have occurred and gone unhandled during processing.</summary> private List<Exception> _exceptions; /// <summary>Whether to stop accepting new messages.</summary> private bool _decliningPermanently; /// <summary>The number of operations (including service tasks) currently running asynchronously.</summary> /// <remarks>Must always be accessed from inside a lock.</remarks> private int _numberOfOutstandingOperations; /// <summary>The number of service tasks in async mode currently running.</summary> /// <remarks>Must always be accessed from inside a lock.</remarks> private int _numberOfOutstandingServiceTasks; /// <summary>The next available ID we can assign to a message about to be processed.</summary> private PaddedInt64 _nextAvailableInputMessageId; // initialized to 0... very important for a reordering buffer /// <summary>A task has reserved the right to run the completion routine.</summary> private bool _completionReserved; /// <summary>This counter is set by the processing loop to prevent itself from trying to keep alive.</summary> private int _keepAliveBanCounter; /// <summary>Initializes the target core.</summary> /// <param name="owningTarget">The target using this helper.</param> /// <param name="callAction">An action to invoke for all accepted items.</param> /// <param name="reorderingBuffer">The reordering buffer used by the owner; may be null.</param> /// <param name="dataflowBlockOptions">The options to use to configure this block. The target core assumes these options are immutable.</param> /// <param name="targetCoreOptions">Options for how the target core should behave.</param> internal TargetCore( ITargetBlock<TInput> owningTarget, Action<KeyValuePair<TInput, long>> callAction, IReorderingBuffer reorderingBuffer, ExecutionDataflowBlockOptions dataflowBlockOptions, TargetCoreOptions targetCoreOptions) { // Validate internal arguments Debug.Assert(owningTarget != null, "Core must be associated with a target block."); Debug.Assert(dataflowBlockOptions != null, "Options must be provided to configure the core."); Debug.Assert(callAction != null, "Action to invoke for each item is required."); // Store arguments and do additional initialization _owningTarget = owningTarget; _callAction = callAction; _reorderingBuffer = reorderingBuffer; _dataflowBlockOptions = dataflowBlockOptions; _targetCoreOptions = targetCoreOptions; _messages = (dataflowBlockOptions.MaxDegreeOfParallelism == 1) ? (IProducerConsumerQueue<KeyValuePair<TInput, long>>)new SingleProducerSingleConsumerQueue<KeyValuePair<TInput, long>>() : (IProducerConsumerQueue<KeyValuePair<TInput, long>>)new MultiProducerMultiConsumerQueue<KeyValuePair<TInput, long>>(); if (_dataflowBlockOptions.BoundedCapacity != System.Threading.Tasks.Dataflow.DataflowBlockOptions.Unbounded) { Debug.Assert(_dataflowBlockOptions.BoundedCapacity > 0, "Positive bounding count expected; should have been verified by options ctor"); _boundingState = new BoundingStateWithPostponed<TInput>(_dataflowBlockOptions.BoundedCapacity); } } /// <summary>Internal Complete entry point with extra parameters for different contexts.</summary> /// <param name="exception">If not null, the block will be faulted.</param> /// <param name="dropPendingMessages">If true, any unprocessed input messages will be dropped.</param> /// <param name="storeExceptionEvenIfAlreadyCompleting">If true, an exception will be stored after _decliningPermanently has been set to true.</param> /// <param name="unwrapInnerExceptions">If true, exception will be treated as an AggregateException.</param> /// <param name="revertProcessingState">Indicates whether the processing state is dirty and has to be reverted.</param> internal void Complete(Exception exception, bool dropPendingMessages, bool storeExceptionEvenIfAlreadyCompleting = false, bool unwrapInnerExceptions = false, bool revertProcessingState = false) { Debug.Assert(storeExceptionEvenIfAlreadyCompleting || !revertProcessingState, "Indicating dirty processing state may only come with storeExceptionEvenIfAlreadyCompleting==true."); Contract.EndContractBlock(); // Ensure that no new messages may be added lock (IncomingLock) { // Faulting from outside is allowed until we start declining permanently. // Faulting from inside is allowed at any time. if (exception != null && (!_decliningPermanently || storeExceptionEvenIfAlreadyCompleting)) { Debug.Assert(_numberOfOutstandingOperations > 0 || !storeExceptionEvenIfAlreadyCompleting, "Calls with storeExceptionEvenIfAlreadyCompleting==true may only be coming from processing task."); #pragma warning disable 0420 Common.AddException(ref _exceptions, exception, unwrapInnerExceptions); } // Clear the messages queue if requested if (dropPendingMessages) { KeyValuePair<TInput, long> dummy; while (_messages.TryDequeue(out dummy)) ; } // Revert the dirty processing state if requested if (revertProcessingState) { Debug.Assert(_numberOfOutstandingOperations > 0 && (!UsesAsyncCompletion || _numberOfOutstandingServiceTasks > 0), "The processing state must be dirty when revertProcessingState==true."); _numberOfOutstandingOperations--; if (UsesAsyncCompletion) _numberOfOutstandingServiceTasks--; } // Trigger completion _decliningPermanently = true; CompleteBlockIfPossible(); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> internal DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, bool consumeToAccept) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader)); if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept)); Contract.EndContractBlock(); lock (IncomingLock) { // If we shouldn't be accepting more messages, don't. if (_decliningPermanently) { CompleteBlockIfPossible(); return DataflowMessageStatus.DecliningPermanently; } // We can directly accept the message if: // 1) we are not bounding, OR // 2) we are bounding AND there is room available AND there are no postponed messages AND no messages are currently being transfered to the input queue. // (If there were any postponed messages, we would need to postpone so that ordering would be maintained.) // (Unlike all other blocks, TargetCore can accept messages while processing, because // input message IDs are properly assigned and the correct order is preserved.) if (_boundingState == null || (_boundingState.OutstandingTransfers == 0 && _boundingState.CountIsLessThanBound && _boundingState.PostponedMessages.Count == 0)) { // Consume the message from the source if necessary if (consumeToAccept) { Debug.Assert(source != null, "We must have thrown if source == null && consumeToAccept == true."); bool consumed; messageValue = source.ConsumeMessage(messageHeader, _owningTarget, out consumed); if (!consumed) return DataflowMessageStatus.NotAvailable; } // Assign a message ID - strictly sequential, no gaps. // Once consumed, enqueue the message with its ID and kick off asynchronous processing. long messageId = _nextAvailableInputMessageId.Value++; Debug.Assert(messageId != Common.INVALID_REORDERING_ID, "The assigned message ID is invalid."); if (_boundingState != null) _boundingState.CurrentCount += 1; // track this new item against our bound _messages.Enqueue(new KeyValuePair<TInput, long>(messageValue, messageId)); ProcessAsyncIfNecessary(); return DataflowMessageStatus.Accepted; } // Otherwise, we try to postpone if a source was provided else if (source != null) { Debug.Assert(_boundingState != null && _boundingState.PostponedMessages != null, "PostponedMessages must have been initialized during construction in non-greedy mode."); // Store the message's info and kick off asynchronous processing _boundingState.PostponedMessages.Push(source, messageHeader); ProcessAsyncIfNecessary(); return DataflowMessageStatus.Postponed; } // We can't do anything else about this message return DataflowMessageStatus.Declined; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> internal Task Completion { get { return _completionSource.Task; } } /// <summary>Gets the number of items waiting to be processed by this target.</summary> internal int InputCount { get { return _messages.GetCountSafe(IncomingLock); } } /// <summary>Signals to the target core that a previously launched asynchronous operation has now completed.</summary> internal void SignalOneAsyncMessageCompleted() { SignalOneAsyncMessageCompleted(boundingCountChange: 0); } /// <summary>Signals to the target core that a previously launched asynchronous operation has now completed.</summary> /// <param name="boundingCountChange">The number of elements by which to change the bounding count, if bounding is occurring.</param> internal void SignalOneAsyncMessageCompleted(int boundingCountChange) { lock (IncomingLock) { // We're no longer processing, so decrement the DOP counter Debug.Assert(_numberOfOutstandingOperations > 0, "Operations may only be completed if any are outstanding."); if (_numberOfOutstandingOperations > 0) _numberOfOutstandingOperations--; // Fix up the bounding count if necessary if (_boundingState != null && boundingCountChange != 0) { Debug.Assert(boundingCountChange <= 0 && _boundingState.CurrentCount + boundingCountChange >= 0, "Expected a negative bounding change and not to drop below zero."); _boundingState.CurrentCount += boundingCountChange; } // However, we may have given up early because we hit our own configured // processing limits rather than because we ran out of work to do. If that's // the case, make sure we spin up another task to keep going. ProcessAsyncIfNecessary(repeat: true); // If, however, we stopped because we ran out of work to do and we // know we'll never get more, then complete. CompleteBlockIfPossible(); } } /// <summary>Gets whether this instance has been constructed for async processing.</summary> private bool UsesAsyncCompletion { get { return (_targetCoreOptions & TargetCoreOptions.UsesAsyncCompletion) != 0; } } /// <summary>Gets whether there's room to launch more processing operations.</summary> private bool HasRoomForMoreOperations { get { Debug.Assert(_numberOfOutstandingOperations >= 0, "Number of outstanding operations should never be negative."); Debug.Assert(_numberOfOutstandingServiceTasks >= 0, "Number of outstanding service tasks should never be negative."); Debug.Assert(_numberOfOutstandingOperations >= _numberOfOutstandingServiceTasks, "Number of outstanding service tasks should never exceed the number of outstanding operations."); Common.ContractAssertMonitorStatus(IncomingLock, held: true); // In async mode, we increment _numberOfOutstandingOperations before we start // our own processing loop which should not count towards the MaxDOP. return (_numberOfOutstandingOperations - _numberOfOutstandingServiceTasks) < _dataflowBlockOptions.ActualMaxDegreeOfParallelism; } } /// <summary>Gets whether there's room to launch more service tasks for doing/launching processing operations.</summary> private bool HasRoomForMoreServiceTasks { get { Debug.Assert(_numberOfOutstandingOperations >= 0, "Number of outstanding operations should never be negative."); Debug.Assert(_numberOfOutstandingServiceTasks >= 0, "Number of outstanding service tasks should never be negative."); Debug.Assert(_numberOfOutstandingOperations >= _numberOfOutstandingServiceTasks, "Number of outstanding service tasks should never exceed the number of outstanding operations."); Common.ContractAssertMonitorStatus(IncomingLock, held: true); if (!UsesAsyncCompletion) { // Sync mode: // We don't count service tasks, because our tasks are counted as operations. // Therefore, return HasRoomForMoreOperations. return HasRoomForMoreOperations; } else { // Async mode: // We allow up to MaxDOP true service tasks. // Checking whether there is room for more processing operations is not necessary, // but doing so will help us avoid spinning up a task that will go away without // launching any processing operation. return HasRoomForMoreOperations && _numberOfOutstandingServiceTasks < _dataflowBlockOptions.ActualMaxDegreeOfParallelism; } } } /// <summary>Called when new messages are available to be processed.</summary> /// <param name="repeat">Whether this call is the continuation of a previous message loop.</param> private void ProcessAsyncIfNecessary(bool repeat = false) { Common.ContractAssertMonitorStatus(IncomingLock, held: true); if (HasRoomForMoreServiceTasks) { ProcessAsyncIfNecessary_Slow(repeat); } } /// <summary> /// Slow path for ProcessAsyncIfNecessary. /// Separating out the slow path into its own method makes it more likely that the fast path method will get inlined. /// </summary> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void ProcessAsyncIfNecessary_Slow(bool repeat) { Debug.Assert(HasRoomForMoreServiceTasks, "There must be room to process asynchronously."); Common.ContractAssertMonitorStatus(IncomingLock, held: true); // Determine preconditions to launching a processing task bool messagesAvailableOrPostponed = !_messages.IsEmpty || (!_decliningPermanently && _boundingState != null && _boundingState.CountIsLessThanBound && _boundingState.PostponedMessages.Count > 0); // If all conditions are met, launch away if (messagesAvailableOrPostponed && !CanceledOrFaulted) { // Any book keeping related to the processing task like incrementing the // DOP counter or eventually recording the tasks reference must be done // before the task starts. That is because the task itself will do the // reverse operation upon its completion. _numberOfOutstandingOperations++; if (UsesAsyncCompletion) _numberOfOutstandingServiceTasks++; var taskForInputProcessing = new Task(thisTargetCore => ((TargetCore<TInput>)thisTargetCore).ProcessMessagesLoopCore(), this, Common.GetCreationOptionsForTask(repeat)); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TaskLaunchedForMessageHandling( _owningTarget, taskForInputProcessing, DataflowEtwProvider.TaskLaunchedReason.ProcessingInputMessages, _messages.Count + (_boundingState != null ? _boundingState.PostponedMessages.Count : 0)); } #endif // Start the task handling scheduling exceptions Exception exception = Common.StartTaskSafe(taskForInputProcessing, _dataflowBlockOptions.TaskScheduler); if (exception != null) { // Get out from under currently held locks. Complete re-acquires the locks it needs. Task.Factory.StartNew(exc => Complete(exception: (Exception)exc, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: false, revertProcessingState: true), exception, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default); } } } /// <summary>Task body used to process messages.</summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ProcessMessagesLoopCore() { Common.ContractAssertMonitorStatus(IncomingLock, held: false); KeyValuePair<TInput, long> messageWithId = default(KeyValuePair<TInput, long>); try { bool useAsyncCompletion = UsesAsyncCompletion; bool shouldAttemptPostponedTransfer = _boundingState != null && _boundingState.BoundedCapacity > 1; int numberOfMessagesProcessedByThisTask = 0; int numberOfMessagesProcessedSinceTheLastKeepAlive = 0; int maxMessagesPerTask = _dataflowBlockOptions.ActualMaxMessagesPerTask; while (numberOfMessagesProcessedByThisTask < maxMessagesPerTask && !CanceledOrFaulted) { // If we're bounding, try to transfer a message from the postponed queue // to the input queue. This enables us to more quickly unblock sources // sending data to the block (otherwise, no postponed messages will be consumed // until the input queue is entirely empty). If the bounded size is 1, // there's no need to transfer, as attempting to get the next message will // just go and consume the postponed message anyway, and we'll save // the extra trip through the _messages queue. KeyValuePair<TInput, long> transferMessageWithId; if (shouldAttemptPostponedTransfer && TryConsumePostponedMessage(forPostponementTransfer: true, result: out transferMessageWithId)) { lock (IncomingLock) { Debug.Assert( _boundingState.OutstandingTransfers > 0 && _boundingState.OutstandingTransfers <= _dataflowBlockOptions.ActualMaxDegreeOfParallelism, "Expected TryConsumePostponedMessage to have incremented the count and for the count to not exceed the DOP."); _boundingState.OutstandingTransfers--; // was incremented in TryConsumePostponedMessage _messages.Enqueue(transferMessageWithId); ProcessAsyncIfNecessary(); } } if (useAsyncCompletion) { // Get the next message if DOP is available. // If we can't get a message or DOP is not available, bail out. if (!TryGetNextMessageForNewAsyncOperation(out messageWithId)) break; } else { // Try to get a message for sequential execution, i.e. without checking DOP availability if (!TryGetNextAvailableOrPostponedMessage(out messageWithId)) { // Try to keep the task alive only if MaxDOP=1 if (_dataflowBlockOptions.MaxDegreeOfParallelism != 1) break; // If this task has processed enough messages without being kept alive, // it has served its purpose. Don't keep it alive. if (numberOfMessagesProcessedSinceTheLastKeepAlive > Common.KEEP_ALIVE_NUMBER_OF_MESSAGES_THRESHOLD) break; // If keep alive is banned, don't attempt it if (_keepAliveBanCounter > 0) { _keepAliveBanCounter--; break; } // Reset the keep alive counter. (Keep this line together with TryKeepAliveUntil.) numberOfMessagesProcessedSinceTheLastKeepAlive = 0; // Try to keep the task alive briefly until a new message arrives if (!Common.TryKeepAliveUntil(_keepAlivePredicate, this, out messageWithId)) { // Keep alive was unsuccessful. // Therefore ban further attempts temporarily. _keepAliveBanCounter = Common.KEEP_ALIVE_BAN_COUNT; break; } } } // We have popped a message from the queue. // So increment the counter of processed messages. numberOfMessagesProcessedByThisTask++; numberOfMessagesProcessedSinceTheLastKeepAlive++; // Invoke the user action _callAction(messageWithId); } } catch (Exception exc) { Common.StoreDataflowMessageValueIntoExceptionData(exc, messageWithId.Key); Complete(exc, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: false); } finally { lock (IncomingLock) { // We incremented _numberOfOutstandingOperations before we launched this task. // So we must decremented it before exiting. // Note that each async task additionally incremented it before starting and // is responsible for decrementing it prior to exiting. Debug.Assert(_numberOfOutstandingOperations > 0, "Expected a positive number of outstanding operations, since we're completing one here."); _numberOfOutstandingOperations--; // If we are in async mode, we've also incremented _numberOfOutstandingServiceTasks. // Now it's time to decrement it. if (UsesAsyncCompletion) { Debug.Assert(_numberOfOutstandingServiceTasks > 0, "Expected a positive number of outstanding service tasks, since we're completing one here."); _numberOfOutstandingServiceTasks--; } // However, we may have given up early because we hit our own configured // processing limits rather than because we ran out of work to do. If that's // the case, make sure we spin up another task to keep going. ProcessAsyncIfNecessary(repeat: true); // If, however, we stopped because we ran out of work to do and we // know we'll never get more, then complete. CompleteBlockIfPossible(); } } } /// <summary>Retrieves the next message from the input queue for the useAsyncCompletion mode.</summary> /// <param name="messageWithId">The next message retrieved.</param> /// <returns>true if a message was found and removed; otherwise, false.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private bool TryGetNextMessageForNewAsyncOperation(out KeyValuePair<TInput, long> messageWithId) { Debug.Assert(UsesAsyncCompletion, "Only valid to use when in async mode."); Common.ContractAssertMonitorStatus(IncomingLock, held: false); bool parallelismAvailable; lock (IncomingLock) { // If we have room for another asynchronous operation, reserve it. // If later it turns out that we had no work to fill the slot, we'll undo the addition. parallelismAvailable = HasRoomForMoreOperations; if (parallelismAvailable) ++_numberOfOutstandingOperations; } messageWithId = default(KeyValuePair<TInput, long>); if (parallelismAvailable) { // If a parallelism slot was available, try to get an item. // Be careful, because an exception may be thrown from ConsumeMessage // and we have already incremented _numberOfOutstandingOperations. bool gotMessage = false; try { gotMessage = TryGetNextAvailableOrPostponedMessage(out messageWithId); } catch { // We have incremented the counter, but we didn't get a message. // So we must undo the increment and eventually complete the block. SignalOneAsyncMessageCompleted(); // Re-throw the exception. The processing loop will catch it. throw; } // There may not be an error, but may have still failed to get a message. // So we must undo the increment and eventually complete the block. if (!gotMessage) SignalOneAsyncMessageCompleted(); return gotMessage; } // If there was no parallelism available, we didn't increment _numberOfOutstandingOperations. // So there is nothing to do except to return false. return false; } /// <summary> /// Either takes the next available message from the input queue or retrieves a postponed /// message from a source, based on whether we're in greedy or non-greedy mode. /// </summary> /// <param name="messageWithId">The retrieved item with its Id.</param> /// <returns>true if a message could be removed and returned; otherwise, false.</returns> private bool TryGetNextAvailableOrPostponedMessage(out KeyValuePair<TInput, long> messageWithId) { Common.ContractAssertMonitorStatus(IncomingLock, held: false); // First try to get a message from our input buffer. if (_messages.TryDequeue(out messageWithId)) { return true; } // If we can't, but if we have any postponed messages due to bounding, then // try to consume one of these postponed messages. // Since we are not currently holding the lock, it is possible that new messages get queued up // by the time we take the lock to manipulate _boundingState. So we have to double-check the // input queue once we take the lock before we consider postponed messages. else if (_boundingState != null && TryConsumePostponedMessage(forPostponementTransfer: false, result: out messageWithId)) { return true; } // Otherwise, there's no message available. else { messageWithId = default(KeyValuePair<TInput, long>); return false; } } /// <summary>Consumes a single postponed message.</summary> /// <param name="forPostponementTransfer"> /// true if the method is being called to consume a message that'll then be stored into the input queue; /// false if the method is being called to consume a message that'll be processed immediately. /// If true, the bounding state's ForcePostponement will be updated. /// If false, the method will first try (while holding the lock) to consume from the input queue before /// consuming a postponed message. /// </param> /// <param name="result">The consumed message.</param> /// <returns>true if a message was consumed; otherwise, false.</returns> private bool TryConsumePostponedMessage( bool forPostponementTransfer, out KeyValuePair<TInput, long> result) { Debug.Assert( _dataflowBlockOptions.BoundedCapacity != System.Threading.Tasks.Dataflow.DataflowBlockOptions.Unbounded, "Only valid to use when in bounded mode."); Common.ContractAssertMonitorStatus(IncomingLock, held: false); // Iterate until we either consume a message successfully or there are no more postponed messages. bool countIncrementedExpectingToGetItem = false; long messageId = Common.INVALID_REORDERING_ID; while (true) { KeyValuePair<ISourceBlock<TInput>, DataflowMessageHeader> element; lock (IncomingLock) { // If we are declining permanently, don't consume postponed messages. if (_decliningPermanently) break; // New messages may have been queued up while we weren't holding the lock. // In particular, the input queue may have been filled up and messages may have // gotten postponed. If we process such a postponed message, we would mess up the // order. Therefore, we have to double-check the input queue first. if (!forPostponementTransfer && _messages.TryDequeue(out result)) return true; // We can consume a message to process if there's one to process and also if // if we have logical room within our bound for the message. if (!_boundingState.CountIsLessThanBound || !_boundingState.PostponedMessages.TryPop(out element)) { if (countIncrementedExpectingToGetItem) { countIncrementedExpectingToGetItem = false; _boundingState.CurrentCount -= 1; } break; } if (!countIncrementedExpectingToGetItem) { countIncrementedExpectingToGetItem = true; messageId = _nextAvailableInputMessageId.Value++; // optimistically assign an ID Debug.Assert(messageId != Common.INVALID_REORDERING_ID, "The assigned message ID is invalid."); _boundingState.CurrentCount += 1; // optimistically take bounding space if (forPostponementTransfer) { Debug.Assert(_boundingState.OutstandingTransfers >= 0, "Expected TryConsumePostponedMessage to not be negative."); _boundingState.OutstandingTransfers++; // temporarily force postponement until we've successfully consumed the element } } } // Must not call to source while holding lock bool consumed; TInput consumedValue = element.Key.ConsumeMessage(element.Value, _owningTarget, out consumed); if (consumed) { result = new KeyValuePair<TInput, long>(consumedValue, messageId); return true; } else { if (forPostponementTransfer) { // We didn't consume message so we need to decrement because we haven't consumed the element. _boundingState.OutstandingTransfers--; } } } // We optimistically acquired a message ID for a message that, in the end, we never got. // So, we need to let the reordering buffer (if one exists) know that it should not // expect an item with this ID. Otherwise, it would stall forever. if (_reorderingBuffer != null && messageId != Common.INVALID_REORDERING_ID) _reorderingBuffer.IgnoreItem(messageId); // Similarly, we optimistically increased the bounding count, expecting to get another message in. // Since we didn't, we need to fix the bounding count back to what it should have been. if (countIncrementedExpectingToGetItem) ChangeBoundingCount(-1); // Inform the caller that no message could be consumed. result = default(KeyValuePair<TInput, long>); return false; } /// <summary>Gets whether the target has had cancellation requested or an exception has occurred.</summary> private bool CanceledOrFaulted { get { return _dataflowBlockOptions.CancellationToken.IsCancellationRequested || Volatile.Read(ref _exceptions) != null; } } /// <summary>Completes the block once all completion conditions are met.</summary> private void CompleteBlockIfPossible() { Common.ContractAssertMonitorStatus(IncomingLock, held: true); bool noMoreMessages = _decliningPermanently && _messages.IsEmpty; if (noMoreMessages || CanceledOrFaulted) { CompleteBlockIfPossible_Slow(); } } /// <summary> /// Slow path for CompleteBlockIfPossible. /// Separating out the slow path into its own method makes it more likely that the fast path method will get inlined. /// </summary> private void CompleteBlockIfPossible_Slow() { Debug.Assert((_decliningPermanently && _messages.IsEmpty) || CanceledOrFaulted, "There must be no more messages."); Common.ContractAssertMonitorStatus(IncomingLock, held: true); bool notCurrentlyProcessing = _numberOfOutstandingOperations == 0; if (notCurrentlyProcessing && !_completionReserved) { // Make sure no one else tries to call CompleteBlockOncePossible _completionReserved = true; // Make sure the target is declining _decliningPermanently = true; // Get out from under currently held locks. This is to avoid // invoking synchronous continuations off of _completionSource.Task // while holding a lock. Task.Factory.StartNew(state => ((TargetCore<TInput>)state).CompleteBlockOncePossible(), this, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default); } } /// <summary> /// Completes the block. This must only be called once, and only once all of the completion conditions are met. /// As such, it must only be called from CompleteBlockIfPossible. /// </summary> private void CompleteBlockOncePossible() { // Since the lock is needed only for the Assert, we do this only in DEBUG mode #if DEBUG lock (IncomingLock) Debug.Assert(_numberOfOutstandingOperations == 0, "Everything must be done by now."); #endif // Release any postponed messages if (_boundingState != null) { // Note: No locks should be held at this point. Common.ReleaseAllPostponedMessages(_owningTarget, _boundingState.PostponedMessages, ref _exceptions); } // For good measure and help in preventing leaks, clear out the incoming message queue, // which may still contain orphaned data if we were canceled or faulted. However, // we don't reset the bounding count here, as the block as a whole may still be active. KeyValuePair<TInput, long> ignored; IProducerConsumerQueue<KeyValuePair<TInput, long>> messages = _messages; while (messages.TryDequeue(out ignored)) ; // If we completed with any unhandled exception, finish in an error state if (Volatile.Read(ref _exceptions) != null) { // It's ok to read _exceptions' content here, because // at this point no more exceptions can be generated and thus no one will // be writing to it. _completionSource.TrySetException(Volatile.Read(ref _exceptions)); } // If we completed with cancellation, finish in a canceled state else if (_dataflowBlockOptions.CancellationToken.IsCancellationRequested) { _completionSource.TrySetCanceled(); } // Otherwise, finish in a successful state. else { _completionSource.TrySetResult(default(VoidResult)); } #if FEATURE_TRACING // We only want to do tracing for block completion if this target core represents the whole block. // If it only represents a part of the block (i.e. there's a source associated with it as well), // then we shouldn't log just for the first half of the block; the source half will handle logging. DataflowEtwProvider etwLog; if ((_targetCoreOptions & TargetCoreOptions.RepresentsBlockCompletion) != 0 && (etwLog = DataflowEtwProvider.Log).IsEnabled()) { etwLog.DataflowBlockCompleted(_owningTarget); } #endif } /// <summary>Gets whether the target core is operating in a bounded mode.</summary> internal bool IsBounded { get { return _boundingState != null; } } /// <summary>Increases or decreases the bounding count.</summary> /// <param name="count">The incremental addition (positive to increase, negative to decrease).</param> internal void ChangeBoundingCount(int count) { Debug.Assert(count != 0, "Should only be called when the count is actually changing."); Common.ContractAssertMonitorStatus(IncomingLock, held: false); if (_boundingState != null) { lock (IncomingLock) { Debug.Assert(count > 0 || (count < 0 && _boundingState.CurrentCount + count >= 0), "If count is negative, it must not take the total count negative."); _boundingState.CurrentCount += count; ProcessAsyncIfNecessary(); CompleteBlockIfPossible(); } } } /// <summary>Gets the object to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { var displayTarget = _owningTarget as IDebuggerDisplay; return string.Format("Block=\"{0}\"", displayTarget != null ? displayTarget.Content : _owningTarget); } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> internal ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _dataflowBlockOptions; } } /// <summary>Gets information about this helper to be used for display in a debugger.</summary> /// <returns>Debugging information about this target.</returns> internal DebuggingInformation GetDebuggingInformation() { return new DebuggingInformation(this); } /// <summary>Provides a wrapper for commonly needed debugging information.</summary> internal sealed class DebuggingInformation { /// <summary>The target being viewed.</summary> private readonly TargetCore<TInput> _target; /// <summary>Initializes the debugging helper.</summary> /// <param name="target">The target being viewed.</param> internal DebuggingInformation(TargetCore<TInput> target) { _target = target; } /// <summary>Gets the number of messages waiting to be processed.</summary> internal int InputCount { get { return _target._messages.Count; } } /// <summary>Gets the messages waiting to be processed.</summary> internal IEnumerable<TInput> InputQueue { get { return _target._messages.Select(kvp => kvp.Key).ToList(); } } /// <summary>Gets any postponed messages.</summary> internal QueuedMap<ISourceBlock<TInput>, DataflowMessageHeader> PostponedMessages { get { return _target._boundingState != null ? _target._boundingState.PostponedMessages : null; } } /// <summary>Gets the current number of outstanding input processing operations.</summary> internal int CurrentDegreeOfParallelism { get { return _target._numberOfOutstandingOperations - _target._numberOfOutstandingServiceTasks; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> internal ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _target._dataflowBlockOptions; } } /// <summary>Gets whether the block is declining further messages.</summary> internal bool IsDecliningPermanently { get { return _target._decliningPermanently; } } /// <summary>Gets whether the block is completed.</summary> internal bool IsCompleted { get { return _target.Completion.IsCompleted; } } } } }
using System; using System.Collections.Generic; using DotNetXmlSwfChart; namespace testWeb.tests { public class BarStackedTwo : ChartTestBase { #region ChartInclude public override ChartHTML ChartInclude { get { ChartHTML chartHtml = new ChartHTML(); chartHtml.height = 300; chartHtml.bgColor = "eecc55"; chartHtml.flashFile = "charts/charts.swf"; chartHtml.libraryPath = "charts/charts_library"; chartHtml.xmlSource = "xmlData.aspx"; return chartHtml; } } #endregion #region Chart public override Chart Chart { get { Chart c = new Chart(); c.AddChartType(XmlSwfChartType.BarStacked); c.AxisCategory = SetAxisCategory(c.ChartType[0]); c.AxisTicks = SetAxisTicks(); c.AxisValue = SetAxisValue(); c.ChartBorder = SetChartBorder(); c.Data = SetChartData(); c.ChartGridH = SetChartGrid(ChartGridType.Horizontal); c.ChartGridV = SetChartGrid(ChartGridType.Vertical); c.ChartRectangle = SetChartRectangle(); c.ChartTransition = SetChartTransition(); c.AddDrawText(CreateDrawText(1)); c.AddDrawText(CreateDrawText(2)); c.LegendLabel = SetLegendLabel(); c.LegendRectangle = SetLegendRectangle(); c.LegendTransition = SetLegendTransition(); c.AddSeriesColor("5a4b6e"); c.AddSeriesColor("4c6b41"); return c; } } #endregion #region Helpers private AxisCategory SetAxisCategory(XmlSwfChartType xmlSwfChartType) { AxisCategory ac = new AxisCategory(xmlSwfChartType); ac.Font = "Arial"; ac.Bold = true; ac.Size = 13; ac.Color = "000022"; ac.Alpha = 50; ac.Skip = 0; ac.Orientation = "diagonal_up"; return ac; } private AxisTicks SetAxisTicks() { AxisTicks at = new AxisTicks(); at.ValueTicks = false; at.CategoryTicks = true; at.MajorThickness = 0; at.MinorThickness = 0; at.MinorCount = 3; at.MajorColor = "000000"; at.MinorColor = "888888"; at.Position = "outside"; return at; } private AxisValue SetAxisValue() { AxisValue av = new AxisValue(); av.Font = "Arial"; av.Bold = true; av.Size = 10; av.Color = "000022"; av.Alpha = 50; av.Steps = 4; av.Prefix = ""; av.Suffix = ""; av.Decimals = 0; av.Separator = ""; av.ShowMin = true; av.Orientation = "horizontal"; return av; } private ChartBorder SetChartBorder() { ChartBorder cb = new ChartBorder(); cb.Color = "000000"; cb.TopThickness = 0; cb.BottomThickness = 0; cb.LeftThickness = 3; cb.RightThickness = 0; return cb; } private ChartData SetChartData() { ChartData cd = new ChartData(); cd.AddDataPoint("region A", "2004", -60); cd.AddDataPoint("region A", "2005", -25); cd.AddDataPoint("region A", "2006", 75); cd.AddDataPoint("region A", "2007", 50); cd.AddDataPoint("region B", "2004", 60); cd.AddDataPoint("region B", "2005", 10); cd.AddDataPoint("region B", "2006", 75); cd.AddDataPoint("region B", "2007", 25); return cd; } private ChartGrid SetChartGrid(ChartGridType chartGridType) { ChartGrid cg = new ChartGrid(chartGridType); cg.Alpha = 10; cg.Color = "000000"; switch (chartGridType) { case ChartGridType.Horizontal: cg.Thickness = 5; break; case ChartGridType.Vertical: cg.Thickness = 1; break; } return cg; } private ChartRectangle SetChartRectangle() { ChartRectangle cr = new ChartRectangle(); cr.X = 50; cr.Y = 50; cr.Width = 320; cr.Height = 200; cr.PositiveColor = "00ff00"; cr.NegativeColor = "ff0000"; cr.PositiveAlpha = 20; cr.NegativeAlpha = 20; return cr; } private ChartTransition SetChartTransition() { ChartTransition ct = new ChartTransition(); ct.TransitionType = TransitionType.slide_right; ct.Delay = 0; ct.Duration = 0.75; ct.Order = TransitionOrder.series; return ct; } private DrawText CreateDrawText(int p) { DrawText dt = new DrawText(); dt.Transition = TransitionType.dissolve; dt.Delay = 1.5; dt.Duration = 0.5; dt.Color="000033"; dt.Alpha = 15; dt.Font = "Arial"; dt.Rotation = 0; dt.Bold = true; dt.Size = 30; dt.X = 0; dt.Y = 5; dt.Width = 372; dt.Height = 40; dt.HAlign = TextHAlign.right; dt.VAlign = TextVAlign.bottom; dt.Text = "regional report"; if (p == 2) { dt.Color = "ffffff"; dt.Rotation = -5; dt.Size = 150; dt.X = 110; dt.Y = 290; dt.Width = 400; dt.Height = 50; dt.HAlign = TextHAlign.left; dt.Text = "2007"; } return dt; } private LegendLabel SetLegendLabel() { LegendLabel ll = new LegendLabel(); ll.Layout = LegendLabelLayout.vertical; ll.Font = "Arial"; ll.Bold = true; ll.Size = 13; ll.Color = "000022"; ll.Alpha = 50; return ll; } private LegendRectangle SetLegendRectangle() { LegendRectangle lr = new LegendRectangle(); lr.X = 50; lr.Y = 15; lr.Width = 10; lr.Height = 30; lr.Margin = 0; lr.FillColor = "000066"; lr.FillAlpha = 0; lr.LineColor = "000000"; lr.LineAlpha = 0; lr.LineThickness = 0; return lr; } private LegendTransition SetLegendTransition() { LegendTransition lt = new LegendTransition(); lt.Type = TransitionType.dissolve; lt.Delay = 2; lt.Duration = 0.5; return lt; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Transactions; namespace System.Data.ProviderBase { internal abstract partial class DbConnectionInternal { internal static readonly StateChangeEventArgs StateChangeClosed = new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed); internal static readonly StateChangeEventArgs StateChangeOpen = new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open); private readonly bool _allowSetConnectionString; private readonly bool _hidePassword; private readonly ConnectionState _state; private readonly WeakReference _owningObject = new WeakReference(null, false); // [usage must be thread safe] the owning object, when not in the pool. (both Pooled and Non-Pooled connections) private DbConnectionPool _connectionPool; // the pooler that the connection came from (Pooled connections only) private DbReferenceCollection _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated private int _pooledCount; // [usage must be thread safe] the number of times this object has been pushed into the pool less the number of times it's been popped (0 != inPool) private bool _connectionIsDoomed; // true when the connection should no longer be used. private bool _cannotBePooled; // true when the connection should no longer be pooled. private DateTime _createTime; // when the connection was created. #if DEBUG private int _activateCount; // debug only counter to verify activate/deactivates are in sync. #endif //DEBUG protected DbConnectionInternal() : this(ConnectionState.Open, true, false) { } // Constructor for internal connections internal DbConnectionInternal(ConnectionState state, bool hidePassword, bool allowSetConnectionString) { _allowSetConnectionString = allowSetConnectionString; _hidePassword = hidePassword; _state = state; } internal bool AllowSetConnectionString { get { return _allowSetConnectionString; } } internal bool CanBePooled { get { bool flag = (!_connectionIsDoomed && !_cannotBePooled && !_owningObject.IsAlive); return flag; } } protected internal bool IsConnectionDoomed { get { return _connectionIsDoomed; } } internal bool IsEmancipated { get { // NOTE: There are race conditions between PrePush, PostPop and this // property getter -- only use this while this object is locked; // (DbConnectionPool.Clear and ReclaimEmancipatedObjects // do this for us) // The functionality is as follows: // // _pooledCount is incremented when the connection is pushed into the pool // _pooledCount is decremented when the connection is popped from the pool // _pooledCount is set to -1 when the connection is not pooled (just in case...) // // That means that: // // _pooledCount > 1 connection is in the pool multiple times (This should not happen) // _pooledCount == 1 connection is in the pool // _pooledCount == 0 connection is out of the pool // _pooledCount == -1 connection is not a pooled connection; we shouldn't be here for non-pooled connections. // _pooledCount < -1 connection out of the pool multiple times // // Now, our job is to return TRUE when the connection is out // of the pool and it's owning object is no longer around to // return it. bool value = (_pooledCount < 1) && !_owningObject.IsAlive; return value; } } internal bool IsInPool { get { Debug.Assert(_pooledCount <= 1 && _pooledCount >= -1, "Pooled count for object is invalid"); return (_pooledCount == 1); } } protected internal object Owner { // We use a weak reference to the owning object so we can identify when // it has been garbage collected without thowing exceptions. get { return _owningObject.Target; } } internal DbConnectionPool Pool { get { return _connectionPool; } } protected internal DbReferenceCollection ReferenceCollection { get { return _referenceCollection; } } abstract public string ServerVersion { get; } // this should be abstract but until it is added to all the providers virtual will have to do virtual public string ServerVersionNormalized { get { throw ADP.NotSupported(); } } public bool ShouldHidePassword { get { return _hidePassword; } } public ConnectionState State { get { return _state; } } internal void AddWeakReference(object value, int tag) { if (null == _referenceCollection) { _referenceCollection = CreateReferenceCollection(); if (null == _referenceCollection) { throw ADP.InternalError(ADP.InternalErrorCode.CreateReferenceCollectionReturnedNull); } } _referenceCollection.Add(value, tag); } abstract public DbTransaction BeginTransaction(IsolationLevel il); virtual public void ChangeDatabase(string value) { throw ADP.MethodNotImplemented(); } virtual internal void PrepareForReplaceConnection() { // By default, there is no preparation required } virtual protected void PrepareForCloseConnection() { // By default, there is no preparation required } virtual protected object ObtainAdditionalLocksForClose() { return null; // no additional locks in default implementation } virtual protected void ReleaseAdditionalLocksForClose(object lockToken) { // no additional locks in default implementation } virtual protected DbReferenceCollection CreateReferenceCollection() { throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToConstructReferenceCollectionOnStaticObject); } abstract protected void Deactivate(); internal void DeactivateConnection() { // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); #endif // DEBUG if (!_connectionIsDoomed && Pool.UseLoadBalancing) { // If we're not already doomed, check the connection's lifetime and // doom it if it's lifetime has elapsed. DateTime now = DateTime.UtcNow; if ((now.Ticks - _createTime.Ticks) > Pool.LoadBalanceTimeout.Ticks) { DoNotPoolThisConnection(); } } Deactivate(); } protected internal void DoNotPoolThisConnection() { _cannotBePooled = true; } /// <devdoc>Ensure that this connection cannot be put back into the pool.</devdoc> protected internal void DoomThisConnection() { _connectionIsDoomed = true; } protected internal virtual DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions) { Debug.Assert(outerConnection != null, "outerConnection may not be null."); DbMetaDataFactory metaDataFactory = factory.GetMetaDataFactory(poolGroup, this); Debug.Assert(metaDataFactory != null, "metaDataFactory may not be null."); return metaDataFactory.GetSchema(outerConnection, collectionName, restrictions); } internal void MakeNonPooledObject(object owningObject) { // Used by DbConnectionFactory to indicate that this object IS NOT part of // a connection pool. _connectionPool = null; _owningObject.Target = owningObject; _pooledCount = -1; } internal void MakePooledConnection(DbConnectionPool connectionPool) { // Used by DbConnectionFactory to indicate that this object IS part of // a connection pool. _createTime = DateTime.UtcNow; _connectionPool = connectionPool; } internal void NotifyWeakReference(int message) { DbReferenceCollection referenceCollection = ReferenceCollection; if (null != referenceCollection) { referenceCollection.Notify(message); } } internal virtual void OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) { if (!TryOpenConnection(outerConnection, connectionFactory, null, null)) { throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending); } } /// <devdoc>The default implementation is for the open connection objects, and /// it simply throws. Our private closed-state connection objects /// override this and do the correct thing.</devdoc> // User code should either override DbConnectionInternal.Activate when it comes out of the pool // or override DbConnectionFactory.CreateConnection when the connection is created for non-pooled connections internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) { throw ADP.ConnectionAlreadyOpen(State); } internal virtual bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) { throw ADP.MethodNotImplemented(); } protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) { // ?->Connecting: prevent set_ConnectionString during Open if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this)) { DbConnectionInternal openConnection = null; try { connectionFactory.PermissionDemand(outerConnection); if (!connectionFactory.TryGetConnection(outerConnection, retry, userOptions, this, out openConnection)) { return false; } } catch { // This should occur for all exceptions, even ADP.UnCatchableExceptions. connectionFactory.SetInnerConnectionTo(outerConnection, this); throw; } if (null == openConnection) { connectionFactory.SetInnerConnectionTo(outerConnection, this); throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull); } connectionFactory.SetInnerConnectionEvent(outerConnection, openConnection); } return true; } internal void PrePush(object expectedOwner) { // Called by DbConnectionPool when we're about to be put into it's pool, we // take this opportunity to ensure ownership and pool counts are legit. // IMPORTANT NOTE: You must have taken a lock on the object before // you call this method to prevent race conditions with Clear and // ReclaimEmancipatedObjects. //3 // The following tests are retail assertions of things we can't allow to happen. if (null == expectedOwner) { if (null != _owningObject.Target) { throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasOwner); // new unpooled object has an owner } } else if (_owningObject.Target != expectedOwner) { throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); // unpooled object has incorrect owner } if (0 != _pooledCount) { throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time } _pooledCount++; _owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2% } internal void PostPop(object newOwner) { // Called by DbConnectionPool right after it pulls this from it's pool, we // take this opportunity to ensure ownership and pool counts are legit. Debug.Assert(!IsEmancipated, "pooled object not in pool"); // When another thread is clearing this pool, it // will doom all connections in this pool without prejudice which // causes the following assert to fire, which really mucks up stress // against checked bits. The assert is benign, so we're commenting // it out. //Debug.Assert(CanBePooled, "pooled object is not poolable"); // IMPORTANT NOTE: You must have taken a lock on the object before // you call this method to prevent race conditions with Clear and // ReclaimEmancipatedObjects. if (null != _owningObject.Target) { throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectHasOwner); // pooled connection already has an owner! } _owningObject.Target = newOwner; _pooledCount--; //3 // The following tests are retail assertions of things we can't allow to happen. if (null != Pool) { if (0 != _pooledCount) { throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectInPoolMoreThanOnce); // popping object off stack with multiple pooledCount } } else if (-1 != _pooledCount) { throw ADP.InternalError(ADP.InternalErrorCode.NonPooledObjectUsedMoreThanOnce); // popping object off stack with multiple pooledCount } } internal void RemoveWeakReference(object value) { DbReferenceCollection referenceCollection = ReferenceCollection; if (null != referenceCollection) { referenceCollection.Remove(value); } } /// <summary> /// When overridden in a derived class, will check if the underlying connection is still actually alive /// </summary> /// <param name="throwOnException">If true an exception will be thrown if the connection is dead instead of returning true\false /// (this allows the caller to have the real reason that the connection is not alive (e.g. network error, etc))</param> /// <returns>True if the connection is still alive, otherwise false (If not overridden, then always true)</returns> internal virtual bool IsConnectionAlive(bool throwOnException = false) { return true; } } }
//--------------------------------------------------------------------------- // <copyright file="FlowPosition.cs" company="Microsoft"> // Copyright (C) 2003 by Microsoft Corporation. All rights reserved. // </copyright> // // Description: // FlowPosition represents a navigational position in a document's content flow. // // History: // 02/10/2003 - Zhenbin Xu (ZhenbinX) - Created. // //--------------------------------------------------------------------------- namespace System.Windows.Documents { using MS.Internal.Documents; using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Windows.Controls; //===================================================================== /// <summary> /// FlowPosition represents a navigational position in a document's content flow. /// </summary> /// <remarks> /// A FlowPosition is represented by a FlowNode in the backing store and offset within /// the flow node (starts with 0, on the left side of the symbol). e.g. /// &lt;P&gt; H A L &lt;/P&gt; /// 0 1 0 1 2 3 0 1 /// </remarks> internal sealed class FlowPosition : IComparable { //-------------------------------------------------------------------- // // Connstructors // //--------------------------------------------------------------------- #region Constructors internal FlowPosition(FixedTextContainer container, FlowNode node, int offset) { Debug.Assert(!FlowNode.IsNull(node)); _container = container; _flowNode = node; _offset = offset; } #endregion Constructors //-------------------------------------------------------------------- // // Public Methods // //--------------------------------------------------------------------- #region Public Methods /// <summary> /// Create a shallow copy of this objet /// </summary> /// <returns>A clone of this FlowPosition</returns> public object Clone() { return new FlowPosition(_container, _flowNode, _offset); } // Compare two FixedTextPointer based on their flow order and offset public int CompareTo(object o) { if (o == null) { throw new ArgumentNullException("o"); } FlowPosition flow = o as FlowPosition; if (flow == null) { throw new ArgumentException(SR.Get(SRID.UnexpectedParameterType, o.GetType(), typeof(FlowPosition)), "o"); } return _OverlapAwareCompare(flow); } /// <summary> /// Compute hash code. A flow position is predominantly identified /// by its flow node and the offset. /// </summary> /// <returns>int - hash code</returns> public override int GetHashCode() { return _flowNode.GetHashCode()^_offset.GetHashCode(); } #if DEBUG /// <summary> /// Create a string representation of this object /// </summary> /// <returns>string - A string representation of this object</returns> public override string ToString() { return String.Format(CultureInfo.InvariantCulture, "FP[{0}+{1}]", _flowNode, _offset); } #endif #endregion Public Methods //-------------------------------------------------------------------- // // Public Properties // //--------------------------------------------------------------------- //-------------------------------------------------------------------- // // Public Events // //--------------------------------------------------------------------- //-------------------------------------------------------------------- // // Internal Methods // //--------------------------------------------------------------------- #region Internal Methods //-------------------------------------------------------------------- // Text OM Helper //--------------------------------------------------------------------- #region Text OM Helper // Returns the count of symbols between pos1 and pos2 internal int GetDistance(FlowPosition flow) { Debug.Assert(flow != null); // if both clings to the same flow node, simply // compare the offset if (_flowNode.Equals(flow._flowNode)) { return flow._offset - _offset; } // otherwise scan to find out distance // Make sure scanning from low to high flow order int np = _OverlapAwareCompare(flow); FlowPosition flowScan, flowEnd; if (np == -1) { // scan forward flowScan = (FlowPosition)this.Clone(); flowEnd = flow; } else { // scan backward flowScan = (FlowPosition)flow.Clone(); flowEnd = this; } // scan from low to high and accumulate counts // devirtualize the node as it scans int distance = 0; while (!flowScan._IsSamePosition(flowEnd)) { if (flowScan._flowNode.Equals(flowEnd._flowNode)) { distance += (flowEnd._offset - flowScan._offset); break; } int scan = flowScan._vScan(LogicalDirection.Forward, -1); distance += scan; } return np * (-1) * distance; } // Returns TextPointerContext.None if query is Backward at TextContainer.Start or Forward at TetContainer.End internal TextPointerContext GetPointerContext(LogicalDirection dir) { Debug.Assert(dir == LogicalDirection.Forward || dir == LogicalDirection.Backward); return _vGetSymbolType(dir); } // returns remaining text length on dir internal int GetTextRunLength(LogicalDirection dir) { Debug.Assert(GetPointerContext(dir) == TextPointerContext.Text); FlowPosition flow = GetClingPosition(dir); if (dir == LogicalDirection.Forward) { return flow._NodeLength - flow._offset; } else { return flow._offset; } } // Get Text until end-of-run or maxLength/limit is hit. internal int GetTextInRun(LogicalDirection dir, int maxLength, char[] chars, int startIndex) { Debug.Assert(GetPointerContext(dir) == TextPointerContext.Text); // make sure the position is clinged to text run FlowPosition flow = GetClingPosition(dir); int runLength = flow._NodeLength; int remainingLength; if (dir == LogicalDirection.Forward) { remainingLength = runLength - flow._offset; } else { remainingLength = flow._offset; } maxLength = Math.Min(maxLength, remainingLength); // // string text = _container.FixedTextBuilder.GetFlowText(flow._flowNode); if (dir == LogicalDirection.Forward) { Array.Copy(text.ToCharArray(flow._offset, maxLength), 0, chars, startIndex, maxLength); } else { Array.Copy(text.ToCharArray(flow._offset - maxLength, maxLength), 0, chars, startIndex, maxLength); } return maxLength; } // Get Embedeed Object instance internal object GetAdjacentElement(LogicalDirection dir) { FlowPosition flow = GetClingPosition(dir); FlowNodeType type = flow._flowNode.Type; Debug.Assert(type == FlowNodeType.Object || type == FlowNodeType.Noop || type == FlowNodeType.Start || type == FlowNodeType.End); if (type == FlowNodeType.Noop) { return String.Empty; } else { Object obj = ((FixedElement)flow._flowNode.Cookie).GetObject(); Image image = obj as Image; if (type == FlowNodeType.Object && image != null) { //Set width and height properties by looking at corresponding SOMImage FixedSOMElement[] elements = flow._flowNode.FixedSOMElements; if (elements != null && elements.Length > 0) { FixedSOMImage somImage = elements[0] as FixedSOMImage; if (somImage != null) { image.Width = somImage.BoundingRect.Width; image.Height = somImage.BoundingRect.Height; } } } return obj; } } // return FixedElement on the direction internal FixedElement GetElement(LogicalDirection dir) { FlowPosition flow = GetClingPosition(dir); return (FixedElement)flow._flowNode.Cookie; } // Immediate scoping element. If no element scops the position, // returns the container element. internal FixedElement GetScopingElement() { FlowPosition flowScan = (FlowPosition)this.Clone(); int nestedElement = 0; TextPointerContext tst; while (flowScan.FlowNode.Fp > 0 && !IsVirtual(_FixedFlowMap[flowScan.FlowNode.Fp - 1]) && // do not de-virtualize nodes (tst = flowScan.GetPointerContext(LogicalDirection.Backward))!= TextPointerContext.None) { if (tst == TextPointerContext.ElementStart) { if (nestedElement == 0) { FlowPosition flowEnd = flowScan.GetClingPosition(LogicalDirection.Backward); return (FixedElement)flowEnd._flowNode.Cookie; } nestedElement--; } else if (tst == TextPointerContext.ElementEnd) { nestedElement++; } flowScan.Move(LogicalDirection.Backward); } return _container.ContainerElement; } // return false if distance exceeds the size of the document internal bool Move(int distance) { LogicalDirection dir = (distance >= 0 ? LogicalDirection.Forward : LogicalDirection.Backward); distance = Math.Abs(distance); FlowNode startNode = _flowNode; // save state int startOffset = _offset; // keep moving until we hit distance while (distance > 0) { int scan = _vScan(dir, distance); if (scan == 0) { //restore state and return false _flowNode = startNode; _offset = startOffset; return false; } distance -= scan; } return true; } // Skip current symbol or run internal bool Move(LogicalDirection dir) { if (_vScan(dir, -1) > 0) { return true; } return false; } // Move to next FlowPosition internal void MoveTo(FlowPosition flow) { _flowNode = flow._flowNode; _offset = flow._offset; } #endregion Text OM Helper //-------------------------------------------------------------------- // Internal Methods //--------------------------------------------------------------------- internal void AttachElement(FixedElement e) { _flowNode.AttachElement(e); } internal void GetFlowNode(LogicalDirection direction, out FlowNode flowNode, out int offsetStart) { FlowPosition fp = GetClingPosition(direction); offsetStart = fp._offset; flowNode = fp._flowNode; } // return FlowNode within this range internal void GetFlowNodes(FlowPosition pEnd, out FlowNode[] flowNodes, out int offsetStart, out int offsetEnd) { Debug.Assert(this._OverlapAwareCompare(pEnd) < 0); flowNodes = null; offsetStart = 0; offsetEnd = 0; FlowPosition flowScan = GetClingPosition(LogicalDirection.Forward); offsetStart = flowScan._offset; ArrayList ar = new ArrayList(); int distance = GetDistance(pEnd); // keep moving until we hit distance while (distance > 0) { int scan = flowScan._vScan(LogicalDirection.Forward, distance); distance -= scan; if (flowScan.IsRun || flowScan.IsObject) { ar.Add(flowScan._flowNode); offsetEnd = flowScan._offset; } } flowNodes = (FlowNode [])ar.ToArray(typeof(FlowNode)); } // A canonical position is one that clings to a FlowNode internal FlowPosition GetClingPosition(LogicalDirection dir) { FlowPosition flow = (FlowPosition)this.Clone(); FlowNode fn; if (dir == LogicalDirection.Forward) { if (_offset == _NodeLength) { // This position is at right side of a FlowNode // look for next run fn = _xGetNextFlowNode(); if (!FlowNode.IsNull(fn)) { flow._flowNode = fn; flow._offset = 0; } #if DEBUG else { DocumentsTrace.FixedTextOM.FlowPosition.Trace("GetClingPosition: Next FlowNode is null"); } #endif } } else { Debug.Assert(dir == LogicalDirection.Backward); if (_offset == 0) { // This position is at left side of a FlowNode // look for previous run fn = _xGetPreviousFlowNode(); if (!FlowNode.IsNull(fn)) { flow._flowNode = fn; flow._offset = flow._NodeLength; } #if DEBUG else { DocumentsTrace.FixedTextOM.FlowPosition.Trace("GetClingPosition: Next FlowNode is null"); } #endif } } return flow; } internal bool IsVirtual(FlowNode flowNode) { return (flowNode.Type == FlowNodeType.Virtual); } #endregion Internal Methods //-------------------------------------------------------------------- // // Internal Properties // //--------------------------------------------------------------------- #region Internal Properties internal FixedTextContainer TextContainer { get { return _container; } } internal bool IsBoundary { get { return (_flowNode.Type == FlowNodeType.Boundary); } } internal bool IsStart { get { return (_flowNode.Type == FlowNodeType.Start); } } internal bool IsEnd { get { return (_flowNode.Type == FlowNodeType.End); } } // If th_Is position _Is symbol internal bool IsSymbol { get { FlowNodeType t = _flowNode.Type; return (t == FlowNodeType.Start || t == FlowNodeType.End || t == FlowNodeType.Object); } } // If the FlowNode has run length internal bool IsRun { get { return (_flowNode.Type == FlowNodeType.Run); } } // If the FlowNode has run length internal bool IsObject { get { return (_flowNode.Type == FlowNodeType.Object); } } internal FlowNode FlowNode { get { return this._flowNode; } } #endregion Internal Properties //-------------------------------------------------------------------- // // Private Methods // //--------------------------------------------------------------------- #region Private Methods //-------------------------------------------------------------------- // Helper functions that could result in de-virtualization //--------------------------------------------------------------------- // scan one node forward, return characters/symbols passed // limit < 0 means scan entire node. private int _vScan(LogicalDirection dir, int limit) { if (limit == 0) { return 0; } FlowNode flowNode = _flowNode; int scanned = 0; if (dir == LogicalDirection.Forward) { if (_offset == _NodeLength || flowNode.Type == FlowNodeType.Boundary) { // This position is at right side of a FlowNode flowNode = _xGetNextFlowNode(); if (FlowNode.IsNull(flowNode)) { return scanned; } _flowNode = flowNode; scanned = _NodeLength; } else { scanned = _NodeLength - _offset; } _offset = _NodeLength; if (limit > 0 && scanned > limit) { int back = scanned - limit; scanned = limit; _offset -= back; } } else { Debug.Assert(dir == LogicalDirection.Backward); if (_offset == 0 || flowNode.Type == FlowNodeType.Boundary) { // This position is at left side of a FlowNode // look for previous run flowNode = _xGetPreviousFlowNode(); if (FlowNode.IsNull(flowNode)) { return scanned; } _flowNode = flowNode; scanned = _NodeLength; } else { scanned = _offset; } _offset = 0; if (limit > 0 && scanned > limit) { int back = scanned - limit; scanned = limit; _offset += back; } } return scanned; } private TextPointerContext _vGetSymbolType(LogicalDirection dir) { FlowNode flowNode = _flowNode; if (dir == LogicalDirection.Forward) { if (_offset == _NodeLength) { // This position is at right side of a FlowNode // look for next run flowNode = _xGetNextFlowNode(); } if (!FlowNode.IsNull(flowNode)) { return _FlowNodeTypeToTextSymbol(flowNode.Type); } } else { Debug.Assert(dir == LogicalDirection.Backward); if (_offset == 0) { // This position is at left side of a FlowNode // look for previous run flowNode = _xGetPreviousFlowNode(); } if (!FlowNode.IsNull(flowNode)) { return _FlowNodeTypeToTextSymbol(flowNode.Type); } } return TextPointerContext.None; } //-------------------------------------------------------------------- // Helper functions that have raw access to backing store and provided // a non-virtualied view on top of virtualized content. //--------------------------------------------------------------------- // return null if no previous node private FlowNode _xGetPreviousFlowNode() { if (_flowNode.Fp > 1) { FlowNode flow = _FixedFlowMap[_flowNode.Fp - 1]; // devirtualize the backing store if (IsVirtual(flow)) { _FixedTextBuilder.EnsureTextOMForPage((int)flow.Cookie); flow = _FixedFlowMap[_flowNode.Fp - 1]; } // filter out boundary node if (flow.Type != FlowNodeType.Boundary) { return flow; } } return null; } // return null if no next node private FlowNode _xGetNextFlowNode() { if (_flowNode.Fp < _FixedFlowMap.FlowCount - 1) { FlowNode flow = _FixedFlowMap[_flowNode.Fp + 1]; // devirtualize the backing store if (IsVirtual(flow)) { _FixedTextBuilder.EnsureTextOMForPage((int)flow.Cookie); flow = _FixedFlowMap[_flowNode.Fp + 1]; } // filter out boundary node if (flow.Type != FlowNodeType.Boundary) { return flow; } } return null; } //-------------------------------------------------------------------- // Helper functions //--------------------------------------------------------------------- // see if the two FlowPosition are indeed same position private bool _IsSamePosition(FlowPosition flow) { if (flow == null) { return false; } return (_OverlapAwareCompare(flow) == 0); } // intelligent compare routine that understands position overlap private int _OverlapAwareCompare(FlowPosition flow) { Debug.Assert(flow != null); if ((object)this == (object)flow) { return 0; } int comp = this._flowNode.CompareTo(flow._flowNode); if (comp < 0) { // Check overlap positions // Positions are the same if they are at end of previous run or begin of next run if (this._flowNode.Fp == flow._flowNode.Fp - 1 && this._offset == _NodeLength && flow._offset == 0) { return 0; } } else if (comp > 0) { // Check overlap positions // Positions are the same if they are at end of previous run or begin of next run if (flow._flowNode.Fp == this._flowNode.Fp - 1 && flow._offset == flow._NodeLength && this._offset == 0) { return 0; } } else { // compare offset only Debug.Assert(this._flowNode.Equals(flow._flowNode)); comp = this._offset.CompareTo(flow._offset); } return comp; } // Convert Flow Node Type to TextPointerContext private TextPointerContext _FlowNodeTypeToTextSymbol(FlowNodeType t) { switch (t) { case FlowNodeType.Start: return TextPointerContext.ElementStart; case FlowNodeType.End: return TextPointerContext.ElementEnd; case FlowNodeType.Run: return TextPointerContext.Text; case FlowNodeType.Object: case FlowNodeType.Noop: return TextPointerContext.EmbeddedElement; default: return TextPointerContext.None; } } #endregion Private Methods //-------------------------------------------------------------------- // // Private Properties // //--------------------------------------------------------------------- #region Private Properties // Get length of this node structure private int _NodeLength { get { if (IsRun) { return (int)_flowNode.Cookie; } else { return 1; } } } private FixedTextBuilder _FixedTextBuilder { get { return _container.FixedTextBuilder; } } private FixedFlowMap _FixedFlowMap { get { return _container.FixedTextBuilder.FixedFlowMap; } } #endregion Private Properties //-------------------------------------------------------------------- // // Private Fields // //--------------------------------------------------------------------- #region Private Fields private FixedTextContainer _container; // the container has the backing store for flow nodes private FlowNode _flowNode; // flow node private int _offset; // offset into flow #endregion Private Fields } }
using System; using System.Collections.Generic; using System.Threading; namespace NetworkUtility { /// <summary> /// Allows raised events to be queued for redundant calls in thread-safe synchronized objects. /// </summary> public static class EventQueueManager { private static object _syncRoot = new object(); private static Queue<Tuple<Delegate, Action<Exception, object[]>, object[]>> _queuedEvents = null; /// <summary> /// Invokes a function, which may cause events to be raised, and returns the result. /// </summary> /// <typeparam name="T1">Type of first argument to pass to <paramref name="func" />.</typeparam> /// <typeparam name="T2">Type of second argument to pass to <paramref name="func" />.</typeparam> /// <typeparam name="T3">Type of third argument to pass to <paramref name="func" />.</typeparam> /// <typeparam name="T4">Type of fourth argument to pass to <paramref name="func" />.</typeparam> /// <typeparam name="TResult">Type of value returned from <paramref name="func" />.</typeparam> /// <param name="arg1">Value of first argument to pass to <paramref name="func" />.</param> /// <param name="arg2">Value of second argument to pass to <paramref name="func" />.</param> /// <param name="arg3">Value of third argument to pass to <paramref name="func" />.</param> /// <param name="arg4">Value of fourth argument to pass to <paramref name="func" />.</param> /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="func" /> is being invoked.</param> /// <param name="func">Function to be invoked, which may result in events being raised.</param> /// <returns><typeparamref name="TResult" /> value returned from <paramref name="func" />.</returns> /// <remarks>While <paramref name="func" /> is being invoked, any calls to the <see cref="EventQueueManager" /> <code>Raise</code> /// will result in the event handler being queued for invocation until the call to <paramref name="func" /> is finished.</remarks> public static TResult Get<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, object syncRoot, Func<T1, T2, T3, T4, TResult> func) { return (TResult)(InvokeGet(func, syncRoot, arg1, arg2, arg3, arg4)); } /// <summary> /// Invokes a method which may cause events to be raised. /// </summary> /// <typeparam name="T1">Type of first argument to pass to <paramref name="method" />.</typeparam> /// <typeparam name="T2">Type of second argument to pass to <paramref name="method" />.</typeparam> /// <typeparam name="T3">Type of third argument to pass to <paramref name="method" />.</typeparam> /// <typeparam name="T4">Type of fourth argument to pass to <paramref name="method" />.</typeparam> /// <param name="arg1">Value of first argument to pass to <paramref name="method" />.</param> /// <param name="arg2">Value of second argument to pass to <paramref name="method" />.</param> /// <param name="arg3">Value of third argument to pass to <paramref name="method" />.</param> /// <param name="arg4">Value of fourth argument to pass to <paramref name="method" />.</param> /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="method" /> is being invoked.</param> /// <param name="method">Method to be invoked, which may result in events being raised.</param> /// <remarks>While <paramref name="method" /> is being invoked, any calls to the <see cref="EventQueueManager" /> <code>Raise</code> /// will result in the event handler being queued for invocation until the call to <paramref name="method" /> is finished.</remarks> public static void Invoke<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, object syncRoot, Action<T1, T2, T3, T4> method) { InvokeGet(method, syncRoot, arg1, arg2, arg3, arg4); } /// <summary> /// Invokes a function, which may cause events to be raised, and returns the result. /// </summary> /// <typeparam name="T1">Type of first argument to pass to <paramref name="func" />.</typeparam> /// <typeparam name="T2">Type of second argument to pass to <paramref name="func" />.</typeparam> /// <typeparam name="T3">Type of third argument to pass to <paramref name="func" />.</typeparam> /// <typeparam name="TResult">Type of value returned from <paramref name="func" />.</typeparam> /// <param name="arg1">Value of first argument to pass to <paramref name="func" />.</param> /// <param name="arg2">Value of second argument to pass to <paramref name="func" />.</param> /// <param name="arg3">Value of third argument to pass to <paramref name="func" />.</param> /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="func" /> is being invoked.</param> /// <param name="func">Function to be invoked, which may result in events being raised.</param> /// <returns><typeparamref name="TResult" /> value returned from <paramref name="func" />.</returns> /// <remarks>While <paramref name="func" /> is being invoked, any calls to the <see cref="EventQueueManager" /> <code>Raise</code> /// will result in the event handler being queued for invocation until the call to <paramref name="func" /> is finished.</remarks> public static TResult Get<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3, object syncRoot, Func<T1, T2, T3, TResult> func) { return (TResult)(InvokeGet(func, syncRoot, arg1, arg2, arg3)); } /// <summary> /// Invokes a method which may cause events to be raised. /// </summary> /// <typeparam name="T1">Type of first argument to pass to <paramref name="method" />.</typeparam> /// <typeparam name="T2">Type of second argument to pass to <paramref name="method" />.</typeparam> /// <typeparam name="T3">Type of third argument to pass to <paramref name="method" />.</typeparam> /// <param name="arg1">Value of first argument to pass to <paramref name="method" />.</param> /// <param name="arg2">Value of second argument to pass to <paramref name="method" />.</param> /// <param name="arg3">Value of third argument to pass to <paramref name="method" />.</param> /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="method" /> is being invoked.</param> /// <param name="method">Method to be invoked, which may result in events being raised.</param> /// <remarks>While <paramref name="method" /> is being invoked, any calls to the <see cref="EventQueueManager" /> <code>Raise</code> /// will result in the event handler being queued for invocation until the call to <paramref name="method" /> is finished.</remarks> public static void Invoke<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3, object syncRoot, Action<T1, T2, T3> method) { InvokeGet(method, syncRoot, arg1, arg2, arg3); } /// <summary> /// Invokes a function, which may cause events to be raised, and returns the result. /// </summary> /// <typeparam name="T1">Type of first argument to pass to <paramref name="func" />.</typeparam> /// <typeparam name="T2">Type of second argument to pass to <paramref name="func" />.</typeparam> /// <typeparam name="TResult">Type of value returned from <paramref name="func" />.</typeparam> /// <param name="arg1">Value of first argument to pass to <paramref name="func" />.</param> /// <param name="arg2">Value of second argument to pass to <paramref name="func" />.</param> /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="func" /> is being invoked.</param> /// <param name="func">Function to be invoked, which may result in events being raised.</param> /// <returns><typeparamref name="TResult" /> value returned from <paramref name="func" />.</returns> /// <remarks>While <paramref name="func" /> is being invoked, any calls to the <see cref="EventQueueManager" /> <code>Raise</code> /// will result in the event handler being queued for invocation until the call to <paramref name="func" /> is finished.</remarks> public static TResult Get<T1, T2, TResult>(T1 arg1, T2 arg2, object syncRoot, Func<T1, T2, TResult> func) { return (TResult)(InvokeGet(func, syncRoot, arg1, arg2)); } /// <summary> /// Invokes a method which may cause events to be raised. /// </summary> /// <typeparam name="T1">Type of first argument to pass to <paramref name="method" />.</typeparam> /// <typeparam name="T2">Type of second argument to pass to <paramref name="method" />.</typeparam> /// <param name="arg1">Value of first argument to pass to <paramref name="method" />.</param> /// <param name="arg2">Value of second argument to pass to <paramref name="method" />.</param> /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="method" /> is being invoked.</param> /// <param name="method">Method to be invoked, which may result in events being raised.</param> /// <remarks>While <paramref name="method" /> is being invoked, any calls to the <see cref="EventQueueManager" /> <code>Raise</code> /// will result in the event handler being queued for invocation until the call to <paramref name="method" /> is finished.</remarks> public static void Invoke<T1, T2>(T1 arg1, T2 arg2, object syncRoot, Action<T1, T2> method) { InvokeGet(method, syncRoot, arg1, arg2); } /// <summary> /// Invokes a function, which may cause events to be raised, and returns the result. /// </summary> /// <typeparam name="T">Type of argument to pass to <paramref name="func" />.</typeparam> /// <typeparam name="TResult">Type of value returned from <paramref name="func" />.</typeparam> /// <param name="arg">Value of argument to pass to <paramref name="func" />.</param> /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="func" /> is being invoked.</param> /// <param name="func">Function to be invoked, which may result in events being raised.</param> /// <returns><typeparamref name="TResult" /> value returned from <paramref name="func" />.</returns> /// <remarks>While <paramref name="func" /> is being invoked, any calls to the <see cref="EventQueueManager" /> <code>Raise</code> /// will result in the event handler being queued for invocation until the call to <paramref name="func" /> is finished.</remarks> public static TResult Get<T, TResult>(T arg, object syncRoot, Func<T, TResult> func) { return (TResult)(InvokeGet(func, syncRoot, arg)); } /// <summary> /// Invokes a method which may cause events to be raised. /// </summary> /// <typeparam name="T">Type of argument to pass to <paramref name="method" />.</typeparam> /// <param name="arg">Value of argument to pass to <paramref name="method" />.</param> /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="method" /> is being invoked.</param> /// <param name="method">Method to be invoked, which may result in events being raised.</param> /// <remarks>While <paramref name="method" /> is being invoked, any calls to the <see cref="EventQueueManager" /> <code>Raise</code> /// will result in the event handler being queued for invocation until the call to <paramref name="method" /> is finished.</remarks> public static void Invoke<T>(T arg, object syncRoot, Action<T> method) { InvokeGet(method, syncRoot, arg); } /// <summary> /// Invokes a function, which may cause events to be raised, and returns the result. /// </summary> /// <typeparam name="TResult">Type of value returned from <paramref name="func" />.</typeparam> /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="func" /> is being invoked.</param> /// <param name="func">Function to be invoked, which may result in events being raised.</param> /// <returns><typeparamref name="TResult" /> value returned from <paramref name="func" />.</returns> /// <remarks>While <paramref name="func" /> is being invoked, any calls to the <see cref="EventQueueManager" /> <code>Raise</code> /// will result in the event handler being queued for invocation until the call to <paramref name="func" /> is finished.</remarks> public static TResult Get<TResult>(object syncRoot, Func<TResult> func) { return (TResult)(InvokeGet(func, syncRoot)); } /// <summary> /// Invokes a method which may cause events to be raised. /// </summary> /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="method" /> is being invoked.</param> /// <param name="method">Method to be invoked, which may result in events being raised.</param> /// <remarks>While <paramref name="method" /> is being invoked, any calls to the <see cref="EventQueueManager" /> <code>Raise</code> /// will result in the event handler being queued for invocation until the call to <paramref name="method" /> is finished.</remarks> public static void Invoke(object syncRoot, Action method) { InvokeGet(method, syncRoot); } /// <summary> /// Invokes a method which may cause events to be raised. /// </summary> /// <param name="method">Method to be invoked, which may result in events being raised.</param> /// <param name="syncRoot">The object on which to acquire an exclusive lock while <paramref name="method" /> is being invoked.</param> /// <param name="args">Arguments to pass to <paramref name="method" />.</param> /// <returns>Value returned from <paramref name="method" />.</returns> /// <remarks>While <paramref name="method" /> is being invoked, any calls to the <see cref="EventQueueManager" /> <code>Raise</code> /// will result in the event handler being queued for invocation until the call to <paramref name="method" /> is finished.</remarks> public static object InvokeGet(Delegate method, object syncRoot, params object[] args) { Queue<Tuple<Delegate, Action<Exception, object[]>, object[]>> queuedEvents; Monitor.Enter(_syncRoot); try { if (_queuedEvents == null) { queuedEvents = new Queue<Tuple<Delegate, Action<Exception, object[]>, object[]>>(); _queuedEvents = queuedEvents; } else queuedEvents = null; } finally { Monitor.Exit(_syncRoot); } object result; try { Monitor.Enter(syncRoot); try { result = method.DynamicInvoke((args == null) ? new object[0] : args); } finally { Monitor.Exit(syncRoot); } } finally { if (queuedEvents != null) { Monitor.Enter(_syncRoot); try { _queuedEvents = null; } finally { Monitor.Exit(_syncRoot); } while (queuedEvents.Count > 0) { Tuple<Delegate, Action<Exception, object[]>, object[]> current = queuedEvents.Dequeue(); try { current.Item1.DynamicInvoke(current.Item3); } catch (Exception e) { if (current.Item2 != null) try { current.Item2(e, current.Item3); } catch { } } } } } return result; } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <typeparam name="T1">Type of first argument to pass to <paramref name="handler" />.</typeparam> /// <typeparam name="T2">Type of second argument to pass to <paramref name="handler" />.</typeparam> /// <typeparam name="T3">Type of third argument to pass to <paramref name="handler" />.</typeparam> /// <typeparam name="T4">Type of fourth argument to pass to <paramref name="handler" />.</typeparam> /// <param name="arg1">Value of first event argument to pass to <paramref name="handler" />.</param> /// <param name="arg2">Value of second event argument to pass to <paramref name="handler" />.</param> /// <param name="arg3">Value of third event argument to pass to <paramref name="handler" />.</param> /// <param name="arg4">Value of fourth event argument to pass to <paramref name="handler" />.</param> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <param name="onException">Method which gets invoked when <paramref name="handler" /> throws an exception.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool Raise<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, Action<T1, T2, T3, T4> handler, Action<Exception, T1, T2, T3, T4> onException) { if (onException != null) return RaiseHandler(handler, new Action<Exception, object[]>((e, a) => onException(e, (T1)(a[0]), (T2)(a[1]), (T3)(a[2]), (T4)(a[3]))), arg1, arg2, arg3, arg4); return RaiseHandler(handler, null as Action<Exception, object[]>, arg1, arg2, arg3, arg4); } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <typeparam name="T1">Type of first argument to pass to <paramref name="handler" />.</typeparam> /// <typeparam name="T2">Type of second argument to pass to <paramref name="handler" />.</typeparam> /// <typeparam name="T3">Type of third argument to pass to <paramref name="handler" />.</typeparam> /// <param name="arg1">Value of first event argument to pass to <paramref name="handler" />.</param> /// <param name="arg2">Value of second event argument to pass to <paramref name="handler" />.</param> /// <param name="arg3">Value of third event argument to pass to <paramref name="handler" />.</param> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <param name="onException">Method which gets invoked when <paramref name="handler" /> throws an exception.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool Raise<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3, Action<T1, T2, T3> handler, Action<Exception, T1, T2, T3> onException) { if (onException != null) return RaiseHandler(handler, new Action<Exception, object[]>((e, a) => onException(e, (T1)(a[0]), (T2)(a[1]), (T3)(a[2]))), arg1, arg2, arg3); return RaiseHandler(handler, null as Action<Exception, object[]>, arg1, arg2, arg3); } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <typeparam name="T1">Type of first argument to pass to <paramref name="handler" />.</typeparam> /// <typeparam name="T2">Type of second argument to pass to <paramref name="handler" />.</typeparam> /// <typeparam name="T3">Type of third argument to pass to <paramref name="handler" />.</typeparam> /// <typeparam name="T4">Type of fourth argument to pass to <paramref name="handler" />.</typeparam> /// <param name="arg1">Value of first event argument to pass to <paramref name="handler" />.</param> /// <param name="arg2">Value of second event argument to pass to <paramref name="handler" />.</param> /// <param name="arg3">Value of third event argument to pass to <paramref name="handler" />.</param> /// <param name="arg4">Value of fourth event argument to pass to <paramref name="handler" />.</param> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool Raise<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, Action<T1, T2, T3, T4> handler) { return Raise<T1, T2, T3, T4>(arg1, arg2, arg3, arg4, handler, null); } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <typeparam name="T1">Type of first argument to pass to <paramref name="handler" />.</typeparam> /// <typeparam name="T2">Type of second argument to pass to <paramref name="handler" />.</typeparam> /// <param name="arg1">Value of first event argument to pass to <paramref name="handler" />.</param> /// <param name="arg2">Value of second event argument to pass to <paramref name="handler" />.</param> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <param name="onException">Method which gets invoked when <paramref name="handler" /> throws an exception.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool Raise<T1, T2>(T1 arg1, T2 arg2, Action<T1, T2> handler, Action<Exception, T1, T2> onException) { if (onException != null) return RaiseHandler(handler, new Action<Exception, object[]>((e, a) => onException(e, (T1)(a[0]), (T2)(a[1]))), arg1, arg2); return RaiseHandler(handler, null as Action<Exception, object[]>, arg1, arg2); } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <typeparam name="T">Type of argument to pass to <paramref name="handler" />.</typeparam> /// <param name="sender">Object which raised the event.</param> /// <param name="eventArgs">Value of event argument to pass to <paramref name="handler" />.</param> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <param name="onException">Method which gets invoked when <paramref name="handler" /> throws an exception.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool Raise<T>(object sender, T eventArgs, Action<object, T> handler, Action<Exception, object, T> onException) where T : EventArgs { if (onException != null) return RaiseHandler(handler, new Action<Exception, object[]>((e, a) => onException(e, a[0], (T)(a[1]))), sender, eventArgs); return RaiseHandler(handler, null as Action<Exception, object[]>, sender, eventArgs); } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <typeparam name="T1">Type of first argument to pass to <paramref name="handler" />.</typeparam> /// <typeparam name="T2">Type of second argument to pass to <paramref name="handler" />.</typeparam> /// <typeparam name="T3">Type of third argument to pass to <paramref name="handler" />.</typeparam> /// <param name="arg1">Value of first event argument to pass to <paramref name="handler" />.</param> /// <param name="arg2">Value of second event argument to pass to <paramref name="handler" />.</param> /// <param name="arg3">Value of third event argument to pass to <paramref name="handler" />.</param> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool Raise<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3, Action<T1, T2, T3> handler) { return Raise<T1, T2, T3>(arg1, arg2, arg3, handler, null); } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <typeparam name="T">Type of argument to pass to <paramref name="handler" />.</typeparam> /// <param name="arg">Value of event argument to pass to <paramref name="handler" />.</param> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <param name="onException">Method which gets invoked when <paramref name="handler" /> throws an exception.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool Raise<T>(T arg, Action<T> handler, Action<Exception, T> onException) { if (onException != null) return RaiseHandler(handler, new Action<Exception, object[]>((e, a) => onException(e, (T)(a[0]))), arg); return RaiseHandler(handler, null as Action<Exception, object[]>, arg); } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <param name="onException">Method which gets invoked when <paramref name="handler" /> throws an exception.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool Raise(Action handler, Action<Exception> onException) { if (onException != null) return RaiseHandler(handler, new Action<Exception, object[]>((e, a) => onException(e))); return RaiseHandler(handler, null as Action<Exception, object[]>); } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <typeparam name="T1">Type of first argument to pass to <paramref name="handler" />.</typeparam> /// <typeparam name="T2">Type of second argument to pass to <paramref name="handler" />.</typeparam> /// <param name="arg1">Value of first event argument to pass to <paramref name="handler" />.</param> /// <param name="arg2">Value of second event argument to pass to <paramref name="handler" />.</param> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool Raise<T1, T2>(T1 arg1, T2 arg2, Action<T1, T2> handler) { return Raise<T1, T2>(arg1, arg2, handler, null); } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <typeparam name="T">Type of argument to pass to <paramref name="handler" />.</typeparam> /// <param name="sender">Object which raised the event.</param> /// <param name="eventArgs">Value of event argument to pass to <paramref name="handler" />.</param> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool Raise<T>(object sender, T eventArgs, Action<object, T> handler) where T : EventArgs { return Raise<T>(sender, eventArgs, handler, null); } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <typeparam name="T">Type of argument to pass to <paramref name="handler" />.</typeparam> /// <param name="arg">Value of event argument to pass to <paramref name="handler" />.</param> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool Raise<T>(T arg, Action<T> handler) { return Raise<T>(arg, handler, null); } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool Raise(Action handler) { return Raise(handler, null as Action<Exception>); } /// <summary> /// Queues a method invocation to handle an event. /// </summary> /// <param name="handler">Method which gets invoked to handle the event.</param> /// <param name="onException">Method which gets invoked when <paramref name="handler" /> throws an exception.</param> /// <param name="args">Event arguments to pass to <paramref name="handler" />.</param> /// <returns><code>true</code> if <paramref name="handler" /> was immediately invoked or <code>false</code> /// if <paramref name="handler" /> was queued for later execution.</returns> /// <remarks>If none of the <see cref="EventQueueManager" /> <code>Get</code> or <code>Invoke</code> methods are invoking their /// respective delegates, then <paramref name="handler" /> will be invoked immediately. Otherwise, it will be queued for invocation /// after the <code>Get</code> or <code>Invoke</code> method has finished executing the delegate.</remarks> public static bool RaiseHandler(Delegate handler, Action<Exception, object[]> onException, params object[] args) { if (handler == null) throw new ArgumentNullException("handler"); Monitor.Enter(_syncRoot); try { if (_queuedEvents != null) { _queuedEvents.Enqueue(new Tuple<Delegate, Action<Exception, object[]>, object[]>(handler, onException, (args == null) ? new object[0] : args)); return false; } } finally { Monitor.Exit(_syncRoot); } object[] a = (args == null) ? new object[0] : args; try { handler.DynamicInvoke(a); } catch (Exception e) { if (onException != null) try { onException(e, a); } catch { } } return true; } } }
// 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.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; namespace System.Reflection.Metadata { partial class MetadataReader { internal const string ClrPrefix = "<CLR>"; internal static readonly byte[] WinRTPrefix = new[] { (byte)'<', (byte)'W', (byte)'i', (byte)'n', (byte)'R', (byte)'T', (byte)'>' }; #region Projection Tables // Maps names of projected types to projection information for each type. // Both arrays are of the same length and sorted by the type name. private static string[] s_projectedTypeNames; private static ProjectionInfo[] s_projectionInfos; private struct ProjectionInfo { public readonly string WinRTNamespace; public readonly StringHandle.VirtualIndex ClrNamespace; public readonly StringHandle.VirtualIndex ClrName; public readonly AssemblyReferenceHandle.VirtualIndex AssemblyRef; public readonly TypeDefTreatment Treatment; public readonly TypeRefSignatureTreatment SignatureTreatment; public readonly bool IsIDisposable; public ProjectionInfo( string winRtNamespace, StringHandle.VirtualIndex clrNamespace, StringHandle.VirtualIndex clrName, AssemblyReferenceHandle.VirtualIndex clrAssembly, TypeDefTreatment treatment = TypeDefTreatment.RedirectedToClrType, TypeRefSignatureTreatment signatureTreatment = TypeRefSignatureTreatment.None, bool isIDisposable = false) { this.WinRTNamespace = winRtNamespace; this.ClrNamespace = clrNamespace; this.ClrName = clrName; this.AssemblyRef = clrAssembly; this.Treatment = treatment; this.SignatureTreatment = signatureTreatment; this.IsIDisposable = isIDisposable; } } private TypeDefTreatment GetWellKnownTypeDefinitionTreatment(TypeDefinitionHandle typeDef) { InitializeProjectedTypes(); StringHandle name = TypeDefTable.GetName(typeDef); int index = StringHeap.BinarySearchRaw(s_projectedTypeNames, name); if (index < 0) { return TypeDefTreatment.None; } StringHandle namespaceName = TypeDefTable.GetNamespace(typeDef); if (StringHeap.EqualsRaw(namespaceName, StringHeap.GetVirtualString(s_projectionInfos[index].ClrNamespace))) { return s_projectionInfos[index].Treatment; } // TODO: we can avoid this comparison if info.DotNetNamespace == info.WinRtNamespace if (StringHeap.EqualsRaw(namespaceName, s_projectionInfos[index].WinRTNamespace)) { return s_projectionInfos[index].Treatment | TypeDefTreatment.MarkInternalFlag; } return TypeDefTreatment.None; } private int GetProjectionIndexForTypeReference(TypeReferenceHandle typeRef, out bool isIDisposable) { InitializeProjectedTypes(); int index = StringHeap.BinarySearchRaw(s_projectedTypeNames, TypeRefTable.GetName(typeRef)); if (index >= 0 && StringHeap.EqualsRaw(TypeRefTable.GetNamespace(typeRef), s_projectionInfos[index].WinRTNamespace)) { isIDisposable = s_projectionInfos[index].IsIDisposable; return index; } isIDisposable = false; return -1; } internal static AssemblyReferenceHandle GetProjectedAssemblyRef(int projectionIndex) { Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return AssemblyReferenceHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].AssemblyRef); } internal static StringHandle GetProjectedName(int projectionIndex) { Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrName); } internal static StringHandle GetProjectedNamespace(int projectionIndex) { Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrNamespace); } internal static TypeRefSignatureTreatment GetProjectedSignatureTreatment(int projectionIndex) { Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return s_projectionInfos[projectionIndex].SignatureTreatment; } private static void InitializeProjectedTypes() { if (s_projectedTypeNames == null || s_projectionInfos == null) { var systemRuntimeWindowsRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime; var systemRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime; var systemObjectModel = AssemblyReferenceHandle.VirtualIndex.System_ObjectModel; var systemRuntimeWindowsUiXaml = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml; var systemRuntimeInterop = AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime; var systemNumericsVectors = AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors; // sorted by name var keys = new string[50]; var values = new ProjectionInfo[50]; int k = 0, v = 0; // WARNING: Keys must be sorted by name and must only contain ASCII characters. WinRTNamespace must also be ASCII only. keys[k++] = "AttributeTargets"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeTargets, systemRuntime); keys[k++] = "AttributeUsageAttribute"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeUsageAttribute, systemRuntime, treatment: TypeDefTreatment.RedirectedToClrAttribute); keys[k++] = "Color"; values[v++] = new ProjectionInfo("Windows.UI", StringHandle.VirtualIndex.Windows_UI, StringHandle.VirtualIndex.Color, systemRuntimeWindowsRuntime); keys[k++] = "CornerRadius"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.CornerRadius, systemRuntimeWindowsUiXaml); keys[k++] = "DateTime"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.DateTimeOffset, systemRuntime); keys[k++] = "Duration"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Duration, systemRuntimeWindowsUiXaml); keys[k++] = "DurationType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.DurationType, systemRuntimeWindowsUiXaml); keys[k++] = "EventHandler`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.EventHandler1, systemRuntime); keys[k++] = "EventRegistrationToken"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime, StringHandle.VirtualIndex.EventRegistrationToken, systemRuntimeInterop); keys[k++] = "GeneratorPosition"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Controls.Primitives", StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives, StringHandle.VirtualIndex.GeneratorPosition, systemRuntimeWindowsUiXaml); keys[k++] = "GridLength"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridLength, systemRuntimeWindowsUiXaml); keys[k++] = "GridUnitType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridUnitType, systemRuntimeWindowsUiXaml); keys[k++] = "HResult"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Exception, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToClass); keys[k++] = "IBindableIterable"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IEnumerable, systemRuntime); keys[k++] = "IBindableVector"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IList, systemRuntime); keys[k++] = "IClosable"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.IDisposable, systemRuntime, isIDisposable: true); keys[k++] = "ICommand"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Input", StringHandle.VirtualIndex.System_Windows_Input, StringHandle.VirtualIndex.ICommand, systemObjectModel); keys[k++] = "IIterable`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IEnumerable1, systemRuntime); keys[k++] = "IKeyValuePair`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.KeyValuePair2, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToValueType); keys[k++] = "IMapView`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyDictionary2, systemRuntime); keys[k++] = "IMap`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IDictionary2, systemRuntime); keys[k++] = "INotifyCollectionChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.INotifyCollectionChanged, systemObjectModel); keys[k++] = "INotifyPropertyChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.INotifyPropertyChanged, systemObjectModel); keys[k++] = "IReference`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Nullable1, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToValueType); keys[k++] = "IVectorView`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyList1, systemRuntime); keys[k++] = "IVector`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IList1, systemRuntime); keys[k++] = "KeyTime"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.KeyTime, systemRuntimeWindowsUiXaml); keys[k++] = "Matrix"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media", StringHandle.VirtualIndex.Windows_UI_Xaml_Media, StringHandle.VirtualIndex.Matrix, systemRuntimeWindowsUiXaml); keys[k++] = "Matrix3D"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Media3D", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D, StringHandle.VirtualIndex.Matrix3D, systemRuntimeWindowsUiXaml); keys[k++] = "Matrix3x2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix3x2, systemNumericsVectors); keys[k++] = "Matrix4x4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix4x4, systemNumericsVectors); keys[k++] = "NotifyCollectionChangedAction"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedAction, systemObjectModel); keys[k++] = "NotifyCollectionChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs, systemObjectModel); keys[k++] = "NotifyCollectionChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler, systemObjectModel); keys[k++] = "Plane"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Plane, systemNumericsVectors); keys[k++] = "Point"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Point, systemRuntimeWindowsRuntime); keys[k++] = "PropertyChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventArgs, systemObjectModel); keys[k++] = "PropertyChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventHandler, systemObjectModel); keys[k++] = "Quaternion"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Quaternion, systemNumericsVectors); keys[k++] = "Rect"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Rect, systemRuntimeWindowsRuntime); keys[k++] = "RepeatBehavior"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehavior, systemRuntimeWindowsUiXaml); keys[k++] = "RepeatBehaviorType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehaviorType, systemRuntimeWindowsUiXaml); keys[k++] = "Size"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Size, systemRuntimeWindowsRuntime); keys[k++] = "Thickness"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Thickness, systemRuntimeWindowsUiXaml); keys[k++] = "TimeSpan"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.TimeSpan, systemRuntime); keys[k++] = "TypeName"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Type, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToClass); keys[k++] = "Uri"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Uri, systemRuntime); keys[k++] = "Vector2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector2, systemNumericsVectors); keys[k++] = "Vector3"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector3, systemNumericsVectors); keys[k++] = "Vector4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector4, systemNumericsVectors); Debug.Assert(k == keys.Length && v == keys.Length && k == v); AssertSorted(keys); s_projectedTypeNames = keys; s_projectionInfos = values; } } [Conditional("DEBUG")] private static void AssertSorted(string[] keys) { for (int i = 0; i < keys.Length - 1; i++) { Debug.Assert(String.CompareOrdinal(keys[i], keys[i + 1]) < 0); } } // test only internal static string[] GetProjectedTypeNames() { InitializeProjectedTypes(); return s_projectedTypeNames; } #endregion private static uint TreatmentAndRowId(byte treatment, int rowId) { return ((uint)treatment << TokenTypeIds.RowIdBitCount) | (uint)rowId; } #region TypeDef [MethodImpl(MethodImplOptions.NoInlining)] internal uint CalculateTypeDefTreatmentAndRowId(TypeDefinitionHandle handle) { Debug.Assert(_metadataKind != MetadataKind.Ecma335); TypeDefTreatment treatment; TypeAttributes flags = TypeDefTable.GetFlags(handle); EntityHandle extends = TypeDefTable.GetExtends(handle); if ((flags & TypeAttributes.WindowsRuntime) != 0) { if (_metadataKind == MetadataKind.WindowsMetadata) { treatment = GetWellKnownTypeDefinitionTreatment(handle); if (treatment != TypeDefTreatment.None) { return TreatmentAndRowId((byte)treatment, handle.RowId); } // Is this an attribute? if (extends.Kind == HandleKind.TypeReference && IsSystemAttribute((TypeReferenceHandle)extends)) { treatment = TypeDefTreatment.NormalAttribute; } else { treatment = TypeDefTreatment.NormalNonAttribute; } } else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && NeedsWinRTPrefix(flags, extends)) { // WinMDExp emits two versions of RuntimeClasses and Enums: // // public class Foo {} // the WinRT reference class // internal class <CLR>Foo {} // the implementation class that we want WinRT consumers to ignore // // The adapter's job is to undo WinMDExp's transformations. I.e. turn the above into: // // internal class <WinRT>Foo {} // the WinRT reference class that we want CLR consumers to ignore // public class Foo {} // the implementation class // // We only add the <WinRT> prefix here since the WinRT view is the only view that is marked WindowsRuntime // De-mangling the CLR name is done below. // tomat: The CLR adapter implements a back-compat quirk: Enums exported with an older WinMDExp have only one version // not marked with tdSpecialName. These enums should *not* be mangled and flipped to private. // We don't implement this flag since the WinMDs produced by the older WinMDExp are not used in the wild. treatment = TypeDefTreatment.PrefixWinRTName; } else { treatment = TypeDefTreatment.None; } // Scan through Custom Attributes on type, looking for interesting bits. We only // need to do this for RuntimeClasses if ((treatment == TypeDefTreatment.PrefixWinRTName || treatment == TypeDefTreatment.NormalNonAttribute)) { if ((flags & TypeAttributes.Interface) == 0 && HasAttribute(handle, "Windows.UI.Xaml", "TreatAsAbstractComposableClassAttribute")) { treatment |= TypeDefTreatment.MarkAbstractFlag; } } } else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && IsClrImplementationType(handle)) { // <CLR> implementation classes are not marked WindowsRuntime, but still need to be modified // by the adapter. treatment = TypeDefTreatment.UnmangleWinRTName; } else { treatment = TypeDefTreatment.None; } return TreatmentAndRowId((byte)treatment, handle.RowId); } private bool IsClrImplementationType(TypeDefinitionHandle typeDef) { var attrs = TypeDefTable.GetFlags(typeDef); if ((attrs & (TypeAttributes.VisibilityMask | TypeAttributes.SpecialName)) != TypeAttributes.SpecialName) { return false; } return StringHeap.StartsWithRaw(TypeDefTable.GetName(typeDef), ClrPrefix); } #endregion #region TypeRef internal uint CalculateTypeRefTreatmentAndRowId(TypeReferenceHandle handle) { Debug.Assert(_metadataKind != MetadataKind.Ecma335); bool isIDisposable; int projectionIndex = GetProjectionIndexForTypeReference(handle, out isIDisposable); if (projectionIndex >= 0) { return TreatmentAndRowId((byte)TypeRefTreatment.UseProjectionInfo, projectionIndex); } else { return TreatmentAndRowId((byte)GetSpecialTypeRefTreatment(handle), handle.RowId); } } private TypeRefTreatment GetSpecialTypeRefTreatment(TypeReferenceHandle handle) { if (StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "System")) { StringHandle name = TypeRefTable.GetName(handle); if (StringHeap.EqualsRaw(name, "MulticastDelegate")) { return TypeRefTreatment.SystemDelegate; } if (StringHeap.EqualsRaw(name, "Attribute")) { return TypeRefTreatment.SystemAttribute; } } return TypeRefTreatment.None; } private bool IsSystemAttribute(TypeReferenceHandle handle) { return StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") && StringHeap.EqualsRaw(TypeRefTable.GetName(handle), "Attribute"); } private bool IsSystemEnum(TypeReferenceHandle handle) { return StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") && StringHeap.EqualsRaw(TypeRefTable.GetName(handle), "Enum"); } private bool NeedsWinRTPrefix(TypeAttributes flags, EntityHandle extends) { if ((flags & (TypeAttributes.VisibilityMask | TypeAttributes.Interface)) != TypeAttributes.Public) { return false; } if (extends.Kind != HandleKind.TypeReference) { return false; } // Check if the type is a delegate, struct, or attribute TypeReferenceHandle extendsRefHandle = (TypeReferenceHandle)extends; if (StringHeap.EqualsRaw(TypeRefTable.GetNamespace(extendsRefHandle), "System")) { StringHandle nameHandle = TypeRefTable.GetName(extendsRefHandle); if (StringHeap.EqualsRaw(nameHandle, "MulticastDelegate") || StringHeap.EqualsRaw(nameHandle, "ValueType") || StringHeap.EqualsRaw(nameHandle, "Attribute")) { return false; } } return true; } #endregion #region MethodDef private uint CalculateMethodDefTreatmentAndRowId(MethodDefinitionHandle methodDef) { MethodDefTreatment treatment = MethodDefTreatment.Implementation; TypeDefinitionHandle parentTypeDef = GetDeclaringType(methodDef); TypeAttributes parentFlags = TypeDefTable.GetFlags(parentTypeDef); if ((parentFlags & TypeAttributes.WindowsRuntime) != 0) { if (IsClrImplementationType(parentTypeDef)) { treatment = MethodDefTreatment.Implementation; } else if (parentFlags.IsNested()) { treatment = MethodDefTreatment.Implementation; } else if ((parentFlags & TypeAttributes.Interface) != 0) { treatment = MethodDefTreatment.InterfaceMethod; } else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && (parentFlags & TypeAttributes.Public) == 0) { treatment = MethodDefTreatment.Implementation; } else { treatment = MethodDefTreatment.Other; var parentBaseType = TypeDefTable.GetExtends(parentTypeDef); if (parentBaseType.Kind == HandleKind.TypeReference) { switch (GetSpecialTypeRefTreatment((TypeReferenceHandle)parentBaseType)) { case TypeRefTreatment.SystemAttribute: treatment = MethodDefTreatment.AttributeMethod; break; case TypeRefTreatment.SystemDelegate: treatment = MethodDefTreatment.DelegateMethod | MethodDefTreatment.MarkPublicFlag; break; } } } } if (treatment == MethodDefTreatment.Other) { // we want to hide the method if it implements // only redirected interfaces // We also want to check if the methodImpl is IClosable.Close, // so we can change the name bool seenRedirectedInterfaces = false; bool seenNonRedirectedInterfaces = false; bool isIClosableClose = false; foreach (var methodImplHandle in new MethodImplementationHandleCollection(this, parentTypeDef)) { MethodImplementation methodImpl = GetMethodImplementation(methodImplHandle); if (methodImpl.MethodBody == methodDef) { EntityHandle declaration = methodImpl.MethodDeclaration; // See if this MethodImpl implements a redirected interface // In WinMD, MethodImpl will always use MemberRef and TypeRefs to refer to redirected interfaces, // even if they are in the same module. if (declaration.Kind == HandleKind.MemberReference && ImplementsRedirectedInterface((MemberReferenceHandle)declaration, out isIClosableClose)) { seenRedirectedInterfaces = true; if (isIClosableClose) { // This method implements IClosable.Close // Let's rename to IDisposable later // Once we know this implements IClosable.Close, we are done // looking break; } } else { // Now we know this implements a non-redirected interface // But we need to keep looking, just in case we got a methodimpl that // implements the IClosable.Close method and needs to be renamed seenNonRedirectedInterfaces = true; } } } if (isIClosableClose) { treatment = MethodDefTreatment.DisposeMethod; } else if (seenRedirectedInterfaces && !seenNonRedirectedInterfaces) { // Only hide if all the interfaces implemented are redirected treatment = MethodDefTreatment.HiddenInterfaceImplementation; } } // If treatment is other, then this is a non-managed WinRT runtime class definition // Find out about various bits that we apply via attributes and name parsing if (treatment == MethodDefTreatment.Other) { treatment |= GetMethodTreatmentFromCustomAttributes(methodDef); } return TreatmentAndRowId((byte)treatment, methodDef.RowId); } private MethodDefTreatment GetMethodTreatmentFromCustomAttributes(MethodDefinitionHandle methodDef) { MethodDefTreatment treatment = 0; foreach (var caHandle in GetCustomAttributes(methodDef)) { StringHandle namespaceHandle, nameHandle; if (!GetAttributeTypeNameRaw(caHandle, out namespaceHandle, out nameHandle)) { continue; } Debug.Assert(!namespaceHandle.IsVirtual && !nameHandle.IsVirtual); if (StringHeap.EqualsRaw(namespaceHandle, "Windows.UI.Xaml")) { if (StringHeap.EqualsRaw(nameHandle, "TreatAsPublicMethodAttribute")) { treatment |= MethodDefTreatment.MarkPublicFlag; } if (StringHeap.EqualsRaw(nameHandle, "TreatAsAbstractMethodAttribute")) { treatment |= MethodDefTreatment.MarkAbstractFlag; } } } return treatment; } #endregion #region FieldDef /// <summary> /// The backing field of a WinRT enumeration type is not public although the backing fields /// of managed enumerations are. To allow managed languages to directly access this field, /// it is made public by the metadata adapter. /// </summary> private uint CalculateFieldDefTreatmentAndRowId(FieldDefinitionHandle handle) { var flags = FieldTable.GetFlags(handle); FieldDefTreatment treatment = FieldDefTreatment.None; if ((flags & FieldAttributes.RTSpecialName) != 0 && StringHeap.EqualsRaw(FieldTable.GetName(handle), "value__")) { TypeDefinitionHandle typeDef = GetDeclaringType(handle); EntityHandle baseTypeHandle = TypeDefTable.GetExtends(typeDef); if (baseTypeHandle.Kind == HandleKind.TypeReference) { var typeRef = (TypeReferenceHandle)baseTypeHandle; if (StringHeap.EqualsRaw(TypeRefTable.GetName(typeRef), "Enum") && StringHeap.EqualsRaw(TypeRefTable.GetNamespace(typeRef), "System")) { treatment = FieldDefTreatment.EnumValue; } } } return TreatmentAndRowId((byte)treatment, handle.RowId); } #endregion #region MemberRef private uint CalculateMemberRefTreatmentAndRowId(MemberReferenceHandle handle) { MemberRefTreatment treatment; // We need to rename the MemberRef for IClosable.Close as well // so that the MethodImpl for the Dispose method can be correctly shown // as IDisposable.Dispose instead of IDisposable.Close bool isIDisposable; if (ImplementsRedirectedInterface(handle, out isIDisposable) && isIDisposable) { treatment = MemberRefTreatment.Dispose; } else { treatment = MemberRefTreatment.None; } return TreatmentAndRowId((byte)treatment, handle.RowId); } /// <summary> /// We want to know if a given method implements a redirected interface. /// For example, if we are given the method RemoveAt on a class "A" /// which implements the IVector interface (which is redirected /// to IList in .NET) then this method would return true. The most /// likely reason why we would want to know this is that we wish to hide /// (mark private) all methods which implement methods on a redirected /// interface. /// </summary> /// <param name="memberRef">The declaration token for the method</param> /// <param name="isIDisposable"> /// Returns true if the redirected interface is <see cref="IDisposable"/>. /// </param> /// <returns>True if the method implements a method on a redirected interface. /// False otherwise.</returns> private bool ImplementsRedirectedInterface(MemberReferenceHandle memberRef, out bool isIDisposable) { isIDisposable = false; EntityHandle parent = MemberRefTable.GetClass(memberRef); TypeReferenceHandle typeRef; if (parent.Kind == HandleKind.TypeReference) { typeRef = (TypeReferenceHandle)parent; } else if (parent.Kind == HandleKind.TypeSpecification) { BlobHandle blob = TypeSpecTable.GetSignature((TypeSpecificationHandle)parent); BlobReader sig = new BlobReader(BlobHeap.GetMemoryBlock(blob)); if (sig.Length < 2 || sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_GENERICINST || sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_CLASS) { return false; } EntityHandle token = sig.ReadTypeHandle(); if (token.Kind != HandleKind.TypeReference) { return false; } typeRef = (TypeReferenceHandle)token; } else { return false; } return GetProjectionIndexForTypeReference(typeRef, out isIDisposable) >= 0; } #endregion #region AssemblyRef private int FindMscorlibAssemblyRefNoProjection() { for (int i = 1; i <= AssemblyRefTable.NumberOfNonVirtualRows; i++) { if (StringHeap.EqualsRaw(AssemblyRefTable.GetName(i), "mscorlib")) { return i; } } throw new BadImageFormatException(SR.WinMDMissingMscorlibRef); } #endregion #region CustomAttribute internal CustomAttributeValueTreatment CalculateCustomAttributeValueTreatment(CustomAttributeHandle handle) { Debug.Assert(_metadataKind != MetadataKind.Ecma335); var parent = CustomAttributeTable.GetParent(handle); // Check for Windows.Foundation.Metadata.AttributeUsageAttribute. // WinMD rules: // - The attribute is only applicable on TypeDefs. // - Constructor must be a MemberRef with TypeRef. if (!IsWindowsAttributeUsageAttribute(parent, handle)) { return CustomAttributeValueTreatment.None; } var targetTypeDef = (TypeDefinitionHandle)parent; if (StringHeap.EqualsRaw(TypeDefTable.GetNamespace(targetTypeDef), "Windows.Foundation.Metadata")) { if (StringHeap.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "VersionAttribute")) { return CustomAttributeValueTreatment.AttributeUsageVersionAttribute; } if (StringHeap.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "DeprecatedAttribute")) { return CustomAttributeValueTreatment.AttributeUsageDeprecatedAttribute; } } bool allowMultiple = HasAttribute(targetTypeDef, "Windows.Foundation.Metadata", "AllowMultipleAttribute"); return allowMultiple ? CustomAttributeValueTreatment.AttributeUsageAllowMultiple : CustomAttributeValueTreatment.AttributeUsageAllowSingle; } private bool IsWindowsAttributeUsageAttribute(EntityHandle targetType, CustomAttributeHandle attributeHandle) { // Check for Windows.Foundation.Metadata.AttributeUsageAttribute. // WinMD rules: // - The attribute is only applicable on TypeDefs. // - Constructor must be a MemberRef with TypeRef. if (targetType.Kind != HandleKind.TypeDefinition) { return false; } var attributeCtor = CustomAttributeTable.GetConstructor(attributeHandle); if (attributeCtor.Kind != HandleKind.MemberReference) { return false; } var attributeType = MemberRefTable.GetClass((MemberReferenceHandle)attributeCtor); if (attributeType.Kind != HandleKind.TypeReference) { return false; } var attributeTypeRef = (TypeReferenceHandle)attributeType; return StringHeap.EqualsRaw(TypeRefTable.GetName(attributeTypeRef), "AttributeUsageAttribute") && StringHeap.EqualsRaw(TypeRefTable.GetNamespace(attributeTypeRef), "Windows.Foundation.Metadata"); } private bool HasAttribute(EntityHandle token, string asciiNamespaceName, string asciiTypeName) { foreach (var caHandle in GetCustomAttributes(token)) { StringHandle namespaceName, typeName; if (GetAttributeTypeNameRaw(caHandle, out namespaceName, out typeName) && StringHeap.EqualsRaw(typeName, asciiTypeName) && StringHeap.EqualsRaw(namespaceName, asciiNamespaceName)) { return true; } } return false; } private bool GetAttributeTypeNameRaw(CustomAttributeHandle caHandle, out StringHandle namespaceName, out StringHandle typeName) { namespaceName = typeName = default(StringHandle); EntityHandle typeDefOrRef = GetAttributeTypeRaw(caHandle); if (typeDefOrRef.IsNil) { return false; } if (typeDefOrRef.Kind == HandleKind.TypeReference) { TypeReferenceHandle typeRef = (TypeReferenceHandle)typeDefOrRef; var resolutionScope = TypeRefTable.GetResolutionScope(typeRef); if (!resolutionScope.IsNil && resolutionScope.Kind == HandleKind.TypeReference) { // we don't need to handle nested types return false; } // other resolution scopes don't affect full name typeName = TypeRefTable.GetName(typeRef); namespaceName = TypeRefTable.GetNamespace(typeRef); } else if (typeDefOrRef.Kind == HandleKind.TypeDefinition) { TypeDefinitionHandle typeDef = (TypeDefinitionHandle)typeDefOrRef; if (TypeDefTable.GetFlags(typeDef).IsNested()) { // we don't need to handle nested types return false; } typeName = TypeDefTable.GetName(typeDef); namespaceName = TypeDefTable.GetNamespace(typeDef); } else { // invalid metadata return false; } return true; } /// <summary> /// Returns the type definition or reference handle of the attribute type. /// </summary> /// <returns><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/> or nil token if the metadata is invalid and the type can't be determined.</returns> private EntityHandle GetAttributeTypeRaw(CustomAttributeHandle handle) { var ctor = CustomAttributeTable.GetConstructor(handle); if (ctor.Kind == HandleKind.MethodDefinition) { return GetDeclaringType((MethodDefinitionHandle)ctor); } if (ctor.Kind == HandleKind.MemberReference) { // In general the parent can be MethodDef, ModuleRef, TypeDef, TypeRef, or TypeSpec. // For attributes only TypeDef and TypeRef are applicable. EntityHandle typeDefOrRef = MemberRefTable.GetClass((MemberReferenceHandle)ctor); HandleKind handleType = typeDefOrRef.Kind; if (handleType == HandleKind.TypeReference || handleType == HandleKind.TypeDefinition) { return typeDefOrRef; } } return default(EntityHandle); } #endregion } }
/* * Copyright (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 OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Tests.Common { /// <summary> /// Utility functions for carrying out user inventory tests. /// </summary> public static class UserInventoryHelpers { public static readonly string PATH_DELIMITER = "/"; /// <summary> /// Add an existing scene object as an item in the user's inventory. /// </summary> /// <remarks> /// Will be added to the system Objects folder. /// </remarks> /// <param name='scene'></param> /// <param name='so'></param> /// <param name='inventoryIdTail'></param> /// <param name='assetIdTail'></param> /// <returns>The inventory item created.</returns> public static InventoryItemBase AddInventoryItem( Scene scene, SceneObjectGroup so, int inventoryIdTail, int assetIdTail) { return AddInventoryItem( scene, so.Name, TestHelpers.ParseTail(inventoryIdTail), InventoryType.Object, AssetHelpers.CreateAsset(TestHelpers.ParseTail(assetIdTail), so), so.OwnerID); } /// <summary> /// Add an existing scene object as an item in the user's inventory at the given path. /// </summary> /// <param name='scene'></param> /// <param name='so'></param> /// <param name='inventoryIdTail'></param> /// <param name='assetIdTail'></param> /// <returns>The inventory item created.</returns> public static InventoryItemBase AddInventoryItem( Scene scene, SceneObjectGroup so, int inventoryIdTail, int assetIdTail, string path) { return AddInventoryItem( scene, so.Name, TestHelpers.ParseTail(inventoryIdTail), InventoryType.Object, AssetHelpers.CreateAsset(TestHelpers.ParseTail(assetIdTail), so), so.OwnerID, path); } /// <summary> /// Adds the given item to the existing system folder for its type (e.g. an object will go in the "Objects" /// folder). /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="itemType"></param> /// <param name="asset">The serialized asset for this item</param> /// <param name="userId"></param> /// <returns></returns> private static InventoryItemBase AddInventoryItem( Scene scene, string itemName, UUID itemId, InventoryType itemType, AssetBase asset, UUID userId) { return AddInventoryItem( scene, itemName, itemId, itemType, asset, userId, scene.InventoryService.GetFolderForType(userId, (AssetType)asset.Type).Name); } /// <summary> /// Adds the given item to an inventory folder /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="itemType"></param> /// <param name="asset">The serialized asset for this item</param> /// <param name="userId"></param> /// <param name="path">Existing inventory path at which to add.</param> /// <returns></returns> private static InventoryItemBase AddInventoryItem( Scene scene, string itemName, UUID itemId, InventoryType itemType, AssetBase asset, UUID userId, string path) { scene.AssetService.Store(asset); InventoryItemBase item = new InventoryItemBase(); item.Name = itemName; item.AssetID = asset.FullID; item.ID = itemId; item.Owner = userId; item.AssetType = asset.Type; item.InvType = (int)itemType; InventoryFolderBase folder = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, userId, path)[0]; item.Folder = folder.ID; scene.AddInventoryItem(item); return item; } /// <summary> /// Creates a notecard in the objects folder and specify an item id. /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="userId"></param> /// <returns></returns> public static InventoryItemBase CreateInventoryItem(Scene scene, string itemName, UUID userId) { return CreateInventoryItem(scene, itemName, UUID.Random(), UUID.Random(), userId, InventoryType.Notecard); } /// <summary> /// Creates an item of the given type with an accompanying asset. /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="userId"></param> /// <param name="type">Type of item to create</param> /// <returns></returns> public static InventoryItemBase CreateInventoryItem( Scene scene, string itemName, UUID userId, InventoryType type) { return CreateInventoryItem(scene, itemName, UUID.Random(), UUID.Random(), userId, type); } /// <summary> /// Creates a notecard in the objects folder and specify an item id. /// </summary> /// <param name="scene"></param> /// <param name="itemName"></param> /// <param name="itemId"></param> /// <param name="assetId"></param> /// <param name="userId"></param> /// <param name="type">Type of item to create</param> /// <returns></returns> public static InventoryItemBase CreateInventoryItem( Scene scene, string itemName, UUID itemId, UUID assetId, UUID userId, InventoryType itemType) { AssetBase asset = null; if (itemType == InventoryType.Notecard) { asset = AssetHelpers.CreateNotecardAsset(); asset.CreatorID = userId.ToString(); } else if (itemType == InventoryType.Object) { asset = AssetHelpers.CreateAsset(assetId, SceneHelpers.CreateSceneObject(1, userId)); } else { throw new Exception(string.Format("Inventory type {0} not supported", itemType)); } return AddInventoryItem(scene, itemName, itemId, itemType, asset, userId); } /// <summary> /// Create inventory folders starting from the user's root folder. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"> /// The folders to create. Multiple folders can be specified on a path delimited by the PATH_DELIMITER /// </param> /// <param name="useExistingFolders"> /// If true, then folders in the path which already the same name are /// used. This applies to the terminal folder as well. /// If false, then all folders in the path are created, even if there is already a folder at a particular /// level with the same name. /// </param> /// <returns> /// The folder created. If the path contains multiple folders then the last one created is returned. /// Will return null if the root folder could not be found. /// </returns> public static InventoryFolderBase CreateInventoryFolder( IInventoryService inventoryService, UUID userId, string path, bool useExistingFolders) { return CreateInventoryFolder(inventoryService, userId, UUID.Random(), path, useExistingFolders); } /// <summary> /// Create inventory folders starting from the user's root folder. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="folderId"></param> /// <param name="path"> /// The folders to create. Multiple folders can be specified on a path delimited by the PATH_DELIMITER /// </param> /// <param name="useExistingFolders"> /// If true, then folders in the path which already the same name are /// used. This applies to the terminal folder as well. /// If false, then all folders in the path are created, even if there is already a folder at a particular /// level with the same name. /// </param> /// <returns> /// The folder created. If the path contains multiple folders then the last one created is returned. /// Will return null if the root folder could not be found. /// </returns> public static InventoryFolderBase CreateInventoryFolder( IInventoryService inventoryService, UUID userId, UUID folderId, string path, bool useExistingFolders) { InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId); if (null == rootFolder) return null; return CreateInventoryFolder(inventoryService, folderId, rootFolder, path, useExistingFolders); } /// <summary> /// Create inventory folders starting from a given parent folder /// </summary> /// <remarks> /// If any stem of the path names folders that already exist then these are not recreated. This includes the /// final folder. /// TODO: May need to make it an option to create duplicate folders. /// </remarks> /// <param name="inventoryService"></param> /// <param name="folderId">ID of the folder to create</param> /// <param name="parentFolder"></param> /// <param name="path"> /// The folder to create. /// </param> /// <param name="useExistingFolders"> /// If true, then folders in the path which already the same name are /// used. This applies to the terminal folder as well. /// If false, then all folders in the path are created, even if there is already a folder at a particular /// level with the same name. /// </param> /// <returns> /// The folder created. If the path contains multiple folders then the last one created is returned. /// </returns> public static InventoryFolderBase CreateInventoryFolder( IInventoryService inventoryService, UUID folderId, InventoryFolderBase parentFolder, string path, bool useExistingFolders) { string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None); InventoryFolderBase folder = null; if (useExistingFolders) folder = InventoryArchiveUtils.FindFolderByPath(inventoryService, parentFolder, components[0]); if (folder == null) { // Console.WriteLine("Creating folder {0} at {1}", components[0], parentFolder.Name); UUID folderIdForCreate; if (components.Length > 1) folderIdForCreate = UUID.Random(); else folderIdForCreate = folderId; folder = new InventoryFolderBase( folderIdForCreate, components[0], parentFolder.Owner, (short)AssetType.Unknown, parentFolder.ID, 0); inventoryService.AddFolder(folder); } // else // { // Console.WriteLine("Found existing folder {0}", folder.Name); // } if (components.Length > 1) return CreateInventoryFolder(inventoryService, folderId, folder, components[1], useExistingFolders); else return folder; } /// <summary> /// Get the inventory folder that matches the path name. If there are multiple folders then only the first /// is returned. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"></param> /// <returns>null if no folder matching the path was found</returns> public static InventoryFolderBase GetInventoryFolder(IInventoryService inventoryService, UUID userId, string path) { List<InventoryFolderBase> folders = GetInventoryFolders(inventoryService, userId, path); if (folders.Count != 0) return folders[0]; else return null; } /// <summary> /// Get the inventory folders that match the path name. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"></param> /// <returns>An empty list if no matching folders were found</returns> public static List<InventoryFolderBase> GetInventoryFolders(IInventoryService inventoryService, UUID userId, string path) { return InventoryArchiveUtils.FindFoldersByPath(inventoryService, userId, path); } /// <summary> /// Get the inventory item that matches the path name. If there are multiple items then only the first /// is returned. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"></param> /// <returns>null if no item matching the path was found</returns> public static InventoryItemBase GetInventoryItem(IInventoryService inventoryService, UUID userId, string path) { return InventoryArchiveUtils.FindItemByPath(inventoryService, userId, path); } /// <summary> /// Get the inventory items that match the path name. /// </summary> /// <param name="inventoryService"></param> /// <param name="userId"></param> /// <param name="path"></param> /// <returns>An empty list if no matching items were found.</returns> public static List<InventoryItemBase> GetInventoryItems(IInventoryService inventoryService, UUID userId, string path) { return InventoryArchiveUtils.FindItemsByPath(inventoryService, userId, path); } } }
/* * PROPRIETARY INFORMATION. This software is proprietary to * Side Effects Software Inc., and is not to be reproduced, * transmitted, or disclosed in any way without written permission. * * Produced by: * Side Effects Software Inc * 123 Front Street West, Suite 1401 * Toronto, Ontario * Canada M5J 2M2 * 416-504-9876 * * */ // Master control for enabling runtime. #if ( UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_STANDALONE_LINUX || ( UNITY_METRO && UNITY_EDITOR ) ) #define HAPI_ENABLE_RUNTIME #endif using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; public class HoudiniWindowSettings : EditorWindow { #if !( HAPI_ENABLE_RUNTIME ) #pragma warning disable 0414 #endif // !( HAPI_ENABLE_RUNTIME ) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Public public static void ShowWindow() { // Show existing window instance. If one doesn't exist, make one. EditorWindow window = EditorWindow.GetWindow< HoudiniWindowSettings >( false, HoudiniConstants.HAPI_PRODUCT_SHORT_NAME + " " + HoudiniGUIUtility.mySettingsLabel ); window.autoRepaintOnSceneChange = true; } public void OnGUI() { bool gui_enable = GUI.enabled; #if !( HAPI_ENABLE_RUNTIME ) HoudiniGUI.help( HoudiniConstants.HAPI_UNSUPPORTED_PLATFORM_MSG, MessageType.Info ); GUI.enabled = false; #else if ( !HoudiniHost.isInstallationOk() ) { HoudiniGUI.help( HoudiniHost.getMissingEngineInstallHelpString(), MessageType.Info ); GUI.enabled = false; } #endif // !( HAPI_ENABLE_RUNTIME ) myUndoInfo = HoudiniHost.prHostUndoInfo; myScrollPosition = GUILayout.BeginScrollView( myScrollPosition ); if ( GUILayout.Button( HoudiniGUIUtility.myRevertAllSettingsLabel ) ) { if ( EditorUtility.DisplayDialog( "Revert all settings?", "Are you sure you want to revert ALL Houdini plugin settings?", "Yes", "No" ) ) { HoudiniHost.revertAllSettingsToDefaults(); HoudiniHost.repaint(); } } HoudiniGUI.separator(); GUIContent[] modes = new GUIContent[ 6 ]; modes[ 0 ] = new GUIContent( "General" ); modes[ 1 ] = new GUIContent( "Materials" ); modes[ 2 ] = new GUIContent( "Cooking" ); modes[ 3 ] = new GUIContent( "Geometry" ); modes[ 4 ] = new GUIContent( "Curves" ); modes[ 5 ] = new GUIContent( "Advanced" ); mySettingsTabSelection = GUILayout.Toolbar( mySettingsTabSelection, modes ); switch ( mySettingsTabSelection ) { case 0: generateGeneralSettings(); break; case 1: generateMaterialSettings(); break; case 2: generateCookingSettings(); break; case 3: generateGeometrySettings(); break; case 4: generateCurveSettings(); break; case 5: generateAdvancedSettings(); break; default: Debug.LogError( "Invalid Settings Tab." ); break; } GUILayout.EndScrollView(); GUI.enabled = gui_enable; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Private private static void generateGeneralSettings() { // Pin Size { float value = HoudiniHost.prPinSize; bool changed = HoudiniGUI.floatField( "pin_size", "Pin Size", ref value, myUndoInfo, ref myUndoInfo.pinSize ); if ( changed ) { HoudiniHost.prPinSize = value; HoudiniHost.repaint(); } } // Pin Colour { Color value = HoudiniHost.prPinColour; bool changed = HoudiniGUI.colourField( "pin_colour", "Pin Color", ref value, myUndoInfo, ref myUndoInfo.pinColour ); if ( changed ) { HoudiniHost.prPinColour = value; HoudiniHost.repaint(); } } // Auto pin { bool value = HoudiniHost.prAutoPinInstances; bool changed = HoudiniGUI.toggle( "auto_pin_instances", "Auto Pin Instances", ref value, myUndoInfo, ref myUndoInfo.autoPinInstances ); if ( changed ) { HoudiniHost.prAutoPinInstances = value; HoudiniHost.repaint(); } } HoudiniGUI.separator(); // Enable Support Warnings { bool value = HoudiniHost.prEnableSupportWarnings; bool changed = HoudiniGUI.toggle( "enable_support_warnings", "Enable Support Warnings", ref value, myUndoInfo, ref myUndoInfo.enableSupportWarnings ); if ( changed ) HoudiniHost.prEnableSupportWarnings = value; } HoudiniGUI.separator(); // Enable particles { bool value = HoudiniHost.prEnablePointsAsParticles; bool changed = HoudiniGUI.toggle( "enable_points_as_particles", "Create Points as Particles", ref value, myUndoInfo, ref myUndoInfo.enablePointsAsParticles ); if ( changed ) { HoudiniHost.prEnablePointsAsParticles = value; } } } private static void generateMaterialSettings() { // Gamma { float value = HoudiniHost.prGamma; bool changed = HoudiniGUI.floatField( "gamma", "Gamma", ref value, myUndoInfo, ref myUndoInfo.gamma ); if ( changed ) { HoudiniHost.prGamma = value; HoudiniHost.repaint(); } } HoudiniGUI.separator(); // Don't Create Texture Files { bool value = HoudiniHost.prDontCreateTextureFiles; bool changed = HoudiniGUI.toggle( "dont_create_texture_files", "Don't Create Texture Files (use in-memory textures)", ref value, myUndoInfo, ref myUndoInfo.dontCreateTextureFiles ); if ( changed ) { HoudiniHost.prDontCreateTextureFiles = value; HoudiniHost.repaint(); EditorUtility.DisplayDialog( "Rebuilds Required", "This change will take affect for new instantiations or rebuilds.\n" + "A full Unity restart is recommended.", "Ok" ); } } // Extract Textures In Raw Format { bool value = HoudiniHost.prExtractTexturesInRawFormat; bool was_gui_enabled = GUI.enabled; GUI.enabled = HoudiniHost.prDontCreateTextureFiles; bool changed = HoudiniGUI.toggle( "extract_textures_in_raw_format", "Extract Textures In Raw Format (only works for in-memory textures)", ref value, myUndoInfo, ref myUndoInfo.extractTexturesInRawFormat ); if ( changed ) { HoudiniHost.prExtractTexturesInRawFormat = value; HoudiniHost.repaint(); } GUI.enabled = was_gui_enabled; } } private static void generateCookingSettings() { // Enable Cooking { bool value = HoudiniHost.prEnableCooking; bool changed = HoudiniGUI.toggle( "enable_cooking", "Enable Cooking", ref value, myUndoInfo, ref myUndoInfo.enableCooking ); if ( changed ) { HoudiniHost.prEnableCooking = value; HoudiniHost.repaint(); } } HoudiniGUI.separator(); // Cooking Triggers Downstream Cooks { bool value = HoudiniHost.prCookingTriggersDownCooks; bool changed = HoudiniGUI.toggle( "cooking_triggers_downstream_cooks", "Cooking Triggers Downstream Cooks", ref value, myUndoInfo, ref myUndoInfo.cookingTriggersDownCooks ); if ( changed ) { HoudiniHost.prCookingTriggersDownCooks = value; HoudiniHost.repaint(); } } // Playmode Per-Frame Cooking { bool value = HoudiniHost.prPlaymodePerFrameCooking; bool changed = HoudiniGUI.toggle( "playmode_per_frame_cooking", "Playmode Per-Frame Cooking", ref value, myUndoInfo, ref myUndoInfo.playmodePerFrameCooking ); if ( changed ) { HoudiniHost.prPlaymodePerFrameCooking = value; HoudiniHost.repaint(); } } HoudiniGUI.separator(); // Push Unity Transform To Houdini Engine { bool value = HoudiniHost.prPushUnityTransformToHoudini; bool changed = HoudiniGUI.toggle( "push_unity_transform_to_houdini", "Push Unity Transform to Houdini Engine", ref value, myUndoInfo, ref myUndoInfo.pushUnityTransformToHoudini ); if ( changed ) { HoudiniHost.prPushUnityTransformToHoudini = value; HoudiniHost.repaint(); } } // Transform Change Triggers Cooks { bool value = HoudiniHost.prTransformChangeTriggersCooks; bool changed = HoudiniGUI.toggle( "transform_change_triggers_cooks", "Transform Change Triggers Cooks", ref value, myUndoInfo, ref myUndoInfo.transformChangeTriggersCooks ); if ( changed ) { HoudiniHost.prTransformChangeTriggersCooks = value; HoudiniHost.repaint(); } } HoudiniGUI.separator(); // Import Templated Geos { bool value = HoudiniHost.prImportTemplatedGeos; bool changed = HoudiniGUI.toggle( "import_templated_geos", "Import Templated Geos", ref value, myUndoInfo, ref myUndoInfo.importTemplatedGeos ); if ( changed ) { HoudiniHost.prImportTemplatedGeos = value; HoudiniHost.repaint(); } } HoudiniGUI.separator(); // Split Geos by Group { bool value = HoudiniHost.prSplitGeosByGroup; bool changed = HoudiniGUI.toggle( "split_geos_by_group", "Split Geos by Group", ref value, myUndoInfo, ref myUndoInfo.splitGeosByGroup ); if ( changed ) { HoudiniHost.prSplitGeosByGroup = value; HoudiniHost.repaint(); EditorUtility.DisplayDialog( "Rebuild Required", "This change will take affect only after a full asset rebuild.", "Ok" ); } } // Split Points by Vertex Attributes { bool value = HoudiniHost.prSplitPointsByVertexAttributes; bool changed = HoudiniGUI.toggle( "split_points_by_vertex_attributes", "Split Points by Vertex Attributes", ref value, myUndoInfo, ref myUndoInfo.splitGeosByGroup ); if ( changed ) { HoudiniHost.prSplitPointsByVertexAttributes = value; HoudiniHost.repaint(); EditorUtility.DisplayDialog( "Rebuild Required", "This change will take affect only after a full asset rebuild.", "Ok" ); } } } private static void generateGeometrySettings() { // Paint Brush Rate { // Everything is opposite here because the higher the number the slower // the paint rate and we want the user to think the higher the number // the FASTER the rate - so we have to invert. float value = HoudiniHost.prPaintBrushRate; bool changed = HoudiniGUI.floatField( "paint_brush_rate", "Paint Brush Rate", ref value, 0.0f, 1.0f, myUndoInfo, ref myUndoInfo.paintBrushRate ); if ( changed ) { HoudiniHost.prPaintBrushRate = value; HoudiniHost.repaint(); } } // Painting Mode Hot Key { KeyCode value = HoudiniHost.prPaintingModeHotKey; string[] labels = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .Select( v => v.ToString() ) .ToArray(); KeyCode[] values = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .ToArray(); bool changed = HoudiniGUI.dropdown( "painting_mode_hot_key", "Painting Key", ref value, labels, values, myUndoInfo, ref myUndoInfo.paintingModeHotKey ); if ( changed ) { HoudiniHost.prPaintingModeHotKey = (KeyCode) value; HoudiniHost.repaint(); } } // Painting Mode Colour { Color value = HoudiniHost.prPaintingModeColour; bool changed = HoudiniGUI.colourField( "painting_mode_colour", "Painting Mode", ref value, myUndoInfo, ref myUndoInfo.paintingModeColour ); if ( changed ) { HoudiniHost.prPaintingModeColour = value; HoudiniHost.repaint(); } } // Painting Node Switch Hot Key { KeyCode value = HoudiniHost.prPaintingNodeSwitchHotKey; string[] labels = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .Select( v => v.ToString() ) .ToArray(); KeyCode[] values = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .ToArray(); bool changed = HoudiniGUI.dropdown( "painting_node_switch_hot_key", "Node Switch Key", ref value, labels, values, myUndoInfo, ref myUndoInfo.paintingNodeSwitchHotKey ); if ( changed ) { HoudiniHost.prPaintingNodeSwitchHotKey = (KeyCode) value; HoudiniHost.repaint(); } } // Painting Attribute Switch Hot Key { KeyCode value = HoudiniHost.prPaintingAttributeSwitchHotKey; string[] labels = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .Select( v => v.ToString() ) .ToArray(); KeyCode[] values = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .ToArray(); bool changed = HoudiniGUI.dropdown( "painting_attribute_switch_hot_key", "Attr. Switch Key", ref value, labels, values, myUndoInfo, ref myUndoInfo.paintingAttributeSwitchHotKey ); if ( changed ) { HoudiniHost.prPaintingAttributeSwitchHotKey = (KeyCode) value; HoudiniHost.repaint(); } } // Painting Value Change Hot Key { KeyCode value = HoudiniHost.prPaintingValueChangeHotKey; string[] labels = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .Select( v => v.ToString() ) .ToArray(); KeyCode[] values = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .ToArray(); bool changed = HoudiniGUI.dropdown( "painting_value_change_hot_key", "Value Change Key", ref value, labels, values, myUndoInfo, ref myUndoInfo.paintingValueChangeHotKey ); if ( changed ) { HoudiniHost.prPaintingValueChangeHotKey = (KeyCode) value; HoudiniHost.repaint(); } } // Painting Falloff Change Hot Key { KeyCode value = HoudiniHost.prPaintingFalloffChangeHotKey; string[] labels = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .Select( v => v.ToString() ) .ToArray(); KeyCode[] values = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .ToArray(); bool changed = HoudiniGUI.dropdown( "painting_falloff_change_hot_key", "Falloff Change Key", ref value, labels, values, myUndoInfo, ref myUndoInfo.paintingFalloffChangeHotKey ); if ( changed ) { HoudiniHost.prPaintingFalloffChangeHotKey = (KeyCode) value; HoudiniHost.repaint(); } } HoudiniGUI.separator(); // Adding Points Mode Hot Key { KeyCode value = HoudiniHost.prAddingPointsModeHotKey; string[] labels = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .Select( v => v.ToString() ) .ToArray(); KeyCode[] values = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .ToArray(); bool changed = HoudiniGUI.dropdown( "adding_points_mode_hot_key", "Adding Points Key", ref value, labels, values, myUndoInfo, ref myUndoInfo.addingPointsModeHotKey ); if ( changed ) { HoudiniHost.prAddingPointsModeHotKey = (KeyCode) value; HoudiniHost.repaint(); } } // Adding Points Mode Colour { Color value = HoudiniHost.prAddingPointsModeColour; bool changed = HoudiniGUI.colourField( "adding_ponits_mode_colour", "Adding Points Mode", ref value, myUndoInfo, ref myUndoInfo.addingPointsModeColour ); if ( changed ) { HoudiniHost.prAddingPointsModeColour = value; HoudiniHost.repaint(); } } HoudiniGUI.separator(); // Editing Points Mode Hot Key { KeyCode value = HoudiniHost.prEditingPointsModeHotKey; string[] labels = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .Select( v => v.ToString() ) .ToArray(); KeyCode[] values = System.Enum.GetValues( typeof( KeyCode ) ) .Cast< KeyCode >() .ToArray(); bool changed = HoudiniGUI.dropdown( "editing_points_mode_hot_key", "Editing Points Key", ref value, labels, values, myUndoInfo, ref myUndoInfo.editingPointsModeHotKey ); if ( changed ) { HoudiniHost.prEditingPointsModeHotKey = (KeyCode) value; HoudiniHost.repaint(); } } // Editing Points Mode Colour { Color value = HoudiniHost.prEditingPointsModeColour; bool changed = HoudiniGUI.colourField( "editing_ponits_mode_colour", "Editing Points Mode", ref value, myUndoInfo, ref myUndoInfo.editingPointsModeColour ); if ( changed ) { HoudiniHost.prEditingPointsModeColour = value; HoudiniHost.repaint(); } } HoudiniGUI.separator(); // Wireframe Colour { Color value = HoudiniHost.prWireframeColour; bool changed = HoudiniGUI.colourField( "wireframe_colour", "Wireframe", ref value, myUndoInfo, ref myUndoInfo.wireframeColour ); if ( changed ) { HoudiniHost.prWireframeColour = value; HoudiniHost.repaint(); } } // Guide Wireframe Colour { Color value = HoudiniHost.prGuideWireframeColour; bool changed = HoudiniGUI.colourField( "guide_wireframe_colour", "Guide Wireframe", ref value, myUndoInfo, ref myUndoInfo.guideWireframeColour ); if ( changed ) { HoudiniHost.prGuideWireframeColour = value; HoudiniHost.repaint(); } } // Unselectable Guide Wireframe Colour { Color value = HoudiniHost.prUnselectableGuideWireframeColour; bool changed = HoudiniGUI.colourField( "unselectable_guide_wireframe_colour", "Unselectable Guide", ref value, myUndoInfo, ref myUndoInfo.unselectableGuideWireframeColour ); if ( changed ) { HoudiniHost.prUnselectableGuideWireframeColour = value; HoudiniHost.repaint(); } } // Unselected Guide Wireframe Colour { Color value = HoudiniHost.prUnselectedGuideWireframeColour; bool changed = HoudiniGUI.colourField( "unselected_guide_wireframe_colour", "Unselected Guide", ref value, myUndoInfo, ref myUndoInfo.unselectedGuideWireframeColour ); if ( changed ) { HoudiniHost.prUnselectedGuideWireframeColour = value; HoudiniHost.repaint(); } } // Selected Guide Wireframe Colour { Color value = HoudiniHost.prSelectedGuideWireframeColour; bool changed = HoudiniGUI.colourField( "selected_guide_wireframe_colour", "Selected Guide", ref value, myUndoInfo, ref myUndoInfo.selectedGuideWireframeColour ); if ( changed ) { HoudiniHost.prSelectedGuideWireframeColour = value; HoudiniHost.repaint(); } } HoudiniGUI.separator(); // Guide Point Size { float value = HoudiniHost.prGuidePointSize; bool changed = HoudiniGUI.floatField( "guide_point_size", "Guide Point Size", ref value, 4.0f, 40.0f, myUndoInfo, ref myUndoInfo.guidePointSize ); if ( changed ) { HoudiniHost.prGuidePointSize = value; HoudiniHost.repaint(); } } // Min. Distance For Point Selection { float value = HoudiniHost.prMinDistanceForPointSelection; bool changed = HoudiniGUI.floatField( "min_distance_for_point_selection", "Min. Distance For Point Selection", ref value, 1.0f, 20.0f, myUndoInfo, ref myUndoInfo.minDistanceForPointSelection ); if ( changed ) { HoudiniHost.prMinDistanceForPointSelection = value; HoudiniHost.repaint(); } } // Guide Min. Distance For Mid Point Insertion { float value = HoudiniHost.prGuideMinDistanceForMidPointInsertion; bool changed = HoudiniGUI.floatField( "guide_min_distance_for_mid_point_insertion", "Guide Min. Distance For Mid Point Insertion", ref value, 1.0f, 20.0f, myUndoInfo, ref myUndoInfo.guideMinDistanceForMidPointInsertion ); if ( changed ) { HoudiniHost.prGuideMinDistanceForMidPointInsertion = value; HoudiniHost.repaint(); } } HoudiniGUI.separator(); // Create Groups from Bool Attribute { bool value = HoudiniHost.prCreateGroupsFromBoolAttributes; bool changed = HoudiniGUI.toggle( "create_groups_from_bool_attributes", "Create Groups from Bool Attributes", ref value, myUndoInfo, ref myUndoInfo.createGroupsFromBoolAttributes ); if ( changed ) { HoudiniHost.prCreateGroupsFromBoolAttributes = value; HoudiniHost.repaint(); } } } private static void generateCurveSettings() { // Curve Primitive Type Default { int value = HoudiniHost.prCurvePrimitiveTypeDefault; string[] labels = { "Polygon", "NURBS", "Bezier" }; int[] values = { 0, 1, 2 }; bool changed = HoudiniGUI.dropdown( "curve_primitive_type_default", "Initial Type", ref value, labels, values, myUndoInfo, ref myUndoInfo.curvePrimitiveTypeDefault ); if ( changed ) HoudiniHost.prCurvePrimitiveTypeDefault = value; } // Curve Method Default { int value = HoudiniHost.prCurveMethodDefault; string[] labels = { "CVs", "Breakpoints", "Freehand" }; int[] values = { 0, 1, 2 }; bool changed = HoudiniGUI.dropdown( "curve_method_default", "Initial Method", ref value, labels, values, myUndoInfo, ref myUndoInfo.curveMethodDefault ); if ( changed ) HoudiniHost.prCurveMethodDefault = value; } } private static void generateAdvancedSettings() { if ( !myEnableAdvancedSettings ) { if ( HoudiniGUI.button( "allow_advanced_settings", "Allow Editing of Advanced Settings" ) ) { if ( EditorUtility.DisplayDialog( "Careful!", "Changing these settings can cause the Houdini Engine plugin to stop working. " + "Are you sure you want to edit them?", "Yes", "No" ) ) { myEnableAdvancedSettings = true; } } } else { if ( HoudiniGUI.button( "disallow_advanced_settings", "Disallow Editing of Advanced Settings" ) ) { myEnableAdvancedSettings = false; } } HoudiniGUI.separator(); bool gui_enabled = GUI.enabled; GUI.enabled = myEnableAdvancedSettings; // Collision Group Name { string value = HoudiniHost.prCollisionGroupName; bool changed = HoudiniGUI.stringField( "collision_group_name", "Colli. Grp.", ref value, myUndoInfo, ref myUndoInfo.collisionGroupName ); if ( changed ) HoudiniHost.prCollisionGroupName = value; } // Rendered Collision Group Name { string value = HoudiniHost.prRenderedCollisionGroupName; bool changed = HoudiniGUI.stringField( "rendered_collision_group_name", "Rendered Colli. Grp.", ref value, myUndoInfo, ref myUndoInfo.renderedCollisionGroupName ); if ( changed ) HoudiniHost.prRenderedCollisionGroupName = value; } HoudiniGUI.separator(); // Unity Material Attrib Name { string value = HoudiniHost.prUnityMaterialAttribName; bool changed = HoudiniGUI.stringField( "unity_material_attrib_name", "Unity Mat. Attrib.", ref value, myUndoInfo, ref myUndoInfo.unityMaterialAttribName ); if ( changed ) HoudiniHost.prUnityMaterialAttribName = value; } // Unity Sub Material Name Attrib Name { string value = HoudiniHost.prUnitySubMaterialNameAttribName; bool changed = HoudiniGUI.stringField( "unity_sub_material_name_attrib_name", "Unity SubMat. Name Attrib.", ref value, myUndoInfo, ref myUndoInfo.unitySubMaterialNameAttribName ); if ( changed ) HoudiniHost.prUnitySubMaterialNameAttribName = value; } // Unity Sub Material Index Attrib Name { string value = HoudiniHost.prUnitySubMaterialIndexAttribName; bool changed = HoudiniGUI.stringField( "unity_sub_material_index_attrib_name", "Unity SubMat. Index Attrib.", ref value, myUndoInfo, ref myUndoInfo.unitySubMaterialIndexAttribName ); if ( changed ) HoudiniHost.prUnitySubMaterialIndexAttribName = value; } HoudiniGUI.separator(); // Unity Tag Attrib Name { string value = HoudiniHost.prUnityTagAttribName; bool changed = HoudiniGUI.stringField( "unity_tag_attrib_name", "Unity Tag Attrib.", ref value, myUndoInfo, ref myUndoInfo.unityTagAttribName ); if ( changed ) HoudiniHost.prUnityTagAttribName = value; } GUI.enabled = gui_enabled; } private static int mySettingsTabSelection = 0; private static Vector2 myScrollPosition; private static bool myEnableAdvancedSettings = false; private static HoudiniHostUndoInfo myUndoInfo; #if !( HAPI_ENABLE_RUNTIME ) #pragma warning restore 0414 #endif // !( HAPI_ENABLE_RUNTIME ) }
using System; using System.Collections; using Alachisoft.NCache.Common.Net; using Alachisoft.NCache.Runtime.Serialization; using Alachisoft.NCache.Runtime.Serialization.IO; using Alachisoft.NCache.Common.DataStructures; using Alachisoft.NCache.Common.Mirroring; namespace Alachisoft.NGroups { /// <summary> /// Represents the current 'View' of the _members of the group /// <p><b>Author:</b> Chris Koiak, Bela Ban</p> /// <p><b>Date:</b> 12/03/2003</p> /// </summary> [Serializable] public class View : ICloneable, ICompactSerializable { /// <remarks> /// The view id contains the creator address and a lamport time. /// the lamport time is the highest timestamp seen or sent from a view. /// if a view change comes in with a lower lamport time, the event is discarded. /// </remarks> /// <summary> /// A view is uniquely identified by its ViewID /// </summary> private ViewId vid; /// <remarks> /// This list is always ordered, with the coordinator being the first member. /// the second member will be the new coordinator if the current one disappears /// or leaves the group. /// </remarks> /// <summary> /// A list containing all the _members of the view /// </summary> private ArrayList _members; /// <summary> /// contains the mbrs list agains subgroups /// </summary> private Hashtable _sequencerTbl; /// <summary> /// contains the subgroup against the mbr addresses. /// </summary> private Hashtable _mbrsSubgroupMap; private bool _forceInstall; private DistributionMaps _distributionMaps; private string _coordinatorGmsId; /// <summary> /// Map table or some serialized link list for dynamic mirroring. /// </summary> private CacheNode[] _mirrorMapping; private Hashtable nodeGmsIds = new Hashtable(); /// <summary> creates an empty view, should not be used</summary> public View() { } /// <summary> /// Constructor /// </summary> /// <param name="vid">The view id of this view (can not be null)</param> /// <param name="_members">Contains a list of all the _members in the view, can be empty but not null.</param> public View(ViewId vid, ArrayList _members) { this.vid = vid; this._members = _members; } /// <summary> /// Constructor /// </summary> /// <param name="vid">The view id of this view (can not be null)</param> /// <param name="_members">Contains a list of all the _members in the view, can be empty but not null.</param> public View(ViewId vid, ArrayList _members, Hashtable sequencerTbl) { this.vid = vid; this._members = _members; this._sequencerTbl = sequencerTbl; } /// <summary> /// Constructor /// </summary> /// <param name="creator">The creator of this view</param> /// <param name="id">The lamport timestamp of this view</param> /// <param name="_members">Contains a list of all the _members in the view, can be empty but not null.</param> public View(Address creator, long id, ArrayList _members) : this( new ViewId(creator, id), _members) { } /// <summary> returns the view ID of this view /// if this view was created with the empty constructur, null will be returned /// </summary> /// <returns> the view ID of this view /// </returns> public ViewId Vid { get { return vid; } } public bool ForceInstall { get { return _forceInstall; } set { _forceInstall = value; } } public string CoordinatorGmsId { get { return _coordinatorGmsId; } set { _coordinatorGmsId = value; } } public DistributionMaps DistributionMaps { get { return _distributionMaps; } set { _distributionMaps = value; } } public Address Coordinator { get { return _members != null && _members.Count > 0 ? _members[0] as Address : null; } } public Hashtable SequencerTbl { get { return this._sequencerTbl; } set { this._sequencerTbl = value; } } public Hashtable MbrsSubgroupMap { get { return this._mbrsSubgroupMap; } set { this._mbrsSubgroupMap = value; } } /// <summary> returns the creator of this view /// if this view was created with the empty constructur, null will be returned /// </summary> /// <returns> the creator of this view in form of an Address object /// </returns> public Address Creator { get { return vid != null?vid.CoordAddress:null; } } public void AddGmsId(Address node, string id) { if(node != null) nodeGmsIds[node] = id; } public void RemoveGmsId(Address node) { if(node != null) nodeGmsIds.Remove(node); } public void RemoveGmsId(ArrayList nodes) { foreach (Address node in nodes) { if(node != null) nodeGmsIds.Remove(node); } } public Hashtable GmsIds { get { return nodeGmsIds; } } public string GetGmsId(Address node) { return nodeGmsIds[node] as string; } /// <summary> Returns a reference to the List of _members (ordered) /// Do NOT change this list, hence your will invalidate the view /// Make a copy if you have to modify it. /// </summary> /// <returns> a reference to the ordered list of _members in this view /// </returns> public System.Collections.ArrayList Members { get { return _members; } } /// <summary> /// Hashtable or some serialized object used for dynamic mirroring in /// case of Partitioned Replica topology. This along with Distribution Map /// is sent back to the joining node or to all the nodes in the cluster in case of leaving. /// </summary> public CacheNode[] MirrorMapping { get { return _mirrorMapping; } set { _mirrorMapping = value; } } /// <summary> /// Returns true, if this view contains a certain member /// </summary> /// <param name="mbr">The address of the member</param> /// <returns>True, if this view contains a certain member</returns> public bool containsMember( Address mbr ) { if ( mbr == null || _members == null ) { return false; } return _members.Contains(mbr); } /// <summary> /// Returns the number of _members in this view /// </summary> /// <returns>The number of _members in this view</returns> public int size() { if (_members == null) return 0; else return _members.Count; } /// <summary> creates a copy of this view</summary> /// <returns> a copy of this view /// </returns> public virtual object Clone() { ViewId vid2 = vid != null?(ViewId) vid.Clone():null; System.Collections.ArrayList members2 = _members != null?(System.Collections.ArrayList) _members.Clone():null; View v = new View(vid2, members2); if(SequencerTbl != null) v.SequencerTbl = SequencerTbl.Clone() as Hashtable; if (MbrsSubgroupMap != null) v.MbrsSubgroupMap = MbrsSubgroupMap.Clone() as Hashtable; v._coordinatorGmsId = _coordinatorGmsId; if (DistributionMaps != null) v.DistributionMaps = DistributionMaps.Clone() as DistributionMaps; if (MirrorMapping != null) v.MirrorMapping = MirrorMapping; if (nodeGmsIds != null) v.nodeGmsIds = nodeGmsIds.Clone() as Hashtable; return (v); } /// <summary> /// Copys the View /// </summary> /// <returns>A copy of the View</returns> public View Copy() { return (View)Copy(); } /// <summary> /// Returns a string representation of the View /// </summary> /// <returns>A string representation of the View</returns> public override String ToString() { System.Text.StringBuilder ret = new System.Text.StringBuilder(); ret.Append(vid + " [gms_id:" + _coordinatorGmsId +"] " + Global.CollectionToString(_members)); return ret.ToString(); } #region ICompactSerializable Members public virtual void Deserialize(CompactReader reader) { vid = (ViewId) reader.ReadObject(); _members = (ArrayList) reader.ReadObject(); _sequencerTbl = (Hashtable)reader.ReadObject(); _mbrsSubgroupMap = (Hashtable)reader.ReadObject(); _distributionMaps = (DistributionMaps)reader.ReadObject(); _mirrorMapping = reader.ReadObject() as CacheNode[]; nodeGmsIds = reader.ReadObject() as Hashtable; _coordinatorGmsId = reader.ReadObject() as string; } public virtual void Serialize(CompactWriter writer) { writer.WriteObject(vid); writer.WriteObject(_members); writer.WriteObject(_sequencerTbl); writer.WriteObject(_mbrsSubgroupMap); writer.WriteObject(_distributionMaps); writer.WriteObject(_mirrorMapping); writer.WriteObject(nodeGmsIds); writer.WriteObject(_coordinatorGmsId); } #endregion public static View ReadView(CompactReader reader) { byte isNull = reader.ReadByte(); if (isNull == 1) return null; View newView = new View(); newView.Deserialize(reader); return newView; } public static void WriteView(CompactWriter writer, View v) { byte isNull = 1; if (v == null) writer.Write(isNull); else { isNull = 0; writer.Write(isNull); v.Serialize(writer); } return; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.IO { partial class FileSystemInfo { private const int NanosecondsPerTick = 100; /// <summary>The last cached stat information about the file.</summary> private Interop.Sys.FileStatus _fileStatus; /// <summary>true if <see cref="_fileStatus"/> represents a symlink and the target of that symlink is a directory.</summary> private bool _targetOfSymlinkIsDirectory; /// <summary> /// Exists as a path as of last refresh. /// </summary> private bool _exists; /// <summary> /// Whether we've successfully cached a stat structure. /// -1 if we need to refresh _fileStatus, 0 if we've successfully cached one, /// or any other value that serves as an errno error code from the /// last time we tried and failed to refresh _fileStatus. /// </summary> private int _fileStatusInitialized = -1; internal void Invalidate() { _fileStatusInitialized = -1; } public FileAttributes Attributes { get { EnsureStatInitialized(); if (!_exists) return (FileAttributes)(-1); FileAttributes attrs = default(FileAttributes); if (IsDirectoryAssumesInitialized) // this is the one attribute where we follow symlinks { attrs |= FileAttributes.Directory; } if (IsReadOnlyAssumesInitialized) { attrs |= FileAttributes.ReadOnly; } if (IsSymlinkAssumesInitialized) { attrs |= FileAttributes.ReparsePoint; } // If the filename starts with a period, it's hidden. Or if this is a directory ending in a slash, // if the directory name starts with a period, it's hidden. string fileName = Path.GetFileName(FullPath); if (string.IsNullOrEmpty(fileName)) { fileName = Path.GetFileName(Path.GetDirectoryName(FullPath)); } if (!string.IsNullOrEmpty(fileName) && fileName[0] == '.') { attrs |= FileAttributes.Hidden; } return attrs != default(FileAttributes) ? attrs : FileAttributes.Normal; } set { // Validate that only flags from the attribute are being provided. This is an // approximation for the validation done by the Win32 function. const FileAttributes allValidFlags = FileAttributes.Archive | FileAttributes.Compressed | FileAttributes.Device | FileAttributes.Directory | FileAttributes.Encrypted | FileAttributes.Hidden | FileAttributes.Hidden | FileAttributes.IntegrityStream | FileAttributes.Normal | FileAttributes.NoScrubData | FileAttributes.NotContentIndexed | FileAttributes.Offline | FileAttributes.ReadOnly | FileAttributes.ReparsePoint | FileAttributes.SparseFile | FileAttributes.System | FileAttributes.Temporary; if ((value & ~allValidFlags) != 0) { throw new ArgumentException(SR.Arg_InvalidFileAttrs, nameof(value)); } // The only thing we can reasonably change is whether the file object is readonly, // just changing its permissions accordingly. EnsureStatInitialized(); if (!_exists) { ThrowNotFound(FullPath); } IsReadOnlyAssumesInitialized = (value & FileAttributes.ReadOnly) != 0; _fileStatusInitialized = -1; } } internal static void ThrowNotFound(string path) { // Windows distinguishes between whether the directory or the file isn't found, // and throws a different exception in these cases. We attempt to approximate that // here; there is a race condition here, where something could change between // when the error occurs and our checks, but it's the best we can do, and the // worst case in such a race condition (which could occur if the file system is // being manipulated concurrently with these checks) is that we throw a // FileNotFoundException instead of DirectoryNotFoundException. bool directoryError = !Directory.Exists(Path.GetDirectoryName(PathHelpers.TrimEndingDirectorySeparator(path))); throw Interop.GetExceptionForIoErrno(new Interop.ErrorInfo(Interop.Error.ENOENT), path, directoryError); } /// <summary>Gets whether stat reported this system object as a directory.</summary> private bool IsDirectoryAssumesInitialized => (_fileStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR || (IsSymlinkAssumesInitialized && _targetOfSymlinkIsDirectory); /// <summary>Gets whether stat reported this system object as a symlink.</summary> private bool IsSymlinkAssumesInitialized => (_fileStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFLNK; /// <summary> /// Gets or sets whether the file is read-only. This is based on the read/write/execute /// permissions of the object. /// </summary> private bool IsReadOnlyAssumesInitialized { get { Interop.Sys.Permissions readBit, writeBit; if (_fileStatus.Uid == Interop.Sys.GetEUid()) // does the user effectively own the file? { readBit = Interop.Sys.Permissions.S_IRUSR; writeBit = Interop.Sys.Permissions.S_IWUSR; } else if (_fileStatus.Gid == Interop.Sys.GetEGid()) // does the user belong to a group that effectively owns the file? { readBit = Interop.Sys.Permissions.S_IRGRP; writeBit = Interop.Sys.Permissions.S_IWGRP; } else // everyone else { readBit = Interop.Sys.Permissions.S_IROTH; writeBit = Interop.Sys.Permissions.S_IWOTH; } return (_fileStatus.Mode & (int)readBit) != 0 && // has read permission (_fileStatus.Mode & (int)writeBit) == 0; // but not write permission } set { int newMode = _fileStatus.Mode; if (value) // true if going from writable to readable, false if going from readable to writable { // Take away all write permissions from user/group/everyone newMode &= ~(int)(Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IWOTH); } else if ((newMode & (int)Interop.Sys.Permissions.S_IRUSR) != 0) { // Give write permission to the owner if the owner has read permission newMode |= (int)Interop.Sys.Permissions.S_IWUSR; } // Change the permissions on the file if (newMode != _fileStatus.Mode) { bool isDirectory = this is DirectoryInfo; Interop.CheckIo(Interop.Sys.ChMod(FullPath, newMode), FullPath, isDirectory); } } } internal bool ExistsCore { get { if (_fileStatusInitialized == -1) { Refresh(); } return _exists && (this is DirectoryInfo) == IsDirectoryAssumesInitialized; } } internal DateTimeOffset CreationTimeCore { get { EnsureStatInitialized(); if (!_exists) return DateTimeOffset.FromFileTime(0); if ((_fileStatus.Flags & Interop.Sys.FileStatusFlags.HasBirthTime) != 0) return UnixTimeToDateTimeOffset(_fileStatus.BirthTime, _fileStatus.BirthTimeNsec); // fall back to the oldest time we have in between change and modify time if (_fileStatus.MTime < _fileStatus.CTime || (_fileStatus.MTime == _fileStatus.CTime && _fileStatus.MTimeNsec < _fileStatus.CTimeNsec)) return UnixTimeToDateTimeOffset(_fileStatus.MTime, _fileStatus.MTimeNsec); return UnixTimeToDateTimeOffset(_fileStatus.CTime, _fileStatus.CTimeNsec); } set { // There isn't a reliable way to set this; however, we can't just do nothing since the // FileSystemWatcher specifically looks for this call to make a Metadata Change, so we // should set the LastAccessTime of the file to cause the metadata change we need. LastAccessTime = LastAccessTime; } } internal DateTimeOffset LastAccessTimeCore { get { EnsureStatInitialized(); if (!_exists) return DateTimeOffset.FromFileTime(0); return UnixTimeToDateTimeOffset(_fileStatus.ATime, _fileStatus.ATimeNsec); } set { SetAccessWriteTimes(value.ToUnixTimeSeconds(), null); } } internal DateTimeOffset LastWriteTimeCore { get { EnsureStatInitialized(); if (!_exists) return DateTimeOffset.FromFileTime(0); return UnixTimeToDateTimeOffset(_fileStatus.MTime, _fileStatus.MTimeNsec); } set { SetAccessWriteTimes(null, value.ToUnixTimeSeconds()); } } private DateTimeOffset UnixTimeToDateTimeOffset(long seconds, long nanoseconds) { return DateTimeOffset.FromUnixTimeSeconds(seconds).AddTicks(nanoseconds / NanosecondsPerTick).ToLocalTime(); } private void SetAccessWriteTimes(long? accessTime, long? writeTime) { _fileStatusInitialized = -1; // force a refresh so that we have an up-to-date times for values not being overwritten EnsureStatInitialized(); Interop.Sys.UTimBuf buf; // we use utime() not utimensat() so we drop the subsecond part buf.AcTime = accessTime ?? _fileStatus.ATime; buf.ModTime = writeTime ?? _fileStatus.MTime; bool isDirectory = this is DirectoryInfo; Interop.CheckIo(Interop.Sys.UTime(FullPath, ref buf), FullPath, isDirectory); _fileStatusInitialized = -1; } internal long LengthCore { get { EnsureStatInitialized(); return _fileStatus.Size; } } public void Refresh() { // This should not throw, instead we store the result so that we can throw it // when someone actually accesses a property. // Use lstat to get the details on the object, without following symlinks. // If it is a symlink, then subsequently get details on the target of the symlink, // storing those results separately. We only report failure if the initial // lstat fails, as a broken symlink should still report info on exists, attributes, etc. _targetOfSymlinkIsDirectory = false; string path = PathHelpers.TrimEndingDirectorySeparator(FullPath); int result = Interop.Sys.LStat(path, out _fileStatus); if (result < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); // This should never set the error if the file can't be found. // (see the Windows refresh passing returnErrorOnNotFound: false). if (errorInfo.Error == Interop.Error.ENOENT || errorInfo.Error == Interop.Error.ENOTDIR) { _fileStatusInitialized = 0; _exists = false; } else { _fileStatusInitialized = errorInfo.RawErrno; } return; } _exists = true; Interop.Sys.FileStatus targetStatus; if ((_fileStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFLNK && Interop.Sys.Stat(path, out targetStatus) >= 0) { _targetOfSymlinkIsDirectory = (targetStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR; } _fileStatusInitialized = 0; } private void EnsureStatInitialized() { if (_fileStatusInitialized == -1) { Refresh(); } if (_fileStatusInitialized != 0) { int errno = _fileStatusInitialized; _fileStatusInitialized = -1; throw Interop.GetExceptionForIoErrno(new Interop.ErrorInfo(errno), FullPath); } } } }
namespace Xilium.CefGlue { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Xilium.CefGlue.Interop; /// <summary> /// Implement this interface to handle events related to browser requests. The /// methods of this class will be called on the thread indicated. /// </summary> public abstract unsafe partial class CefRequestHandler { private int on_before_browse(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request, int is_redirect) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_frame = CefFrame.FromNative(frame); var m_request = CefRequest.FromNative(request); var m_isRedirect = is_redirect != 0; var result = OnBeforeBrowse(m_browser, m_frame, m_request, m_isRedirect); return result ? 1 : 0; } /// <summary> /// Called on the UI thread before browser navigation. Return true to cancel /// the navigation or false to allow the navigation to proceed. The |request| /// object cannot be modified in this callback. /// CefLoadHandler::OnLoadingStateChange will be called twice in all cases. /// If the navigation is allowed CefLoadHandler::OnLoadStart and /// CefLoadHandler::OnLoadEnd will be called. If the navigation is canceled /// CefLoadHandler::OnLoadError will be called with an |errorCode| value of /// ERR_ABORTED. /// </summary> protected virtual bool OnBeforeBrowse(CefBrowser browser, CefFrame frame, CefRequest request, bool isRedirect) { return false; } private int on_before_resource_load(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_frame = CefFrame.FromNative(frame); var m_request = CefRequest.FromNative(request); var result = OnBeforeResourceLoad(m_browser, m_frame, m_request); m_request.Dispose(); return result ? 1 : 0; } /// <summary> /// Called on the IO thread before a resource request is loaded. The |request| /// object may be modified. To cancel the request return true otherwise return /// false. /// </summary> protected virtual bool OnBeforeResourceLoad(CefBrowser browser, CefFrame frame, CefRequest request) { return false; } private cef_resource_handler_t* get_resource_handler(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_request_t* request) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_frame = CefFrame.FromNative(frame); var m_request = CefRequest.FromNative(request); var handler = GetResourceHandler(m_browser, m_frame, m_request); m_request.Dispose(); return handler != null ? handler.ToNative() : null; } /// <summary> /// Called on the IO thread before a resource is loaded. To allow the resource /// to load normally return NULL. To specify a handler for the resource return /// a CefResourceHandler object. The |request| object should not be modified in /// this callback. /// </summary> protected virtual CefResourceHandler GetResourceHandler(CefBrowser browser, CefFrame frame, CefRequest request) { return null; } private void on_resource_redirect(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, cef_string_t* old_url, cef_string_t* new_url) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_frame = CefFrame.FromNative(frame); var m_oldUrl = cef_string_t.ToString(old_url); var m_newUrl = cef_string_t.ToString(new_url); var o_newUrl = m_newUrl; OnResourceRedirect(m_browser, m_frame, m_oldUrl, ref m_newUrl); if ((object)m_newUrl != (object)o_newUrl) { cef_string_t.Copy(m_newUrl, new_url); } } /// <summary> /// Called on the IO thread when a resource load is redirected. The |old_url| /// parameter will contain the old URL. The |new_url| parameter will contain /// the new URL and can be changed if desired. /// </summary> protected virtual void OnResourceRedirect(CefBrowser browser, CefFrame frame, string oldUrl, ref string newUrl) { } private int get_auth_credentials(cef_request_handler_t* self, cef_browser_t* browser, cef_frame_t* frame, int isProxy, cef_string_t* host, int port, cef_string_t* realm, cef_string_t* scheme, cef_auth_callback_t* callback) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_frame = CefFrame.FromNative(frame); var m_host = cef_string_t.ToString(host); var m_realm = cef_string_t.ToString(realm); var m_scheme = cef_string_t.ToString(scheme); var m_callback = CefAuthCallback.FromNative(callback); var result = GetAuthCredentials(m_browser, m_frame, isProxy != 0, m_host, port, m_realm, m_scheme, m_callback); return result ? 1 : 0; } /// <summary> /// Called on the IO thread when the browser needs credentials from the user. /// |isProxy| indicates whether the host is a proxy server. |host| contains the /// hostname and |port| contains the port number. Return true to continue the /// request and call CefAuthCallback::Continue() when the authentication /// information is available. Return false to cancel the request. /// </summary> protected virtual bool GetAuthCredentials(CefBrowser browser, CefFrame frame, bool isProxy, string host, int port, string realm, string scheme, CefAuthCallback callback) { return false; } private int on_quota_request(cef_request_handler_t* self, cef_browser_t* browser, cef_string_t* origin_url, long new_size, cef_quota_callback_t* callback) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_origin_url = cef_string_t.ToString(origin_url); var m_callback = CefQuotaCallback.FromNative(callback); var result = OnQuotaRequest(m_browser, m_origin_url, new_size, m_callback); return result ? 1 : 0; } /// <summary> /// Called on the IO thread when JavaScript requests a specific storage quota /// size via the webkitStorageInfo.requestQuota function. |origin_url| is the /// origin of the page making the request. |new_size| is the requested quota /// size in bytes. Return true and call CefQuotaCallback::Continue() either in /// this method or at a later time to grant or deny the request. Return false /// to cancel the request. /// </summary> protected virtual bool OnQuotaRequest(CefBrowser browser, string originUrl, long newSize, CefQuotaCallback callback) { callback.Continue(true); return true; } private void on_protocol_execution(cef_request_handler_t* self, cef_browser_t* browser, cef_string_t* url, int* allow_os_execution) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_url = cef_string_t.ToString(url); bool m_allow_os_execution; OnProtocolExecution(m_browser, m_url, out m_allow_os_execution); *allow_os_execution = m_allow_os_execution ? 1 : 0; } /// <summary> /// Called on the UI thread to handle requests for URLs with an unknown /// protocol component. Set |allow_os_execution| to true to attempt execution /// via the registered OS protocol handler, if any. /// SECURITY WARNING: YOU SHOULD USE THIS METHOD TO ENFORCE RESTRICTIONS BASED /// ON SCHEME, HOST OR OTHER URL ANALYSIS BEFORE ALLOWING OS EXECUTION. /// </summary> protected virtual void OnProtocolExecution(CefBrowser browser, string url, out bool allowOSExecution) { allowOSExecution = true; } private int on_certificate_error(cef_request_handler_t* self, CefErrorCode cert_error, cef_string_t* request_url, cef_allow_certificate_error_callback_t* callback) { CheckSelf(self); var m_request_url = cef_string_t.ToString(request_url); var m_callback = CefAllowCertificateErrorCallback.FromNativeOrNull(callback); var result = OnCertificateError(cert_error, m_request_url, m_callback); return result ? 1 : 0; } /// <summary> /// Called on the UI thread to handle requests for URLs with an invalid /// SSL certificate. Return true and call CefAllowCertificateErrorCallback:: /// Continue() either in this method or at a later time to continue or cancel /// the request. Return false to cancel the request immediately. If |callback| /// is empty the error cannot be recovered from and the request will be /// canceled automatically. If CefSettings.ignore_certificate_errors is set /// all invalid certificates will be accepted without calling this method. /// </summary> protected virtual bool OnCertificateError(CefErrorCode certError, string requestUrl, CefAllowCertificateErrorCallback callback) { return false; } private int on_before_plugin_load(cef_request_handler_t* self, cef_browser_t* browser, cef_string_t* url, cef_string_t* policy_url, cef_web_plugin_info_t* info) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_url = cef_string_t.ToString(url); var m_policy_url = cef_string_t.ToString(policy_url); var m_info = CefWebPluginInfo.FromNative(info); var result = OnBeforePluginLoad(m_browser, m_url, m_policy_url, m_info); return result ? 1 : 0; } /// <summary> /// Called on the browser process IO thread before a plugin is loaded. Return /// true to block loading of the plugin. /// </summary> protected virtual bool OnBeforePluginLoad(CefBrowser browser, string url, string policyUrl, CefWebPluginInfo info) { return false; } private void on_plugin_crashed(cef_request_handler_t* self, cef_browser_t* browser, cef_string_t* plugin_path) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); var m_plugin_path = cef_string_t.ToString(plugin_path); OnPluginCrashed(m_browser, m_plugin_path); } /// <summary> /// Called on the browser process UI thread when a plugin has crashed. /// |plugin_path| is the path of the plugin that crashed. /// </summary> protected virtual void OnPluginCrashed(CefBrowser browser, string pluginPath) { } private void on_render_process_terminated(cef_request_handler_t* self, cef_browser_t* browser, CefTerminationStatus status) { CheckSelf(self); var m_browser = CefBrowser.FromNative(browser); OnRenderProcessTerminated(m_browser, status); } /// <summary> /// Called on the browser process UI thread when the render process /// terminates unexpectedly. |status| indicates how the process /// terminated. /// </summary> protected virtual void OnRenderProcessTerminated(CefBrowser browser, CefTerminationStatus status) { } } }
using System; using System.Collections; using System.Reflection; using System.Xml; using System.Xml.Xsl; namespace Stetic { public static class Registry { static ArrayList libraries = new ArrayList (); static ArrayList classes = new ArrayList (); static XslTransform gladeImport, gladeExport; static WidgetLibrary coreLib; public static event EventHandler RegistryChanging; public static event EventHandler RegistryChanged; static int changing; static bool changed; public static void Initialize (WidgetLibrary coreLibrary) { coreLib = coreLibrary; RegisterWidgetLibrary (coreLib); } public static WidgetLibrary CoreWidgetLibrary { get { return coreLib; } } public static void BeginChangeSet () { if (changing == 0) changed = false; changing++; } public static void EndChangeSet () { if (--changing == 0) { if (changed) NotifyChanged (); changed = false; } } public static void RegisterWidgetLibrary (WidgetLibrary library) { NotifyChanging (); try { libraries.Add (library); library.Load (); classes.AddRange (library.AllClasses); UpdateGladeTransform (); } catch (Exception ex) { Console.WriteLine (ex); throw; } finally { NotifyChanged (); } } public static void UnregisterWidgetLibrary (WidgetLibrary library) { if (library == coreLib) return; NotifyChanging (); libraries.Remove (library); InternalUpdate (); NotifyChanged (); } // Returns true if all libraries that need reloading // could be reloaded public static bool ReloadWidgetLibraries () { bool needsReload = false; // If there is a lib which can't be reloaded, // there is no need to start the reloading process foreach (WidgetLibrary lib in libraries) { if (lib != coreLib && lib.NeedsReload) { if (!lib.CanReload) return false; needsReload = true; } } if (!needsReload) return true; try { NotifyChanging (); foreach (WidgetLibrary lib in libraries) if (lib != coreLib && lib.NeedsReload) lib.Reload (); InternalUpdate (); } finally { NotifyChanged (); } return true; } public static bool IsRegistered (WidgetLibrary library) { return libraries.Contains (library); } public static WidgetLibrary GetWidgetLibrary (string name) { foreach (WidgetLibrary lib in libraries) if (lib.Name == name) return lib; return null; } public static bool IsRegistered (string name) { foreach (WidgetLibrary lib in libraries) if (lib.Name == name) return true; return false; } public static WidgetLibrary[] RegisteredWidgetLibraries { get { return (WidgetLibrary[]) libraries.ToArray (typeof(WidgetLibrary)); } } static void NotifyChanging () { if (changing > 0) { if (changed) return; else changed = true; } if (RegistryChanging != null) RegistryChanging (null, EventArgs.Empty); } static void NotifyChanged () { if (changing == 0 && RegistryChanged != null) RegistryChanged (null, EventArgs.Empty); } static void InternalUpdate () { classes.Clear (); foreach (WidgetLibrary lib in libraries) classes.AddRange (lib.AllClasses); UpdateGladeTransform (); } static void UpdateGladeTransform () { XmlDocument doc = CreateGladeTransformBase (); XmlNamespaceManager nsm = new XmlNamespaceManager (doc.NameTable); nsm.AddNamespace ("xsl", "http://www.w3.org/1999/XSL/Transform"); foreach (WidgetLibrary lib in libraries) { foreach (XmlElement elem in lib.GetGladeImportTransformElements ()) doc.FirstChild.PrependChild (doc.ImportNode (elem, true)); } gladeImport = new XslTransform (); gladeImport.Load (doc, null, null); doc = CreateGladeTransformBase (); foreach (WidgetLibrary lib in libraries) { foreach (XmlElement elem in lib.GetGladeExportTransformElements ()) doc.FirstChild.PrependChild (doc.ImportNode (elem, true)); } gladeExport = new XslTransform (); gladeExport.Load (doc, null, null); } static XmlDocument CreateGladeTransformBase () { XmlDocument doc = new XmlDocument (); doc.LoadXml ( "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" + " <xsl:template match='@*|node()'>" + " <xsl:copy>" + " <xsl:apply-templates select='@*|node()' />" + " </xsl:copy>" + " </xsl:template>" + "</xsl:stylesheet>" ); return doc; } public static IEnumerable AllClasses { get { return classes; } } public static XslTransform GladeImportXsl { get { return gladeImport; } } public static XslTransform GladeExportXsl { get { return gladeExport; } } public static EnumDescriptor LookupEnum (string typeName) { foreach (WidgetLibrary lib in libraries) { EnumDescriptor desc = lib.LookupEnum (typeName); if (desc != null) return desc; } return null; } public static ClassDescriptor LookupClassByCName (string cname) { foreach (WidgetLibrary lib in libraries) { ClassDescriptor desc = lib.LookupClassByCName (cname); if (desc != null) return desc; } return null; } public static ClassDescriptor LookupClassByName (string cname) { foreach (WidgetLibrary lib in libraries) { ClassDescriptor desc = lib.LookupClassByName (cname); if (desc != null) return desc; } return null; } static ClassDescriptor FindGroupClass (string name, out string groupname) { int sep = name.LastIndexOf ('.'); string classname = name.Substring (0, sep); groupname = name.Substring (sep + 1); ClassDescriptor klass = LookupClassByName (classname); if (klass == null) { klass = LookupClassByName (name); if (klass == null) throw new ArgumentException ("No class for itemgroup " + name); classname = name; groupname = ""; } return klass; } public static ItemGroup LookupItemGroup (string name) { string groupname; ClassDescriptor klass = FindGroupClass (name, out groupname); foreach (ItemGroup grp in klass.ItemGroups) if (grp.Name == groupname && grp.DeclaringType == klass) return grp; throw new ArgumentException ("No itemgroup '" + groupname + "' in class " + klass.WrappedTypeName); } public static ItemGroup LookupSignalGroup (string name) { string groupname; ClassDescriptor klass = FindGroupClass (name, out groupname); foreach (ItemGroup grp in klass.SignalGroups) if (grp.Name == groupname && grp.DeclaringType == klass) return grp; throw new ArgumentException ("No itemgroup '" + groupname + "' in class " + klass.WrappedTypeName); } public static ItemDescriptor LookupItem (string name) { int sep = name.LastIndexOf ('.'); string classname = name.Substring (0, sep); string propname = name.Substring (sep + 1); ClassDescriptor klass = LookupClassByName (classname); if (klass == null) throw new ArgumentException ("No class " + classname + " for property " + propname); ItemDescriptor idesc = klass[propname]; if (idesc == null) throw new ArgumentException ("Property '" + propname + "' not found in class '" + classname + "'"); return idesc; } public static ItemGroup LookupContextMenu (string classname) { ClassDescriptor klass = LookupClassByName (classname); if (klass == null) throw new ArgumentException ("No class for contextmenu " + classname); return klass.ContextMenu; } public static object NewInstance (string typeName, IProject proj) { return LookupClassByName (typeName).NewInstance (proj); } public static Type GetType (string typeName, bool throwOnError) { Type t = Type.GetType (typeName, false); if (t != null) return t; foreach (WidgetLibrary lib in libraries) { t = lib.GetType (typeName); if (t != null) return t; } if (throwOnError) throw new TypeLoadException ("Could not load type '" + typeName + "'"); return null; } } }
// Copyright 2017 Google Inc. 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. #if UNITY_ANDROID && !UNITY_EDITOR #define RUNNING_ON_ANDROID_DEVICE #endif // UNITY_ANDROID && !UNITY_EDITOR using UnityEngine; using UnityEngine.UI; using System; public class DemoInputManager : MonoBehaviour { private const string MESSAGE_CANVAS_NAME = "MessageCanvas"; private const string MESSAGE_TEXT_NAME = "MessageText"; private const string LASER_GAMEOBJECT_NAME = "Laser"; private const string CONTROLLER_CONNECTING_MESSAGE = "Controller connecting..."; private const string CONTROLLER_DISCONNECTED_MESSAGE = "Controller disconnected"; private const string CONTROLLER_SCANNING_MESSAGE = "Controller scanning..."; private const string VR_SUPPORT_NOT_CHECKED = "Please make sure 'Player Settings > Virtual Reality Supported' is checked\n"; private const string EMPTY_VR_SDK_WARNING_MESSAGE = "Please add Daydream or Cardboard under 'Player Settings > Virtual Reality SDKs'\n"; // Java class, method, and field constants. private const int ANDROID_MIN_DAYDREAM_API = 24; private const string FIELD_SDK_INT = "SDK_INT"; private const string PACKAGE_BUILD_VERSION = "android.os.Build$VERSION"; private const string PACKAGE_DAYDREAM_API_CLASS = "com.google.vr.ndk.base.DaydreamApi"; private const string METHOD_IS_DAYDREAM_READY = "isDaydreamReadyPlatform"; private bool isDaydream = false; public static string CARDBOARD_DEVICE_NAME = "cardboard"; public static string DAYDREAM_DEVICE_NAME = "daydream"; [Tooltip("Reference to GvrControllerMain")] public GameObject controllerMain; public static string CONTROLLER_MAIN_PROP_NAME = "controllerMain"; [Tooltip("Reference to GvrControllerPointer")] public GameObject controllerPointer; public static string CONTROLLER_POINTER_PROP_NAME = "controllerPointer"; [Tooltip("Reference to GvrReticlePointer")] public GameObject reticlePointer; public static string RETICLE_POINTER_PROP_NAME = "reticlePointer"; public GameObject messageCanvas; public Text messageText; #if !RUNNING_ON_ANDROID_DEVICE public enum EmulatedPlatformType { Daydream, Cardboard } [Tooltip("Emulated GVR Platform")] public EmulatedPlatformType gvrEmulatedPlatformType = EmulatedPlatformType.Daydream; public static string EMULATED_PLATFORM_PROP_NAME = "gvrEmulatedPlatformType"; #else // Running on an Android device. private GvrSettings.ViewerPlatformType viewerPlatform; #endif // !RUNNING_ON_ANDROID_DEVICE void Start() { if (messageCanvas == null) { messageCanvas = transform.Find(MESSAGE_CANVAS_NAME).gameObject; if (messageCanvas != null) { messageText = messageCanvas.transform.Find(MESSAGE_TEXT_NAME).GetComponent<Text>(); } } // Message canvas will be enabled later when there's a message to display. messageCanvas.SetActive(false); #if !RUNNING_ON_ANDROID_DEVICE if (playerSettingsHasDaydream() || playerSettingsHasCardboard()) { // The list is populated with valid VR SDK(s), pick the first one. gvrEmulatedPlatformType = (UnityEngine.XR.XRSettings.supportedDevices[0] == DAYDREAM_DEVICE_NAME) ? EmulatedPlatformType.Daydream : EmulatedPlatformType.Cardboard; } isDaydream = (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream); #else // Running on an Android device. viewerPlatform = GvrSettings.ViewerPlatform; // First loaded device in Player Settings. string vrDeviceName = UnityEngine.XR.XRSettings.loadedDeviceName; if (vrDeviceName != CARDBOARD_DEVICE_NAME && vrDeviceName != DAYDREAM_DEVICE_NAME) { Debug.LogErrorFormat("Loaded device was '{0}', must be one of '{1}' or '{2}'", vrDeviceName, DAYDREAM_DEVICE_NAME, CARDBOARD_DEVICE_NAME); return; } // On a non-Daydream ready phone, fall back to Cardboard if it's present in the list of // enabled VR SDKs. // On a Daydream-ready phone, go into Cardboard mode if it's the currently-paired viewer. if ((!IsDeviceDaydreamReady() && playerSettingsHasCardboard()) || (IsDeviceDaydreamReady() && playerSettingsHasCardboard() && GvrSettings.ViewerPlatform == GvrSettings.ViewerPlatformType.Cardboard)) { vrDeviceName = CARDBOARD_DEVICE_NAME; } isDaydream = (vrDeviceName == DAYDREAM_DEVICE_NAME); #endif // !RUNNING_ON_ANDROID_DEVICE SetVRInputMechanism(); } // Runtime switching enabled only in-editor. void Update() { UpdateStatusMessage(); #if !RUNNING_ON_ANDROID_DEVICE UpdateEmulatedPlatformIfPlayerSettingsChanged(); if ((isDaydream && gvrEmulatedPlatformType == EmulatedPlatformType.Daydream) || (!isDaydream && gvrEmulatedPlatformType == EmulatedPlatformType.Cardboard)) { return; } isDaydream = (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream); SetVRInputMechanism(); #else // Running on an Android device. // Viewer type switched at runtime. if (!IsDeviceDaydreamReady() || viewerPlatform == GvrSettings.ViewerPlatform) { return; } isDaydream = (GvrSettings.ViewerPlatform == GvrSettings.ViewerPlatformType.Daydream); viewerPlatform = GvrSettings.ViewerPlatform; SetVRInputMechanism(); #endif // !RUNNING_ON_ANDROID_DEVICE } public bool IsCurrentlyDaydream() { return isDaydream; } public static bool playerSettingsHasDaydream() { string[] playerSettingsVrSdks = UnityEngine.XR.XRSettings.supportedDevices; return Array.Exists<string>(playerSettingsVrSdks, element => element.Equals(DemoInputManager.DAYDREAM_DEVICE_NAME)); } public static bool playerSettingsHasCardboard() { string[] playerSettingsVrSdks = UnityEngine.XR.XRSettings.supportedDevices; return Array.Exists<string>(playerSettingsVrSdks, element => element.Equals(DemoInputManager.CARDBOARD_DEVICE_NAME)); } #if !RUNNING_ON_ANDROID_DEVICE private void UpdateEmulatedPlatformIfPlayerSettingsChanged() { if (!playerSettingsHasDaydream() && !playerSettingsHasCardboard()) { return; } // Player Settings > VR SDK list may have changed at runtime. The emulated platform // may not have been manually updated if that's the case. if (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream && !playerSettingsHasDaydream()) { gvrEmulatedPlatformType = EmulatedPlatformType.Cardboard; } else if (gvrEmulatedPlatformType == EmulatedPlatformType.Cardboard && !playerSettingsHasCardboard()) { gvrEmulatedPlatformType = EmulatedPlatformType.Daydream; } } #endif // !RUNNING_ON_ANDROID_DEVICE #if RUNNING_ON_ANDROID_DEVICE // Running on an Android device. private static bool IsDeviceDaydreamReady() { // Check API level. using (var version = new AndroidJavaClass(PACKAGE_BUILD_VERSION)) { if (version.GetStatic<int>(FIELD_SDK_INT) < ANDROID_MIN_DAYDREAM_API) { return false; } } // API level > 24, check whether the device is Daydream-ready.. AndroidJavaObject androidActivity = null; try { androidActivity = GvrActivityHelper.GetActivity(); } catch (AndroidJavaException e) { Debug.LogError("Exception while connecting to the Activity: " + e); return false; } AndroidJavaClass daydreamApiClass = new AndroidJavaClass(PACKAGE_DAYDREAM_API_CLASS); if (daydreamApiClass == null || androidActivity == null) { return false; } return daydreamApiClass.CallStatic<bool>(METHOD_IS_DAYDREAM_READY, androidActivity); } #endif // RUNNING_ON_ANDROID_DEVICE private void UpdateStatusMessage() { if (messageText == null || messageCanvas == null) { return; } #if UNITY_EDITOR if (!UnityEditor.PlayerSettings.virtualRealitySupported) { messageText.text = VR_SUPPORT_NOT_CHECKED; messageCanvas.SetActive(true); return; } #endif // UNITY_EDITOR bool isVrSdkListEmpty = !playerSettingsHasCardboard() && !playerSettingsHasDaydream(); if (!isDaydream) { if (messageCanvas.activeSelf) { messageText.text = EMPTY_VR_SDK_WARNING_MESSAGE; messageCanvas.SetActive(isVrSdkListEmpty); } return; } string vrSdkWarningMessage = isVrSdkListEmpty ? EMPTY_VR_SDK_WARNING_MESSAGE : ""; string controllerMessage = ""; GvrPointerGraphicRaycaster graphicRaycaster = messageCanvas.GetComponent<GvrPointerGraphicRaycaster>(); // This is an example of how to process the controller's state to display a status message. switch (GvrControllerInput.State) { case GvrConnectionState.Connected: break; case GvrConnectionState.Disconnected: controllerMessage = CONTROLLER_DISCONNECTED_MESSAGE; messageText.color = Color.white; break; case GvrConnectionState.Scanning: controllerMessage = CONTROLLER_SCANNING_MESSAGE; messageText.color = Color.cyan; break; case GvrConnectionState.Connecting: controllerMessage = CONTROLLER_CONNECTING_MESSAGE; messageText.color = Color.yellow; break; case GvrConnectionState.Error: controllerMessage = "ERROR: " + GvrControllerInput.ErrorDetails; messageText.color = Color.red; break; default: // Shouldn't happen. Debug.LogError("Invalid controller state: " + GvrControllerInput.State); break; } messageText.text = string.Format("{0}\n{1}", vrSdkWarningMessage, controllerMessage); if (graphicRaycaster != null) { graphicRaycaster.enabled = !isVrSdkListEmpty || GvrControllerInput.State != GvrConnectionState.Connected; } messageCanvas.SetActive(isVrSdkListEmpty || (GvrControllerInput.State != GvrConnectionState.Connected)); } private void SetVRInputMechanism() { SetGazeInputActive(!isDaydream); SetControllerInputActive(isDaydream); } private void SetGazeInputActive(bool active) { if (reticlePointer == null) { return; } reticlePointer.SetActive(active); // Update the pointer type only if this is currently activated. if (!active) { return; } GvrReticlePointer pointer = reticlePointer.GetComponent<GvrReticlePointer>(); if (pointer != null) { GvrPointerInputModule.Pointer = pointer; } } private void SetControllerInputActive(bool active) { if (controllerMain != null) { controllerMain.SetActive(active); } if (controllerPointer == null) { return; } controllerPointer.SetActive(active); // Update the pointer type only if this is currently activated. if (!active) { return; } GvrLaserPointer pointer = controllerPointer.GetComponentInChildren<GvrLaserPointer>(true); if (pointer != null) { GvrPointerInputModule.Pointer = pointer; } } // #endif // UNITY_ANDROID }
// 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 System.Xml.Xsl.XsltOld { using System; using System.Diagnostics; using System.Xml; using System.Xml.XPath; using System.Collections; internal class Stylesheet { private ArrayList _imports = new ArrayList(); private Hashtable _modeManagers; private Hashtable _templateNameTable = new Hashtable(); private Hashtable _attributeSetTable; private int _templateCount; //private ArrayList preserveSpace; private Hashtable _queryKeyTable; private ArrayList _whitespaceList; private bool _whitespace; private Hashtable _scriptObjectTypes = new Hashtable(); private TemplateManager _templates; private class WhitespaceElement { private int _key; private double _priority; private bool _preserveSpace; internal double Priority { get { return _priority; } } internal int Key { get { return _key; } } internal bool PreserveSpace { get { return _preserveSpace; } } internal WhitespaceElement(int Key, double priority, bool PreserveSpace) { _key = Key; _priority = priority; _preserveSpace = PreserveSpace; } internal void ReplaceValue(bool PreserveSpace) { _preserveSpace = PreserveSpace; } } internal bool Whitespace { get { return _whitespace; } } internal ArrayList Imports { get { return _imports; } } internal Hashtable AttributeSetTable { get { return _attributeSetTable; } } internal void AddSpace(Compiler compiler, string query, double Priority, bool PreserveSpace) { WhitespaceElement elem; if (_queryKeyTable != null) { if (_queryKeyTable.Contains(query)) { elem = (WhitespaceElement)_queryKeyTable[query]; elem.ReplaceValue(PreserveSpace); return; } } else { _queryKeyTable = new Hashtable(); _whitespaceList = new ArrayList(); } int key = compiler.AddQuery(query); elem = new WhitespaceElement(key, Priority, PreserveSpace); _queryKeyTable[query] = elem; _whitespaceList.Add(elem); } internal void SortWhiteSpace() { if (_queryKeyTable != null) { for (int i = 0; i < _whitespaceList.Count; i++) { for (int j = _whitespaceList.Count - 1; j > i; j--) { WhitespaceElement elem1, elem2; elem1 = (WhitespaceElement)_whitespaceList[j - 1]; elem2 = (WhitespaceElement)_whitespaceList[j]; if (elem2.Priority < elem1.Priority) { _whitespaceList[j - 1] = elem2; _whitespaceList[j] = elem1; } } } _whitespace = true; } if (_imports != null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { Stylesheet stylesheet = (Stylesheet)_imports[importIndex]; if (stylesheet.Whitespace) { stylesheet.SortWhiteSpace(); _whitespace = true; } } } } internal bool PreserveWhiteSpace(Processor proc, XPathNavigator node) { // last one should win. I.E. We starting from the end. I.E. Lowest priority should go first if (_whitespaceList != null) { for (int i = _whitespaceList.Count - 1; 0 <= i; i--) { WhitespaceElement elem = (WhitespaceElement)_whitespaceList[i]; if (proc.Matches(node, elem.Key)) { return elem.PreserveSpace; } } } if (_imports != null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { Stylesheet stylesheet = (Stylesheet)_imports[importIndex]; if (!stylesheet.PreserveWhiteSpace(proc, node)) return false; } } return true; } internal void AddAttributeSet(AttributeSetAction attributeSet) { Debug.Assert(attributeSet.Name != null); if (_attributeSetTable == null) { _attributeSetTable = new Hashtable(); } Debug.Assert(_attributeSetTable != null); if (_attributeSetTable.ContainsKey(attributeSet.Name) == false) { _attributeSetTable[attributeSet.Name] = attributeSet; } else { // merge the attribute-sets ((AttributeSetAction)_attributeSetTable[attributeSet.Name]).Merge(attributeSet); } } internal void AddTemplate(TemplateAction template) { XmlQualifiedName mode = template.Mode; // // Ensure template has a unique name // Debug.Assert(_templateNameTable != null); if (template.Name != null) { if (_templateNameTable.ContainsKey(template.Name) == false) { _templateNameTable[template.Name] = template; } else { throw XsltException.Create(SR.Xslt_DupTemplateName, template.Name.ToString()); } } if (template.MatchKey != Compiler.InvalidQueryKey) { if (_modeManagers == null) { _modeManagers = new Hashtable(); } Debug.Assert(_modeManagers != null); if (mode == null) { mode = XmlQualifiedName.Empty; } TemplateManager manager = (TemplateManager)_modeManagers[mode]; if (manager == null) { manager = new TemplateManager(this, mode); _modeManagers[mode] = manager; if (mode.IsEmpty) { Debug.Assert(_templates == null); _templates = manager; } } Debug.Assert(manager != null); template.TemplateId = ++_templateCount; manager.AddTemplate(template); } } internal void ProcessTemplates() { if (_modeManagers != null) { IDictionaryEnumerator enumerator = _modeManagers.GetEnumerator(); while (enumerator.MoveNext()) { Debug.Assert(enumerator.Value is TemplateManager); TemplateManager manager = (TemplateManager)enumerator.Value; manager.ProcessTemplates(); } } if (_imports != null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { Debug.Assert(_imports[importIndex] is Stylesheet); Stylesheet stylesheet = (Stylesheet)_imports[importIndex]; Debug.Assert(stylesheet != null); // // Process templates in imported stylesheet // stylesheet.ProcessTemplates(); } } } internal void ReplaceNamespaceAlias(Compiler compiler) { if (_modeManagers != null) { IDictionaryEnumerator enumerator = _modeManagers.GetEnumerator(); while (enumerator.MoveNext()) { TemplateManager manager = (TemplateManager)enumerator.Value; if (manager.templates != null) { for (int i = 0; i < manager.templates.Count; i++) { TemplateAction template = (TemplateAction)manager.templates[i]; template.ReplaceNamespaceAlias(compiler); } } } } if (_templateNameTable != null) { IDictionaryEnumerator enumerator = _templateNameTable.GetEnumerator(); while (enumerator.MoveNext()) { TemplateAction template = (TemplateAction)enumerator.Value; template.ReplaceNamespaceAlias(compiler); } } if (_imports != null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { Stylesheet stylesheet = (Stylesheet)_imports[importIndex]; stylesheet.ReplaceNamespaceAlias(compiler); } } } internal TemplateAction FindTemplate(Processor processor, XPathNavigator navigator, XmlQualifiedName mode) { Debug.Assert(processor != null && navigator != null); Debug.Assert(mode != null); TemplateAction action = null; // // Try to find template within this stylesheet first // if (_modeManagers != null) { TemplateManager manager = (TemplateManager)_modeManagers[mode]; if (manager != null) { Debug.Assert(manager.Mode.Equals(mode)); action = manager.FindTemplate(processor, navigator); } } // // If unsuccessful, search in imported documents from backwards // if (action == null) { action = FindTemplateImports(processor, navigator, mode); } return action; } internal TemplateAction FindTemplateImports(Processor processor, XPathNavigator navigator, XmlQualifiedName mode) { TemplateAction action = null; // // Do we have imported stylesheets? // if (_imports != null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { Debug.Assert(_imports[importIndex] is Stylesheet); Stylesheet stylesheet = (Stylesheet)_imports[importIndex]; Debug.Assert(stylesheet != null); // // Search in imported stylesheet // action = stylesheet.FindTemplate(processor, navigator, mode); if (action != null) { return action; } } } return action; } internal TemplateAction FindTemplate(Processor processor, XPathNavigator navigator) { Debug.Assert(processor != null && navigator != null); Debug.Assert(_templates == null && _modeManagers == null || _templates == _modeManagers[XmlQualifiedName.Empty]); TemplateAction action = null; // // Try to find template within this stylesheet first // if (_templates != null) { action = _templates.FindTemplate(processor, navigator); } // // If unsuccessful, search in imported documents from backwards // if (action == null) { action = FindTemplateImports(processor, navigator); } return action; } internal TemplateAction FindTemplate(XmlQualifiedName name) { //Debug.Assert(this.templateNameTable == null); TemplateAction action = null; // // Try to find template within this stylesheet first // if (_templateNameTable != null) { action = (TemplateAction)_templateNameTable[name]; } // // If unsuccessful, search in imported documents from backwards // if (action == null && _imports != null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { Debug.Assert(_imports[importIndex] is Stylesheet); Stylesheet stylesheet = (Stylesheet)_imports[importIndex]; Debug.Assert(stylesheet != null); // // Search in imported stylesheet // action = stylesheet.FindTemplate(name); if (action != null) { return action; } } } return action; } internal TemplateAction FindTemplateImports(Processor processor, XPathNavigator navigator) { TemplateAction action = null; // // Do we have imported stylesheets? // if (_imports != null) { for (int importIndex = _imports.Count - 1; importIndex >= 0; importIndex--) { Debug.Assert(_imports[importIndex] is Stylesheet); Stylesheet stylesheet = (Stylesheet)_imports[importIndex]; Debug.Assert(stylesheet != null); // // Search in imported stylesheet // action = stylesheet.FindTemplate(processor, navigator); if (action != null) { return action; } } } return action; } internal Hashtable ScriptObjectTypes { get { return _scriptObjectTypes; } } } }
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // 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; namespace ICSharpCode.NRefactory.CSharp { /// <summary> /// Base class for expressions. /// </summary> /// <remarks> /// This class is useful even though it doesn't provide any additional functionality: /// It can be used to communicate more information in APIs, e.g. "this subnode will always be an expression" /// </remarks> public abstract class Expression : AstNode { #region Null public new static readonly Expression Null = new NullExpression (); sealed class NullExpression : Expression { public override bool IsNull { get { return true; } } public override void AcceptVisitor (IAstVisitor visitor) { } public override T AcceptVisitor<T> (IAstVisitor<T> visitor) { return default (T); } public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data) { return default (S); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { return other == null || other.IsNull; } } #endregion #region PatternPlaceholder public static implicit operator Expression(PatternMatching.Pattern pattern) { return pattern != null ? new PatternPlaceholder(pattern) : null; } sealed class PatternPlaceholder : Expression, PatternMatching.INode { readonly PatternMatching.Pattern child; public PatternPlaceholder(PatternMatching.Pattern child) { this.child = child; } public override NodeType NodeType { get { return NodeType.Pattern; } } public override void AcceptVisitor (IAstVisitor visitor) { visitor.VisitPatternPlaceholder(this, child); } public override T AcceptVisitor<T> (IAstVisitor<T> visitor) { return visitor.VisitPatternPlaceholder(this, child); } public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data) { return visitor.VisitPatternPlaceholder(this, child, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { return child.DoMatch(other, match); } bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo) { return child.DoMatchCollection(role, pos, match, backtrackingInfo); } } #endregion public override NodeType NodeType { get { return NodeType.Expression; } } public new Expression Clone() { return (Expression)base.Clone(); } // Make debugging easier by giving Expressions a ToString() implementation public override string ToString() { return DebugToString(); } public Expression ReplaceWith(Func<Expression, Expression> replaceFunction) { if (replaceFunction == null) throw new ArgumentNullException("replaceFunction"); return (Expression)base.ReplaceWith(node => replaceFunction((Expression)node)); } #region Builder methods /// <summary> /// Builds an member reference expression using this expression as target. /// </summary> public MemberReferenceExpression Member(string memberName) { return new MemberReferenceExpression { Target = this, MemberName = memberName }; } /// <summary> /// Builds an indexer expression using this expression as target. /// </summary> public IndexerExpression Indexer(IEnumerable<Expression> arguments) { IndexerExpression expr = new IndexerExpression(); expr.Target = this; expr.Arguments.AddRange(arguments); return expr; } /// <summary> /// Builds an indexer expression using this expression as target. /// </summary> public IndexerExpression Indexer(params Expression[] arguments) { IndexerExpression expr = new IndexerExpression(); expr.Target = this; expr.Arguments.AddRange(arguments); return expr; } /// <summary> /// Builds an invocation expression using this expression as target. /// </summary> public InvocationExpression Invoke(string methodName, IEnumerable<Expression> arguments) { return Invoke(methodName, null, arguments); } /// <summary> /// Builds an invocation expression using this expression as target. /// </summary> public InvocationExpression Invoke(string methodName, params Expression[] arguments) { return Invoke(methodName, null, arguments); } /// <summary> /// Builds an invocation expression using this expression as target. /// </summary> public InvocationExpression Invoke(string methodName, IEnumerable<AstType> typeArguments, IEnumerable<Expression> arguments) { InvocationExpression ie = new InvocationExpression(); MemberReferenceExpression mre = new MemberReferenceExpression(); mre.Target = this; mre.MemberName = methodName; mre.TypeArguments.AddRange(typeArguments); ie.Target = mre; ie.Arguments.AddRange(arguments); return ie; } /// <summary> /// Builds an invocation expression using this expression as target. /// </summary> public InvocationExpression Invoke(IEnumerable<Expression> arguments) { InvocationExpression ie = new InvocationExpression(); ie.Target = this; ie.Arguments.AddRange(arguments); return ie; } /// <summary> /// Builds an invocation expression using this expression as target. /// </summary> public InvocationExpression Invoke(params Expression[] arguments) { InvocationExpression ie = new InvocationExpression(); ie.Target = this; ie.Arguments.AddRange(arguments); return ie; } public CastExpression CastTo(AstType type) { return new CastExpression { Type = type, Expression = this }; } public AsExpression CastAs(AstType type) { return new AsExpression { Type = type, Expression = this }; } public IsExpression IsType(AstType type) { return new IsExpression { Type = type, Expression = this }; } #endregion } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. using System; using System.Collections.Generic; using System.IO; using System.Diagnostics; using System.Xml; using System.Text.RegularExpressions; using System.Linq; using System.Reflection; namespace UnrealBuildTool { public class Distcc { public static bool ExecuteActions(List<Action> Actions) { bool bDistccResult = true; if (Actions.Count > 0) { // Time to sleep after each iteration of the loop in order to not busy wait. const float LoopSleepTime = 0.1f; int MaxActionsToExecuteInParallel = 0; string UserDir = Environment.GetEnvironmentVariable("HOME"); string HostsInfo = UserDir + "/.dmucs/hosts-info"; System.IO.StreamReader File = new System.IO.StreamReader(HostsInfo); string Line = null; while((Line = File.ReadLine()) != null) { var HostInfo = Line.Split(' '); if (HostInfo.Count () == 3) { int NumCPUs = 0; if (System.Int32.TryParse (HostInfo [1], out NumCPUs)) { MaxActionsToExecuteInParallel += NumCPUs; } } } File.Close(); if (BuildConfiguration.bAllowDistccLocalFallback == false) { Environment.SetEnvironmentVariable("DISTCC_FALLBACK", "0"); } string DistccExecutable = BuildConfiguration.DistccExecutablesPath + "/distcc"; string GetHostExecutable = BuildConfiguration.DistccExecutablesPath + "/gethost"; Log.TraceInformation("Performing {0} actions ({1} in parallel)", Actions.Count, MaxActionsToExecuteInParallel, DistccExecutable, GetHostExecutable); Dictionary<Action, ActionThread> ActionThreadDictionary = new Dictionary<Action, ActionThread>(); int JobNumber = 1; using(ProgressWriter ProgressWriter = new ProgressWriter("Compiling source code...", false)) { int ProgressValue = 0; while(true) { // Count the number of pending and still executing actions. int NumUnexecutedActions = 0; int NumExecutingActions = 0; foreach (Action Action in Actions) { ActionThread ActionThread = null; bool bFoundActionProcess = ActionThreadDictionary.TryGetValue(Action, out ActionThread); if (bFoundActionProcess == false) { NumUnexecutedActions++; } else if (ActionThread != null) { if (ActionThread.bComplete == false) { NumUnexecutedActions++; NumExecutingActions++; } } } // Update the current progress int NewProgressValue = Actions.Count + 1 - NumUnexecutedActions; if (ProgressValue != NewProgressValue) { ProgressWriter.Write(ProgressValue, Actions.Count + 1); ProgressValue = NewProgressValue; } // If there aren't any pending actions left, we're done executing. if (NumUnexecutedActions == 0) { break; } // If there are fewer actions executing than the maximum, look for pending actions that don't have any outdated // prerequisites. foreach (Action Action in Actions) { ActionThread ActionProcess = null; bool bFoundActionProcess = ActionThreadDictionary.TryGetValue(Action, out ActionProcess); if (bFoundActionProcess == false) { if (NumExecutingActions < Math.Max(1,MaxActionsToExecuteInParallel)) { // Determine whether there are any prerequisites of the action that are outdated. bool bHasOutdatedPrerequisites = false; bool bHasFailedPrerequisites = false; foreach (FileItem PrerequisiteItem in Action.PrerequisiteItems) { if (PrerequisiteItem.ProducingAction != null && Actions.Contains(PrerequisiteItem.ProducingAction)) { ActionThread PrerequisiteProcess = null; bool bFoundPrerequisiteProcess = ActionThreadDictionary.TryGetValue( PrerequisiteItem.ProducingAction, out PrerequisiteProcess ); if (bFoundPrerequisiteProcess == true) { if (PrerequisiteProcess == null) { bHasFailedPrerequisites = true; } else if (PrerequisiteProcess.bComplete == false) { bHasOutdatedPrerequisites = true; } else if (PrerequisiteProcess.ExitCode != 0) { bHasFailedPrerequisites = true; } } else { bHasOutdatedPrerequisites = true; } } } // If there are any failed prerequisites of this action, don't execute it. if (bHasFailedPrerequisites) { // Add a null entry in the dictionary for this action. ActionThreadDictionary.Add( Action, null ); } // If there aren't any outdated prerequisites of this action, execute it. else if (!bHasOutdatedPrerequisites) { if ((Action.ActionType == ActionType.Compile || Action.ActionType == ActionType.Link) && DistccExecutable != null && GetHostExecutable != null) { string NewCommandArguments = "--wait -1 \"" + DistccExecutable + "\" " + Action.CommandPath + " " + Action.CommandArguments; Action.CommandPath = GetHostExecutable; Action.CommandArguments = NewCommandArguments; } ActionThread ActionThread = new ActionThread(Action, JobNumber, Actions.Count); JobNumber++; ActionThread.Run(); ActionThreadDictionary.Add(Action, ActionThread); NumExecutingActions++; } } } } System.Threading.Thread.Sleep(TimeSpan.FromSeconds(LoopSleepTime)); } } Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, TraceEventType.Information, "-------- Begin Detailed Action Stats ----------------------------------------------------------"); Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, TraceEventType.Information, "^Action Type^Duration (seconds)^Tool^Task^Using PCH"); double TotalThreadSeconds = 0; // Check whether any of the tasks failed and log action stats if wanted. foreach (KeyValuePair<Action, ActionThread> ActionProcess in ActionThreadDictionary) { Action Action = ActionProcess.Key; ActionThread ActionThread = ActionProcess.Value; // Check for pending actions, preemptive failure if (ActionThread == null) { bDistccResult = false; continue; } // Check for executed action but general failure if (ActionThread.ExitCode != 0) { bDistccResult = false; } // Log CPU time, tool and task. double ThreadSeconds = Action.Duration.TotalSeconds; Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats, TraceEventType.Information, "^{0}^{1:0.00}^{2}^{3}^{4}", Action.ActionType.ToString(), ThreadSeconds, Path.GetFileName(Action.CommandPath), Action.StatusDescription, Action.bIsUsingPCH); // Update statistics switch (Action.ActionType) { case ActionType.BuildProject: UnrealBuildTool.TotalBuildProjectTime += ThreadSeconds; break; case ActionType.Compile: UnrealBuildTool.TotalCompileTime += ThreadSeconds; break; case ActionType.CreateAppBundle: UnrealBuildTool.TotalCreateAppBundleTime += ThreadSeconds; break; case ActionType.GenerateDebugInfo: UnrealBuildTool.TotalGenerateDebugInfoTime += ThreadSeconds; break; case ActionType.Link: UnrealBuildTool.TotalLinkTime += ThreadSeconds; break; default: UnrealBuildTool.TotalOtherActionsTime += ThreadSeconds; break; } // Keep track of total thread seconds spent on tasks. TotalThreadSeconds += ThreadSeconds; } Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats || BuildConfiguration.bPrintDebugInfo, TraceEventType.Information, "-------- End Detailed Actions Stats -----------------------------------------------------------"); // Log total CPU seconds and numbers of processors involved in tasks. Log.WriteLineIf(BuildConfiguration.bLogDetailedActionStats || BuildConfiguration.bPrintDebugInfo, TraceEventType.Information, "Cumulative thread seconds ({0} processors): {1:0.00}", System.Environment.ProcessorCount, TotalThreadSeconds); } return bDistccResult; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using Microsoft.Extensions.Logging; using Orleans.CodeGeneration; namespace Orleans.Runtime { /// <summary> /// A collection of utility functions for dealing with Type information. /// </summary> internal static class TypeUtils { /// <summary> /// The assembly name of the core Orleans assembly. /// </summary> private static readonly AssemblyName OrleansCoreAssembly = typeof(RuntimeVersion).GetTypeInfo().Assembly.GetName(); /// <summary> /// The assembly name of the core Orleans abstractions assembly. /// </summary> private static readonly AssemblyName OrleansAbstractionsAssembly = typeof(IGrain).GetTypeInfo().Assembly.GetName(); private static readonly ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string> ParseableNameCache = new ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string>(); private static readonly ConcurrentDictionary<Tuple<Type, bool>, List<Type>> ReferencedTypes = new ConcurrentDictionary<Tuple<Type, bool>, List<Type>>(); private static readonly CachedReflectionOnlyTypeResolver ReflectionOnlyTypeResolver = new CachedReflectionOnlyTypeResolver(); public static string GetSimpleTypeName(Type t, Predicate<Type> fullName = null) { return GetSimpleTypeName(t.GetTypeInfo(), fullName); } public static string GetSimpleTypeName(TypeInfo typeInfo, Predicate<Type> fullName = null) { if (typeInfo.IsNestedPublic || typeInfo.IsNestedPrivate) { if (typeInfo.DeclaringType.GetTypeInfo().IsGenericType) { return GetTemplatedName( GetUntemplatedTypeName(typeInfo.DeclaringType.Name), typeInfo.DeclaringType, typeInfo.GetGenericArguments(), _ => true) + "." + GetUntemplatedTypeName(typeInfo.Name); } return GetTemplatedName(typeInfo.DeclaringType) + "." + GetUntemplatedTypeName(typeInfo.Name); } var type = typeInfo.AsType(); if (typeInfo.IsGenericType) return GetSimpleTypeName(fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name); return fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name; } public static string GetUntemplatedTypeName(string typeName) { int i = typeName.IndexOf('`'); if (i > 0) { typeName = typeName.Substring(0, i); } i = typeName.IndexOf('<'); if (i > 0) { typeName = typeName.Substring(0, i); } return typeName; } public static string GetSimpleTypeName(string typeName) { int i = typeName.IndexOf('`'); if (i > 0) { typeName = typeName.Substring(0, i); } i = typeName.IndexOf('['); if (i > 0) { typeName = typeName.Substring(0, i); } i = typeName.IndexOf('<'); if (i > 0) { typeName = typeName.Substring(0, i); } return typeName; } public static bool IsConcreteTemplateType(Type t) { if (t.GetTypeInfo().IsGenericType) return true; return t.IsArray && IsConcreteTemplateType(t.GetElementType()); } public static string GetTemplatedName(Type t, Predicate<Type> fullName = null) { if (fullName == null) fullName = _ => true; // default to full type names var typeInfo = t.GetTypeInfo(); if (typeInfo.IsGenericType) return GetTemplatedName(GetSimpleTypeName(typeInfo, fullName), t, typeInfo.GetGenericArguments(), fullName); if (t.IsArray) { return GetTemplatedName(t.GetElementType(), fullName) + "[" + new string(',', t.GetArrayRank() - 1) + "]"; } return GetSimpleTypeName(typeInfo, fullName); } public static bool IsConstructedGenericType(this TypeInfo typeInfo) { // is there an API that returns this info without converting back to type already? return typeInfo.AsType().IsConstructedGenericType; } internal static IEnumerable<TypeInfo> GetTypeInfos(this Type[] types) { return types.Select(t => t.GetTypeInfo()); } public static string GetTemplatedName(string baseName, Type t, Type[] genericArguments, Predicate<Type> fullName) { var typeInfo = t.GetTypeInfo(); if (!typeInfo.IsGenericType || (t.DeclaringType != null && t.DeclaringType.GetTypeInfo().IsGenericType)) return baseName; string s = baseName; s += "<"; s += GetGenericTypeArgs(genericArguments, fullName); s += ">"; return s; } public static string GetGenericTypeArgs(IEnumerable<Type> args, Predicate<Type> fullName) { string s = string.Empty; bool first = true; foreach (var genericParameter in args) { if (!first) { s += ","; } if (!genericParameter.GetTypeInfo().IsGenericType) { s += GetSimpleTypeName(genericParameter, fullName); } else { s += GetTemplatedName(genericParameter, fullName); } first = false; } return s; } public static string GetParameterizedTemplateName(TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null) { if (fullName == null) fullName = tt => true; return GetParameterizedTemplateName(typeInfo, fullName, applyRecursively); } public static string GetParameterizedTemplateName(TypeInfo typeInfo, Predicate<Type> fullName, bool applyRecursively = false) { if (typeInfo.IsGenericType) { return GetParameterizedTemplateName(GetSimpleTypeName(typeInfo, fullName), typeInfo, applyRecursively, fullName); } var t = typeInfo.AsType(); if (fullName != null && fullName(t) == true) { return t.FullName; } return t.Name; } public static string GetParameterizedTemplateName(string baseName, TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null) { if (fullName == null) fullName = tt => false; if (!typeInfo.IsGenericType) return baseName; string s = baseName; s += "<"; bool first = true; foreach (var genericParameter in typeInfo.GetGenericArguments()) { if (!first) { s += ","; } var genericParameterTypeInfo = genericParameter.GetTypeInfo(); if (applyRecursively && genericParameterTypeInfo.IsGenericType) { s += GetParameterizedTemplateName(genericParameterTypeInfo, applyRecursively); } else { s += genericParameter.FullName == null || !fullName(genericParameter) ? genericParameter.Name : genericParameter.FullName; } first = false; } s += ">"; return s; } public static string GetRawClassName(string baseName, Type t) { var typeInfo = t.GetTypeInfo(); return typeInfo.IsGenericType ? baseName + '`' + typeInfo.GetGenericArguments().Length : baseName; } public static string GetRawClassName(string typeName) { int i = typeName.IndexOf('['); return i <= 0 ? typeName : typeName.Substring(0, i); } public static Type[] GenericTypeArgsFromClassName(string className) { return GenericTypeArgsFromArgsString(GenericTypeArgsString(className)); } public static Type[] GenericTypeArgsFromArgsString(string genericArgs) { if (string.IsNullOrEmpty(genericArgs)) return Type.EmptyTypes; var genericTypeDef = genericArgs.Replace("[]", "##"); // protect array arguments return InnerGenericTypeArgs(genericTypeDef); } private static Type[] InnerGenericTypeArgs(string className) { var typeArgs = new List<Type>(); var innerTypes = GetInnerTypes(className); foreach (var innerType in innerTypes) { if (innerType.StartsWith("[[")) // Resolve and load generic types recursively { InnerGenericTypeArgs(GenericTypeArgsString(innerType)); string genericTypeArg = className.Trim('[', ']'); typeArgs.Add(Type.GetType(genericTypeArg.Replace("##", "[]"))); } else { string nonGenericTypeArg = innerType.Trim('[', ']'); typeArgs.Add(Type.GetType(nonGenericTypeArg.Replace("##", "[]"))); } } return typeArgs.ToArray(); } private static string[] GetInnerTypes(string input) { // Iterate over strings of length 2 positionwise. var charsWithPositions = input.Zip(Enumerable.Range(0, input.Length), (c, i) => new { Ch = c, Pos = i }); var candidatesWithPositions = charsWithPositions.Zip(charsWithPositions.Skip(1), (c1, c2) => new { Str = c1.Ch.ToString() + c2.Ch, Pos = c1.Pos }); var results = new List<string>(); int startPos = -1; int endPos = -1; int endTokensNeeded = 0; string curStartToken = ""; string curEndToken = ""; var tokenPairs = new[] { new { Start = "[[", End = "]]" }, new { Start = "[", End = "]" } }; // Longer tokens need to come before shorter ones foreach (var candidate in candidatesWithPositions) { if (startPos == -1) { foreach (var token in tokenPairs) { if (candidate.Str.StartsWith(token.Start)) { curStartToken = token.Start; curEndToken = token.End; startPos = candidate.Pos; break; } } } if (curStartToken != "" && candidate.Str.StartsWith(curStartToken)) endTokensNeeded++; if (curEndToken != "" && candidate.Str.EndsWith(curEndToken)) { endPos = candidate.Pos; endTokensNeeded--; } if (endTokensNeeded == 0 && startPos != -1) { results.Add(input.Substring(startPos, endPos - startPos + 2)); startPos = -1; curStartToken = ""; } } return results.ToArray(); } public static string GenericTypeArgsString(string className) { int startIndex = className.IndexOf('['); int endIndex = className.LastIndexOf(']'); return className.Substring(startIndex + 1, endIndex - startIndex - 1); } public static bool IsGenericClass(string name) { return name.Contains("`") || name.Contains("["); } public static string GetFullName(TypeInfo typeInfo) { if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo)); return GetFullName(typeInfo.AsType()); } public static string GetFullName(Type t) { if (t == null) throw new ArgumentNullException(nameof(t)); if (t.IsNested && !t.IsGenericParameter) { return t.Namespace + "." + t.DeclaringType.Name + "." + t.Name; } if (t.IsArray) { return GetFullName(t.GetElementType()) + "[" + new string(',', t.GetArrayRank() - 1) + "]"; } return t.FullName ?? (t.IsGenericParameter ? t.Name : t.Namespace + "." + t.Name); } /// <summary> /// Returns all fields of the specified type. /// </summary> /// <param name="type">The type.</param> /// <returns>All fields of the specified type.</returns> public static IEnumerable<FieldInfo> GetAllFields(this Type type) { const BindingFlags AllFields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; var current = type; while ((current != typeof(object)) && (current != null)) { var fields = current.GetFields(AllFields); foreach (var field in fields) { yield return field; } current = current.GetTypeInfo().BaseType; } } /// <summary> /// Returns <see langword="true"/> if <paramref name="field"/> is marked as /// <see cref="FieldAttributes.NotSerialized"/>, <see langword="false"/> otherwise. /// </summary> /// <param name="field">The field.</param> /// <returns> /// <see langword="true"/> if <paramref name="field"/> is marked as /// <see cref="FieldAttributes.NotSerialized"/>, <see langword="false"/> otherwise. /// </returns> public static bool IsNotSerialized(this FieldInfo field) => (field.Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized; /// <summary> /// decide whether the class is derived from Grain /// </summary> public static bool IsGrainClass(Type type) { var grainType = typeof(Grain); var grainChevronType = typeof(Grain<>); if (type.Assembly.ReflectionOnly) { grainType = ToReflectionOnlyType(grainType); grainChevronType = ToReflectionOnlyType(grainChevronType); } if (grainType == type || grainChevronType == type) return false; if (!grainType.IsAssignableFrom(type)) return false; // exclude generated classes. return !IsGeneratedType(type); } public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints, bool complain) { complaints = null; if (!IsGrainClass(type)) return false; if (!type.GetTypeInfo().IsAbstract) return true; complaints = complain ? new[] { string.Format("Grain type {0} is abstract and cannot be instantiated.", type.FullName) } : null; return false; } public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints) { return IsConcreteGrainClass(type, out complaints, complain: true); } public static bool IsConcreteGrainClass(Type type) { IEnumerable<string> complaints; return IsConcreteGrainClass(type, out complaints, complain: false); } public static bool IsGeneratedType(Type type) { return TypeHasAttribute(type, typeof(GeneratedCodeAttribute)); } /// <summary> /// Returns true if the provided <paramref name="type"/> is in any of the provided /// <paramref name="namespaces"/>, false otherwise. /// </summary> /// <param name="type">The type to check.</param> /// <param name="namespaces"></param> /// <returns> /// true if the provided <paramref name="type"/> is in any of the provided <paramref name="namespaces"/>, false /// otherwise. /// </returns> public static bool IsInNamespace(Type type, List<string> namespaces) { if (type.Namespace == null) { return false; } foreach (var ns in namespaces) { if (ns.Length > type.Namespace.Length) { continue; } // If the candidate namespace is a prefix of the type's namespace, return true. if (type.Namespace.StartsWith(ns, StringComparison.Ordinal) && (type.Namespace.Length == ns.Length || type.Namespace[ns.Length] == '.')) { return true; } } return false; } /// <summary> /// Returns true if <paramref name="type"/> has implementations of all serialization methods, false otherwise. /// </summary> /// <param name="type">The type.</param> /// <returns> /// true if <paramref name="type"/> has implementations of all serialization methods, false otherwise. /// </returns> public static bool HasAllSerializationMethods(Type type) { // Check if the type has any of the serialization methods. var hasCopier = false; var hasSerializer = false; var hasDeserializer = false; foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) { hasSerializer |= method.GetCustomAttribute<SerializerMethodAttribute>(false) != null; hasDeserializer |= method.GetCustomAttribute<DeserializerMethodAttribute>(false) != null; hasCopier |= method.GetCustomAttribute<CopierMethodAttribute>(false) != null; } var hasAllSerializationMethods = hasCopier && hasSerializer && hasDeserializer; return hasAllSerializationMethods; } public static bool IsGrainMethodInvokerType(Type type) { var generalType = typeof(IGrainMethodInvoker); if (type.Assembly.ReflectionOnly) { generalType = ToReflectionOnlyType(generalType); } return generalType.IsAssignableFrom(type) && TypeHasAttribute(type, typeof(MethodInvokerAttribute)); } private static readonly Lazy<bool> canUseReflectionOnly = new Lazy<bool>(() => { try { ReflectionOnlyTypeResolver.TryResolveType(typeof(TypeUtils).AssemblyQualifiedName, out _); return true; } catch (PlatformNotSupportedException) { return false; } catch (Exception) { // if other exceptions not related to platform ocurr, assume that ReflectionOnly is supported return true; } }); public static bool CanUseReflectionOnly => canUseReflectionOnly.Value; public static Type ResolveReflectionOnlyType(string assemblyQualifiedName) { return ReflectionOnlyTypeResolver.ResolveType(assemblyQualifiedName); } public static Type ToReflectionOnlyType(Type type) { if (CanUseReflectionOnly) { return type.Assembly.ReflectionOnly ? type : ResolveReflectionOnlyType(type.AssemblyQualifiedName); } else { return type; } } public static IEnumerable<Type> GetTypes(Assembly assembly, Predicate<Type> whereFunc, ILogger logger) { return assembly.IsDynamic ? Enumerable.Empty<Type>() : GetDefinedTypes(assembly, logger).Select(t => t.AsType()).Where(type => !type.GetTypeInfo().IsNestedPrivate && whereFunc(type)); } public static IEnumerable<TypeInfo> GetDefinedTypes(Assembly assembly, ILogger logger=null) { try { return assembly.DefinedTypes; } catch (Exception exception) { if (logger != null && logger.IsEnabled(LogLevel.Warning)) { var message = $"Exception loading types from assembly '{assembly.FullName}': {LogFormatter.PrintException(exception)}."; logger.Warn(ErrorCode.Loader_TypeLoadError_5, message, exception); } var typeLoadException = exception as ReflectionTypeLoadException; if (typeLoadException != null) { return typeLoadException.Types?.Where(type => type != null).Select(type => type.GetTypeInfo()) ?? Enumerable.Empty<TypeInfo>(); } return Enumerable.Empty<TypeInfo>(); } } /// <summary> /// Returns a value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method. /// </summary> /// <param name="methodInfo">The method.</param> /// <returns>A value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.</returns> public static bool IsGrainMethod(MethodInfo methodInfo) { if (methodInfo == null) throw new ArgumentNullException("methodInfo", "Cannot inspect null method info"); if (methodInfo.IsStatic || methodInfo.IsSpecialName || methodInfo.DeclaringType == null) { return false; } return methodInfo.DeclaringType.GetTypeInfo().IsInterface && typeof(IAddressable).IsAssignableFrom(methodInfo.DeclaringType); } public static bool TypeHasAttribute(Type type, Type attribType) { if (type.Assembly.ReflectionOnly || attribType.Assembly.ReflectionOnly) { type = ToReflectionOnlyType(type); attribType = ToReflectionOnlyType(attribType); // we can't use Type.GetCustomAttributes here because we could potentially be working with a reflection-only type. return CustomAttributeData.GetCustomAttributes(type).Any( attrib => attribType.IsAssignableFrom(attrib.AttributeType)); } return TypeHasAttribute(type.GetTypeInfo(), attribType); } public static bool TypeHasAttribute(TypeInfo typeInfo, Type attribType) { return typeInfo.GetCustomAttributes(attribType, true).Any(); } /// <summary> /// Returns a sanitized version of <paramref name="type"/>s name which is suitable for use as a class name. /// </summary> /// <param name="type"> /// The grain type. /// </param> /// <returns> /// A sanitized version of <paramref name="type"/>s name which is suitable for use as a class name. /// </returns> public static string GetSuitableClassName(Type type) { return GetClassNameFromInterfaceName(type.GetUnadornedTypeName()); } /// <summary> /// Returns a class-like version of <paramref name="interfaceName"/>. /// </summary> /// <param name="interfaceName"> /// The interface name. /// </param> /// <returns> /// A class-like version of <paramref name="interfaceName"/>. /// </returns> public static string GetClassNameFromInterfaceName(string interfaceName) { string cleanName; if (interfaceName.StartsWith("i", StringComparison.OrdinalIgnoreCase)) { cleanName = interfaceName.Substring(1); } else { cleanName = interfaceName; } return cleanName; } /// <summary> /// Returns the non-generic type name without any special characters. /// </summary> /// <param name="type"> /// The type. /// </param> /// <returns> /// The non-generic type name without any special characters. /// </returns> public static string GetUnadornedTypeName(this Type type) { var index = type.Name.IndexOf('`'); // An ampersand can appear as a suffix to a by-ref type. return (index > 0 ? type.Name.Substring(0, index) : type.Name).TrimEnd('&'); } /// <summary> /// Returns the non-generic method name without any special characters. /// </summary> /// <param name="method"> /// The method. /// </param> /// <returns> /// The non-generic method name without any special characters. /// </returns> public static string GetUnadornedMethodName(this MethodInfo method) { var index = method.Name.IndexOf('`'); return index > 0 ? method.Name.Substring(0, index) : method.Name; } /// <summary>Returns a string representation of <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <returns>A string representation of the <paramref name="type"/>.</returns> public static string GetLogFormat(this Type type) => type.GetParseableName(TypeFormattingOptions.LogFormat); /// <summary>Returns a string representation of <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <param name="options">The type formatting options.</param> /// <param name="getNameFunc">The delegate used to get the unadorned, simple type name of <paramref name="type"/>.</param> /// <returns>A string representation of the <paramref name="type"/>.</returns> public static string GetParseableName(this Type type, TypeFormattingOptions options = null, Func<Type, string> getNameFunc = null) { options = options ?? TypeFormattingOptions.Default; // If a naming function has been specified, skip the cache. if (getNameFunc != null) return BuildParseableName(); return ParseableNameCache.GetOrAdd(Tuple.Create(type, options), _ => BuildParseableName()); string BuildParseableName() { var builder = new StringBuilder(); var typeInfo = type.GetTypeInfo(); GetParseableName( type, builder, new Queue<Type>( typeInfo.IsGenericTypeDefinition ? typeInfo.GetGenericArguments() : typeInfo.GenericTypeArguments), options, getNameFunc ?? (t => t.GetUnadornedTypeName() + options.NameSuffix)); return builder.ToString(); } } /// <summary>Returns a string representation of <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <param name="builder">The <see cref="StringBuilder"/> to append results to.</param> /// <param name="typeArguments">The type arguments of <paramref name="type"/>.</param> /// <param name="options">The type formatting options.</param> /// <param name="getNameFunc">Delegate that returns name for a type.</param> private static void GetParseableName( Type type, StringBuilder builder, Queue<Type> typeArguments, TypeFormattingOptions options, Func<Type, string> getNameFunc) { var typeInfo = type.GetTypeInfo(); if (typeInfo.IsArray) { var elementType = typeInfo.GetElementType().GetParseableName(options); if (!string.IsNullOrWhiteSpace(elementType)) { builder.AppendFormat( "{0}[{1}]", elementType, string.Concat(Enumerable.Range(0, type.GetArrayRank() - 1).Select(_ => ','))); } return; } if (typeInfo.IsGenericParameter) { if (options.IncludeGenericTypeParameters) { builder.Append(type.GetUnadornedTypeName()); } return; } if (typeInfo.DeclaringType != null) { // This is not the root type. GetParseableName(typeInfo.DeclaringType, builder, typeArguments, options, t => t.GetUnadornedTypeName()); builder.Append(options.NestedTypeSeparator); } else if (!string.IsNullOrWhiteSpace(type.Namespace) && options.IncludeNamespace) { // This is the root type, so include the namespace. var namespaceName = type.Namespace; if (options.NestedTypeSeparator != '.') { namespaceName = namespaceName.Replace('.', options.NestedTypeSeparator); } if (options.IncludeGlobal) { builder.AppendFormat("global::"); } builder.AppendFormat("{0}{1}", namespaceName, options.NestedTypeSeparator); } if (type.IsConstructedGenericType) { // Get the unadorned name, the generic parameters, and add them together. var unadornedTypeName = getNameFunc(type); builder.Append(EscapeIdentifier(unadornedTypeName)); var generics = Enumerable.Range(0, Math.Min(typeInfo.GetGenericArguments().Count(), typeArguments.Count)) .Select(_ => typeArguments.Dequeue()) .ToList(); if (generics.Count > 0 && options.IncludeTypeParameters) { var genericParameters = string.Join( ",", generics.Select(generic => GetParseableName(generic, options))); builder.AppendFormat("<{0}>", genericParameters); } } else if (typeInfo.IsGenericTypeDefinition) { // Get the unadorned name, the generic parameters, and add them together. var unadornedTypeName = getNameFunc(type); builder.Append(EscapeIdentifier(unadornedTypeName)); var generics = Enumerable.Range(0, Math.Min(type.GetGenericArguments().Count(), typeArguments.Count)) .Select(_ => typeArguments.Dequeue()) .ToList(); if (generics.Count > 0 && options.IncludeTypeParameters) { var genericParameters = string.Join( ",", generics.Select(_ => options.IncludeGenericTypeParameters ? _.ToString() : string.Empty)); builder.AppendFormat("<{0}>", genericParameters); } } else { builder.Append(EscapeIdentifier(getNameFunc(type))); } } /// <summary> /// Returns the namespaces of the specified types. /// </summary> /// <param name="types"> /// The types to include. /// </param> /// <returns> /// The namespaces of the specified types. /// </returns> public static IEnumerable<string> GetNamespaces(params Type[] types) { return types.Select(type => "global::" + type.Namespace).Distinct(); } /// <summary> /// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="T"> /// The containing type of the method. /// </typeparam> /// <typeparam name="TResult"> /// The return type of the method. /// </typeparam> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </returns> public static MethodInfo Method<T, TResult>(Expression<Func<T, TResult>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns the <see cref="PropertyInfo"/> for the simple member access in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="T"> /// The containing type of the property. /// </typeparam> /// <typeparam name="TResult"> /// The return type of the property. /// </typeparam> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="PropertyInfo"/> for the simple member access call in the provided <paramref name="expression"/>. /// </returns> public static PropertyInfo Property<T, TResult>(Expression<Func<T, TResult>> expression) { var property = expression.Body as MemberExpression; if (property != null) { return property.Member as PropertyInfo; } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns the <see cref="PropertyInfo"/> for the simple member access in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="TResult"> /// The return type of the property. /// </typeparam> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="PropertyInfo"/> for the simple member access call in the provided <paramref name="expression"/>. /// </returns> public static PropertyInfo Property<TResult>(Expression<Func<TResult>> expression) { var property = expression.Body as MemberExpression; if (property != null) { return property.Member as PropertyInfo; } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="T"> /// The containing type of the method. /// </typeparam> /// <typeparam name="TResult"> /// The return type of the method. /// </typeparam> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>. /// </returns> public static MemberInfo Member<T, TResult>(Expression<Func<T, TResult>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } var property = expression.Body as MemberExpression; if (property != null) { return property.Member; } throw new ArgumentException("Expression type unsupported."); } /// <summary>Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.</summary> /// <typeparam name="TResult">The return type of the method.</typeparam> /// <param name="expression">The expression.</param> /// <returns>The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.</returns> public static MemberInfo Member<TResult>(Expression<Func<TResult>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } var property = expression.Body as MemberExpression; if (property != null) { return property.Member; } throw new ArgumentException("Expression type unsupported."); } /// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</summary> /// <typeparam name="T">The containing type of the method.</typeparam> /// <param name="expression">The expression.</param> /// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns> public static MethodInfo Method<T>(Expression<Func<T>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } throw new ArgumentException("Expression type unsupported."); } /// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="T">The containing type of the method.</typeparam> /// <param name="expression">The expression.</param> /// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns> public static MethodInfo Method<T>(Expression<Action<T>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </summary> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </returns> public static MethodInfo Method(Expression<Action> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } throw new ArgumentException("Expression type unsupported."); } /// <summary>Returns the namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</summary> /// <param name="type">The type.</param> /// <returns>The namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</returns> public static string GetNamespaceOrEmpty(this Type type) { if (type == null || string.IsNullOrEmpty(type.Namespace)) { return string.Empty; } return type.Namespace; } /// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param> /// <returns>The types referenced by the provided <paramref name="type"/>.</returns> public static IList<Type> GetTypes(this Type type, bool includeMethods = false) { List<Type> results; var key = Tuple.Create(type, includeMethods); if (!ReferencedTypes.TryGetValue(key, out results)) { results = GetTypes(type, includeMethods, null).ToList(); ReferencedTypes.TryAdd(key, results); } return results; } /// <summary> /// Get a public or non-public constructor that matches the constructor arguments signature /// </summary> /// <param name="type">The type to use.</param> /// <param name="constructorArguments">The constructor argument types to match for the signature.</param> /// <returns>A constructor that matches the signature or <see langword="null"/>.</returns> public static ConstructorInfo GetConstructorThatMatches(Type type, Type[] constructorArguments) { var constructorInfo = type.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, constructorArguments, null); return constructorInfo; } /// <summary> /// Returns a value indicating whether or not the provided assembly is the Orleans assembly or references it. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>A value indicating whether or not the provided assembly is the Orleans assembly or references it.</returns> internal static bool IsOrleansOrReferencesOrleans(Assembly assembly) { // We want to be loosely coupled to the assembly version if an assembly depends on an older Orleans, // but we want a strong assembly match for the Orleans binary itself // (so we don't load 2 different versions of Orleans by mistake) var references = assembly.GetReferencedAssemblies(); return DoReferencesContain(references, OrleansCoreAssembly) || DoReferencesContain(references, OrleansAbstractionsAssembly) || string.Equals(assembly.GetName().FullName, OrleansCoreAssembly.FullName, StringComparison.Ordinal); } /// <summary> /// Returns a value indicating whether or not the specified references contain the provided assembly name. /// </summary> /// <param name="references">The references.</param> /// <param name="assemblyName">The assembly name.</param> /// <returns>A value indicating whether or not the specified references contain the provided assembly name.</returns> private static bool DoReferencesContain(IReadOnlyCollection<AssemblyName> references, AssemblyName assemblyName) { if (references.Count == 0) { return false; } return references.Any(asm => string.Equals(asm.Name, assemblyName.Name, StringComparison.Ordinal)); } /// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param> /// <param name="exclude">Types to exclude</param> /// <returns>The types referenced by the provided <paramref name="type"/>.</returns> private static IEnumerable<Type> GetTypes( this Type type, bool includeMethods, HashSet<Type> exclude) { exclude = exclude ?? new HashSet<Type>(); if (!exclude.Add(type)) { yield break; } yield return type; if (type.IsArray) { foreach (var elementType in type.GetElementType().GetTypes(false, exclude: exclude)) { yield return elementType; } } if (type.IsConstructedGenericType) { foreach (var genericTypeArgument in type.GetGenericArguments().SelectMany(_ => GetTypes(_, false, exclude: exclude))) { yield return genericTypeArgument; } } if (!includeMethods) { yield break; } foreach (var method in type.GetMethods()) { foreach (var referencedType in GetTypes(method.ReturnType, false, exclude: exclude)) { yield return referencedType; } foreach (var parameter in method.GetParameters()) { foreach (var referencedType in GetTypes(parameter.ParameterType, false, exclude: exclude)) { yield return referencedType; } } } } private static string EscapeIdentifier(string identifier) { if (IsCSharpKeyword(identifier)) return "@" + identifier; return identifier; } internal static bool IsCSharpKeyword(string identifier) { switch (identifier) { case "abstract": case "add": case "alias": case "as": case "ascending": case "async": case "await": case "base": case "bool": case "break": case "byte": case "case": case "catch": case "char": case "checked": case "class": case "const": case "continue": case "decimal": case "default": case "delegate": case "descending": case "do": case "double": case "dynamic": case "else": case "enum": case "event": case "explicit": case "extern": case "false": case "finally": case "fixed": case "float": case "for": case "foreach": case "from": case "get": case "global": case "goto": case "group": case "if": case "implicit": case "in": case "int": case "interface": case "internal": case "into": case "is": case "join": case "let": case "lock": case "long": case "nameof": case "namespace": case "new": case "null": case "object": case "operator": case "orderby": case "out": case "override": case "params": case "partial": case "private": case "protected": case "public": case "readonly": case "ref": case "remove": case "return": case "sbyte": case "sealed": case "select": case "set": case "short": case "sizeof": case "stackalloc": case "static": case "string": case "struct": case "switch": case "this": case "throw": case "true": case "try": case "typeof": case "uint": case "ulong": case "unchecked": case "unsafe": case "ushort": case "using": case "value": case "var": case "virtual": case "void": case "volatile": case "when": case "where": case "while": case "yield": return true; default: 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. // This file contains two ICryptoTransforms: ToBase64Transform and FromBase64Transform // they may be attached to a CryptoStream in either read or write mode using System.Buffers; using System.Buffers.Text; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Security.Cryptography { public enum FromBase64TransformMode { IgnoreWhiteSpaces = 0, DoNotIgnoreWhiteSpaces = 1, } public class ToBase64Transform : ICryptoTransform { // converting to Base64 takes 3 bytes input and generates 4 bytes output public int InputBlockSize => 3; public int OutputBlockSize => 4; public bool CanTransformMultipleBlocks => false; public virtual bool CanReuseTransform => true; public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { // inputCount < InputBlockSize is not allowed ThrowHelper.ValidateTransformBlock(inputBuffer, inputOffset, inputCount, InputBlockSize); if (outputBuffer == null) ThrowHelper.ThrowArgumentNull(ThrowHelper.ExceptionArgument.outputBuffer); // For now, only convert 3 bytes to 4 Span<byte> input = inputBuffer.AsSpan(inputOffset, InputBlockSize); Span<byte> output = outputBuffer.AsSpan(outputOffset, OutputBlockSize); OperationStatus status = Base64.EncodeToUtf8(input, output, out int consumed, out int written, isFinalBlock: false); if (written != OutputBlockSize) { ThrowHelper.ThrowCryptographicException(); } Debug.Assert(status == OperationStatus.NeedMoreData); Debug.Assert(consumed == InputBlockSize); return written; } public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { // inputCount <= InputBlockSize is allowed ThrowHelper.ValidateTransformBlock(inputBuffer, inputOffset, inputCount); // Convert.ToBase64CharArray already does padding, so all we have to check is that // the inputCount wasn't 0 if (inputCount == 0) { return Array.Empty<byte>(); } else if (inputCount > InputBlockSize) { ThrowHelper.ThrowArgumentOutOfRange(ThrowHelper.ExceptionArgument.inputCount); } // Again, for now only a block at a time Span<byte> input = inputBuffer.AsSpan(inputOffset, inputCount); byte[] output = new byte[OutputBlockSize]; OperationStatus status = Base64.EncodeToUtf8(input, output, out int consumed, out int written, isFinalBlock: true); if (written != OutputBlockSize) { ThrowHelper.ThrowCryptographicException(); } Debug.Assert(status == OperationStatus.Done); Debug.Assert(consumed == inputCount); return output; } // Must implement IDisposable, but in this case there's nothing to do. public void Dispose() { Clear(); } public void Clear() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } ~ToBase64Transform() { // A finalizer is not necessary here, however since we shipped a finalizer that called // Dispose(false) in desktop v2.0, we need to keep it in case any existing code had subclassed // this transform and expects to have a base class finalizer call its dispose method. Dispose(false); } } public class FromBase64Transform : ICryptoTransform { private byte[] _inputBuffer = new byte[4]; private int _inputIndex; private readonly FromBase64TransformMode _whitespaces; public FromBase64Transform() : this(FromBase64TransformMode.IgnoreWhiteSpaces) { } public FromBase64Transform(FromBase64TransformMode whitespaces) { _whitespaces = whitespaces; } // A buffer with size 32 is stack allocated, to cover common cases and benefit from JIT's optimizations. private const int StackAllocSize = 32; // Converting from Base64 generates 3 bytes output from each 4 bytes input block public int InputBlockSize => 4; public int OutputBlockSize => 3; public bool CanTransformMultipleBlocks => true; public virtual bool CanReuseTransform => true; public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { // inputCount != InputBlockSize is allowed ThrowHelper.ValidateTransformBlock(inputBuffer, inputOffset, inputCount); if (_inputBuffer == null) ThrowHelper.ThrowObjectDisposed(); if (outputBuffer == null) ThrowHelper.ThrowArgumentNull(ThrowHelper.ExceptionArgument.outputBuffer); // The common case is inputCount = InputBlockSize byte[] tmpBufferArray = null; Span<byte> tmpBuffer = stackalloc byte[StackAllocSize]; if (inputCount > StackAllocSize) { tmpBuffer = tmpBufferArray = CryptoPool.Rent(inputCount); } tmpBuffer = GetTempBuffer(inputBuffer.AsSpan(inputOffset, inputCount), tmpBuffer); int bytesToTransform = _inputIndex + tmpBuffer.Length; // Too little data to decode: save data to _inputBuffer, so it can be transformed later if (bytesToTransform < InputBlockSize) { tmpBuffer.CopyTo(_inputBuffer.AsSpan(_inputIndex)); _inputIndex = bytesToTransform; ReturnToCryptoPool(tmpBufferArray, tmpBuffer.Length); return 0; } ConvertFromBase64(tmpBuffer, outputBuffer.AsSpan(outputOffset), out _, out int written); ReturnToCryptoPool(tmpBufferArray, tmpBuffer.Length); return written; } public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { // inputCount != InputBlockSize is allowed ThrowHelper.ValidateTransformBlock(inputBuffer, inputOffset, inputCount); if (_inputBuffer == null) { ThrowHelper.ThrowObjectDisposed(); } if (inputCount == 0) { return Array.Empty<byte>(); } // The common case is inputCount <= Base64InputBlockSize byte[] tmpBufferArray = null; Span<byte> tmpBuffer = stackalloc byte[StackAllocSize]; if (inputCount > StackAllocSize) { tmpBuffer = tmpBufferArray = CryptoPool.Rent(inputCount); } tmpBuffer = GetTempBuffer(inputBuffer.AsSpan(inputOffset, inputCount), tmpBuffer); int bytesToTransform = _inputIndex + tmpBuffer.Length; // Too little data to decode if (bytesToTransform < InputBlockSize) { // reinitialize the transform Reset(); ReturnToCryptoPool(tmpBufferArray, tmpBuffer.Length); return Array.Empty<byte>(); } int outputSize = GetOutputSize(bytesToTransform, tmpBuffer); byte[] output = new byte[outputSize]; ConvertFromBase64(tmpBuffer, output, out int consumed, out int written); Debug.Assert(written == outputSize); ReturnToCryptoPool(tmpBufferArray, tmpBuffer.Length); // reinitialize the transform Reset(); return output; } private Span<byte> GetTempBuffer(Span<byte> inputBuffer, Span<byte> tmpBuffer) { if (_whitespaces == FromBase64TransformMode.DoNotIgnoreWhiteSpaces) { return inputBuffer; } return DiscardWhiteSpaces(inputBuffer, tmpBuffer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Span<byte> DiscardWhiteSpaces(Span<byte> inputBuffer, Span<byte> tmpBuffer) { int count = 0; for (int i = 0; i < inputBuffer.Length; i++) { if (!IsWhitespace(inputBuffer[i])) { tmpBuffer[count++] = inputBuffer[i]; } } return tmpBuffer.Slice(0, count); } private static bool IsWhitespace(byte value) { // We assume ASCII encoded data. If there is any non-ASCII char, it is invalid // Base64 and will be caught during decoding. // SPACE 32 // TAB 9 // LF 10 // VTAB 11 // FORM FEED 12 // CR 13 return value == 32 || ((uint)value - 9 <= (13 - 9)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private int GetOutputSize(int bytesToTransform, Span<byte> tmpBuffer) { int outputSize = Base64.GetMaxDecodedFromUtf8Length(bytesToTransform); const byte padding = (byte)'='; int len = tmpBuffer.Length; // In Base64 there are maximum 2 padding chars if (tmpBuffer[len - 2] == padding) { outputSize--; } if (tmpBuffer[len - 1] == padding) { outputSize--; } return outputSize; } private void ConvertFromBase64(Span<byte> tmpBuffer, Span<byte> outputBuffer, out int consumed, out int written) { int bytesToTransform = _inputIndex + tmpBuffer.Length; Debug.Assert(bytesToTransform >= 4); byte[] transformBufferArray = null; Span<byte> transformBuffer = stackalloc byte[StackAllocSize]; if (bytesToTransform > StackAllocSize) { transformBuffer = transformBufferArray = CryptoPool.Rent(bytesToTransform); } // Copy _inputBuffer to transformBuffer and append tmpBuffer Debug.Assert(_inputIndex < _inputBuffer.Length); _inputBuffer.AsSpan(0, _inputIndex).CopyTo(transformBuffer); tmpBuffer.CopyTo(transformBuffer.Slice(_inputIndex)); // Save data that won't be transformed to _inputBuffer, so it can be transformed later _inputIndex = bytesToTransform & 3; // bit hack for % 4 bytesToTransform -= _inputIndex; // only transform up to the next multiple of 4 Debug.Assert(_inputIndex < _inputBuffer.Length); tmpBuffer.Slice(tmpBuffer.Length - _inputIndex).CopyTo(_inputBuffer); transformBuffer = transformBuffer.Slice(0, bytesToTransform); OperationStatus status = Base64.DecodeFromUtf8(transformBuffer, outputBuffer, out consumed, out written); if (status == OperationStatus.Done) { Debug.Assert(consumed == bytesToTransform); } else { Debug.Assert(status == OperationStatus.InvalidData); ThrowHelper.ThrowBase64FormatException(); } ReturnToCryptoPool(transformBufferArray, transformBuffer.Length); } private void ReturnToCryptoPool(byte[] array, int clearSize) { if (array != null) { CryptoPool.Return(array, clearSize); } } public void Clear() { Dispose(); } // Reset the state of the transform so it can be used again private void Reset() { _inputIndex = 0; } // must implement IDisposable, which in this case means clearing the input buffer public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // we always want to clear the input buffer if (disposing) { if (_inputBuffer != null) { CryptographicOperations.ZeroMemory(_inputBuffer); _inputBuffer = null; } Reset(); } } ~FromBase64Transform() { Dispose(false); } } internal class ThrowHelper { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ValidateTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount) { if (inputBuffer == null) ThrowArgumentNull(ExceptionArgument.inputBuffer); if ((uint)inputCount > inputBuffer.Length) ThrowArgumentOutOfRange(ExceptionArgument.inputCount); if (inputOffset < 0) ThrowArgumentOutOfRange(ExceptionArgument.inputOffset); if ((inputBuffer.Length - inputCount) < inputOffset) ThrowInvalidOffLen(); } public static void ValidateTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, int inputBlockSize) { ValidateTransformBlock(inputBuffer, inputOffset, inputCount); if (inputCount < inputBlockSize) ThrowArgumentOutOfRange(ExceptionArgument.inputCount); } public static void ThrowArgumentNull(ExceptionArgument argument) => throw new ArgumentNullException(argument.ToString()); public static void ThrowArgumentOutOfRange(ExceptionArgument argument) => throw new ArgumentOutOfRangeException(argument.ToString(), SR.ArgumentOutOfRange_NeedNonNegNum); public static void ThrowInvalidOffLen() => throw new ArgumentException(SR.Argument_InvalidOffLen); public static void ThrowObjectDisposed() => throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); public static void ThrowCryptographicException() => throw new CryptographicException(SR.Cryptography_SSE_InvalidDataSize); public static void ThrowBase64FormatException() => throw new FormatException(); public enum ExceptionArgument { inputBuffer, outputBuffer, inputOffset, inputCount } } }
#region Author /************************************************************************************************************ Author: EpixCode (Keven Poulin) Website: http://www.EpixCode.com GitHub: https://github.com/EpixCode Twitter: https://twitter.com/EpixCode (@EpixCode) LinkedIn: http://www.linkedin.com/in/kevenpoulin ************************************************************************************************************/ #endregion #region Copyright /************************************************************************************************************ Copyright (C) 2014 EpixCode 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 Class Documentation /************************************************************************************************************ Class Name: WeakDictionary.cs Namespace: Com.EpixCode.Util.WeakReference.WeakDictionary Type: Util / Collection Definition: [WeakDictionary] is an alternative to [ConditionalWeakTable] (Only available in .NET Framework 4 +) for Unity. It gives the ability to index a dictionary with weak key objects reference that will automatically be released if they are no longer used. Example: WeakDictionary<object, string> myWeakDictionary = new WeakDictionary<object, string>(); myWeakDictionary.Add(myObject, "myString"); ************************************************************************************************************/ #endregion using UnityEngine; using System; using System.Collections; using System.Collections.Generic; internal class HashableWeakRef<T> : IEquatable<HashableWeakRef<T>>, IDisposable where T : class { private System.WeakReference _weakReference; private int _hashcode; public T Target { get { return (T)_weakReference.Target; } } public HashableWeakRef(T aTarget) { if (aTarget != null) { _weakReference = new System.WeakReference(aTarget); _hashcode = aTarget.GetHashCode(); } else { throw new InvalidOperationException("Can't create HashableWeakRef out of a null reference!"); } } public override int GetHashCode() { return _hashcode; } public override bool Equals(object aObj) { if (_weakReference != null) { return this.Target.Equals(aObj); } return false; } public bool Equals(HashableWeakRef<T> aObj) { if (_weakReference != null) { return this.Target.Equals(aObj); } return false; } public static bool operator ==(HashableWeakRef<T> aFirstRef, HashableWeakRef<T> aSecondRef) { return aFirstRef.Equals(aSecondRef); } public static bool operator !=(HashableWeakRef<T> aFirstRef, HashableWeakRef<T> aSecondRef) { return !aFirstRef.Equals(aSecondRef); } public bool IsAlive { get { return (bool)(_weakReference != null && _weakReference.IsAlive && !_weakReference.Target.Equals(null)); } } public void Dispose() { if(_weakReference != null && !_weakReference.Target.Equals(null)) { if(_weakReference.Target is IDisposable) { (_weakReference.Target as IDisposable).Dispose(); } } } } public class WeakDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>, ICollection<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>, IEnumerable where TKey : class { /********************************************************* * Member Variables *********************************************************/ private IDictionary<object, TValue> _refDict = new Dictionary<object, TValue>(); private bool _isAutoCean = true; /********************************************************* * Accessors / Mutators *********************************************************/ public int Count { get { return _refDict.Count; } } public bool IsReadOnly { get { return _refDict.IsReadOnly; } } public ICollection<TKey> Keys { get { ICollection<TKey> keyList = new List<TKey>(); foreach (KeyValuePair<TKey, TValue> entry in this) { keyList.Add(entry.Key); } return keyList; } } public ICollection<TValue> Values { get { return _refDict.Values; } } public TValue this[TKey key] { get { return _refDict[key]; } set { _refDict[key] = value; } } public bool IsAutoClean { get { return _isAutoCean; } set { _isAutoCean = value; } } /********************************************************** * Explicit Methods *********************************************************/ IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } bool IDictionary<TKey, TValue>.Remove(TKey key) { return _refDict.Remove(key); } /********************************************************** * Public Methods *********************************************************/ public void Add(TKey aKey, TValue aValue) { HashableWeakRef<TKey> weakKey = new HashableWeakRef<TKey>(aKey); _refDict.Add(weakKey, aValue); } public void Add(KeyValuePair<TKey, TValue> aItem) { Add(aItem.Key, aItem.Value); } public bool Remove(TKey aKey) { return _refDict.Remove(aKey); } public bool Remove(KeyValuePair<TKey, TValue> aItem) { return Remove(aItem.Key); } public bool ContainsKey(TKey aKey) { return _refDict.ContainsKey(aKey); } public bool Contains(KeyValuePair<TKey, TValue> aItem) { return _refDict.ContainsKey(aItem.Key); } public void Clear() { _refDict.Clear(); } public bool Clean() { List<HashableWeakRef<TKey>> weakKeyListToRemove = new List<HashableWeakRef<TKey>>(); bool success = false; foreach (KeyValuePair<object, TValue> entry in _refDict) { HashableWeakRef<TKey> weakKey = (HashableWeakRef<TKey>)entry.Key; if (!weakKey.IsAlive) { weakKeyListToRemove.Add(weakKey); } } for (int i = 0; i < weakKeyListToRemove.Count; i++) { Clean(weakKeyListToRemove[i]); success = true; } return success; } private bool Clean(HashableWeakRef<TKey> aKey) { bool success = false; if (!aKey.IsAlive) { if (_refDict[aKey] is IDisposable) { (_refDict[aKey] as IDisposable).Dispose(); } _refDict.Remove(aKey); success = true; } return success; } public bool TryGetValue(TKey aKey, out TValue aValue) { if (ContainsKey(aKey)) { aValue = this[aKey]; return true; } aValue = default(TValue); return false; } public void CopyTo(KeyValuePair<TKey, TValue>[] aArray, int aIndex) { foreach (KeyValuePair<object, TValue> entry in _refDict) { KeyValuePair<TKey, TValue> pair = new KeyValuePair<TKey, TValue>(((HashableWeakRef<TKey>)entry.Key).Target, entry.Value); aArray.SetValue(pair, aIndex); aIndex = aIndex + 1; } } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { if (IsAutoClean) { Clean(); } foreach (KeyValuePair<object, TValue> entry in _refDict) { HashableWeakRef<TKey> weakKey = (HashableWeakRef<TKey>)entry.Key; yield return new KeyValuePair<TKey, TValue>(weakKey.Target, entry.Value); } } }
/* * Copyright 2015 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using ZXing.Common; namespace ZXing.OneD { /// <summary> /// This object renders a CODE93 code as a BitMatrix /// </summary> public class Code93Writer : OneDimensionalCodeWriter { private static readonly IList<BarcodeFormat> supportedWriteFormats = new List<BarcodeFormat> { BarcodeFormat.CODE_93 }; /// <summary> /// returns supported formats /// </summary> protected override IList<BarcodeFormat> SupportedWriteFormats { get { return supportedWriteFormats; } } /// <summary> /// </summary> /// <param name="contents">barcode contents to encode.It should not be encoded for extended characters.</param> /// <returns>a { @code bool[]} of horizontal pixels(false = white, true = black)</returns> public override bool[] encode(String contents) { contents = convertToExtended(contents); int length = contents.Length; if (length > 80) { throw new ArgumentException( "Requested contents should be less than 80 digits long after converting to extended encoding, but got " + length); } //length of code + 2 start/stop characters + 2 checksums, each of 9 bits, plus a termination bar int codeWidth = (contents.Length + 2 + 2) * 9 + 1; bool[] result = new bool[codeWidth]; //start character (*) int pos = appendPattern(result, 0, Code93Reader.ASTERISK_ENCODING); for (int i = 0; i < length; i++) { int indexInString = Code93Reader.ALPHABET_STRING.IndexOf(contents[i]); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[indexInString]); } //add two checksums int check1 = computeChecksumIndex(contents, 20); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check1]); //append the contents to reflect the first checksum added contents += Code93Reader.ALPHABET_STRING[check1]; int check2 = computeChecksumIndex(contents, 15); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check2]); //end character (*) pos += appendPattern(result, pos, Code93Reader.ASTERISK_ENCODING); //termination bar (single black bar) result[pos] = true; return result; } /// <summary> /// </summary> /// <param name="target">output to append to</param> /// <param name="pos">start position</param> /// <param name="pattern">pattern to append</param> /// <param name="startColor">unused</param> /// <returns>9</returns> [Obsolete("without replacement; intended as an internal-only method")] protected new static int appendPattern(bool[] target, int pos, int[] pattern, bool startColor) { foreach (var bit in pattern) { target[pos++] = bit != 0; } return 9; } private static int appendPattern(bool[] target, int pos, int a) { for (int i = 0; i < 9; i++) { int temp = a & (1 << (8 - i)); target[pos + i] = temp != 0; } return 9; } private static int computeChecksumIndex(String contents, int maxWeight) { int weight = 1; int total = 0; for (int i = contents.Length - 1; i >= 0; i--) { int indexInString = Code93Reader.ALPHABET_STRING.IndexOf(contents[i]); total += indexInString * weight; if (++weight > maxWeight) { weight = 1; } } return total % 47; } internal static String convertToExtended(String contents) { int length = contents.Length; var extendedContent = new System.Text.StringBuilder(length * 2); for (int i = 0; i < length; i++) { char character = contents[i]; // ($)=a, (%)=b, (/)=c, (+)=d. see Code93Reader.ALPHABET_STRING if (character == 0) { // NUL: (%)U extendedContent.Append("bU"); } else if (character <= 26) { // SOH - SUB: ($)A - ($)Z extendedContent.Append('a'); extendedContent.Append((char) ('A' + character - 1)); } else if (character <= 31) { // ESC - US: (%)A - (%)E extendedContent.Append('b'); extendedContent.Append((char) ('A' + character - 27)); } else if (character == ' ' || character == '$' || character == '%' || character == '+') { // space $ % + extendedContent.Append(character); } else if (character <= ',') { // ! " # & ' ( ) * ,: (/)A - (/)L extendedContent.Append('c'); extendedContent.Append((char) ('A' + character - '!')); } else if (character <= '9') { extendedContent.Append(character); } else if (character == ':') { // :: (/)Z extendedContent.Append("cZ"); } else if (character <= '?') { // ; - ?: (%)F - (%)J extendedContent.Append('b'); extendedContent.Append((char) ('F' + character - ';')); } else if (character == '@') { // @: (%)V extendedContent.Append("bV"); } else if (character <= 'Z') { // A - Z extendedContent.Append(character); } else if (character <= '_') { // [ - _: (%)K - (%)O extendedContent.Append('b'); extendedContent.Append((char) ('K' + character - '[')); } else if (character == '`') { // `: (%)W extendedContent.Append("bW"); } else if (character <= 'z') { // a - z: (*)A - (*)Z extendedContent.Append('d'); extendedContent.Append((char) ('A' + character - 'a')); } else if (character <= 127) { // { - DEL: (%)P - (%)T extendedContent.Append('b'); extendedContent.Append((char) ('P' + character - '{')); } else { throw new ArgumentException( "Requested content contains a non-encodable character: '" + character + "'"); } } return extendedContent.ToString(); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.IndicesGetMapping1 { public partial class IndicesGetMapping1YamlTests { public class IndicesGetMapping110BasicYamlBase : YamlTestsBase { public IndicesGetMapping110BasicYamlBase() : base() { //do indices.create _body = new { mappings= new { type_1= new {}, type_2= new {} } }; this.Do(()=> _client.IndicesCreate("test_1", _body)); //do indices.create _body = new { mappings= new { type_2= new {}, type_3= new {} } }; this.Do(()=> _client.IndicesCreate("test_2", _body)); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetMapping2Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetMapping2Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMappingForAll()); //match _response.test_1.mappings.type_1.properties: this.IsMatch(_response.test_1.mappings.type_1.properties, new {}); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //match _response.test_2.mappings.type_2.properties: this.IsMatch(_response.test_2.mappings.type_2.properties, new {}); //match _response.test_2.mappings.type_3.properties: this.IsMatch(_response.test_2.mappings.type_3.properties, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMapping3Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMapping3Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1")); //match _response.test_1.mappings.type_1.properties: this.IsMatch(_response.test_1.mappings.type_1.properties, new {}); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMappingAll4Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMappingAll4Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1", "_all")); //match _response.test_1.mappings.type_1.properties: this.IsMatch(_response.test_1.mappings.type_1.properties, new {}); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMapping5Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMapping5Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1", "*")); //match _response.test_1.mappings.type_1.properties: this.IsMatch(_response.test_1.mappings.type_1.properties, new {}); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMappingType6Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMappingType6Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1", "type_1")); //match _response.test_1.mappings.type_1.properties: this.IsMatch(_response.test_1.mappings.type_1.properties, new {}); //is_false _response.test_1.mappings.type_2; this.IsFalse(_response.test_1.mappings.type_2); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMappingTypeType7Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMappingTypeType7Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1", "type_1,type_2")); //match _response.test_1.mappings.type_1.properties: this.IsMatch(_response.test_1.mappings.type_1.properties, new {}); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMappingType8Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMappingType8Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1", "*2")); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //is_false _response.test_1.mappings.type_1; this.IsFalse(_response.test_1.mappings.type_1); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetMappingType9Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetMappingType9Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMappingForAll("type_2")); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //match _response.test_2.mappings.type_2.properties: this.IsMatch(_response.test_2.mappings.type_2.properties, new {}); //is_false _response.test_1.mappings.type_1; this.IsFalse(_response.test_1.mappings.type_1); //is_false _response.test_2.mappings.type_3; this.IsFalse(_response.test_2.mappings.type_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAllMappingType10Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetAllMappingType10Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("_all", "type_2")); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //match _response.test_2.mappings.type_2.properties: this.IsMatch(_response.test_2.mappings.type_2.properties, new {}); //is_false _response.test_1.mappings.type_1; this.IsFalse(_response.test_1.mappings.type_1); //is_false _response.test_2.mappings.type_3; this.IsFalse(_response.test_2.mappings.type_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetMappingType11Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetMappingType11Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("*", "type_2")); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //match _response.test_2.mappings.type_2.properties: this.IsMatch(_response.test_2.mappings.type_2.properties, new {}); //is_false _response.test_1.mappings.type_1; this.IsFalse(_response.test_1.mappings.type_1); //is_false _response.test_2.mappings.type_3; this.IsFalse(_response.test_2.mappings.type_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexIndexMappingType12Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexIndexMappingType12Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1,test_2", "type_2")); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //match _response.test_2.mappings.type_2.properties: this.IsMatch(_response.test_2.mappings.type_2.properties, new {}); //is_false _response.test_2.mappings.type_3; this.IsFalse(_response.test_2.mappings.type_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMappingType13Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMappingType13Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("*2", "type_2")); //match _response.test_2.mappings.type_2.properties: this.IsMatch(_response.test_2.mappings.type_2.properties, new {}); //is_false _response.test_1; this.IsFalse(_response.test_1); //is_false _response.test_2.mappings.type_3; this.IsFalse(_response.test_2.mappings.type_3); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.CoreServices.Layout; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; namespace OpenLiveWriter.InternalWriterPlugin.Controls { internal class MapPushpinForm : MiniForm { private string UNTITLED_PUSHPIN = Res.Get(StringId.PushpinUntitled); private System.Windows.Forms.Label labelTitle; private System.Windows.Forms.TextBox textBoxTitle; private System.Windows.Forms.Label labelNotes; private System.Windows.Forms.TextBox textBoxNotes; private System.Windows.Forms.TextBox textBoxPhotoUrl; private System.Windows.Forms.Label labelPhotoUrl; private System.Windows.Forms.TextBox textBoxMoreInfoUrl; private System.Windows.Forms.Label labelMoreInfoUrl; private System.Windows.Forms.Button buttonSave; private System.Windows.Forms.Button buttonCancel; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private MapPushpinEditedHandler _pushpinEditedHandler; public MapPushpinForm(IWin32Window parentFrame, Point location, MapPushpinEditedHandler pushpinEditedHandler) : this(parentFrame, location, pushpinEditedHandler, null) { } public MapPushpinForm(IWin32Window parentFrame, Point location, MapPushpinEditedHandler pushpinEditedHandler, MapPushpinInfo pushpinInfo) : base(parentFrame) { // // Required for Windows Form Designer support // InitializeComponent(); if (SystemInformation.HighContrast) this.BackColor = SystemColors.Control; this.labelTitle.Text = Res.Get(StringId.PushpinTitle); this.textBoxTitle.Text = Res.Get(StringId.PushpinUntitled); this.labelNotes.Text = Res.Get(StringId.PushpinNotes); this.labelPhotoUrl.Text = Res.Get(StringId.PushpinPhotoUrl); this.labelMoreInfoUrl.Text = Res.Get(StringId.PushpinMoreInfoUrl); this.buttonSave.Text = Res.Get(StringId.SaveButton); this.buttonCancel.Text = Res.Get(StringId.CancelButton); _pushpinEditedHandler = pushpinEditedHandler; if (pushpinInfo == null) pushpinInfo = new MapPushpinInfo(String.Empty); textBoxTitle.Text = pushpinInfo.Title; if (textBoxTitle.Text == String.Empty) textBoxTitle.Text = UNTITLED_PUSHPIN; textBoxNotes.Text = pushpinInfo.Notes; textBoxPhotoUrl.Text = pushpinInfo.PhotoUrl; textBoxMoreInfoUrl.Text = pushpinInfo.MoreInfoUrl; if (pushpinInfo.Title == String.Empty) { Text = Res.Get(StringId.PushpinAdd); } else { Text = Res.Get(StringId.PushpinEdit); } Location = location; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); LayoutHelper.FixupOKCancel(buttonSave, buttonCancel); } private void buttonSave_Click(object sender, System.EventArgs e) { string title = StringHelper.Ellipsis(textBoxTitle.Text.Trim(), 600); if (title == String.Empty) { title = textBoxTitle.Text = UNTITLED_PUSHPIN; } // initialize the pushpin info MapPushpinInfo pushpinInfo = new MapPushpinInfo(title); // treat an empty title as the same as "Cancel" -- since this dialog dismisses // on deactivation we can't really throw up a message-box if (pushpinInfo.Title != String.Empty) { pushpinInfo.Notes = StringHelper.Ellipsis(textBoxNotes.Text.Trim(), 600); pushpinInfo.PhotoUrl = StringHelper.RestrictLength(UrlHelper.FixUpUrl(textBoxPhotoUrl.Text), 600); pushpinInfo.MoreInfoUrl = StringHelper.RestrictLength(UrlHelper.FixUpUrl(textBoxMoreInfoUrl.Text), 600); _pushpinEditedHandler(pushpinInfo); } Close(); } private void buttonCancel_Click(object sender, System.EventArgs e) { Close(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); e.Graphics.ResetClip(); BidiGraphics g = new BidiGraphics(e.Graphics, Bounds, false); using (Brush brush = new SolidBrush(SystemColors.ActiveCaption)) { g.FillRectangle(brush, new Rectangle(0, 0, Width - 1, SystemInformation.ToolWindowCaptionHeight)); } using (Pen borderPen = new Pen(Color.FromArgb(127, 157, 185))) { g.DrawRectangle(borderPen, new Rectangle(0, 0, Width - 1, Height - 1)); g.DrawLine(borderPen, 0, SystemInformation.ToolWindowCaptionHeight, Width - 1, SystemInformation.ToolWindowCaptionHeight); } using (Font boldFont = new Font(Font, FontStyle.Bold)) g.DrawText(Text, boldFont, new Rectangle(4, 2, Width - 2, SystemInformation.ToolWindowCaptionHeight - 1), SystemColors.ActiveCaptionText); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.labelTitle = new System.Windows.Forms.Label(); this.textBoxTitle = new System.Windows.Forms.TextBox(); this.textBoxNotes = new System.Windows.Forms.TextBox(); this.labelNotes = new System.Windows.Forms.Label(); this.textBoxPhotoUrl = new System.Windows.Forms.TextBox(); this.labelPhotoUrl = new System.Windows.Forms.Label(); this.textBoxMoreInfoUrl = new System.Windows.Forms.TextBox(); this.labelMoreInfoUrl = new System.Windows.Forms.Label(); this.buttonSave = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.SuspendLayout(); // // labelTitle // this.labelTitle.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelTitle.Location = new System.Drawing.Point(8, 23); this.labelTitle.Name = "labelTitle"; this.labelTitle.Size = new System.Drawing.Size(185, 14); this.labelTitle.TabIndex = 1; this.labelTitle.Text = "&Title:"; // // textBoxTitle // this.textBoxTitle.Location = new System.Drawing.Point(8, 39); this.textBoxTitle.Name = "textBoxTitle"; this.textBoxTitle.Size = new System.Drawing.Size(220, 21); this.textBoxTitle.TabIndex = 2; this.textBoxTitle.Text = "Untitled pushpin"; // // textBoxNotes // this.textBoxNotes.AcceptsReturn = true; this.textBoxNotes.Location = new System.Drawing.Point(8, 81); this.textBoxNotes.Multiline = true; this.textBoxNotes.Name = "textBoxNotes"; this.textBoxNotes.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textBoxNotes.Size = new System.Drawing.Size(220, 67); this.textBoxNotes.TabIndex = 4; this.textBoxNotes.Text = ""; // // labelNotes // this.labelNotes.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelNotes.Location = new System.Drawing.Point(8, 66); this.labelNotes.Name = "labelNotes"; this.labelNotes.Size = new System.Drawing.Size(215, 14); this.labelNotes.TabIndex = 3; this.labelNotes.Text = "&Notes:"; // // textBoxPhotoUrl // this.textBoxPhotoUrl.Location = new System.Drawing.Point(8, 168); this.textBoxPhotoUrl.Name = "textBoxPhotoUrl"; this.textBoxPhotoUrl.Size = new System.Drawing.Size(220, 21); this.textBoxPhotoUrl.TabIndex = 6; this.textBoxPhotoUrl.Text = ""; // // labelPhotoUrl // this.labelPhotoUrl.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelPhotoUrl.Location = new System.Drawing.Point(8, 153); this.labelPhotoUrl.Name = "labelPhotoUrl"; this.labelPhotoUrl.Size = new System.Drawing.Size(211, 14); this.labelPhotoUrl.TabIndex = 5; this.labelPhotoUrl.Text = "&Photo URL:"; // // textBoxMoreInfoUrl // this.textBoxMoreInfoUrl.Location = new System.Drawing.Point(8, 211); this.textBoxMoreInfoUrl.Name = "textBoxMoreInfoUrl"; this.textBoxMoreInfoUrl.Size = new System.Drawing.Size(220, 21); this.textBoxMoreInfoUrl.TabIndex = 8; this.textBoxMoreInfoUrl.Text = ""; // // labelMoreInfoUrl // this.labelMoreInfoUrl.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelMoreInfoUrl.Location = new System.Drawing.Point(8, 195); this.labelMoreInfoUrl.Name = "labelMoreInfoUrl"; this.labelMoreInfoUrl.Size = new System.Drawing.Size(216, 14); this.labelMoreInfoUrl.TabIndex = 7; this.labelMoreInfoUrl.Text = "&URL for more info:"; // // buttonSave // this.buttonSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonSave.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonSave.Location = new System.Drawing.Point(73, 238); this.buttonSave.Name = "buttonSave"; this.buttonSave.TabIndex = 9; this.buttonSave.Text = "&Save"; this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click); // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonCancel.Location = new System.Drawing.Point(154, 238); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.TabIndex = 10; this.buttonCancel.Text = "Cancel"; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // MapPushpinForm // this.AcceptButton = this.buttonSave; this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.BackColor = System.Drawing.Color.White; this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(236, 268); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonSave); this.Controls.Add(this.textBoxMoreInfoUrl); this.Controls.Add(this.textBoxPhotoUrl); this.Controls.Add(this.textBoxNotes); this.Controls.Add(this.textBoxTitle); this.Controls.Add(this.labelMoreInfoUrl); this.Controls.Add(this.labelPhotoUrl); this.Controls.Add(this.labelNotes); this.Controls.Add(this.labelTitle); this.Name = "MapPushpinForm"; this.Text = "MapPushpinForm"; this.ResumeLayout(false); } #endregion } internal delegate void MapPushpinEditedHandler(MapPushpinInfo pushpinInfo); internal class MapPushpinInfo { public MapPushpinInfo(string title) { _title = title; } public string Title { get { return _title; } set { _title = value; } } private string _title; public string Notes { get { return _notes; } set { _notes = value; } } private string _notes = String.Empty; public string PhotoUrl { get { return _photoUrl; } set { _photoUrl = value; } } private string _photoUrl = String.Empty; public string MoreInfoUrl { get { return _moreInfoUrl; } set { _moreInfoUrl = value; } } private string _moreInfoUrl = String.Empty; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using TWCore.Compression; using TWCore.IO; using TWCore.Messaging; using TWCore.Reflection; using TWCore.Serialization; using TWCore.Serialization.MsgPack; using TWCore.Serialization.NSerializer; using TWCore.Serialization.PWSerializer; using TWCore.Serialization.PWSerializer.Deserializer; using TWCore.Serialization.RawSerializer; using TWCore.Serialization.Utf8Json; using TWCore.Serialization.WSerializer; using TWCore.Services; // ReSharper disable UnusedMember.Global // ReSharper disable InconsistentNaming // ReSharper disable RedundantArgumentDefaultValue // ReSharper disable FieldCanBeMadeReadOnly.Local // ReSharper disable RedundantAssignment // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable UnusedVariable namespace TWCore.Tests { /// <inheritdoc /> public class SerializerTest : ContainerParameterService { public SerializerTest() : base("serializertest", "Serializer Test") { } protected override void OnHandler(ParameterHandlerInfo info) { Core.Log.Warning("Starting Serializer TEST"); if (info.Arguments?.Contains("/complex") == true) { var file = "c:\\temp\\complex.test.nbin.gz"; var serializer = SerializerManager.GetByFileName(file); AssemblyResolverManager.RegisterDomain(new[] { @"C:\AGSW_GIT\Travel\src\Flights\Engines\Services\Agsw.Travel.Flights.Engines.Service\bin\Release\netcoreapp2.2" }); //AssemblyResolverManager.RegisterDomain(new[] { @"C:\Repo\AgswGit\Travel\src\Flights\Engines\Services\Agsw.Travel.Flights.Engines.Service\bin\Release\netcoreapp2.2" }); object value = null; try { value = serializer.DeserializeFromFile<object>(file); //value = rMsg.Body.GetValue(); } catch(DeserializerException exGO) { var jsonSerializer = new JsonTextSerializer { Indent = true }; jsonSerializer.SerializeToFile(exGO.Value, "c:\\temp\\complexObject-GenericObject.json"); var val = exGO.Value["Products"][5]; } RunTestEx(value, 500, null); //GC.Collect(); //GC.WaitForFullGCComplete(); //RunTestEx(value, 200, new GZipCompressor()); //GC.Collect(); //GC.WaitForFullGCComplete(); //RunTestEx(value, 200, new DeflateCompressor()); return; } var sTest = new STest { FirstName = "Daniel", LastName = "Redondo", Age = 33, value = 166 }; var collection = new List<List<STest>>(); for (var i = 0; i <= 10; i++) { var colSTest = new List<STest> { sTest,sTest,sTest,sTest,sTest,sTest, sTest,sTest,sTest,sTest,sTest,sTest, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+0, Age = 1 , Brother = sTest }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+1, Age =2 , Brother = sTest }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+2, Age = 3 , Brother = sTest }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+3, Age = 4 , Brother = sTest }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+4, Age = 5 , Brother = sTest}, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+5, Age = 6 , Brother = sTest}, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+6, Age = 7 , Brother = sTest}, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+7, Age = 8 , Brother = sTest}, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+8, Age = 9 , Brother = sTest}, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+9, Age = 10 , Brother = sTest }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+10, Age = 11 }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+11, Age = 12 }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+12, Age = 13 }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+13, Age = 14 }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+14, Age = 15 }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+15, Age = 16 }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+16, Age = 17 }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+17, Age = 18 }, new STest { FirstName = "Person" , LastName = "Person" + i + "." + i+18, Age = 19 }, //new STest2 { FirstName = "Person" , LastName = "Person" + i + "." + i+19, Age = 20, New = "This is a test" } }; collection.Add(colSTest); } var lt = new List<STest> { new STest { FirstName = "Name1" , LastName = "LName1" , Age = 11 }, //new STest2 { FirstName = "Name2" , LastName = "LName2", Age = 20, New = "This is a test" } }; var lt2 = new List<Test3> { new Test3 { Values = new List<int> {2, 3, 4, 5} }, new Test3 { Values = new List<int> {10, 11, 12, 13} } }; var dct = new Dictionary<string, int> { ["Value1"] = 1, ["Value2"] = 2, ["Value3"] = 3, }; var colClone = collection[0].DeepClone(); var clone = collection.DeepClone(); if (info.Arguments?.Contains("/parallel") == true) { RunSingleTest(collection[0], 2, false); Core.Log.InfoBasic("Press ENTER to Start:"); Console.ReadLine(); Task.WaitAll( Enumerable.Range(0, 8).Select(i => Task.Run(() => RunSingleTest(collection[0], 200_000, false))).ToArray() ); Console.ReadLine(); return; } RunTest(collection[0], 200_000, false); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void RunTest(object value, int times, bool useGZip) { var vType = value?.GetType() ?? typeof(object); var compressor = useGZip ? CompressorManager.GetByEncodingType("gzip") : null; var memStream = new RecycleMemoryStream(); var jsonSerializer = new JsonTextSerializer { Compressor = compressor }; var xmlSerializer = new XmlTextSerializer { Compressor = compressor }; var binarySerializer = new BinaryFormatterSerializer { Compressor = compressor }; var ut8JsonSerializer = new Utf8JsonTextSerializer { Compressor = compressor }; var msgPackSerializer = new MsgPackSerializer { Compressor = compressor }; var nBinarySerializer = new NBinarySerializer { Compressor = compressor }; var rawBinarySerializer = new RawBinarySerializer { Compressor = compressor }; var wBinarySerializer = new WBinarySerializer { Compressor = compressor }; var pwBinarySerializer = new PWBinarySerializer { Compressor = compressor }; Core.Log.Warning("Running Serializer Test. Use GZIP = {0}", useGZip); Core.Log.WriteEmptyLine(); Core.Log.InfoBasic("By size:"); Core.Log.InfoBasic("\tJson Bytes Count: {0}", SerializerSizeProcess(value, vType, jsonSerializer)); Core.Log.InfoBasic("\tXml Bytes Count: {0}", SerializerSizeProcess(value, vType, xmlSerializer)); Core.Log.InfoBasic("\tBinaryFormatter Bytes Count: {0}", SerializerSizeProcess(value, vType, binarySerializer)); Core.Log.InfoBasic("\tUtf8Json Bytes Count: {0}", SerializerSizeProcess(value, vType, ut8JsonSerializer)); Core.Log.InfoBasic("\tMessagePack Bytes Count: {0}", SerializerSizeProcess(value, vType, msgPackSerializer)); Core.Log.InfoBasic("\tNBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, nBinarySerializer)); Core.Log.InfoBasic("\tRawBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, rawBinarySerializer)); Core.Log.InfoBasic("\tWBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, wBinarySerializer)); Core.Log.InfoBasic("\tPortable WBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, pwBinarySerializer)); Core.Log.WriteEmptyLine(); Core.Log.InfoBasic("By Times: {0}", times); SerializerProcess("Json", value, vType, times, jsonSerializer, memStream); SerializerProcess("Utf8Json", value, vType, times, ut8JsonSerializer, memStream); SerializerProcess("NBinary", value, vType, times, nBinarySerializer, memStream); SerializerProcess("RawBinary", value, vType, times, rawBinarySerializer, memStream); SerializerProcess("WBinary", value, vType, times, wBinarySerializer, memStream); SerializerProcess("PWBinary", value, vType, times, pwBinarySerializer, memStream); Console.ReadLine(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void RunTestEx(object value, int times, ICompressor compressor) { var vType = value?.GetType() ?? typeof(object); //var memStream = new MemoryStream(); var memStream = new RecycleMemoryStream(); //var jsonSerializer = new JsonTextSerializer { Compressor = compressor }; //var ut8JsonSerializer = new Utf8JsonTextSerializer { Compressor = compressor }; var nBinarySerializer = new NBinarySerializer { Compressor = compressor }; var rawBinarySerializer = new RawBinarySerializer { Compressor = compressor }; Core.Log.Warning("Running Serializer Test. Use Compressor = {0}", compressor?.EncodingType ?? "(no)"); Core.Log.WriteEmptyLine(); Core.Log.InfoBasic("By size:"); //Core.Log.InfoBasic("\tNewtonsoft Bytes Count: {0}", SerializerSizeProcess(value, vType, jsonSerializer)); //Core.Log.InfoBasic("\tUTF8Json Bytes Count: {0}", SerializerSizeProcess(value, vType, ut8JsonSerializer)); Core.Log.InfoBasic("\tNBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, nBinarySerializer)); Core.Log.InfoBasic("\tRawBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, rawBinarySerializer)); Core.Log.WriteEmptyLine(); Console.ReadLine(); Core.Log.InfoBasic("By Times: {0}", times); //SerializerProcess("Json", value, vType, times, jsonSerializer, memStream); //SerializerProcess("UTF8Json", value, vType, times, ut8JsonSerializer, memStream); SerializerProcess("NBinary", value, vType, times, nBinarySerializer, memStream); SerializerProcess("RawBinary", value, vType, times, rawBinarySerializer, memStream); Console.ReadLine(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void RunSingleTest(object value, int times, bool useGZip) { var vType = value?.GetType() ?? typeof(object); var memStream = new RecycleMemoryStream(); var compressor = useGZip ? CompressorManager.GetByEncodingType("gzip") : null; var nBinarySerializer = new NBinarySerializer { Compressor = compressor }; Core.Log.Warning("Running Serializer Test. Use GZIP = {0}, Times = {1}", useGZip, times); SerializerProcess("NBinary", value, vType, times, nBinarySerializer, memStream, false); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static string SerializerSizeProcess(object value, Type valueType, ISerializer serializer) { var memStream = new MemoryStream(); serializer.Serialize(value, valueType, memStream); memStream.Position = 0; var obj = serializer.Deserialize(memStream, valueType); return memStream.Length.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SerializerProcess(string name, object value, Type valueType, int times, ISerializer serializer, Stream memStream, bool sleep = true) { double totalValue; memStream.Position = 0; if (sleep) { GC.Collect(); GC.WaitForPendingFinalizers(); Thread.Sleep(1500); } using (var w = Watch.Create(name + " SERIALIZER")) { for (var i = 0; i < times; i++) { serializer.Serialize(value, valueType, memStream); memStream.Position = 0; } totalValue = w.GlobalElapsedMilliseconds; } Core.Log.InfoBasic("\t" + name + " SERIALIZER - Average Time: {0}ms", totalValue / times); if (sleep) { GC.Collect(); GC.WaitForPendingFinalizers(); Thread.Sleep(1500); } using (var w = Watch.Create(name + " DESERIALIZER")) { for (var i = 0; i < times; i++) { serializer.Deserialize(memStream, valueType); memStream.Position = 0; } totalValue = w.GlobalElapsedMilliseconds; } Core.Log.InfoBasic("\t"+ name + " DESERIALIZER - Average Time: {0}ms", totalValue / times); if (sleep) Thread.Sleep(1000); Core.Log.WriteEmptyLine(); } } [Serializable] public sealed class STest //: INSerializable { public int value; public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public STest Brother { get; set; } //void INSerializable.Serialize(SerializersTable table) //{ // table.WriteValue(FirstName); // table.WriteValue(LastName); // table.WriteValue(Age); // table.WriteGenericValue(Brother); //} } //[Serializable] //public class STest2 : STest//, INSerializable //{ // public string New { get; set; } // //void INSerializable.Serialize(SerializersTable table) // //{ // // table.WriteValue(FirstName); // // table.WriteValue(LastName); // // table.WriteValue(Age); // // table.WriteGenericValue(Brother); // // table.WriteValue(New); // //} //} public sealed class Test3 { public List<int> Values { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Xunit; namespace System.Drawing.Primitives.Tests { public partial class ColorTests { public static readonly IEnumerable<object[]> NamedArgbValues = new[] { new object[] {"Transparent", 0, 255, 255, 255}, new object[] {"AliceBlue", 255, 240, 248, 255}, new object[] {"AntiqueWhite", 255, 250, 235, 215}, new object[] {"Aqua", 255, 0, 255, 255}, new object[] {"Aquamarine", 255, 127, 255, 212}, new object[] {"Azure", 255, 240, 255, 255}, new object[] {"Beige", 255, 245, 245, 220}, new object[] {"Bisque", 255, 255, 228, 196}, new object[] {"Black", 255, 0, 0, 0}, new object[] {"BlanchedAlmond", 255, 255, 235, 205}, new object[] {"Blue", 255, 0, 0, 255}, new object[] {"BlueViolet", 255, 138, 43, 226}, new object[] {"Brown", 255, 165, 42, 42}, new object[] {"BurlyWood", 255, 222, 184, 135}, new object[] {"CadetBlue", 255, 95, 158, 160}, new object[] {"Chartreuse", 255, 127, 255, 0}, new object[] {"Chocolate", 255, 210, 105, 30}, new object[] {"Coral", 255, 255, 127, 80}, new object[] {"CornflowerBlue", 255, 100, 149, 237}, new object[] {"Cornsilk", 255, 255, 248, 220}, new object[] {"Crimson", 255, 220, 20, 60}, new object[] {"Cyan", 255, 0, 255, 255}, new object[] {"DarkBlue", 255, 0, 0, 139}, new object[] {"DarkCyan", 255, 0, 139, 139}, new object[] {"DarkGoldenrod", 255, 184, 134, 11}, new object[] {"DarkGray", 255, 169, 169, 169}, new object[] {"DarkGreen", 255, 0, 100, 0}, new object[] {"DarkKhaki", 255, 189, 183, 107}, new object[] {"DarkMagenta", 255, 139, 0, 139}, new object[] {"DarkOliveGreen", 255, 85, 107, 47}, new object[] {"DarkOrange", 255, 255, 140, 0}, new object[] {"DarkOrchid", 255, 153, 50, 204}, new object[] {"DarkRed", 255, 139, 0, 0}, new object[] {"DarkSalmon", 255, 233, 150, 122}, new object[] {"DarkSeaGreen", 255, 143, 188, 139}, new object[] {"DarkSlateBlue", 255, 72, 61, 139}, new object[] {"DarkSlateGray", 255, 47, 79, 79}, new object[] {"DarkTurquoise", 255, 0, 206, 209}, new object[] {"DarkViolet", 255, 148, 0, 211}, new object[] {"DeepPink", 255, 255, 20, 147}, new object[] {"DeepSkyBlue", 255, 0, 191, 255}, new object[] {"DimGray", 255, 105, 105, 105}, new object[] {"DodgerBlue", 255, 30, 144, 255}, new object[] {"Firebrick", 255, 178, 34, 34}, new object[] {"FloralWhite", 255, 255, 250, 240}, new object[] {"ForestGreen", 255, 34, 139, 34}, new object[] {"Fuchsia", 255, 255, 0, 255}, new object[] {"Gainsboro", 255, 220, 220, 220}, new object[] {"GhostWhite", 255, 248, 248, 255}, new object[] {"Gold", 255, 255, 215, 0}, new object[] {"Goldenrod", 255, 218, 165, 32}, new object[] {"Gray", 255, 128, 128, 128}, new object[] {"Green", 255, 0, 128, 0}, new object[] {"GreenYellow", 255, 173, 255, 47}, new object[] {"Honeydew", 255, 240, 255, 240}, new object[] {"HotPink", 255, 255, 105, 180}, new object[] {"IndianRed", 255, 205, 92, 92}, new object[] {"Indigo", 255, 75, 0, 130}, new object[] {"Ivory", 255, 255, 255, 240}, new object[] {"Khaki", 255, 240, 230, 140}, new object[] {"Lavender", 255, 230, 230, 250}, new object[] {"LavenderBlush", 255, 255, 240, 245}, new object[] {"LawnGreen", 255, 124, 252, 0}, new object[] {"LemonChiffon", 255, 255, 250, 205}, new object[] {"LightBlue", 255, 173, 216, 230}, new object[] {"LightCoral", 255, 240, 128, 128}, new object[] {"LightCyan", 255, 224, 255, 255}, new object[] {"LightGoldenrodYellow", 255, 250, 250, 210}, new object[] {"LightGreen", 255, 144, 238, 144}, new object[] {"LightGray", 255, 211, 211, 211}, new object[] {"LightPink", 255, 255, 182, 193}, new object[] {"LightSalmon", 255, 255, 160, 122}, new object[] {"LightSeaGreen", 255, 32, 178, 170}, new object[] {"LightSkyBlue", 255, 135, 206, 250}, new object[] {"LightSlateGray", 255, 119, 136, 153}, new object[] {"LightSteelBlue", 255, 176, 196, 222}, new object[] {"LightYellow", 255, 255, 255, 224}, new object[] {"Lime", 255, 0, 255, 0}, new object[] {"LimeGreen", 255, 50, 205, 50}, new object[] {"Linen", 255, 250, 240, 230}, new object[] {"Magenta", 255, 255, 0, 255}, new object[] {"Maroon", 255, 128, 0, 0}, new object[] {"MediumAquamarine", 255, 102, 205, 170}, new object[] {"MediumBlue", 255, 0, 0, 205}, new object[] {"MediumOrchid", 255, 186, 85, 211}, new object[] {"MediumPurple", 255, 147, 112, 219}, new object[] {"MediumSeaGreen", 255, 60, 179, 113}, new object[] {"MediumSlateBlue", 255, 123, 104, 238}, new object[] {"MediumSpringGreen", 255, 0, 250, 154}, new object[] {"MediumTurquoise", 255, 72, 209, 204}, new object[] {"MediumVioletRed", 255, 199, 21, 133}, new object[] {"MidnightBlue", 255, 25, 25, 112}, new object[] {"MintCream", 255, 245, 255, 250}, new object[] {"MistyRose", 255, 255, 228, 225}, new object[] {"Moccasin", 255, 255, 228, 181}, new object[] {"NavajoWhite", 255, 255, 222, 173}, new object[] {"Navy", 255, 0, 0, 128}, new object[] {"OldLace", 255, 253, 245, 230}, new object[] {"Olive", 255, 128, 128, 0}, new object[] {"OliveDrab", 255, 107, 142, 35}, new object[] {"Orange", 255, 255, 165, 0}, new object[] {"OrangeRed", 255, 255, 69, 0}, new object[] {"Orchid", 255, 218, 112, 214}, new object[] {"PaleGoldenrod", 255, 238, 232, 170}, new object[] {"PaleGreen", 255, 152, 251, 152}, new object[] {"PaleTurquoise", 255, 175, 238, 238}, new object[] {"PaleVioletRed", 255, 219, 112, 147}, new object[] {"PapayaWhip", 255, 255, 239, 213}, new object[] {"PeachPuff", 255, 255, 218, 185}, new object[] {"Peru", 255, 205, 133, 63}, new object[] {"Pink", 255, 255, 192, 203}, new object[] {"Plum", 255, 221, 160, 221}, new object[] {"PowderBlue", 255, 176, 224, 230}, new object[] {"Purple", 255, 128, 0, 128}, new object[] {"Red", 255, 255, 0, 0}, new object[] {"RosyBrown", 255, 188, 143, 143}, new object[] {"RoyalBlue", 255, 65, 105, 225}, new object[] {"SaddleBrown", 255, 139, 69, 19}, new object[] {"Salmon", 255, 250, 128, 114}, new object[] {"SandyBrown", 255, 244, 164, 96}, new object[] {"SeaGreen", 255, 46, 139, 87}, new object[] {"SeaShell", 255, 255, 245, 238}, new object[] {"Sienna", 255, 160, 82, 45}, new object[] {"Silver", 255, 192, 192, 192}, new object[] {"SkyBlue", 255, 135, 206, 235}, new object[] {"SlateBlue", 255, 106, 90, 205}, new object[] {"SlateGray", 255, 112, 128, 144}, new object[] {"Snow", 255, 255, 250, 250}, new object[] {"SpringGreen", 255, 0, 255, 127}, new object[] {"SteelBlue", 255, 70, 130, 180}, new object[] {"Tan", 255, 210, 180, 140}, new object[] {"Teal", 255, 0, 128, 128}, new object[] {"Thistle", 255, 216, 191, 216}, new object[] {"Tomato", 255, 255, 99, 71}, new object[] {"Turquoise", 255, 64, 224, 208}, new object[] {"Violet", 255, 238, 130, 238}, new object[] {"Wheat", 255, 245, 222, 179}, new object[] {"White", 255, 255, 255, 255}, new object[] {"WhiteSmoke", 255, 245, 245, 245}, new object[] {"Yellow", 255, 255, 255, 0}, new object[] {"YellowGreen", 255, 154, 205, 50}, }; public static readonly IEnumerable<object[]> ColorNames = typeof(Color).GetProperties() .Where(p => p.PropertyType == typeof(Color)) .Select(p => new object[] { p.Name }) .ToArray(); private Color? GetColorByProperty(string name) { return (Color?)typeof(Color).GetProperty(name)?.GetValue(null); } [Theory] [MemberData(nameof(NamedArgbValues))] public void ArgbValues(string name, int alpha, int red, int green, int blue) { Color? color = GetColorByProperty(name); if (color.HasValue) { Assert.Equal(alpha, color.Value.A); Assert.Equal(red, color.Value.R); Assert.Equal(green, color.Value.G); Assert.Equal(blue, color.Value.B); } } [Theory] [InlineData(255, 255, 255, 255)] [InlineData(0, 0, 0, 0)] [InlineData(255, 0, 0, 0)] [InlineData(0, 255, 0, 0)] [InlineData(0, 0, 255, 0)] [InlineData(0, 0, 0, 255)] [InlineData(1, 2, 3, 4)] public void FromArgb_Roundtrips(int a, int r, int g, int b) { Color c1 = Color.FromArgb(unchecked((int)((uint)a << 24 | (uint)r << 16 | (uint)g << 8 | (uint)b))); Assert.Equal(a, c1.A); Assert.Equal(r, c1.R); Assert.Equal(g, c1.G); Assert.Equal(b, c1.B); Color c2 = Color.FromArgb(a, r, g, b); Assert.Equal(a, c2.A); Assert.Equal(r, c2.R); Assert.Equal(g, c2.G); Assert.Equal(b, c2.B); Color c3 = Color.FromArgb(r, g, b); Assert.Equal(255, c3.A); Assert.Equal(r, c3.R); Assert.Equal(g, c3.G); Assert.Equal(b, c3.B); } [Fact] public void Empty() { Assert.True(Color.Empty.IsEmpty); Assert.False(Color.FromArgb(0, Color.Black).IsEmpty); } [Fact] public void IsNamedColor() { Assert.True(Color.AliceBlue.IsNamedColor); Assert.True(Color.FromName("AliceBlue").IsNamedColor); Assert.False(Color.FromArgb(Color.AliceBlue.A, Color.AliceBlue.R, Color.AliceBlue.G, Color.AliceBlue.B).IsNamedColor); } [Theory] [MemberData(nameof(ColorNames))] public void KnownNames(string name) { Assert.Equal(name, Color.FromName(name).Name); var colorByProperty = GetColorByProperty(name); if (colorByProperty.HasValue) { Assert.Equal(name, colorByProperty.Value.Name); } } [Fact] public void Name() { Assert.Equal("1122ccff", Color.FromArgb(0x11, 0x22, 0xcc, 0xff).Name); } public static IEnumerable<object[]> ColorNamePairs => ColorNames.Zip(ColorNames.Skip(1), (l, r) => new[] { l[0], r[0] }); [Theory] [MemberData(nameof(ColorNamePairs))] public void GetHashCode(string name1, string name2) { Assert.NotEqual(name1, name2); Color c1 = GetColorByProperty(name1) ?? Color.FromName(name1); Color c2 = GetColorByProperty(name2) ?? Color.FromName(name2); Assert.NotEqual(c2.GetHashCode(), c1.GetHashCode()); Assert.Equal(c1.GetHashCode(), Color.FromName(name1).GetHashCode()); } [Theory] [InlineData(0x11cc8833, 0x11, 0xcc, 0x88, 0x33)] [InlineData(unchecked((int)0xf1cc8833), 0xf1, 0xcc, 0x88, 0x33)] public void ToArgb(int argb, int alpha, int red, int green, int blue) { Assert.Equal(argb, Color.FromArgb(alpha, red, green, blue).ToArgb()); } [Fact] public void ToStringEmpty() { Assert.Equal("Color [Empty]", Color.Empty.ToString()); } [Theory] [MemberData(nameof(ColorNames))] [InlineData("SomeUnknownColorName")] public void ToStringNamed(string name) { string expected = $"Color [{name}]"; Assert.Equal(expected, Color.FromName(name).ToString()); } [Theory] [InlineData("Color [A=0, R=0, G=0, B=0]", 0, 0, 0, 0)] [InlineData("Color [A=1, R=2, G=3, B=4]", 1, 2, 3, 4)] [InlineData("Color [A=255, R=255, G=255, B=255]", 255, 255, 255, 255)] public void ToStringArgb(string expected, int alpha, int red, int green, int blue) { Assert.Equal(expected, Color.FromArgb(alpha, red, green, blue).ToString()); } public static IEnumerable<object[]> InvalidValues => new[] { new object[] {-1}, new object[] {256}, }; [Theory] [MemberData(nameof(InvalidValues))] public void FromArgb_InvalidAlpha(int alpha) { AssertExtensions.Throws<ArgumentException>(null, () => { Color.FromArgb(alpha, Color.Red); }); AssertExtensions.Throws<ArgumentException>(null, () => { Color.FromArgb(alpha, 0, 0, 0); }); } [Theory] [MemberData(nameof(InvalidValues))] public void FromArgb_InvalidRed(int red) { AssertExtensions.Throws<ArgumentException>(null, () => { Color.FromArgb(red, 0, 0); }); AssertExtensions.Throws<ArgumentException>(null, () => { Color.FromArgb(0, red, 0, 0); }); } [Theory] [MemberData(nameof(InvalidValues))] public void FromArgb_InvalidGreen(int green) { AssertExtensions.Throws<ArgumentException>(null, () => { Color.FromArgb(0, green, 0); }); AssertExtensions.Throws<ArgumentException>(null, () => { Color.FromArgb(0, 0, green, 0); }); } [Theory] [MemberData(nameof(InvalidValues))] public void FromArgb_InvalidBlue(int blue) { AssertExtensions.Throws<ArgumentException>(null, () => { Color.FromArgb(0, 0, blue); }); AssertExtensions.Throws<ArgumentException>(null, () => { Color.FromArgb(0, 0, 0, blue); }); } [Fact] public void FromName_Invalid() { Color c = Color.FromName("OingoBoingo"); Assert.True(c.IsNamedColor); Assert.Equal(0, c.ToArgb()); Assert.Equal("OingoBoingo", c.Name); } private void CheckRed(Color color) { Assert.Equal(255, color.A); Assert.Equal(255, color.R); Assert.Equal(0, color.G); Assert.Equal(0, color.B); Assert.Equal("Red", color.Name); Assert.False(color.IsEmpty, "IsEmpty"); Assert.True(color.IsNamedColor, "IsNamedColor"); } [Theory] [InlineData(0, 0, 0, 0f)] [InlineData(255, 255, 255, 1f)] [InlineData(255, 0, 0, 0.5f)] [InlineData(0, 255, 0, 0.5f)] [InlineData(0, 0, 255, 0.5f)] [InlineData(255, 255, 0, 0.5f)] [InlineData(255, 0, 255, 0.5f)] [InlineData(0, 255, 255, 0.5f)] [InlineData(51, 255, 255, 0.6f)] [InlineData(255, 51, 255, 0.6f)] [InlineData(255, 255, 51, 0.6f)] [InlineData(255, 51, 51, 0.6f)] [InlineData(51, 255, 51, 0.6f)] [InlineData(51, 51, 255, 0.6f)] [InlineData(51, 51, 51, 0.2f)] public void GetBrightness(int r, int g, int b, float expected) { Assert.Equal(expected, Color.FromArgb(r, g, b).GetBrightness()); } [Theory] [InlineData(0, 0, 0, 0f)] [InlineData(255, 255, 255, 0f)] [InlineData(255, 0, 0, 0f)] [InlineData(0, 255, 0, 120f)] [InlineData(0, 0, 255, 240f)] [InlineData(255, 255, 0, 60f)] [InlineData(255, 0, 255, 300f)] [InlineData(0, 255, 255, 180f)] [InlineData(51, 255, 255, 180f)] [InlineData(255, 51, 255, 300f)] [InlineData(255, 255, 51, 60f)] [InlineData(255, 51, 51, 0f)] [InlineData(51, 255, 51, 120f)] [InlineData(51, 51, 255, 240f)] [InlineData(51, 51, 51, 0f)] public void GetHue(int r, int g, int b, float expected) { Assert.Equal(expected, Color.FromArgb(r, g, b).GetHue()); } [Theory] [InlineData(0, 0, 0, 0f)] [InlineData(255, 255, 255, 0f)] [InlineData(255, 0, 0, 1f)] [InlineData(0, 255, 0, 1f)] [InlineData(0, 0, 255, 1f)] [InlineData(255, 255, 0, 1f)] [InlineData(255, 0, 255, 1f)] [InlineData(0, 255, 255, 1f)] [InlineData(51, 255, 255, 1f)] [InlineData(255, 51, 255, 1f)] [InlineData(255, 255, 51, 1f)] [InlineData(255, 51, 51, 1f)] [InlineData(51, 255, 51, 1f)] [InlineData(51, 51, 255, 1f)] [InlineData(51, 51, 51, 0f)] [InlineData(204, 51, 51, 0.6f)] [InlineData(221, 221, 204, 0.2f)] public void GetSaturation(int r, int g, int b, float expected) { Assert.Equal(expected, Color.FromArgb(r, g, b).GetSaturation()); } public static IEnumerable<object[]> Equality_MemberData() { yield return new object[] { Color.AliceBlue, Color.AliceBlue, true }; yield return new object[] { Color.AliceBlue, Color.White, false}; yield return new object[] { Color.AliceBlue, Color.Black, false }; yield return new object[] { Color.FromArgb(255, 1, 2, 3), Color.FromArgb(255, 1, 2, 3), true }; yield return new object[] { Color.FromArgb(255, 1, 2, 3), Color.FromArgb(1, 2, 3), true }; yield return new object[] { Color.FromArgb(0, 1, 2, 3), Color.FromArgb(255, 1, 2, 3), false }; yield return new object[] { Color.FromArgb(0, 1, 2, 3), Color.FromArgb(1, 2, 3), false }; yield return new object[] { Color.FromArgb(0, 1, 2, 3), Color.FromArgb(0, 0, 2, 3), false }; yield return new object[] { Color.FromArgb(0, 1, 2, 3), Color.FromArgb(0, 1, 0, 3), false }; yield return new object[] { Color.FromArgb(0, 1, 2, 3), Color.FromArgb(0, 1, 2, 0), false }; yield return new object[] { Color.FromName("SomeName"), Color.FromName("SomeName"), true }; yield return new object[] { Color.FromName("SomeName"), Color.FromName("SomeOtherName"), false }; yield return new object[] { Color.FromArgb(0, 0, 0), default(Color), false }; string someNameConstructed = string.Join("", "Some", "Name"); Assert.NotSame("SomeName", someNameConstructed); // If this fails the above must be changed so this test is correct. yield return new object[] {Color.FromName("SomeName"), Color.FromName(someNameConstructed), true}; } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // desktop incorrectly does "name.Equals(name)" in Equals [Theory] [MemberData(nameof(Equality_MemberData))] public void Equality(Color left, Color right, bool expected) { Assert.True(left.Equals(left), "left should always Equals itself"); Assert.True(right.Equals(right), "right should always Equals itself"); Assert.True(left.Equals((object)left), "left should always Equals itself"); Assert.True(right.Equals((object)right), "right should always Equals itself"); Assert.Equal(expected, left == right); Assert.Equal(expected, right == left); Assert.Equal(expected, left.Equals(right)); Assert.Equal(expected, right.Equals(left)); Assert.Equal(expected, left.Equals((object)right)); Assert.Equal(expected, right.Equals((object)left)); Assert.Equal(!expected, left != right); Assert.Equal(!expected, right != left); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttributesAreValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(Color.Aquamarine); DebuggerAttributes.ValidateDebuggerDisplayReferences(Color.FromArgb(4, 3, 2, 1)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans.Concurrency; using Orleans.Configuration; using Orleans.Runtime; namespace Orleans.Streams { internal class PersistentStreamPullingAgent : SystemTarget, IPersistentStreamPullingAgent { private static readonly IBackoffProvider DeliveryBackoffProvider = new ExponentialBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(1)); private static readonly IBackoffProvider ReadLoopBackoff = new ExponentialBackoff(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(1)); private const int ReadLoopRetryMax = 6; private static readonly IStreamFilterPredicateWrapper DefaultStreamFilter = new DefaultStreamFilterPredicateWrapper(); private const int StreamInactivityCheckFrequency = 10; private readonly string streamProviderName; private readonly IStreamPubSub pubSub; private readonly Dictionary<StreamId, StreamConsumerCollection> pubSubCache; private readonly SafeRandom safeRandom; private readonly StreamPullingAgentOptions options; private readonly ILogger logger; private readonly CounterStatistic numReadMessagesCounter; private readonly CounterStatistic numSentMessagesCounter; private int numMessages; private IQueueAdapter queueAdapter; private IQueueCache queueCache; private IQueueAdapterReceiver receiver; private IStreamFailureHandler streamFailureHandler; private DateTime lastTimeCleanedPubSubCache; private IDisposable timer; internal readonly QueueId QueueId; private Task receiverInitTask; private bool IsShutdown => timer == null; private string StatisticUniquePostfix => streamProviderName + "." + QueueId; internal PersistentStreamPullingAgent( GrainId id, string strProviderName, IStreamProviderRuntime runtime, ILoggerFactory loggerFactory, IStreamPubSub streamPubSub, QueueId queueId, StreamPullingAgentOptions options) : base(id, runtime.ExecutingSiloAddress, true, loggerFactory) { if (runtime == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: runtime reference should not be null"); if (strProviderName == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: strProviderName should not be null"); QueueId = queueId; streamProviderName = strProviderName; pubSub = streamPubSub; pubSubCache = new Dictionary<StreamId, StreamConsumerCollection>(); safeRandom = new SafeRandom(); this.options = options; numMessages = 0; logger = runtime.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger($"{this.GetType().Namespace}.{((ISystemTargetBase)this).GrainId}.{streamProviderName}"); logger.Info(ErrorCode.PersistentStreamPullingAgent_01, "Created {0} {1} for Stream Provider {2} on silo {3} for Queue {4}.", GetType().Name, ((ISystemTargetBase)this).GrainId.ToDetailedString(), streamProviderName, Silo, QueueId.ToStringWithHashCode()); numReadMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_READ_MESSAGES, StatisticUniquePostfix)); numSentMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_SENT_MESSAGES, StatisticUniquePostfix)); // TODO: move queue cache size statistics tracking into queue cache implementation once Telemetry APIs and LogStatistics have been reconciled. //IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, statUniquePostfix), () => queueCache != null ? queueCache.Size : 0); } /// <summary> /// Take responsibility for a new queues that was assigned to me via a new range. /// We first store the new queue in our internal data structure, try to initialize it and start a pumping timer. /// ERROR HANDLING: /// The responsibility to handle initialization and shutdown failures is inside the INewQueueAdapterReceiver code. /// The agent will call Initialize once and log an error. It will not call initialize again. /// The receiver itself may attempt later to recover from this error and do initialization again. /// The agent will assume initialization has succeeded and will subsequently start calling pumping receive. /// Same applies to shutdown. /// </summary> /// <param name="qAdapter"></param> /// <param name="queueAdapterCache"></param> /// <param name="failureHandler"></param> /// <returns></returns> public Task Initialize(Immutable<IQueueAdapter> qAdapter, Immutable<IQueueAdapterCache> queueAdapterCache, Immutable<IStreamFailureHandler> failureHandler) { if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null"); if (failureHandler.Value == null) throw new ArgumentNullException("failureHandler", "Init: streamDeliveryFailureHandler should not be null"); return OrleansTaskExtentions.WrapInTask(() => InitializeInternal(qAdapter.Value, queueAdapterCache.Value, failureHandler.Value)); } private void InitializeInternal(IQueueAdapter qAdapter, IQueueAdapterCache queueAdapterCache, IStreamFailureHandler failureHandler) { logger.Info(ErrorCode.PersistentStreamPullingAgent_02, "Init of {0} {1} on silo {2} for queue {3}.", GetType().Name, ((ISystemTargetBase)this).GrainId.ToDetailedString(), Silo, QueueId.ToStringWithHashCode()); // Remove cast once we cleanup queueAdapter = qAdapter; streamFailureHandler = failureHandler; lastTimeCleanedPubSubCache = DateTime.UtcNow; try { receiver = queueAdapter.CreateReceiver(QueueId); } catch (Exception exc) { logger.Error(ErrorCode.PersistentStreamPullingAgent_02, "Exception while calling IQueueAdapter.CreateNewReceiver.", exc); throw; } try { if (queueAdapterCache != null) { queueCache = queueAdapterCache.CreateQueueCache(QueueId); } } catch (Exception exc) { logger.Error(ErrorCode.PersistentStreamPullingAgent_23, "Exception while calling IQueueAdapterCache.CreateQueueCache.", exc); throw; } try { receiverInitTask = OrleansTaskExtentions.SafeExecute(() => receiver.Initialize(this.options.InitQueueTimeout)) .LogException(logger, ErrorCode.PersistentStreamPullingAgent_03, $"QueueAdapterReceiver {QueueId.ToStringWithHashCode()} failed to Initialize."); receiverInitTask.Ignore(); } catch { // Just ignore this exception and proceed as if Initialize has succeeded. // We already logged individual exceptions for individual calls to Initialize. No need to log again. } // Setup a reader for a new receiver. // Even if the receiver failed to initialise, treat it as OK and start pumping it. It's receiver responsibility to retry initialization. var randomTimerOffset = safeRandom.NextTimeSpan(this.options.GetQueueMsgsTimerPeriod); timer = RegisterTimer(AsyncTimerCallback, QueueId, randomTimerOffset, this.options.GetQueueMsgsTimerPeriod); IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_PUBSUB_CACHE_SIZE, StatisticUniquePostfix), () => pubSubCache.Count); logger.Info((int)ErrorCode.PersistentStreamPullingAgent_04, "Taking queue {0} under my responsibility.", QueueId.ToStringWithHashCode()); } public async Task Shutdown() { // Stop pulling from queues that are not in my range anymore. logger.Info(ErrorCode.PersistentStreamPullingAgent_05, "Shutdown of {0} responsible for queue: {1}", GetType().Name, QueueId.ToStringWithHashCode()); if (timer != null) { IDisposable tmp = timer; timer = null; Utils.SafeExecute(tmp.Dispose, this.logger); } this.queueCache = null; Task localReceiverInitTask = receiverInitTask; if (localReceiverInitTask != null) { try { await localReceiverInitTask; receiverInitTask = null; } catch (Exception) { receiverInitTask = null; // squelch } } try { IQueueAdapterReceiver localReceiver = this.receiver; this.receiver = null; if (localReceiver != null) { var task = OrleansTaskExtentions.SafeExecute(() => localReceiver.Shutdown(this.options.InitQueueTimeout)); task = task.LogException(logger, ErrorCode.PersistentStreamPullingAgent_07, $"QueueAdapterReceiver {QueueId} failed to Shutdown."); await task; } } catch { // Just ignore this exception and proceed as if Shutdown has succeeded. // We already logged individual exceptions for individual calls to Shutdown. No need to log again. } var unregisterTasks = new List<Task>(); var meAsStreamProducer = this.AsReference<IStreamProducerExtension>(); foreach (var tuple in pubSubCache) { tuple.Value.DisposeAll(logger); var streamId = tuple.Key; logger.Info(ErrorCode.PersistentStreamPullingAgent_06, "Unregister PersistentStreamPullingAgent Producer for stream {0}.", streamId); unregisterTasks.Add(pubSub.UnregisterProducer(streamId, streamProviderName, meAsStreamProducer)); } try { await Task.WhenAll(unregisterTasks); } catch (Exception exc) { logger.Warn(ErrorCode.PersistentStreamPullingAgent_08, "Failed to unregister myself as stream producer to some streams that used to be in my responsibility.", exc); } pubSubCache.Clear(); IntValueStatistic.Delete(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_PUBSUB_CACHE_SIZE, StatisticUniquePostfix)); //IntValueStatistic.Delete(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, StatisticUniquePostfix)); } public Task AddSubscriber( GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.PersistentStreamPullingAgent_09, "AddSubscriber: Stream={0} Subscriber={1}.", streamId, streamConsumer); // cannot await here because explicit consumers trigger this call, so it could cause a deadlock. AddSubscriber_Impl(subscriptionId, streamId, streamConsumer, null, filter) .LogException(logger, ErrorCode.PersistentStreamPullingAgent_26, $"Failed to add subscription for stream {streamId}.") .Ignore(); return Task.CompletedTask; } // Called by rendezvous when new remote subscriber subscribes to this stream. private async Task AddSubscriber_Impl( GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, StreamSequenceToken cacheToken, IStreamFilterPredicateWrapper filter) { if (IsShutdown) return; StreamConsumerCollection streamDataCollection; if (!pubSubCache.TryGetValue(streamId, out streamDataCollection)) { // If stream is not in pubsub cache, then we've received no events on this stream, and will aquire the subscriptions from pubsub when we do. return; } StreamConsumerData data; if (!streamDataCollection.TryGetConsumer(subscriptionId, out data)) data = streamDataCollection.AddConsumer(subscriptionId, streamId, streamConsumer, filter ?? DefaultStreamFilter); if (await DoHandshakeWithConsumer(data, cacheToken)) { if (data.State == StreamConsumerDataState.Inactive) RunConsumerCursor(data, data.Filter).Ignore(); // Start delivering events if not actively doing so } } private async Task<bool> DoHandshakeWithConsumer( StreamConsumerData consumerData, StreamSequenceToken cacheToken) { StreamHandshakeToken requestedHandshakeToken = null; // if not cache, then we can't get cursor and there is no reason to ask consumer for token. if (queueCache != null) { Exception exceptionOccured = null; try { requestedHandshakeToken = await AsyncExecutorWithRetries.ExecuteWithRetries( i => consumerData.StreamConsumer.GetSequenceToken(consumerData.SubscriptionId), AsyncExecutorWithRetries.INFINITE_RETRIES, (exception, i) => !(exception is ClientNotAvailableException), this.options.MaxEventDeliveryTime, DeliveryBackoffProvider); if (requestedHandshakeToken != null) { consumerData.SafeDisposeCursor(logger); consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, requestedHandshakeToken.Token); } else { if (consumerData.Cursor == null) // if the consumer did not ask for a specific token and we already have a cursor, jsut keep using it. consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, cacheToken); } } catch (Exception exception) { exceptionOccured = exception; } if (exceptionOccured != null) { bool faultedSubscription = await ErrorProtocol(consumerData, exceptionOccured, false, null, requestedHandshakeToken?.Token); if (faultedSubscription) return false; } } consumerData.LastToken = requestedHandshakeToken; // use what ever the consumer asked for as LastToken for next handshake (even if he asked for null). // if we don't yet have a cursor (had errors in the handshake or data not available exc), get a cursor at the event that triggered that consumer subscription. if (consumerData.Cursor == null && queueCache != null) { try { consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, cacheToken); } catch (Exception) { consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, null); // just in case last GetCacheCursor failed. } } return true; } public Task RemoveSubscriber(GuidId subscriptionId, StreamId streamId) { RemoveSubscriber_Impl(subscriptionId, streamId); return Task.CompletedTask; } public void RemoveSubscriber_Impl(GuidId subscriptionId, StreamId streamId) { if (IsShutdown) return; StreamConsumerCollection streamData; if (!pubSubCache.TryGetValue(streamId, out streamData)) return; // remove consumer bool removed = streamData.RemoveConsumer(subscriptionId, logger); if (removed && logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.PersistentStreamPullingAgent_10, "Removed Consumer: subscription={0}, for stream {1}.", subscriptionId, streamId); if (streamData.Count == 0) pubSubCache.Remove(streamId); } private async Task AsyncTimerCallback(object state) { var queueId = (QueueId)state; try { Task localReceiverInitTask = receiverInitTask; if (localReceiverInitTask != null) { await localReceiverInitTask; receiverInitTask = null; } if (IsShutdown) return; // timer was already removed, last tick // loop through the queue until it is empty. while (!IsShutdown) // timer will be set to null when we are asked to shudown. { int maxCacheAddCount = queueCache?.GetMaxAddCount() ?? QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG; if (maxCacheAddCount != QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG && maxCacheAddCount <= 0) return; // If read succeeds and there is more data, we continue reading. // If read succeeds and there is no more data, we break out of loop // If read fails, we retry 6 more times, with backoff policy. // we log each failure as warnings. After 6 times retry if still fail, we break out of loop and log an error bool moreData = await AsyncExecutorWithRetries.ExecuteWithRetries( i => ReadFromQueue(queueId, receiver, maxCacheAddCount), ReadLoopRetryMax, ReadLoopRetryExceptionFilter, Constants.INFINITE_TIMESPAN, ReadLoopBackoff); if (!moreData) return; } } catch (Exception exc) { receiverInitTask = null; logger.Error(ErrorCode.PersistentStreamPullingAgent_12, $"Giving up reading from queue {queueId} after retry attempts {ReadLoopRetryMax}", exc); } } private bool ReadLoopRetryExceptionFilter(Exception e, int retryCounter) { this.logger.Warn(ErrorCode.PersistentStreamPullingAgent_12, $"Exception while retrying the {retryCounter}th time reading from queue {this.QueueId}", e); return !IsShutdown; } /// <summary> /// Read from queue. /// Returns true, if data was read, false if it was not /// </summary> /// <param name="myQueueId"></param> /// <param name="rcvr"></param> /// <param name="maxCacheAddCount"></param> /// <returns></returns> private async Task<bool> ReadFromQueue(QueueId myQueueId, IQueueAdapterReceiver rcvr, int maxCacheAddCount) { if (rcvr == null) { return false; } var now = DateTime.UtcNow; // Try to cleanup the pubsub cache at the cadence of 10 times in the configurable StreamInactivityPeriod. if ((now - lastTimeCleanedPubSubCache) >= this.options.StreamInactivityPeriod.Divide(StreamInactivityCheckFrequency)) { lastTimeCleanedPubSubCache = now; CleanupPubSubCache(now); } if (queueCache != null) { IList<IBatchContainer> purgedItems; if (queueCache.TryPurgeFromCache(out purgedItems)) { try { await rcvr.MessagesDeliveredAsync(purgedItems); } catch (Exception exc) { logger.Warn(ErrorCode.PersistentStreamPullingAgent_27, $"Exception calling MessagesDeliveredAsync on queue {myQueueId}. Ignoring.", exc); } } } if (queueCache != null && queueCache.IsUnderPressure()) { // Under back pressure. Exit the loop. Will attempt again in the next timer callback. logger.Info((int)ErrorCode.PersistentStreamPullingAgent_24, "Stream cache is under pressure. Backing off."); return false; } // Retrieve one multiBatch from the queue. Every multiBatch has an IEnumerable of IBatchContainers, each IBatchContainer may have multiple events. IList<IBatchContainer> multiBatch = await rcvr.GetQueueMessagesAsync(maxCacheAddCount); if (multiBatch == null || multiBatch.Count == 0) return false; // queue is empty. Exit the loop. Will attempt again in the next timer callback. queueCache?.AddToCache(multiBatch); numMessages += multiBatch.Count; numReadMessagesCounter.IncrementBy(multiBatch.Count); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.PersistentStreamPullingAgent_11, "Got {0} messages from queue {1}. So far {2} msgs from this queue.", multiBatch.Count, myQueueId.ToStringWithHashCode(), numMessages); foreach (var group in multiBatch .Where(m => m != null) .GroupBy(container => new Tuple<Guid, string>(container.StreamGuid, container.StreamNamespace))) { var streamId = StreamId.GetStreamId(group.Key.Item1, queueAdapter.Name, group.Key.Item2); StreamSequenceToken startToken = group.First().SequenceToken; StreamConsumerCollection streamData; if (pubSubCache.TryGetValue(streamId, out streamData)) { streamData.RefreshActivity(now); if (streamData.StreamRegistered) { StartInactiveCursors(streamData, startToken); // if this is an existing stream, start any inactive cursors } else { if(this.logger.IsEnabled(LogLevel.Debug)) this.logger.LogDebug($"Pulled new messages in stream {streamId} from the queue, but pulling agent haven't succeeded in" + $"RegisterStream yet, will start deliver on this stream after RegisterStream succeeded"); } } else { RegisterStream(streamId, startToken, now).Ignore(); // if this is a new stream register as producer of stream in pub sub system } } return true; } private void CleanupPubSubCache(DateTime now) { if (pubSubCache.Count == 0) return; var toRemove = pubSubCache.Where(pair => pair.Value.IsInactive(now, this.options.StreamInactivityPeriod)) .ToList(); toRemove.ForEach(tuple => { pubSubCache.Remove(tuple.Key); tuple.Value.DisposeAll(logger); }); } private async Task RegisterStream(StreamId streamId, StreamSequenceToken firstToken, DateTime now) { var streamData = new StreamConsumerCollection(now); pubSubCache.Add(streamId, streamData); // Create a fake cursor to point into a cache. // That way we will not purge the event from the cache, until we talk to pub sub. // This will help ensure the "casual consistency" between pre-existing subscripton (of a potentially new already subscribed consumer) // and later production. var pinCursor = queueCache?.GetCacheCursor(streamId, firstToken); try { await RegisterAsStreamProducer(streamId, firstToken); streamData.StreamRegistered = true; } finally { // Cleanup the fake pinning cursor. pinCursor?.Dispose(); } } private void StartInactiveCursors(StreamConsumerCollection streamData, StreamSequenceToken startToken) { foreach (StreamConsumerData consumerData in streamData.AllConsumers()) { consumerData.Cursor?.Refresh(startToken); if (consumerData.State == StreamConsumerDataState.Inactive) { // wake up inactive consumers RunConsumerCursor(consumerData, consumerData.Filter).Ignore(); } } } private async Task RunConsumerCursor(StreamConsumerData consumerData, IStreamFilterPredicateWrapper filterWrapper) { try { // double check in case of interleaving if (consumerData.State == StreamConsumerDataState.Active || consumerData.Cursor == null) return; consumerData.State = StreamConsumerDataState.Active; while (consumerData.Cursor != null) { IBatchContainer batch = null; Exception exceptionOccured = null; try { batch = GetBatchForConsumer(consumerData.Cursor, filterWrapper, consumerData.StreamId); if (batch == null) { break; } } catch (Exception exc) { exceptionOccured = exc; consumerData.SafeDisposeCursor(logger); consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, null); } // Apply filtering to this batch, if applicable if (filterWrapper != null && batch != null) { try { // Apply batch filter to this input batch, to see whether we should deliver it to this consumer. if (!batch.ShouldDeliver( consumerData.StreamId, filterWrapper.FilterData, filterWrapper.ShouldReceive)) continue; // Skip this batch -- nothing to do } catch (Exception exc) { var message = $"Ignoring exception while trying to evaluate subscription filter function {filterWrapper} on stream {consumerData.StreamId} in PersistentStreamPullingAgentGrain.RunConsumerCursor"; logger.Warn((int)ErrorCode.PersistentStreamPullingAgent_13, message, exc); } } try { numSentMessagesCounter.Increment(); if (batch != null) { StreamHandshakeToken newToken = await AsyncExecutorWithRetries.ExecuteWithRetries( i => DeliverBatchToConsumer(consumerData, batch), AsyncExecutorWithRetries.INFINITE_RETRIES, (exception, i) => !(exception is ClientNotAvailableException), this.options.MaxEventDeliveryTime, DeliveryBackoffProvider); if (newToken != null) { consumerData.LastToken = newToken; IQueueCacheCursor newCursor = queueCache.GetCacheCursor(consumerData.StreamId, newToken.Token); consumerData.SafeDisposeCursor(logger); consumerData.Cursor = newCursor; } } } catch (Exception exc) { consumerData.Cursor?.RecordDeliveryFailure(); var message = $"Exception while trying to deliver msgs to stream {consumerData.StreamId} in PersistentStreamPullingAgentGrain.RunConsumerCursor"; logger.Error(ErrorCode.PersistentStreamPullingAgent_14, message, exc); exceptionOccured = exc is ClientNotAvailableException ? exc : new StreamEventDeliveryFailureException(consumerData.StreamId); } // if we failed to deliver a batch if (exceptionOccured != null) { bool faultedSubscription = await ErrorProtocol(consumerData, exceptionOccured, true, batch, batch?.SequenceToken); if (faultedSubscription) return; } } consumerData.State = StreamConsumerDataState.Inactive; } catch (Exception exc) { // RunConsumerCursor is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception logger.Error(ErrorCode.PersistentStreamPullingAgent_15, "Ignored RunConsumerCursor Error", exc); consumerData.State = StreamConsumerDataState.Inactive; throw; } } private IBatchContainer GetBatchForConsumer(IQueueCacheCursor cursor, IStreamFilterPredicateWrapper filterWrapper, StreamId streamId) { if (this.options.BatchContainerBatchSize <= 1) { Exception ignore; if (!cursor.MoveNext()) { return null; } return cursor.GetCurrent(out ignore); } else if (this.options.BatchContainerBatchSize > 1) { Exception ignore; int i = 0; var batchContainers = new List<IBatchContainer>(); while (i < this.options.BatchContainerBatchSize) { if (!cursor.MoveNext()) { break; } var batchContainer = cursor.GetCurrent(out ignore); if (!batchContainer.ShouldDeliver( streamId, filterWrapper.FilterData, filterWrapper.ShouldReceive)) continue; batchContainers.Add(batchContainer); i++; } if (i == 0) { return null; } return new BatchContainerBatch(batchContainers); } return null; } private async Task<StreamHandshakeToken> DeliverBatchToConsumer(StreamConsumerData consumerData, IBatchContainer batch) { try { StreamHandshakeToken newToken = await ContextualizedDeliverBatchToConsumer(consumerData, batch); consumerData.LastToken = StreamHandshakeToken.CreateDeliveyToken(batch.SequenceToken); // this is the currently delivered token return newToken; } catch (Exception ex) { this.logger.LogWarning(ex, "Failed to deliver message to consumer on {SubscriptionId} for stream {StreamId}, may retry.", consumerData.SubscriptionId, consumerData.StreamId); throw; } } /// <summary> /// Add call context for batch delivery call, then clear context immediately, without giving up turn. /// </summary> private Task<StreamHandshakeToken> ContextualizedDeliverBatchToConsumer(StreamConsumerData consumerData, IBatchContainer batch) { bool isRequestContextSet = batch.ImportRequestContext(); try { return consumerData.StreamConsumer.DeliverBatch(consumerData.SubscriptionId, consumerData.StreamId, batch.AsImmutable(), consumerData.LastToken); } finally { if (isRequestContextSet) { // clear RequestContext before await! RequestContext.Clear(); } } } private static async Task DeliverErrorToConsumer(StreamConsumerData consumerData, Exception exc, IBatchContainer batch) { Task errorDeliveryTask; bool isRequestContextSet = batch != null && batch.ImportRequestContext(); try { errorDeliveryTask = consumerData.StreamConsumer.ErrorInStream(consumerData.SubscriptionId, exc); } finally { if (isRequestContextSet) { RequestContext.Clear(); // clear RequestContext before await! } } await errorDeliveryTask; } private async Task<bool> ErrorProtocol(StreamConsumerData consumerData, Exception exceptionOccured, bool isDeliveryError, IBatchContainer batch, StreamSequenceToken token) { // for loss of client, we just remove the subscription if (exceptionOccured is ClientNotAvailableException) { logger.Warn(ErrorCode.Stream_ConsumerIsDead, "Consumer {0} on stream {1} is no longer active - permanently removing Consumer.", consumerData.StreamConsumer, consumerData.StreamId); pubSub.UnregisterConsumer(consumerData.SubscriptionId, consumerData.StreamId, consumerData.StreamId.ProviderName).Ignore(); return true; } // notify consumer about the error or that the data is not available. await OrleansTaskExtentions.ExecuteAndIgnoreException( () => DeliverErrorToConsumer( consumerData, exceptionOccured, batch)); // record that there was a delivery failure if (isDeliveryError) { await OrleansTaskExtentions.ExecuteAndIgnoreException( () => streamFailureHandler.OnDeliveryFailure( consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token)); } else { await OrleansTaskExtentions.ExecuteAndIgnoreException( () => streamFailureHandler.OnSubscriptionFailure( consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token)); } // if configured to fault on delivery failure and this is not an implicit subscription, fault and remove the subscription if (streamFailureHandler.ShouldFaultSubsriptionOnError && !SubscriptionMarker.IsImplicitSubscription(consumerData.SubscriptionId.Guid)) { try { // notify consumer of faulted subscription, if we can. await OrleansTaskExtentions.ExecuteAndIgnoreException( () => DeliverErrorToConsumer( consumerData, new FaultedSubscriptionException(consumerData.SubscriptionId, consumerData.StreamId), batch)); // mark subscription as faulted. await pubSub.FaultSubscription(consumerData.StreamId, consumerData.SubscriptionId); } finally { // remove subscription RemoveSubscriber_Impl(consumerData.SubscriptionId, consumerData.StreamId); } return true; } return false; } private static async Task<ISet<PubSubSubscriptionState>> PubsubRegisterProducer(IStreamPubSub pubSub, StreamId streamId, string streamProviderName, IStreamProducerExtension meAsStreamProducer, ILogger logger) { try { var streamData = await pubSub.RegisterProducer(streamId, streamProviderName, meAsStreamProducer); return streamData; } catch (Exception e) { logger.Error(ErrorCode.PersistentStreamPullingAgent_17, $"RegisterAsStreamProducer failed due to {e}", e); throw e; } } private async Task RegisterAsStreamProducer(StreamId streamId, StreamSequenceToken streamStartToken) { try { if (pubSub == null) throw new NullReferenceException("Found pubSub reference not set up correctly in RetreaveNewStream"); IStreamProducerExtension meAsStreamProducer = this.AsReference<IStreamProducerExtension>(); ISet<PubSubSubscriptionState> streamData = null; await AsyncExecutorWithRetries.ExecuteWithRetries( async i => { streamData = await PubsubRegisterProducer(pubSub, streamId, streamProviderName, meAsStreamProducer, logger); }, AsyncExecutorWithRetries.INFINITE_RETRIES, (exception, i) => !IsShutdown, Constants.INFINITE_TIMESPAN, DeliveryBackoffProvider); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.PersistentStreamPullingAgent_16, "Got back {0} Subscribers for stream {1}.", streamData.Count, streamId); var addSubscriptionTasks = new List<Task>(streamData.Count); foreach (PubSubSubscriptionState item in streamData) { addSubscriptionTasks.Add(AddSubscriber_Impl(item.SubscriptionId, item.Stream, item.Consumer, streamStartToken, item.Filter)); } await Task.WhenAll(addSubscriptionTasks); } catch (Exception exc) { // RegisterAsStreamProducer is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception logger.Error(ErrorCode.PersistentStreamPullingAgent_17, "Ignored RegisterAsStreamProducer Error", exc); throw; } } } }
#region License // Copyright 2014 MorseCode Software // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MorseCode.RxMvvm.Common.DiscriminatedUnion { using System; using System.Diagnostics.Contracts; /// <summary> /// Provides <see langword="static"/> factory methods for creating discriminating unions. /// </summary> public static partial class DiscriminatedUnion { /// <summary> /// Creates an instance of a class implementing <see cref="IDiscriminatedUnion{TCommon,T1,T2,T3}"/> holding a value of type <typeparamref name="T1"/>. /// </summary> /// <param name="value"> /// The value to hold in the discriminated union. /// </param> /// <typeparam name="TCommon"> /// The common type of all types allowed in the discriminated union. /// </typeparam> /// <typeparam name="T1"> /// The first type of the discriminated union. /// </typeparam> /// <typeparam name="T2"> /// The second type of the discriminated union. /// </typeparam> /// <typeparam name="T3"> /// The third type of the discriminated union. /// </typeparam> /// <returns> /// An instance of a class implementing <see cref="IDiscriminatedUnion{TCommon,T1,T2,T3}"/>. /// </returns> public static IDiscriminatedUnion<TCommon, T1, T2, T3> First<TCommon, T1, T2, T3>(T1 value) where T1 : TCommon where T2 : TCommon where T3 : TCommon where TCommon : class { Contract.Ensures(Contract.Result<IDiscriminatedUnion<TCommon, T1, T2, T3>>() != null); return new DiscriminatedUnionFirst<TCommon, T1, T2, T3>(value); } /// <summary> /// Creates an instance of a class implementing <see cref="IDiscriminatedUnion{TCommon,T1,T2,T3}"/> holding a value of type <typeparamref name="T2"/>. /// </summary> /// <param name="value"> /// The value to hold in the discriminated union. /// </param> /// <typeparam name="TCommon"> /// The common type of all types allowed in the discriminated union. /// </typeparam> /// <typeparam name="T1"> /// The first type of the discriminated union. /// </typeparam> /// <typeparam name="T2"> /// The second type of the discriminated union. /// </typeparam> /// <typeparam name="T3"> /// The third type of the discriminated union. /// </typeparam> /// <returns> /// An instance of a class implementing <see cref="IDiscriminatedUnion{TCommon,T1,T2,T3}"/>. /// </returns> public static IDiscriminatedUnion<TCommon, T1, T2, T3> Second<TCommon, T1, T2, T3>(T2 value) where T1 : TCommon where T2 : TCommon where T3 : TCommon where TCommon : class { Contract.Ensures(Contract.Result<IDiscriminatedUnion<TCommon, T1, T2, T3>>() != null); return new DiscriminatedUnionSecond<TCommon, T1, T2, T3>(value); } /// <summary> /// Creates an instance of a class implementing <see cref="IDiscriminatedUnion{TCommon,T1,T2,T3}"/> holding a value of type <typeparamref name="T3"/>. /// </summary> /// <param name="value"> /// The value to hold in the discriminated union. /// </param> /// <typeparam name="TCommon"> /// The common type of all types allowed in the discriminated union. /// </typeparam> /// <typeparam name="T1"> /// The first type of the discriminated union. /// </typeparam> /// <typeparam name="T2"> /// The second type of the discriminated union. /// </typeparam> /// <typeparam name="T3"> /// The third type of the discriminated union. /// </typeparam> /// <returns> /// An instance of a class implementing <see cref="IDiscriminatedUnion{TCommon,T1,T2,T3}"/>. /// </returns> public static IDiscriminatedUnion<TCommon, T1, T2, T3> Third<TCommon, T1, T2, T3>(T3 value) where T1 : TCommon where T2 : TCommon where T3 : TCommon where TCommon : class { Contract.Ensures(Contract.Result<IDiscriminatedUnion<TCommon, T1, T2, T3>>() != null); return new DiscriminatedUnionThird<TCommon, T1, T2, T3>(value); } [Serializable] private class DiscriminatedUnionFirst<TCommon, T1, T2, T3> : DiscriminatedUnion<TCommon, T1, T2, T3> where T1 : TCommon where T2 : TCommon where T3 : TCommon where TCommon : class { private readonly T1 value; /// <summary> /// Initializes a new instance of the <see cref="DiscriminatedUnionFirst{TCommon,T1,T2,T3}"/> class. /// </summary> /// <param name="value"> /// The value. /// </param> public DiscriminatedUnionFirst(T1 value) { this.value = value; } /// <summary> /// Gets a value indicating whether the discriminated union is holding a value of the type <typeparamref name="T1" />. /// </summary> public override bool IsFirst { get { return true; } } /// <summary> /// Gets a value indicating whether the discriminated union is holding a value of the type <typeparamref name="T2" />. /// </summary> public override bool IsSecond { get { return false; } } /// <summary> /// Gets a value indicating whether the discriminated union is holding a value of the type <typeparamref name="T3" />. /// </summary> public override bool IsThird { get { return false; } } /// <summary> /// Gets the value of type <typeparamref name="T1" /> if <see cref="IsFirst"/> is <c>true</c>, otherwise returns the default value for type <typeparamref name="T1" />. /// </summary> // ReSharper disable MemberHidesStaticFromOuterClass public override T1 First { // ReSharper restore MemberHidesStaticFromOuterClass get { return this.value; } } /// <summary> /// Gets the value of type <typeparamref name="T2" /> if <see cref="IsSecond"/> is <c>true</c>, otherwise returns the default value for type <typeparamref name="T2" />. /// </summary> // ReSharper disable MemberHidesStaticFromOuterClass public override T2 Second { // ReSharper restore MemberHidesStaticFromOuterClass get { return default(T2); } } /// <summary> /// Gets the value of type <typeparamref name="T3" /> if <see cref="IsThird"/> is <c>true</c>, otherwise returns the default value for type <typeparamref name="T3" />. /// </summary> // ReSharper disable MemberHidesStaticFromOuterClass public override T3 Third { // ReSharper restore MemberHidesStaticFromOuterClass get { return default(T3); } } /// <summary> /// Gets the value as <typeparamref name="TCommon" /> regardless of which of the two values are held in the discriminated union. /// </summary> public override TCommon Value { get { return this.value; } } /// <summary> /// Executes an action based on which value is contained in the discriminated union. /// </summary> /// <param name="first"> /// The action to run if <see cref="IsFirst"/> is <c>true</c>. /// </param> /// <param name="second"> /// The action to run if <see cref="IsSecond"/> is <c>true</c>. /// </param> /// <param name="third"> /// The action to run if <see cref="IsThird"/> is <c>true</c>. /// </param> public override void Switch(Action<T1> first, Action<T2> second, Action<T3> third) { first(this.value); } /// <summary> /// Executes a function based on which value is contained in the discriminated union. /// </summary> /// <param name="first"> /// The function to run if <see cref="IsFirst"/> is <c>true</c>. /// </param> /// <param name="second"> /// The function to run if <see cref="IsSecond"/> is <c>true</c>. /// </param> /// <param name="third"> /// The function to run if <see cref="IsThird"/> is <c>true</c>. /// </param> /// <typeparam name="TResult"> /// The type of the result. /// </typeparam> /// <returns> /// The result of type <typeparamref name="TResult"/> of the function executed. /// </returns> public override TResult Switch<TResult>(Func<T1, TResult> first, Func<T2, TResult> second, Func<T3, TResult> third) { return first(this.value); } } [Serializable] private class DiscriminatedUnionSecond<TCommon, T1, T2, T3> : DiscriminatedUnion<TCommon, T1, T2, T3> where T1 : TCommon where T2 : TCommon where T3 : TCommon where TCommon : class { private readonly T2 value; /// <summary> /// Initializes a new instance of the <see cref="DiscriminatedUnionSecond{TCommon,T1,T2,T3}"/> class. /// </summary> /// <param name="value"> /// The value. /// </param> public DiscriminatedUnionSecond(T2 value) { this.value = value; } /// <summary> /// Gets a value indicating whether the discriminated union is holding a value of the type <typeparamref name="T1" />. /// </summary> public override bool IsFirst { get { return false; } } /// <summary> /// Gets a value indicating whether the discriminated union is holding a value of the type <typeparamref name="T2" />. /// </summary> public override bool IsSecond { get { return true; } } /// <summary> /// Gets a value indicating whether the discriminated union is holding a value of the type <typeparamref name="T3" />. /// </summary> public override bool IsThird { get { return false; } } /// <summary> /// Gets the value of type <typeparamref name="T1" /> if <see cref="IsFirst"/> is <c>true</c>, otherwise returns the default value for type <typeparamref name="T1" />. /// </summary> // ReSharper disable MemberHidesStaticFromOuterClass public override T1 First { // ReSharper restore MemberHidesStaticFromOuterClass get { return default(T1); } } /// <summary> /// Gets the value of type <typeparamref name="T2" /> if <see cref="IsSecond"/> is <c>true</c>, otherwise returns the default value for type <typeparamref name="T2" />. /// </summary> // ReSharper disable MemberHidesStaticFromOuterClass public override T2 Second { // ReSharper restore MemberHidesStaticFromOuterClass get { return this.value; } } /// <summary> /// Gets the value of type <typeparamref name="T3" /> if <see cref="IsThird"/> is <c>true</c>, otherwise returns the default value for type <typeparamref name="T3" />. /// </summary> // ReSharper disable MemberHidesStaticFromOuterClass public override T3 Third { // ReSharper restore MemberHidesStaticFromOuterClass get { return default(T3); } } /// <summary> /// Gets the value as <typeparamref name="TCommon" /> regardless of which of the two values are held in the discriminated union. /// </summary> public override TCommon Value { get { return this.value; } } /// <summary> /// Executes an action based on which value is contained in the discriminated union. /// </summary> /// <param name="first"> /// The action to run if <see cref="IsFirst"/> is <c>true</c>. /// </param> /// <param name="second"> /// The action to run if <see cref="IsSecond"/> is <c>true</c>. /// </param> /// <param name="third"> /// The action to run if <see cref="IsThird"/> is <c>true</c>. /// </param> public override void Switch(Action<T1> first, Action<T2> second, Action<T3> third) { second(this.value); } /// <summary> /// Executes a function based on which value is contained in the discriminated union. /// </summary> /// <param name="first"> /// The function to run if <see cref="IsFirst"/> is <c>true</c>. /// </param> /// <param name="second"> /// The function to run if <see cref="IsSecond"/> is <c>true</c>. /// </param> /// <param name="third"> /// The function to run if <see cref="IsThird"/> is <c>true</c>. /// </param> /// <typeparam name="TResult"> /// The type of the result. /// </typeparam> /// <returns> /// The result of type <typeparamref name="TResult"/> of the function executed. /// </returns> public override TResult Switch<TResult>(Func<T1, TResult> first, Func<T2, TResult> second, Func<T3, TResult> third) { return second(this.value); } } [Serializable] private class DiscriminatedUnionThird<TCommon, T1, T2, T3> : DiscriminatedUnion<TCommon, T1, T2, T3> where T1 : TCommon where T2 : TCommon where T3 : TCommon where TCommon : class { private readonly T3 value; /// <summary> /// Initializes a new instance of the <see cref="DiscriminatedUnionThird{TCommon,T1,T2,T3}"/> class. /// </summary> /// <param name="value"> /// The value. /// </param> public DiscriminatedUnionThird(T3 value) { this.value = value; } /// <summary> /// Gets a value indicating whether the discriminated union is holding a value of the type <typeparamref name="T1" />. /// </summary> public override bool IsFirst { get { return false; } } /// <summary> /// Gets a value indicating whether the discriminated union is holding a value of the type <typeparamref name="T2" />. /// </summary> public override bool IsSecond { get { return false; } } /// <summary> /// Gets a value indicating whether the discriminated union is holding a value of the type <typeparamref name="T3" />. /// </summary> public override bool IsThird { get { return true; } } /// <summary> /// Gets the value of type <typeparamref name="T1" /> if <see cref="IsFirst"/> is <c>true</c>, otherwise returns the default value for type <typeparamref name="T1" />. /// </summary> // ReSharper disable MemberHidesStaticFromOuterClass public override T1 First { // ReSharper restore MemberHidesStaticFromOuterClass get { return default(T1); } } /// <summary> /// Gets the value of type <typeparamref name="T2" /> if <see cref="IsSecond"/> is <c>true</c>, otherwise returns the default value for type <typeparamref name="T2" />. /// </summary> // ReSharper disable MemberHidesStaticFromOuterClass public override T2 Second { // ReSharper restore MemberHidesStaticFromOuterClass get { return default(T2); } } /// <summary> /// Gets the value of type <typeparamref name="T3" /> if <see cref="IsThird"/> is <c>true</c>, otherwise returns the default value for type <typeparamref name="T3" />. /// </summary> // ReSharper disable MemberHidesStaticFromOuterClass public override T3 Third { // ReSharper restore MemberHidesStaticFromOuterClass get { return this.value; } } /// <summary> /// Gets the value as <typeparamref name="TCommon" /> regardless of which of the two values are held in the discriminated union. /// </summary> public override TCommon Value { get { return this.value; } } /// <summary> /// Executes an action based on which value is contained in the discriminated union. /// </summary> /// <param name="first"> /// The action to run if <see cref="IsFirst"/> is <c>true</c>. /// </param> /// <param name="second"> /// The action to run if <see cref="IsSecond"/> is <c>true</c>. /// </param> /// <param name="third"> /// The action to run if <see cref="IsThird"/> is <c>true</c>. /// </param> public override void Switch(Action<T1> first, Action<T2> second, Action<T3> third) { third(this.value); } /// <summary> /// Executes a function based on which value is contained in the discriminated union. /// </summary> /// <param name="first"> /// The function to run if <see cref="IsFirst"/> is <c>true</c>. /// </param> /// <param name="second"> /// The function to run if <see cref="IsSecond"/> is <c>true</c>. /// </param> /// <param name="third"> /// The function to run if <see cref="IsThird"/> is <c>true</c>. /// </param> /// <typeparam name="TResult"> /// The type of the result. /// </typeparam> /// <returns> /// The result of type <typeparamref name="TResult"/> of the function executed. /// </returns> public override TResult Switch<TResult>(Func<T1, TResult> first, Func<T2, TResult> second, Func<T3, TResult> third) { return third(this.value); } } } }
//Copyright (c) Service Stack LLC. All Rights Reserved. //License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt using System; namespace ServiceStack { [Flags] public enum RequestAttributes : long { None = 0, Any = AnyNetworkAccessType | AnySecurityMode | AnyHttpMethod | AnyCallStyle | AnyFormat, AnyNetworkAccessType = External | Localhost | LocalSubnet, AnySecurityMode = Secure | InSecure, AnyHttpMethod = HttpHead | HttpGet | HttpPost | HttpPut | HttpDelete | HttpPatch | HttpOptions | HttpOther, AnyCallStyle = OneWay | Reply, AnyFormat = Soap11 | Soap12 | Xml | Json | Jsv | Html | ProtoBuf | Csv | MsgPack | Yaml | FormatOther, AnyEndpoint = Http | MessageQueue | Tcp | EndpointOther, InternalNetworkAccess = Localhost | LocalSubnet, //Whether it came from an Internal or External address Localhost = 1 << 0, LocalSubnet = 1 << 1, External = 1 << 2, //Called over a secure or insecure channel Secure = 1 << 3, InSecure = 1 << 4, //HTTP request type HttpHead = 1 << 5, HttpGet = 1 << 6, HttpPost = 1 << 7, HttpPut = 1 << 8, HttpDelete = 1 << 9, HttpPatch = 1 << 10, HttpOptions = 1 << 11, HttpOther = 1 << 12, //Call Styles OneWay = 1 << 13, Reply = 1 << 14, //Different formats Soap11 = 1 << 15, Soap12 = 1 << 16, //POX Xml = 1 << 17, //Javascript Json = 1 << 18, //Jsv i.e. TypeSerializer Jsv = 1 << 19, //e.g. protobuf-net ProtoBuf = 1 << 20, //e.g. text/csv Csv = 1 << 21, Html = 1 << 22, Yaml = 1 << 23, MsgPack = 1 << 24, FormatOther = 1 << 25, //Different endpoints Http = 1 << 26, MessageQueue = 1 << 27, Tcp = 1 << 28, EndpointOther = 1 << 29, } public enum Network : long { Localhost = 1 << 0, LocalSubnet = 1 << 1, External = 1 << 2, } public enum Security : long { Secure = 1 << 3, InSecure = 1 << 4, } public enum Http : long { Head = 1 << 5, Get = 1 << 6, Post = 1 << 7, Put = 1 << 8, Delete = 1 << 9, Patch = 1 << 10, Options = 1 << 11, Other = 1 << 12, } public enum CallStyle : long { OneWay = 1 << 13, Reply = 1 << 14, } public enum Format : long { Soap11 = 1 << 15, Soap12 = 1 << 16, Xml = 1 << 17, Json = 1 << 18, Jsv = 1 << 19, ProtoBuf = 1 << 20, Csv = 1 << 21, Html = 1 << 22, Yaml = 1 << 23, MsgPack = 1 << 24, Other = 1 << 25, } public enum Endpoint : long { Http = 1 << 26, Mq = 1 << 27, Tcp = 1 << 28, Other = 1 << 29, } public static class RequestAttributesExtensions { public static bool IsLocalhost(this RequestAttributes attrs) { return (RequestAttributes.Localhost & attrs) == RequestAttributes.Localhost; } public static bool IsLocalSubnet(this RequestAttributes attrs) { return (RequestAttributes.LocalSubnet & attrs) == RequestAttributes.LocalSubnet; } public static bool IsExternal(this RequestAttributes attrs) { return (RequestAttributes.External & attrs) == RequestAttributes.External; } public static Format ToFormat(this string format) { try { return (Format)Enum.Parse(typeof(Format), format.ToUpper().Replace("X-", ""), true); } catch (Exception) { return Format.Other; } } public static string FromFormat(this Format format) { var formatStr = format.ToString().ToLower(); if (format == Format.ProtoBuf || format == Format.MsgPack) return "x-" + formatStr; return formatStr; } public static Format ToFormat(this Feature feature) { switch (feature) { case Feature.Xml: return Format.Xml; case Feature.Json: return Format.Json; case Feature.Jsv: return Format.Jsv; case Feature.Csv: return Format.Csv; case Feature.Html: return Format.Html; case Feature.MsgPack: return Format.MsgPack; case Feature.ProtoBuf: return Format.ProtoBuf; case Feature.Soap11: return Format.Soap11; case Feature.Soap12: return Format.Soap12; } return Format.Other; } public static Feature ToFeature(this Format format) { switch (format) { case Format.Xml: return Feature.Xml; case Format.Json: return Feature.Json; case Format.Jsv: return Feature.Jsv; case Format.Csv: return Feature.Csv; case Format.Html: return Feature.Html; case Format.MsgPack: return Feature.MsgPack; case Format.ProtoBuf: return Feature.ProtoBuf; case Format.Soap11: return Feature.Soap11; case Format.Soap12: return Feature.Soap12; } return Feature.CustomFormat; } public static Feature ToSoapFeature(this RequestAttributes attributes) { if ((RequestAttributes.Soap11 & attributes) == RequestAttributes.Soap11) return Feature.Soap11; if ((RequestAttributes.Soap12 & attributes) == RequestAttributes.Soap12) return Feature.Soap12; return Feature.None; } } }
// 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, // 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.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.PythonTools; using Microsoft.PythonTools.Interpreter; namespace TestUtilities.Python { public class MockInterpreterOptionsService : IInterpreterOptionsService, IInterpreterRegistryService { readonly List<IPythonInterpreterFactoryProvider> _providers; readonly IPythonInterpreterFactory _noInterpretersValue; IPythonInterpreterFactory _defaultInterpreter; readonly Dictionary<IPythonInterpreterFactory, IReadOnlyList<IPackageManager>> _packageManagers; public MockInterpreterOptionsService() { _providers = new List<IPythonInterpreterFactoryProvider>(); _noInterpretersValue = new MockPythonInterpreterFactory(new VisualStudioInterpreterConfiguration("2.7", "No Interpreters", version: new Version(2, 7))); _packageManagers = new Dictionary<IPythonInterpreterFactory, IReadOnlyList<IPackageManager>>(); } public void AddProvider(IPythonInterpreterFactoryProvider provider) { _providers.Add(provider); provider.InterpreterFactoriesChanged += provider_InterpreterFactoriesChanged; var evt = InterpretersChanged; if (evt != null) { evt(this, EventArgs.Empty); } } public void ClearProviders() { foreach (var p in _providers) { p.InterpreterFactoriesChanged -= provider_InterpreterFactoriesChanged; } _providers.Clear(); var evt = InterpretersChanged; if (evt != null) { evt(this, EventArgs.Empty); } } void provider_InterpreterFactoriesChanged(object sender, EventArgs e) { var evt = InterpretersChanged; if (evt != null) { evt(this, EventArgs.Empty); } } public IEnumerable<IPythonInterpreterFactory> Interpreters { get { return _providers.Where(p => p != null).SelectMany(p => p.GetInterpreterFactories()); } } public IEnumerable<InterpreterConfiguration> Configurations { get { return _providers.Where(p => p != null).SelectMany(p => p.GetInterpreterFactories()).Select(x => x.Configuration); } } public IEnumerable<IPythonInterpreterFactory> InterpretersOrDefault { get { if (Interpreters.Any()) { return Interpreters; } return Enumerable.Repeat(_noInterpretersValue, 1); } } public IPythonInterpreterFactory NoInterpretersValue { get { return _noInterpretersValue; } } public event EventHandler InterpretersChanged; public void BeginSuppressInterpretersChangedEvent() { throw new NotImplementedException(); } public void EndSuppressInterpretersChangedEvent() { throw new NotImplementedException(); } public IPythonInterpreterFactory DefaultInterpreter { get { return _defaultInterpreter ?? _noInterpretersValue; } set { if (value == _noInterpretersValue) { value = null; } if (value != _defaultInterpreter) { _defaultInterpreter = value; var evt = DefaultInterpreterChanged; if (evt != null) { evt(this, EventArgs.Empty); } } } } public string DefaultInterpreterId { get { return DefaultInterpreter?.Configuration?.Id; } set { DefaultInterpreter = FindInterpreter(value); } } public event EventHandler DefaultInterpreterChanged; public bool IsInterpreterGeneratingDatabase(IPythonInterpreterFactory interpreter) { throw new NotImplementedException(); } public void RemoveConfigurableInterpreter(string id) { throw new NotImplementedException(); } public bool IsConfigurable(string id) { return true; //throw new NotImplementedException(); } public IPythonInterpreterFactory FindInterpreter(string id) { foreach (var interp in _providers) { foreach (var config in interp.GetInterpreterConfigurations()) { if (config.Id == id) { return interp.GetInterpreterFactory(id); } } } return null; } public Task<object> LockInterpreterAsync(IPythonInterpreterFactory factory, object moniker, TimeSpan timeout) { throw new NotImplementedException(); } public bool IsInterpreterLocked(IPythonInterpreterFactory factory, object moniker) { throw new NotImplementedException(); } public bool UnlockInterpreter(object cookie) { throw new NotImplementedException(); } public InterpreterConfiguration FindConfiguration(string id) { foreach (var interp in _providers) { foreach (var config in interp.GetInterpreterConfigurations()) { if (config.Id == id) { return config; } } } return null; } public string AddConfigurableInterpreter(string name, InterpreterConfiguration config) { throw new NotImplementedException(); } public object GetProperty(string id, string propName) { foreach (var interp in _providers) { foreach (var config in interp.GetInterpreterConfigurations()) { if (config.Id == id) { return interp.GetProperty(id, propName); } } } return null; } public void GetSerializationInfo(IPythonInterpreterFactory factory, out string assembly, out string typeName, out Dictionary<string, object> properties) { var f = factory as ICustomInterpreterSerialization ?? (ICustomInterpreterSerialization)new MockPythonInterpreterFactory(factory.Configuration); if (!f.GetSerializationInfo(out assembly, out typeName, out properties)) { throw new InvalidOperationException($"Failed to serialize {factory.Configuration.Id}"); } } public void AddPackageManagers(IPythonInterpreterFactory factory, IReadOnlyList<IPackageManager> packageManagers) { _packageManagers[factory] = packageManagers; } public IEnumerable<IPackageManager> GetPackageManagers(IPythonInterpreterFactory factory) { try { return _packageManagers[factory]; } catch (KeyNotFoundException) { return Enumerable.Empty<IPackageManager>(); } } } }