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. // ---------------------------------------------------------------------------------- // 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 System.Diagnostics.Contracts; 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) { Debug.Assert(pStream != default(IntPtr)); #if ENABLE_WINRT // 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; #if CORECLR // Temp Workaround for coreclr McgMarshal.ComRelease_StdCall(pMarshal); return true; #else 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, 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); } #endif } /// <summary> /// Get from cache if available, else allocate from heap /// </summary> #if !RHTESTCL [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] #endif static internal 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 static internal 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.IsWinRTInterface()) { // // 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; } 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 unsafe static 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(); } } } }
// 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.Security; namespace System.Runtime.Serialization { using System; using System.Collections; using System.Diagnostics; using System.Collections.Generic; using System.IO; using System.Globalization; using System.Reflection; using System.Threading; using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Linq; #if USE_REFEMIT || uapaot public sealed class ClassDataContract : DataContract #else internal sealed class ClassDataContract : DataContract #endif { public XmlDictionaryString[] ContractNamespaces; public XmlDictionaryString[] MemberNames; public XmlDictionaryString[] MemberNamespaces; private XmlDictionaryString[] _childElementNamespaces; private ClassDataContractCriticalHelper _helper; private bool _isScriptObject; #if uapaot public ClassDataContract() : base(new ClassDataContractCriticalHelper()) { InitClassDataContract(); } #endif internal ClassDataContract(Type type) : base(new ClassDataContractCriticalHelper(type)) { InitClassDataContract(); } private ClassDataContract(Type type, XmlDictionaryString ns, string[] memberNames) : base(new ClassDataContractCriticalHelper(type, ns, memberNames)) { InitClassDataContract(); } private void InitClassDataContract() { _helper = base.Helper as ClassDataContractCriticalHelper; this.ContractNamespaces = _helper.ContractNamespaces; this.MemberNames = _helper.MemberNames; this.MemberNamespaces = _helper.MemberNamespaces; _isScriptObject = _helper.IsScriptObject; } internal ClassDataContract BaseContract { get { return _helper.BaseContract; } } internal List<DataMember> Members { get { return _helper.Members; } } public XmlDictionaryString[] ChildElementNamespaces { get { if (_childElementNamespaces == null) { lock (this) { if (_childElementNamespaces == null) { if (_helper.ChildElementNamespaces == null) { XmlDictionaryString[] tempChildElementamespaces = CreateChildElementNamespaces(); Interlocked.MemoryBarrier(); _helper.ChildElementNamespaces = tempChildElementamespaces; } _childElementNamespaces = _helper.ChildElementNamespaces; } } } return _childElementNamespaces; } set { _childElementNamespaces = value; } } internal MethodInfo OnSerializing { get { return _helper.OnSerializing; } } internal MethodInfo OnSerialized { get { return _helper.OnSerialized; } } internal MethodInfo OnDeserializing { get { return _helper.OnDeserializing; } } internal MethodInfo OnDeserialized { get { return _helper.OnDeserialized; } } internal MethodInfo ExtensionDataSetMethod { get { return _helper.ExtensionDataSetMethod; } } #if !uapaot public override DataContractDictionary KnownDataContracts { get { return _helper.KnownDataContracts; } } #endif public override bool IsISerializable { get { return _helper.IsISerializable; } set { _helper.IsISerializable = value; } } internal bool IsNonAttributedType { get { return _helper.IsNonAttributedType; } } #if uapaot public bool HasDataContract { get { return _helper.HasDataContract; } set { _helper.HasDataContract = value; } } #endif public bool HasExtensionData { get { return _helper.HasExtensionData; } set { _helper.HasExtensionData = value; } } internal bool IsKeyValuePairAdapter { get { return _helper.IsKeyValuePairAdapter; } } internal Type[] KeyValuePairGenericArguments { get { return _helper.KeyValuePairGenericArguments; } } internal ConstructorInfo KeyValuePairAdapterConstructorInfo { get { return _helper.KeyValuePairAdapterConstructorInfo; } } internal MethodInfo GetKeyValuePairMethodInfo { get { return _helper.GetKeyValuePairMethodInfo; } } internal ConstructorInfo GetISerializableConstructor() { return _helper.GetISerializableConstructor(); } private ConstructorInfo _nonAttributedTypeConstructor; internal ConstructorInfo GetNonAttributedTypeConstructor() { if (_nonAttributedTypeConstructor == null) { // Cache the ConstructorInfo to improve performance. _nonAttributedTypeConstructor = _helper.GetNonAttributedTypeConstructor(); } return _nonAttributedTypeConstructor; } private Func<object> _makeNewInstance; private Func<object> MakeNewInstance { get { if (_makeNewInstance == null) { _makeNewInstance = FastInvokerBuilder.GetMakeNewInstanceFunc(UnderlyingType); } return _makeNewInstance; } } internal bool CreateNewInstanceViaDefaultConstructor(out object obj) { ConstructorInfo ci = GetNonAttributedTypeConstructor(); if (ci == null) { obj = null; return false; } if (ci.IsPublic) { // Optimization for calling public default ctor. obj = MakeNewInstance(); } else { obj = ci.Invoke(Array.Empty<object>()); } return true; } #if uapaot private XmlFormatClassWriterDelegate _xmlFormatWriterDelegate; public XmlFormatClassWriterDelegate XmlFormatWriterDelegate #else internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate #endif { get { #if uapaot if (DataContractSerializer.Option == SerializationOption.CodeGenOnly || (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatWriterDelegate != null)) { return _xmlFormatWriterDelegate; } #endif if (_helper.XmlFormatWriterDelegate == null) { lock (this) { if (_helper.XmlFormatWriterDelegate == null) { XmlFormatClassWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateClassWriter(this); Interlocked.MemoryBarrier(); _helper.XmlFormatWriterDelegate = tempDelegate; } } } return _helper.XmlFormatWriterDelegate; } set { #if uapaot _xmlFormatWriterDelegate = value; #endif } } #if uapaot private XmlFormatClassReaderDelegate _xmlFormatReaderDelegate; public XmlFormatClassReaderDelegate XmlFormatReaderDelegate #else internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate #endif { get { #if uapaot if (DataContractSerializer.Option == SerializationOption.CodeGenOnly || (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatReaderDelegate != null)) { return _xmlFormatReaderDelegate; } #endif if (_helper.XmlFormatReaderDelegate == null) { lock (this) { if (_helper.XmlFormatReaderDelegate == null) { XmlFormatClassReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateClassReader(this); Interlocked.MemoryBarrier(); _helper.XmlFormatReaderDelegate = tempDelegate; } } } return _helper.XmlFormatReaderDelegate; } set { #if uapaot _xmlFormatReaderDelegate = value; #endif } } internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames) { ClassDataContract cdc = (ClassDataContract)DataContract.GetDataContractFromGeneratedAssembly(type); if (cdc == null) { return new ClassDataContract(type, ns, memberNames); } else { ClassDataContract cloned = cdc.Clone(); cloned.UpdateNamespaceAndMembers(type, ns, memberNames); return cloned; } } internal static void CheckAndAddMember(List<DataMember> members, DataMember memberContract, Dictionary<string, DataMember> memberNamesTable) { DataMember existingMemberContract; if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract)) { Type declaringType = memberContract.MemberInfo.DeclaringType; DataContract.ThrowInvalidDataContractException( SR.Format((declaringType.IsEnum ? SR.DupEnumMemberValue : SR.DupMemberName), existingMemberContract.MemberInfo.Name, memberContract.MemberInfo.Name, DataContract.GetClrTypeFullName(declaringType), memberContract.Name), declaringType); } memberNamesTable.Add(memberContract.Name, memberContract); members.Add(memberContract); } internal static XmlDictionaryString GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary) { childType = DataContract.UnwrapNullableType(childType); if (!childType.IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType) && DataContract.GetBuiltInDataContract(childType) == null && childType != Globals.TypeOfDBNull) { string ns = DataContract.GetStableName(childType).Namespace; if (ns.Length > 0 && ns != dataContract.Namespace.Value) return dictionary.Add(ns); } return null; } private static bool IsArraySegment(Type t) { return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>)); } /// <SecurityNote> /// RequiresReview - callers may need to depend on isNonAttributedType for a security decision /// isNonAttributedType must be calculated correctly /// IsNonAttributedTypeValidForSerialization is used as part of the isNonAttributedType calculation and /// is therefore marked SRR /// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value /// </SecurityNote> internal static bool IsNonAttributedTypeValidForSerialization(Type type) { if (type.IsArray) return false; if (type.IsEnum) return false; if (type.IsGenericParameter) return false; if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) return false; if (type.IsPointer) return false; if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) return false; Type[] interfaceTypes = type.GetInterfaces(); if (!IsArraySegment(type)) { foreach (Type interfaceType in interfaceTypes) { if (CollectionDataContract.IsCollectionInterface(interfaceType)) return false; } } if (type.IsSerializable) return false; if (Globals.TypeOfISerializable.IsAssignableFrom(type)) return false; if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) return false; if (type.IsValueType) { return type.IsVisible; } else { return (type.IsVisible && type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()) != null); } } private static readonly Dictionary<string, string[]> s_knownSerializableTypeInfos = new Dictionary<string, string[]> { { "System.Collections.Generic.KeyValuePair`2", Array.Empty<string>() }, { "System.Collections.Generic.Queue`1", new [] { "_syncRoot" } }, { "System.Collections.Generic.Stack`1", new [] {"_syncRoot" } }, { "System.Collections.ObjectModel.ReadOnlyCollection`1", new [] {"_syncRoot" } }, { "System.Collections.ObjectModel.ReadOnlyDictionary`2", new [] {"_syncRoot", "_keys","_values" } }, { "System.Tuple`1", Array.Empty<string>() }, { "System.Tuple`2", Array.Empty<string>() }, { "System.Tuple`3", Array.Empty<string>() }, { "System.Tuple`4", Array.Empty<string>() }, { "System.Tuple`5", Array.Empty<string>() }, { "System.Tuple`6", Array.Empty<string>() }, { "System.Tuple`7", Array.Empty<string>() }, { "System.Tuple`8", Array.Empty<string>() }, { "System.Collections.Queue", new [] {"_syncRoot" } }, { "System.Collections.Stack", new [] {"_syncRoot" } }, { "System.Globalization.CultureInfo", Array.Empty<string>() }, { "System.Version", Array.Empty<string>() }, }; private static string GetGeneralTypeName(Type type) { return type.IsGenericType && !type.IsGenericParameter ? type.GetGenericTypeDefinition().FullName : type.FullName; } internal static bool IsKnownSerializableType(Type type) { // Applies to known types that DCS understands how to serialize/deserialize // string typeFullName = GetGeneralTypeName(type); return s_knownSerializableTypeInfos.ContainsKey(typeFullName) || Globals.TypeOfException.IsAssignableFrom(type); } internal static bool IsNonSerializedMember(Type type, string memberName) { string typeFullName = GetGeneralTypeName(type); string[] members; return s_knownSerializableTypeInfos.TryGetValue(typeFullName, out members) && members.Contains(memberName); } private XmlDictionaryString[] CreateChildElementNamespaces() { if (Members == null) return null; XmlDictionaryString[] baseChildElementNamespaces = null; if (this.BaseContract != null) baseChildElementNamespaces = this.BaseContract.ChildElementNamespaces; int baseChildElementNamespaceCount = (baseChildElementNamespaces != null) ? baseChildElementNamespaces.Length : 0; XmlDictionaryString[] childElementNamespaces = new XmlDictionaryString[Members.Count + baseChildElementNamespaceCount]; if (baseChildElementNamespaceCount > 0) Array.Copy(baseChildElementNamespaces, 0, childElementNamespaces, 0, baseChildElementNamespaces.Length); XmlDictionary dictionary = new XmlDictionary(); for (int i = 0; i < this.Members.Count; i++) { childElementNamespaces[i + baseChildElementNamespaceCount] = GetChildNamespaceToDeclare(this, this.Members[i].MemberType, dictionary); } return childElementNamespaces; } private void EnsureMethodsImported() { _helper.EnsureMethodsImported(); } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { if (_isScriptObject) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } XmlFormatWriterDelegate(xmlWriter, obj, context, this); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { if (_isScriptObject) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } xmlReader.Read(); object o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces); xmlReader.ReadEndElement(); return o; } /// <SecurityNote> /// Review - calculates whether this class requires MemberAccessPermission for deserialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForRead(SecurityException securityException) { EnsureMethodsImported(); if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForRead(securityException)) return true; if (ConstructorRequiresMemberAccess(GetNonAttributedTypeConstructor())) { if (Globals.TypeOfScriptObject_IsAssignableFrom(UnderlyingType)) { return true; } if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustNonAttributedSerializableTypeNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnDeserializing)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnDeserializingNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnDeserializing.Name), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnDeserialized)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnDeserializedNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnDeserialized.Name), securityException)); } return true; } if (this.Members != null) { for (int i = 0; i < this.Members.Count; i++) { if (this.Members[i].RequiresMemberAccessForSet()) { if (securityException != null) { if (this.Members[i].MemberInfo is FieldInfo) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractFieldSetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractPropertySetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } } return true; } } } return false; } /// <SecurityNote> /// Review - calculates whether this class requires MemberAccessPermission for serialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForWrite(SecurityException securityException) { EnsureMethodsImported(); if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForWrite(securityException)) return true; if (MethodRequiresMemberAccess(this.OnSerializing)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnSerializingNotPublic, DataContract.GetClrTypeFullName(this.UnderlyingType), this.OnSerializing.Name), securityException)); } return true; } if (MethodRequiresMemberAccess(this.OnSerialized)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractOnSerializedNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.OnSerialized.Name), securityException)); } return true; } if (this.Members != null) { for (int i = 0; i < this.Members.Count; i++) { if (this.Members[i].RequiresMemberAccessForGet()) { if (securityException != null) { if (this.Members[i].MemberInfo is FieldInfo) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractFieldGetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustDataContractPropertyGetNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.Members[i].MemberInfo.Name), securityException)); } } return true; } } } return false; } private class ClassDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private static Type[] s_serInfoCtorArgs; private ClassDataContract _baseContract; private List<DataMember> _members; private MethodInfo _onSerializing, _onSerialized; private MethodInfo _onDeserializing, _onDeserialized; private MethodInfo _extensionDataSetMethod; private DataContractDictionary _knownDataContracts; private bool _isISerializable; private bool _isKnownTypeAttributeChecked; private bool _isMethodChecked; /// <SecurityNote> /// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and hasDataContract /// </SecurityNote> private bool _isNonAttributedType; /// <SecurityNote> /// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and isNonAttributedType /// </SecurityNote> private bool _hasDataContract; private bool _hasExtensionData; private bool _isScriptObject; private XmlDictionaryString[] _childElementNamespaces; private XmlFormatClassReaderDelegate _xmlFormatReaderDelegate; private XmlFormatClassWriterDelegate _xmlFormatWriterDelegate; public XmlDictionaryString[] ContractNamespaces; public XmlDictionaryString[] MemberNames; public XmlDictionaryString[] MemberNamespaces; internal ClassDataContractCriticalHelper() : base() { } internal ClassDataContractCriticalHelper(Type type) : base(type) { XmlQualifiedName stableName = GetStableNameAndSetHasDataContract(type); if (type == Globals.TypeOfDBNull) { this.StableName = stableName; _members = new List<DataMember>(); XmlDictionary dictionary = new XmlDictionary(2); this.Name = dictionary.Add(StableName.Name); this.Namespace = dictionary.Add(StableName.Namespace); this.ContractNamespaces = this.MemberNames = this.MemberNamespaces = Array.Empty<XmlDictionaryString>(); EnsureMethodsImported(); return; } Type baseType = type.BaseType; _isISerializable = (Globals.TypeOfISerializable.IsAssignableFrom(type)); SetIsNonAttributedType(type); if (_isISerializable) { if (HasDataContract) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.ISerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type)))); if (baseType != null && !(baseType.IsSerializable && Globals.TypeOfISerializable.IsAssignableFrom(baseType))) baseType = null; } SetKeyValuePairAdapterFlags(type); this.IsValueType = type.IsValueType; if (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) { DataContract baseContract = DataContract.GetDataContract(baseType); if (baseContract is CollectionDataContract) this.BaseContract = ((CollectionDataContract)baseContract).SharedTypeContract as ClassDataContract; else this.BaseContract = baseContract as ClassDataContract; if (this.BaseContract != null && this.BaseContract.IsNonAttributedType && !_isNonAttributedType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError (new InvalidDataContractException(SR.Format(SR.AttributedTypesCannotInheritFromNonAttributedSerializableTypes, DataContract.GetClrTypeFullName(type), DataContract.GetClrTypeFullName(baseType)))); } } else { this.BaseContract = null; } _hasExtensionData = (Globals.TypeOfIExtensibleDataObject.IsAssignableFrom(type)); if (_hasExtensionData && !HasDataContract && !IsNonAttributedType) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.OnlyDataContractTypesCanHaveExtensionData, DataContract.GetClrTypeFullName(type)))); } if (_isISerializable) { SetDataContractName(stableName); } else { this.StableName = stableName; ImportDataMembers(); XmlDictionary dictionary = new XmlDictionary(2 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = dictionary.Add(StableName.Namespace); int baseMemberCount = 0; int baseContractCount = 0; if (BaseContract == null) { MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; ContractNamespaces = new XmlDictionaryString[1]; } else { baseMemberCount = BaseContract.MemberNames.Length; MemberNames = new XmlDictionaryString[Members.Count + baseMemberCount]; Array.Copy(BaseContract.MemberNames, 0, MemberNames, 0, baseMemberCount); MemberNamespaces = new XmlDictionaryString[Members.Count + baseMemberCount]; Array.Copy(BaseContract.MemberNamespaces, 0, MemberNamespaces, 0, baseMemberCount); baseContractCount = BaseContract.ContractNamespaces.Length; ContractNamespaces = new XmlDictionaryString[1 + baseContractCount]; Array.Copy(BaseContract.ContractNamespaces, 0, ContractNamespaces, 0, baseContractCount); } ContractNamespaces[baseContractCount] = Namespace; for (int i = 0; i < Members.Count; i++) { MemberNames[i + baseMemberCount] = dictionary.Add(Members[i].Name); MemberNamespaces[i + baseMemberCount] = Namespace; } } EnsureMethodsImported(); _isScriptObject = this.IsNonAttributedType && Globals.TypeOfScriptObject_IsAssignableFrom(this.UnderlyingType); } internal ClassDataContractCriticalHelper(Type type, XmlDictionaryString ns, string[] memberNames) : base(type) { this.StableName = new XmlQualifiedName(GetStableNameAndSetHasDataContract(type).Name, ns.Value); ImportDataMembers(); XmlDictionary dictionary = new XmlDictionary(1 + Members.Count); Name = dictionary.Add(StableName.Name); Namespace = ns; ContractNamespaces = new XmlDictionaryString[] { Namespace }; MemberNames = new XmlDictionaryString[Members.Count]; MemberNamespaces = new XmlDictionaryString[Members.Count]; for (int i = 0; i < Members.Count; i++) { Members[i].Name = memberNames[i]; MemberNames[i] = dictionary.Add(Members[i].Name); MemberNamespaces[i] = Namespace; } EnsureMethodsImported(); } private void EnsureIsReferenceImported(Type type) { DataContractAttribute dataContractAttribute; bool isReference = false; bool hasDataContractAttribute = TryGetDCAttribute(type, out dataContractAttribute); if (BaseContract != null) { if (hasDataContractAttribute && dataContractAttribute.IsReferenceSetExplicitly) { bool baseIsReference = this.BaseContract.IsReference; if ((baseIsReference && !dataContractAttribute.IsReference) || (!baseIsReference && dataContractAttribute.IsReference)) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.InconsistentIsReference, DataContract.GetClrTypeFullName(type), dataContractAttribute.IsReference, DataContract.GetClrTypeFullName(this.BaseContract.UnderlyingType), this.BaseContract.IsReference), type); } else { isReference = dataContractAttribute.IsReference; } } else { isReference = this.BaseContract.IsReference; } } else if (hasDataContractAttribute) { if (dataContractAttribute.IsReference) isReference = dataContractAttribute.IsReference; } if (isReference && type.IsValueType) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.ValueTypeCannotHaveIsReference, DataContract.GetClrTypeFullName(type), true, false), type); return; } this.IsReference = isReference; } private void ImportDataMembers() { Type type = this.UnderlyingType; EnsureIsReferenceImported(type); List<DataMember> tempMembers = new List<DataMember>(); Dictionary<string, DataMember> memberNamesTable = new Dictionary<string, DataMember>(); MemberInfo[] memberInfos; bool isPodSerializable = !_isNonAttributedType || IsKnownSerializableType(type); if (!isPodSerializable) { memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); } else { memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } for (int i = 0; i < memberInfos.Length; i++) { MemberInfo member = memberInfos[i]; if (HasDataContract) { object[] memberAttributes = member.GetCustomAttributes(typeof(DataMemberAttribute), false).ToArray(); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name)); DataMember memberContract = new DataMember(member); if (member is PropertyInfo) { PropertyInfo property = (PropertyInfo)member; MethodInfo getMethod = property.GetMethod; if (getMethod != null && IsMethodOverriding(getMethod)) continue; MethodInfo setMethod = property.SetMethod; if (setMethod != null && IsMethodOverriding(setMethod)) continue; if (getMethod == null) ThrowInvalidDataContractException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property.Name)); if (setMethod == null) { if (!SetIfGetOnlyCollection(memberContract)) { ThrowInvalidDataContractException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property.Name)); } } if (getMethod.GetParameters().Length > 0) ThrowInvalidDataContractException(SR.Format(SR.IndexedPropertyCannotBeSerialized, property.DeclaringType, property.Name)); } else if (!(member is FieldInfo)) ThrowInvalidDataContractException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(type), member.Name)); DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0]; if (memberAttribute.IsNameSetExplicitly) { if (memberAttribute.Name == null || memberAttribute.Name.Length == 0) ThrowInvalidDataContractException(SR.Format(SR.InvalidDataMemberName, member.Name, DataContract.GetClrTypeFullName(type))); memberContract.Name = memberAttribute.Name; } else memberContract.Name = member.Name; memberContract.Name = DataContract.EncodeLocalName(memberContract.Name); memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); memberContract.IsRequired = memberAttribute.IsRequired; if (memberAttribute.IsRequired && this.IsReference) { ThrowInvalidDataContractException( SR.Format(SR.IsRequiredDataMemberOnIsReferenceDataContractType, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name, true), type); } memberContract.EmitDefaultValue = memberAttribute.EmitDefaultValue; memberContract.Order = memberAttribute.Order; CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } } else if (!isPodSerializable) { FieldInfo field = member as FieldInfo; PropertyInfo property = member as PropertyInfo; if ((field == null && property == null) || (field != null && field.IsInitOnly)) continue; object[] memberAttributes = member.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).ToArray(); if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name)); else continue; } DataMember memberContract = new DataMember(member); if (property != null) { MethodInfo getMethod = property.GetMethod; if (getMethod == null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0) continue; MethodInfo setMethod = property.SetMethod; if (setMethod == null) { if (!SetIfGetOnlyCollection(memberContract)) continue; } else { if (!setMethod.IsPublic || IsMethodOverriding(setMethod)) continue; } } memberContract.Name = DataContract.EncodeLocalName(member.Name); memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } else { FieldInfo field = member as FieldInfo; bool canSerializeMember; // Previously System.SerializableAttribute was not available in NetCore, so we had // a list of known [Serializable] types for type in the framework. Although now SerializableAttribute // is available in NetCore, some framework types still do not have [Serializable] // yet, e.g. ReadOnlyDictionary<TKey, TValue>. So, we still need to maintain the known serializable // type list. if (IsKnownSerializableType(type)) { canSerializeMember = CanSerializeMember(field); } else { canSerializeMember = field != null && !field.IsNotSerialized; } if (canSerializeMember) { DataMember memberContract = new DataMember(member); memberContract.Name = DataContract.EncodeLocalName(member.Name); object[] optionalFields = field.GetCustomAttributes(Globals.TypeOfOptionalFieldAttribute, false); if (optionalFields == null || optionalFields.Length == 0) { if (this.IsReference) { ThrowInvalidDataContractException( SR.Format(SR.NonOptionalFieldMemberOnIsReferenceSerializableType, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name, true), type); } memberContract.IsRequired = true; } memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType); CheckAndAddMember(tempMembers, memberContract, memberNamesTable); } } } if (tempMembers.Count > 1) tempMembers.Sort(DataMemberComparer.Singleton); SetIfMembersHaveConflict(tempMembers); Interlocked.MemoryBarrier(); _members = tempMembers; } private static bool CanSerializeMember(FieldInfo field) { return field != null && !ClassDataContract.IsNonSerializedMember(field.DeclaringType, field.Name); } private bool SetIfGetOnlyCollection(DataMember memberContract) { //OK to call IsCollection here since the use of surrogated collection types is not supported in get-only scenarios if (CollectionDataContract.IsCollection(memberContract.MemberType, false /*isConstructorRequired*/) && !memberContract.MemberType.IsValueType) { memberContract.IsGetOnlyCollection = true; return true; } return false; } private void SetIfMembersHaveConflict(List<DataMember> members) { if (BaseContract == null) return; int baseTypeIndex = 0; List<Member> membersInHierarchy = new List<Member>(); foreach (DataMember member in members) { membersInHierarchy.Add(new Member(member, this.StableName.Namespace, baseTypeIndex)); } ClassDataContract currContract = BaseContract; while (currContract != null) { baseTypeIndex++; foreach (DataMember member in currContract.Members) { membersInHierarchy.Add(new Member(member, currContract.StableName.Namespace, baseTypeIndex)); } currContract = currContract.BaseContract; } IComparer<Member> comparer = DataMemberConflictComparer.Singleton; membersInHierarchy.Sort(comparer); for (int i = 0; i < membersInHierarchy.Count - 1; i++) { int startIndex = i; int endIndex = i; bool hasConflictingType = false; while (endIndex < membersInHierarchy.Count - 1 && String.CompareOrdinal(membersInHierarchy[endIndex].member.Name, membersInHierarchy[endIndex + 1].member.Name) == 0 && String.CompareOrdinal(membersInHierarchy[endIndex].ns, membersInHierarchy[endIndex + 1].ns) == 0) { membersInHierarchy[endIndex].member.ConflictingMember = membersInHierarchy[endIndex + 1].member; if (!hasConflictingType) { if (membersInHierarchy[endIndex + 1].member.HasConflictingNameAndType) { hasConflictingType = true; } else { hasConflictingType = (membersInHierarchy[endIndex].member.MemberType != membersInHierarchy[endIndex + 1].member.MemberType); } } endIndex++; } if (hasConflictingType) { for (int j = startIndex; j <= endIndex; j++) { membersInHierarchy[j].member.HasConflictingNameAndType = true; } } i = endIndex + 1; } } private XmlQualifiedName GetStableNameAndSetHasDataContract(Type type) { return DataContract.GetStableName(type, out _hasDataContract); } /// <SecurityNote> /// RequiresReview - marked SRR because callers may need to depend on isNonAttributedType for a security decision /// isNonAttributedType must be calculated correctly /// SetIsNonAttributedType should not be called before GetStableNameAndSetHasDataContract since it /// is dependent on the correct calculation of hasDataContract /// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value /// </SecurityNote> private void SetIsNonAttributedType(Type type) { _isNonAttributedType = !type.IsSerializable && !_hasDataContract && IsNonAttributedTypeValidForSerialization(type); } private static bool IsMethodOverriding(MethodInfo method) { return method.IsVirtual && ((method.Attributes & MethodAttributes.NewSlot) == 0); } internal void EnsureMethodsImported() { if (!_isMethodChecked && UnderlyingType != null) { lock (this) { if (!_isMethodChecked) { Type type = this.UnderlyingType; MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < methods.Length; i++) { MethodInfo method = methods[i]; Type prevAttributeType = null; ParameterInfo[] parameters = method.GetParameters(); if (HasExtensionData && IsValidExtensionDataSetMethod(method, parameters)) { if (method.Name == Globals.ExtensionDataSetExplicitMethod || !method.IsPublic) _extensionDataSetMethod = XmlFormatGeneratorStatics.ExtensionDataSetExplicitMethodInfo; else _extensionDataSetMethod = method; } if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializingAttribute, _onSerializing, ref prevAttributeType)) _onSerializing = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializedAttribute, _onSerialized, ref prevAttributeType)) _onSerialized = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializingAttribute, _onDeserializing, ref prevAttributeType)) _onDeserializing = method; if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializedAttribute, _onDeserialized, ref prevAttributeType)) _onDeserialized = method; } Interlocked.MemoryBarrier(); _isMethodChecked = true; } } } } private bool IsValidExtensionDataSetMethod(MethodInfo method, ParameterInfo[] parameters) { if (method.Name == Globals.ExtensionDataSetExplicitMethod || method.Name == Globals.ExtensionDataSetMethod) { if (_extensionDataSetMethod != null) ThrowInvalidDataContractException(SR.Format(SR.DuplicateExtensionDataSetMethod, method, _extensionDataSetMethod, DataContract.GetClrTypeFullName(method.DeclaringType))); if (method.ReturnType != Globals.TypeOfVoid) DataContract.ThrowInvalidDataContractException(SR.Format(SR.ExtensionDataSetMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfExtensionDataObject) DataContract.ThrowInvalidDataContractException(SR.Format(SR.ExtensionDataSetParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfExtensionDataObject), method.DeclaringType); return true; } return false; } private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType) { if (method.IsDefined(attributeType, false)) { if (currentCallback != null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateCallback, method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); else if (prevAttributeType != null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateAttribute, prevAttributeType, attributeType, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); else if (method.IsVirtual) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbacksCannotBeVirtualMethods, method, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); else { if (method.ReturnType != Globals.TypeOfVoid) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType); if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfStreamingContext) DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfStreamingContext), method.DeclaringType); prevAttributeType = attributeType; } return true; } return false; } internal ClassDataContract BaseContract { get { return _baseContract; } set { _baseContract = value; if (_baseContract != null && IsValueType) ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName.Name, StableName.Namespace, _baseContract.StableName.Name, _baseContract.StableName.Namespace)); } } internal List<DataMember> Members { get { return _members; } } internal MethodInfo OnSerializing { get { EnsureMethodsImported(); return _onSerializing; } } internal MethodInfo OnSerialized { get { EnsureMethodsImported(); return _onSerialized; } } internal MethodInfo OnDeserializing { get { EnsureMethodsImported(); return _onDeserializing; } } internal MethodInfo OnDeserialized { get { EnsureMethodsImported(); return _onDeserialized; } } internal MethodInfo ExtensionDataSetMethod { get { EnsureMethodsImported(); return _extensionDataSetMethod; } } internal override DataContractDictionary KnownDataContracts { get { if (_knownDataContracts != null) { return _knownDataContracts; } if (!_isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!_isKnownTypeAttributeChecked) { _knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Interlocked.MemoryBarrier(); _isKnownTypeAttributeChecked = true; } } } return _knownDataContracts; } set { _knownDataContracts = value; } } internal override bool IsISerializable { get { return _isISerializable; } set { _isISerializable = value; } } internal bool HasDataContract { get { return _hasDataContract; } #if uapaot set { _hasDataContract = value; } #endif } internal bool HasExtensionData { get { return _hasExtensionData; } set { _hasExtensionData = value; } } internal bool IsNonAttributedType { get { return _isNonAttributedType; } } private void SetKeyValuePairAdapterFlags(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter) { _isKeyValuePairAdapter = true; _keyValuePairGenericArguments = type.GetGenericArguments(); _keyValuePairCtorInfo = type.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfKeyValuePair.MakeGenericType(_keyValuePairGenericArguments) }); _getKeyValuePairMethodInfo = type.GetMethod("GetKeyValuePair", Globals.ScanAllMembers); } } private bool _isKeyValuePairAdapter; private Type[] _keyValuePairGenericArguments; private ConstructorInfo _keyValuePairCtorInfo; private MethodInfo _getKeyValuePairMethodInfo; internal bool IsKeyValuePairAdapter { get { return _isKeyValuePairAdapter; } } internal bool IsScriptObject { get { return _isScriptObject; } } internal Type[] KeyValuePairGenericArguments { get { return _keyValuePairGenericArguments; } } internal ConstructorInfo KeyValuePairAdapterConstructorInfo { get { return _keyValuePairCtorInfo; } } internal MethodInfo GetKeyValuePairMethodInfo { get { return _getKeyValuePairMethodInfo; } } internal ConstructorInfo GetISerializableConstructor() { if (!IsISerializable) return null; ConstructorInfo ctor = UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, SerInfoCtorArgs, null); if (ctor == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(UnderlyingType)))); return ctor; } internal ConstructorInfo GetNonAttributedTypeConstructor() { if (!this.IsNonAttributedType) return null; Type type = UnderlyingType; if (type.IsValueType) return null; ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.NonAttributedSerializableTypesMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type)))); return ctor; } internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate { get { return _xmlFormatWriterDelegate; } set { _xmlFormatWriterDelegate = value; } } internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate { get { return _xmlFormatReaderDelegate; } set { _xmlFormatReaderDelegate = value; } } public XmlDictionaryString[] ChildElementNamespaces { get { return _childElementNamespaces; } set { _childElementNamespaces = value; } } private static Type[] SerInfoCtorArgs { get { if (s_serInfoCtorArgs == null) s_serInfoCtorArgs = new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; return s_serInfoCtorArgs; } } internal struct Member { internal Member(DataMember member, string ns, int baseTypeIndex) { this.member = member; this.ns = ns; this.baseTypeIndex = baseTypeIndex; } internal DataMember member; internal string ns; internal int baseTypeIndex; } internal class DataMemberConflictComparer : IComparer<Member> { public int Compare(Member x, Member y) { int nsCompare = String.CompareOrdinal(x.ns, y.ns); if (nsCompare != 0) return nsCompare; int nameCompare = String.CompareOrdinal(x.member.Name, y.member.Name); if (nameCompare != 0) return nameCompare; return x.baseTypeIndex - y.baseTypeIndex; } internal static DataMemberConflictComparer Singleton = new DataMemberConflictComparer(); } internal ClassDataContractCriticalHelper Clone() { ClassDataContractCriticalHelper clonedHelper = new ClassDataContractCriticalHelper(this.UnderlyingType); clonedHelper._baseContract = this._baseContract; clonedHelper._childElementNamespaces = this._childElementNamespaces; clonedHelper.ContractNamespaces = this.ContractNamespaces; clonedHelper._hasDataContract = this._hasDataContract; clonedHelper._isMethodChecked = this._isMethodChecked; clonedHelper._isNonAttributedType = this._isNonAttributedType; clonedHelper.IsReference = this.IsReference; clonedHelper.IsValueType = this.IsValueType; clonedHelper.MemberNames = this.MemberNames; clonedHelper.MemberNamespaces = this.MemberNamespaces; clonedHelper._members = this._members; clonedHelper.Name = this.Name; clonedHelper.Namespace = this.Namespace; clonedHelper._onDeserialized = this._onDeserialized; clonedHelper._onDeserializing = this._onDeserializing; clonedHelper._onSerialized = this._onSerialized; clonedHelper._onSerializing = this._onSerializing; clonedHelper.StableName = this.StableName; clonedHelper.TopLevelElementName = this.TopLevelElementName; clonedHelper.TopLevelElementNamespace = this.TopLevelElementNamespace; clonedHelper._xmlFormatReaderDelegate = this._xmlFormatReaderDelegate; clonedHelper._xmlFormatWriterDelegate = this._xmlFormatWriterDelegate; return clonedHelper; } } internal class DataMemberComparer : IComparer<DataMember> { public int Compare(DataMember x, DataMember y) { int orderCompare = x.Order - y.Order; if (orderCompare != 0) return orderCompare; return String.CompareOrdinal(x.Name, y.Name); } internal static DataMemberComparer Singleton = new DataMemberComparer(); } #if !uapaot /// <summary> /// Get object type for Xml/JsonFormmatReaderGenerator /// </summary> internal Type ObjectType { get { Type type = UnderlyingType; if (type.IsValueType && !IsNonAttributedType) { type = Globals.TypeOfValueType; } return type; } } #endif internal ClassDataContract Clone() { ClassDataContract clonedDc = new ClassDataContract(this.UnderlyingType); clonedDc._helper = _helper.Clone(); clonedDc.ContractNamespaces = this.ContractNamespaces; clonedDc.ChildElementNamespaces = this.ChildElementNamespaces; clonedDc.MemberNames = this.MemberNames; clonedDc.MemberNamespaces = this.MemberNamespaces; clonedDc.XmlFormatWriterDelegate = this.XmlFormatWriterDelegate; clonedDc.XmlFormatReaderDelegate = this.XmlFormatReaderDelegate; return clonedDc; } internal void UpdateNamespaceAndMembers(Type type, XmlDictionaryString ns, string[] memberNames) { this.StableName = new XmlQualifiedName(GetStableName(type).Name, ns.Value); this.Namespace = ns; XmlDictionary dictionary = new XmlDictionary(1 + memberNames.Length); this.Name = dictionary.Add(StableName.Name); this.Namespace = ns; this.ContractNamespaces = new XmlDictionaryString[] { ns }; this.MemberNames = new XmlDictionaryString[memberNames.Length]; this.MemberNamespaces = new XmlDictionaryString[memberNames.Length]; for (int i = 0; i < memberNames.Length; i++) { this.MemberNames[i] = dictionary.Add(memberNames[i]); this.MemberNamespaces[i] = ns; } } internal Type UnadaptedClassType { get { if (IsKeyValuePairAdapter) { return Globals.TypeOfKeyValuePair.MakeGenericType(KeyValuePairGenericArguments); } else { return UnderlyingType; } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using Microsoft.Research.ClousotRegression; using System.Diagnostics.Contracts; namespace WebExamples { public class Tutorial { [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=11,MethodILOffset=42)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=27,MethodILOffset=42)] public static void SwapElements(ref int x, ref int y) { Contract.Ensures(x == Contract.OldValue(y)); Contract.Ensures(y == Contract.OldValue(x)); var tmp = y; y = x; x = tmp; } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=9,MethodILOffset=27)] public static void OrderAPair(ref int x, ref int y) { Contract.Ensures(x <= y); if (x > y) SwapElements(ref x, ref y); } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=126,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=114,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=46,MethodILOffset=131)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=46,MethodILOffset=119)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=96,MethodILOffset=119)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=35,MethodILOffset=131)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=50,MethodILOffset=131)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=77,MethodILOffset=131)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=35,MethodILOffset=119)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=50,MethodILOffset=119)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=77,MethodILOffset=119)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=103,MethodILOffset=119)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=103,MethodILOffset=131)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=114,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=114,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=96,MethodILOffset=119)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=96,MethodILOffset=119)] [Pure] public static int LinearSearch(int[] array, int from, int value) { Contract.Requires(array != null); Contract.Requires(from >= 0); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < array.Length); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= from); // We need it! Contract.Ensures(Contract.Result<int>() == -1 || array[Contract.Result<int>()] == value); for (int i = from; i < array.Length; i++) { if (array[i] == value) return i; } return -1; } #if !CLOUSOT2 [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=8,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=14,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=8,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=127,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=132,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=63,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=8,MethodILOffset=137)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=93,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=100,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=106,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=107,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=109,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=116,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=8,MethodILOffset=120)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=7,MethodILOffset=70)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=19,MethodILOffset=70)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=53,MethodILOffset=137)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"assert is valid",PrimaryILOffset=87,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=53,MethodILOffset=120)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=106,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=106,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=107,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=107,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=116,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=116,MethodILOffset=0)] public static int ZerosAtBeginning(int[] array) { Contract.Requires(array != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<int>(), index => array[index] == 0)); var i = 0; while (i < array.Length) { var nextZero = LinearSearch(array, i, 0); if (nextZero != -1) { Contract.Assert(nextZero >= i); array[nextZero] = array[i]; array[i] = 0; } else { return i; } i++; } return i; } #endif } static public class RiseForFun { [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.False,Message=@"assert is false",PrimaryILOffset=8,MethodILOffset=0)] static void Assert() { int x = 0, y = 0; Contract.Assert(x > y); } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=11,MethodILOffset=22)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=11,MethodILOffset=24)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible negation of MinValue of type Int32. The static checker determined that the condition 'i != Int32.MinValue' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add a precondition to document it: Contract.Requires(i != Int32.MinValue);",PrimaryILOffset=21,MethodILOffset=0)] static int Abs(int i) { Contract.Ensures(Contract.Result<int>() >= 0); // will this expression always return a positive value? return i > 0 ? i : -i; } #if !CLOUSOT2 [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as receiver)",PrimaryILOffset=2,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as receiver)",PrimaryILOffset=11,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=12,MethodILOffset=11)] // [RegressionOutcome(Outcome=ProofOutcome.False,Message=@"requires (always false) may be reachable: HasValue",PrimaryILOffset=12,MethodILOffset=21)] [RegressionOutcome(Outcome=ProofOutcome.False,Message=@"requires is false: HasValue",PrimaryILOffset=12,MethodILOffset=21)] static int CorrectUsage(int? opt) { if (opt.HasValue) return opt.Value + 1; return opt.Value; } #endif } class ArrayBounds { // What can possibly go wrong here? [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible use of a null array 'a'. The static checker determined that the condition 'a != null' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add a precondition to document it: Contract.Requires(a != null);",PrimaryILOffset=9,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Array access might be below the lower bound",PrimaryILOffset=9,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Array access might be above the upper bound",PrimaryILOffset=9,MethodILOffset=0)] static int Sum(int[] a, int start, int numItems) { int result = 0; for (int i = start; i < start + numItems; i++) result += a[i]; return result; } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=40,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=61,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=61,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=61,MethodILOffset=0)] static int SumFixed(int[] a, int start, int numItems) { Contract.Requires(a != null); Contract.Requires(0 <= start); Contract.Requires(0 <= numItems); Contract.Requires(start + numItems <= a.Length); int result = 0; for (int i = start; i < start + numItems; i++) result += a[i]; return result; } } class MinIndexExample { // Compute the index of the minimal element in data, or return -1 [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=73,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=59,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=62,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=34,MethodILOffset=78)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=23,MethodILOffset=78)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=38,MethodILOffset=78)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=59,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=59,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=62,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=62,MethodILOffset=0)] static int MinIndex(int[] data) { Contract.Requires(data != null); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < data.Length); var result = -1; for (int i = 0; i < data.Length; i++) { if (result < 0) { result = i; } else if (data[i] < data[result]) { result = i; } } return result; } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=21,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=7,MethodILOffset=13)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Array access might be below the lower bound",PrimaryILOffset=21,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=21,MethodILOffset=0)] static int BadUser(int[] data) { Contract.Requires(data != null); var minIndex = MinIndex(data); var minValue = data[minIndex]; return minValue; } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=25,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=7,MethodILOffset=13)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=25,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=25,MethodILOffset=0)] static int GoodUser(int[] data) { Contract.Requires(data != null); var minIndex = MinIndex(data); if (minIndex >= 0) { var minValue = data[minIndex]; return minValue; } return Int32.MinValue; } } static class Search { [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=28,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Array access might be above the upper bound",PrimaryILOffset=28,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=36,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=36,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=15,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=28,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=36,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"No underflow",PrimaryILOffset=22,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possible overflow in the arithmetic operation",PrimaryILOffset=22,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Division by zero ok",PrimaryILOffset=24,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"No overflow",PrimaryILOffset=24,MethodILOffset=0)] public static int BinarySearch_Wrong(int[] arr, int what) { Contract.Requires(arr != null); var inf = 0; var sup = arr.Length; while (inf <= sup) { var mid = checked((inf + sup)/ 2); if (arr[mid] == what) return what; if (arr[mid] < what) { sup = mid - 1; } else { inf = mid+1; } } return -1; } [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=32,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=32,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=40,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=40,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=15,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=32,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=40,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"No underflow",PrimaryILOffset=25,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"No overflow",PrimaryILOffset=25,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Division by zero ok",PrimaryILOffset=27,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"No overflow",PrimaryILOffset=27,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"No underflow",PrimaryILOffset=28,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"No overflow",PrimaryILOffset=28,MethodILOffset=0)] public static int BinarySearch_Correct(int[] arr, int what) { Contract.Requires(arr != null); var inf = 0; var sup = arr.Length - 1; while (inf <= sup) { var len = sup - inf; var mid = checked(inf + (sup - inf) / 2); if (arr[mid] == what) return what; if (arr[mid] < what) { sup = mid - 1; } else { inf = mid + 1; } } return -1; } } } namespace VMCAI { public class VMCAI { [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Array creation : ok",PrimaryILOffset=178,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=192,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=192,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=217,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=217,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=247,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=247,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Array creation : ok",PrimaryILOffset=259,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=278,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=278,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Lower bound access ok",PrimaryILOffset=279,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"Upper bound access ok",PrimaryILOffset=279,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=176,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=254,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=192,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=217,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=247,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=278,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=279,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=44,MethodILOffset=293)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as array)",PrimaryILOffset=66,MethodILOffset=293)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"No overflow (caused by a negative array size)",PrimaryILOffset=178,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"No overflow (caused by a negative array size)",PrimaryILOffset=259,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=20,MethodILOffset=293)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=33,MethodILOffset=293)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=51,MethodILOffset=293)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=70,MethodILOffset=293)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=115,MethodILOffset=293)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"ensures is valid",PrimaryILOffset=160,MethodILOffset=293)] public char[] Sanitize(char[] str, ref int lower, ref int upper) { Contract.Requires(str != null); Contract.Ensures(upper >= 0); Contract.Ensures(lower >= 0); Contract.Ensures(lower + upper <= str.Length); Contract.Ensures(lower + upper == Contract.Result<char[]>().Length); Contract.Ensures(Contract.ForAll(0, lower+upper, index => 'a' <= Contract.Result<char[]>()[index])); Contract.Ensures(Contract.ForAll(0, lower + upper, index => Contract.Result<char[]>()[index] <= 'z')); upper = lower = 0; var tmp = new char[str.Length]; int j = 0; for (int i = 0; i < str.Length; i++) { var ch = str[i]; if ('a' <= ch && ch <= 'z') { lower++; tmp[j++] = ch;} else if ('A' <= ch && ch<= 'Z') { upper++; tmp[j++] = (char)(ch | ' ');} } var result = new char[j]; for (int i = 0; i < j; i++) { result[i] = tmp[i]; } return result; } } } namespace ExamplesFromResearchPapers { public class SrivastavaGulwaniPLDI09 { [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"assert is valid",PrimaryILOffset=48,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message=@"assert is valid",PrimaryILOffset=64,MethodILOffset=0)] public void Example(bool b1, bool b2, bool b3) { int d, t, s; d = t = s = 0; while (b3) { if (b1) { t++; s = 0; } else if (b2) { if (s < 5) { d++; s++; } } } Contract.Assert(s + d + t >= 0); Contract.Assert(d <= s + 5 * t); } } public class Bagnara_LeviTalk { [ClousotRegressionTest] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=51,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=51,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=77,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=77,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=63,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=63,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=64,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=64,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Lower bound access ok",PrimaryILOffset=84,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Upper bound access ok",PrimaryILOffset=84,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as array)",PrimaryILOffset=14,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as array)",PrimaryILOffset=51,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as array)",PrimaryILOffset=77,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as array)",PrimaryILOffset=63,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as array)",PrimaryILOffset=64,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="valid non-null reference (as array)",PrimaryILOffset=84,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="Division by zero ok",PrimaryILOffset=95,MethodILOffset=0)] [RegressionOutcome(Outcome=ProofOutcome.True,Message="No overflow",PrimaryILOffset=95,MethodILOffset=0)] public void ShellSort(int n, int[] array) { Contract.Requires(array != null); Contract.Requires(n == array.Length); // just to adapt Bagnara example faithfully int h, i, j, B; h = 1; while (h * 3 + 1 < n) { h = 3 * h + 1; } while (h > 0) { i = h - 1; while(i < n) { B = array[i]; j = i; while (j >= h && array[j - h] > B) { array[j] = array[j - h]; j = j - h; } array[j] = B; i++; } h = h / 3; } } } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using JetBrains.Annotations; using NodaTime.Annotations; using NodaTime.Text; using NodaTime.Utility; using System; using System.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using static NodaTime.NodaConstants; namespace NodaTime { /// <summary> /// Represents an instant on the global timeline, with nanosecond resolution. /// </summary> /// <remarks> /// <para> /// An <see cref="Instant"/> has no concept of a particular time zone or calendar: it simply represents a point in /// time that can be globally agreed-upon. /// </para> /// <para> /// Equality and ordering comparisons are defined in the natural way, with earlier points on the timeline /// being considered "less than" later points. /// </para> /// </remarks> /// <threadsafety>This type is an immutable value type. See the thread safety section of the user guide for more information.</threadsafety> [TypeConverter(typeof(InstantTypeConverter))] [XmlSchemaProvider(nameof(AddSchema))] public readonly struct Instant : IEquatable<Instant>, IComparable<Instant>, IFormattable, IComparable, IXmlSerializable { // These correspond to -9998-01-01 and 9999-12-31 respectively. internal const int MinDays = -4371222; internal const int MaxDays = 2932896; private const long MinTicks = MinDays * TicksPerDay; private const long MaxTicks = (MaxDays + 1) * TicksPerDay - 1; private const long MinMilliseconds = MinDays * (long) MillisecondsPerDay; private const long MaxMilliseconds = (MaxDays + 1) * (long) MillisecondsPerDay - 1; private const long MinSeconds = MinDays * (long) SecondsPerDay; private const long MaxSeconds = (MaxDays + 1) * (long) SecondsPerDay - 1; /// <summary> /// Represents the smallest possible <see cref="Instant"/>. /// </summary> /// <remarks>This value is equivalent to -9998-01-01T00:00:00Z</remarks> public static Instant MinValue { get; } = new Instant(MinDays, 0); /// <summary> /// Represents the largest possible <see cref="Instant"/>. /// </summary> /// <remarks>This value is equivalent to 9999-12-31T23:59:59.999999999Z</remarks> public static Instant MaxValue { get; } = new Instant(MaxDays, NanosecondsPerDay - 1); /// <summary> /// Instant which is invalid *except* for comparison purposes; it is earlier than any valid value. /// This must never be exposed. /// </summary> internal static readonly Instant BeforeMinValue = new Instant(Duration.MinDays, deliberatelyInvalid: true); /// <summary> /// Instant which is invalid *except* for comparison purposes; it is later than any valid value. /// This must never be exposed. /// </summary> internal static readonly Instant AfterMaxValue = new Instant(Duration.MaxDays, deliberatelyInvalid: true); /// <summary> /// Time elapsed since the Unix epoch. /// </summary> private readonly Duration duration; #pragma warning disable CA1801 // Remove/use unused parameter /// <summary> /// Constructor which should *only* be used to construct the invalid instances. /// </summary> private Instant([Trusted] int days, bool deliberatelyInvalid) { this.duration = new Duration(days, 0); } #pragma warning restore CA1801 /// <summary> /// Constructor which constructs a new instance with the given duration, which /// is trusted to be valid. Should only be called from FromTrustedDuration and /// FromUntrustedDuration. /// </summary> private Instant([Trusted] Duration duration) { this.duration = duration; } internal Instant([Trusted] int days, [Trusted] long nanoOfDay) { Preconditions.DebugCheckArgumentRange(nameof(days), days, MinDays, MaxDays); Preconditions.DebugCheckArgumentRange(nameof(nanoOfDay), nanoOfDay, 0, NanosecondsPerDay - 1); duration = new Duration(days, nanoOfDay); } /// <summary> /// Creates an Instant with the given duration, with no validation (in release mode). /// </summary> internal static Instant FromTrustedDuration([Trusted] Duration duration) { Preconditions.DebugCheckArgumentRange(nameof(duration), duration.FloorDays, MinDays, MaxDays); return new Instant(duration); } /// <summary> /// Creates an Instant with the given duration, validating that it has a suitable /// "day" part. (It is assumed that the nanoOfDay is okay.) /// </summary> internal static Instant FromUntrustedDuration(Duration duration) { int days = duration.FloorDays; if (days < MinDays || days > MaxDays) { throw new OverflowException("Operation would overflow range of Instant"); } return new Instant(duration); } /// <summary> /// Returns whether or not this is a valid instant. Returns true for all but /// <see cref="BeforeMinValue"/> and <see cref="AfterMaxValue"/>. /// </summary> internal bool IsValid => DaysSinceEpoch >= MinDays && DaysSinceEpoch <= MaxDays; /// <summary> /// Get the elapsed time since the Unix epoch, to nanosecond resolution. /// </summary> /// <returns>The elapsed time since the Unix epoch.</returns> internal Duration TimeSinceEpoch => duration; /// <summary> /// Number of days since the local unix epoch. /// </summary> internal int DaysSinceEpoch => duration.FloorDays; /// <summary> /// Nanosecond within the day. /// </summary> internal long NanosecondOfDay => duration.NanosecondOfFloorDay; #region IComparable<Instant> and IComparable Members /// <summary> /// Compares the current object with another object of the same type. /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. /// The return value has the following meanings: /// <list type = "table"> /// <listheader> /// <term>Value</term> /// <description>Meaning</description> /// </listheader> /// <item> /// <term>&lt; 0</term> /// <description>This object is less than the <paramref name = "other" /> parameter.</description> /// </item> /// <item> /// <term>0</term> /// <description>This object is equal to <paramref name = "other" />.</description> /// </item> /// <item> /// <term>&gt; 0</term> /// <description>This object is greater than <paramref name = "other" />.</description> /// </item> /// </list> /// </returns> public int CompareTo(Instant other) => duration.CompareTo(other.duration); /// <summary> /// Implementation of <see cref="IComparable.CompareTo"/> to compare two instants. /// See the type documentation for a description of ordering semantics. /// </summary> /// <remarks> /// This uses explicit interface implementation to avoid it being called accidentally. The generic implementation should usually be preferred. /// </remarks> /// <exception cref="ArgumentException"><paramref name="obj"/> is non-null but does not refer to an instance of <see cref="Instant"/>.</exception> /// <param name="obj">The object to compare this value with.</param> /// <returns>The result of comparing this instant with another one; see <see cref="CompareTo(NodaTime.Instant)"/> for general details. /// If <paramref name="obj"/> is null, this method returns a value greater than 0. /// </returns> int IComparable.CompareTo(object obj) { if (obj is null) { return 1; } Preconditions.CheckArgument(obj is Instant, nameof(obj), "Object must be of type NodaTime.Instant."); return CompareTo((Instant) obj); } #endregion #region Object overrides /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; /// otherwise, <c>false</c>. /// </returns> public override bool Equals(object? obj) => obj is Instant other && Equals(other); /// <summary> /// Returns a hash code for this instance. /// See the type documentation for a description of equality semantics. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data /// structures like a hash table. /// </returns> public override int GetHashCode() => duration.GetHashCode(); #endregion // Object overrides /// <summary> /// Returns a new value of this instant with the given number of ticks added to it. /// </summary> /// <param name="ticks">The ticks to add to this instant to create the return value.</param> /// <returns>The result of adding the given number of ticks to this instant.</returns> [Pure] public Instant PlusTicks(long ticks) => FromUntrustedDuration(duration + Duration.FromTicks(ticks)); /// <summary> /// Returns a new value of this instant with the given number of nanoseconds added to it. /// </summary> /// <param name="nanoseconds">The nanoseconds to add to this instant to create the return value.</param> /// <returns>The result of adding the given number of ticks to this instant.</returns> [Pure] public Instant PlusNanoseconds(long nanoseconds) => FromUntrustedDuration(duration + Duration.FromNanoseconds(nanoseconds)); #region Operators /// <summary> /// Implements the operator + (addition) for <see cref="Instant" /> + <see cref="Duration" />. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns>A new <see cref="Instant" /> representing the sum of the given values.</returns> public static Instant operator +(Instant left, Duration right) => FromUntrustedDuration(left.duration + right); /// <summary> /// Adds the given offset to this instant, to return a <see cref="LocalInstant" />. /// A positive offset indicates that the local instant represents a "later local time" than the UTC /// representation of this instant. /// </summary> /// <remarks> /// This was previously an operator+ implementation, but operators can't be internal. /// </remarks> /// <param name="offset">The right hand side of the operator.</param> /// <returns>A new <see cref="LocalInstant" /> representing the sum of the given values.</returns> [Pure] internal LocalInstant Plus(Offset offset) => new LocalInstant(duration.PlusSmallNanoseconds(offset.Nanoseconds)); /// <summary> /// Adds the given offset to this instant, either returning a normal LocalInstant, /// or <see cref="LocalInstant.BeforeMinValue"/> or <see cref="LocalInstant.AfterMaxValue"/> /// if the value would overflow. /// </summary> /// <param name="offset"></param> /// <returns></returns> internal LocalInstant SafePlus(Offset offset) { int days = duration.FloorDays; // If we can do the arithmetic safely, do so. if (days > MinDays && days < MaxDays) { return Plus(offset); } // Handle BeforeMinValue and BeforeMaxValue simply. if (days < MinDays) { return LocalInstant.BeforeMinValue; } if (days > MaxDays) { return LocalInstant.AfterMaxValue; } // Okay, do the arithmetic as a Duration, then check the result for overflow, effectively. var asDuration = duration.PlusSmallNanoseconds(offset.Nanoseconds); if (asDuration.FloorDays < Instant.MinDays) { return LocalInstant.BeforeMinValue; } if (asDuration.FloorDays > Instant.MaxDays) { return LocalInstant.AfterMaxValue; } return new LocalInstant(asDuration); } /// <summary> /// Adds a duration to an instant. Friendly alternative to <c>operator+()</c>. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns>A new <see cref="Instant" /> representing the sum of the given values.</returns> public static Instant Add(Instant left, Duration right) => left + right; /// <summary> /// Returns the result of adding a duration to this instant, for a fluent alternative to <c>operator+()</c>. /// </summary> /// <param name="duration">The duration to add</param> /// <returns>A new <see cref="Instant" /> representing the result of the addition.</returns> [Pure] public Instant Plus(Duration duration) => this + duration; /// <summary> /// Implements the operator - (subtraction) for <see cref="Instant" /> - <see cref="Instant" />. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns>A new <see cref="Duration" /> representing the difference of the given values.</returns> public static Duration operator -(Instant left, Instant right) => left.duration - right.duration; /// <summary> /// Implements the operator - (subtraction) for <see cref="Instant" /> - <see cref="Duration" />. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns>A new <see cref="Instant" /> representing the difference of the given values.</returns> public static Instant operator -(Instant left, Duration right) => FromUntrustedDuration(left.duration - right); /// <summary> /// Subtracts one instant from another. Friendly alternative to <c>operator-()</c>. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns>A new <see cref="Duration" /> representing the difference of the given values.</returns> public static Duration Subtract(Instant left, Instant right) => left - right; /// <summary> /// Returns the result of subtracting another instant from this one, for a fluent alternative to <c>operator-()</c>. /// </summary> /// <param name="other">The other instant to subtract</param> /// <returns>A new <see cref="Instant" /> representing the result of the subtraction.</returns> [Pure] public Duration Minus(Instant other) => this - other; /// <summary> /// Subtracts a duration from an instant. Friendly alternative to <c>operator-()</c>. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns>A new <see cref="Instant" /> representing the difference of the given values.</returns> [Pure] public static Instant Subtract(Instant left, Duration right) => left - right; /// <summary> /// Returns the result of subtracting a duration from this instant, for a fluent alternative to <c>operator-()</c>. /// </summary> /// <param name="duration">The duration to subtract</param> /// <returns>A new <see cref="Instant" /> representing the result of the subtraction.</returns> [Pure] public Instant Minus(Duration duration) => this - duration; /// <summary> /// Implements the operator == (equality). /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if values are equal to each other, otherwise <c>false</c>.</returns> public static bool operator ==(Instant left, Instant right) => left.duration == right.duration; /// <summary> /// Implements the operator != (inequality). /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if values are not equal to each other, otherwise <c>false</c>.</returns> public static bool operator !=(Instant left, Instant right) => !(left == right); /// <summary> /// Implements the operator &lt; (less than). /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if the left value is less than the right value, otherwise <c>false</c>.</returns> public static bool operator <(Instant left, Instant right) => left.duration < right.duration; /// <summary> /// Implements the operator &lt;= (less than or equal). /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if the left value is less than or equal to the right value, otherwise <c>false</c>.</returns> public static bool operator <=(Instant left, Instant right) => left.duration <= right.duration; /// <summary> /// Implements the operator &gt; (greater than). /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if the left value is greater than the right value, otherwise <c>false</c>.</returns> public static bool operator >(Instant left, Instant right) => left.duration > right.duration; /// <summary> /// Implements the operator &gt;= (greater than or equal). /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if the left value is greater than or equal to the right value, otherwise <c>false</c>.</returns> public static bool operator >=(Instant left, Instant right) => left.duration >= right.duration; #endregion // Operators #region Convenience methods /// <summary> /// Returns a new instant corresponding to the given UTC date and time in the ISO calendar. /// In most cases applications should use <see cref="ZonedDateTime" /> to represent a date /// and time, but this method is useful in some situations where an <see cref="Instant" /> is /// required, such as time zone testing. /// </summary> /// <param name="year">The year. This is the "absolute year", /// so a value of 0 means 1 BC, for example.</param> /// <param name="monthOfYear">The month of year.</param> /// <param name="dayOfMonth">The day of month.</param> /// <param name="hourOfDay">The hour.</param> /// <param name="minuteOfHour">The minute.</param> /// <returns>An <see cref="Instant"/> value representing the given date and time in UTC and the ISO calendar.</returns> public static Instant FromUtc(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour) { var days = new LocalDate(year, monthOfYear, dayOfMonth).DaysSinceEpoch; var nanoOfDay = new LocalTime(hourOfDay, minuteOfHour).NanosecondOfDay; return new Instant(days, nanoOfDay); } /// <summary> /// Returns a new instant corresponding to the given UTC date and /// time in the ISO calendar. In most cases applications should /// use <see cref="ZonedDateTime" /> /// to represent a date and time, but this method is useful in some /// situations where an Instant is required, such as time zone testing. /// </summary> /// <param name="year">The year. This is the "absolute year", /// so a value of 0 means 1 BC, for example.</param> /// <param name="monthOfYear">The month of year.</param> /// <param name="dayOfMonth">The day of month.</param> /// <param name="hourOfDay">The hour.</param> /// <param name="minuteOfHour">The minute.</param> /// <param name="secondOfMinute">The second.</param> /// <returns>An <see cref="Instant"/> value representing the given date and time in UTC and the ISO calendar.</returns> public static Instant FromUtc(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute) { var days = new LocalDate(year, monthOfYear, dayOfMonth).DaysSinceEpoch; var nanoOfDay = new LocalTime(hourOfDay, minuteOfHour, secondOfMinute).NanosecondOfDay; return new Instant(days, nanoOfDay); } /// <summary> /// Returns the later instant of the given two. /// </summary> /// <param name="x">The first instant to compare.</param> /// <param name="y">The second instant to compare.</param> /// <returns>The later instant of <paramref name="x"/> or <paramref name="y"/>.</returns> public static Instant Max(Instant x, Instant y) { return x > y ? x : y; } /// <summary> /// Returns the earlier instant of the given two. /// </summary> /// <param name="x">The first instant to compare.</param> /// <param name="y">The second instant to compare.</param> /// <returns>The earlier instant of <paramref name="x"/> or <paramref name="y"/>.</returns> public static Instant Min(Instant x, Instant y) => x < y ? x : y; #endregion #region Formatting /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// The value of the current instance in the default format pattern ("g"), using the current thread's /// culture to obtain a format provider. /// </returns> public override string ToString() => InstantPattern.BclSupport.Format(this, null, CultureInfo.CurrentCulture); /// <summary> /// Formats the value of the current instance using the specified pattern. /// </summary> /// <returns> /// A <see cref="System.String" /> containing the value of the current instance in the specified format. /// </returns> /// <param name="patternText">The <see cref="System.String" /> specifying the pattern to use, /// or null to use the default format pattern ("g"). /// </param> /// <param name="formatProvider">The <see cref="System.IFormatProvider" /> to use when formatting the value, /// or null to use the current thread's culture to obtain a format provider. /// </param> /// <filterpriority>2</filterpriority> public string ToString(string? patternText, IFormatProvider? formatProvider) => InstantPattern.BclSupport.Format(this, patternText, formatProvider); #endregion Formatting #region IEquatable<Instant> Members /// <summary> /// Indicates whether the value of this instant is equal to the value of the specified instant. /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="other">The value to compare with this instance.</param> /// <returns> /// true if the value of this instant is equal to the value of the <paramref name="other" /> parameter; /// otherwise, false. /// </returns> public bool Equals(Instant other) => this == other; #endregion /// <summary> /// Returns the Julian Date of this instance - the number of days since /// <see cref="NodaConstants.JulianEpoch"/> (noon on January 1st, 4713 BCE in the Julian calendar). /// </summary> /// <returns>The number of days (including fractional days) since the Julian Epoch.</returns> [Pure] [TestExemption(TestExemptionCategory.ConversionName)] public double ToJulianDate() => (this - JulianEpoch).TotalDays; /// <summary> /// Constructs a <see cref="DateTime"/> from this Instant which has a <see cref="DateTime.Kind" /> /// of <see cref="DateTimeKind.Utc"/> and represents the same instant of time as this value. /// </summary> /// <remarks> /// <para> /// If the date and time is not on a tick boundary (the unit of granularity of DateTime) the value will be truncated /// towards the start of time. /// </para> /// </remarks> /// <exception cref="InvalidOperationException">The final date/time is outside the range of <c>DateTime</c>.</exception> /// <returns>A <see cref="DateTime"/> representing the same instant in time as this value, with a kind of "universal".</returns> [Pure] public DateTime ToDateTimeUtc() { if (this < BclEpoch) { throw new InvalidOperationException("Instant out of range for DateTime"); } return new DateTime(BclTicksAtUnixEpoch + ToUnixTimeTicks(), DateTimeKind.Utc); } /// <summary> /// Constructs a <see cref="DateTimeOffset"/> from this Instant which has an offset of zero. /// </summary> /// <remarks> /// <para> /// If the date and time is not on a tick boundary (the unit of granularity of DateTime) the value will be truncated /// towards the start of time. /// </para> /// </remarks> /// <exception cref="InvalidOperationException">The final date/time is outside the range of <c>DateTimeOffset</c>.</exception> /// <returns>A <see cref="DateTimeOffset"/> representing the same instant in time as this value.</returns> [Pure] public DateTimeOffset ToDateTimeOffset() { if (this < BclEpoch) { throw new InvalidOperationException("Instant out of range for DateTimeOffset"); } return new DateTimeOffset(BclTicksAtUnixEpoch + ToUnixTimeTicks(), TimeSpan.Zero); } /// <summary> /// Converts a <see cref="DateTimeOffset"/> into a new Instant representing the same instant in time. Note that /// the offset information is not preserved in the returned Instant. /// </summary> /// <returns>An <see cref="Instant"/> value representing the same instant in time as the given <see cref="DateTimeOffset"/>.</returns> /// <param name="dateTimeOffset">Date and time value with an offset.</param> public static Instant FromDateTimeOffset(DateTimeOffset dateTimeOffset) => BclEpoch.PlusTicks(dateTimeOffset.Ticks - dateTimeOffset.Offset.Ticks); /// <summary> /// Converts a Julian Date representing the given number of days /// since <see cref="NodaConstants.JulianEpoch"/> (noon on January 1st, 4713 BCE in the Julian calendar) /// into an <see cref="Instant"/>. /// </summary> /// <param name="julianDate">The number of days since the Julian Epoch to convert into an <see cref="Instant"/>.</param> /// <returns>An <see cref="Instant"/> value which is <paramref name="julianDate"/> days after the Julian Epoch.</returns> public static Instant FromJulianDate(double julianDate) => JulianEpoch + Duration.FromDays(julianDate); /// <summary> /// Converts a <see cref="DateTime"/> into a new Instant representing the same instant in time. /// </summary> /// <returns>An <see cref="Instant"/> value representing the same instant in time as the given universal <see cref="DateTime"/>.</returns> /// <param name="dateTime">Date and time value which must have a <see cref="DateTime.Kind"/> of <see cref="DateTimeKind.Utc"/></param> /// <exception cref="ArgumentException"><paramref name="dateTime"/> is not of <see cref="DateTime.Kind"/> /// <see cref="DateTimeKind.Utc"/>.</exception> public static Instant FromDateTimeUtc(DateTime dateTime) { Preconditions.CheckArgument(dateTime.Kind == DateTimeKind.Utc, nameof(dateTime), "Invalid DateTime.Kind for Instant.FromDateTimeUtc"); return BclEpoch.PlusTicks(dateTime.Ticks); } /// <summary> /// Initializes a new instance of the <see cref="Instant" /> struct based /// on a number of seconds since the Unix epoch of (ISO) January 1st 1970, midnight, UTC. /// </summary> /// <param name="seconds">Number of seconds since the Unix epoch. May be negative (for instants before the epoch).</param> /// <returns>An <see cref="Instant"/> at exactly the given number of seconds since the Unix epoch.</returns> /// <exception cref="ArgumentOutOfRangeException">The constructed instant would be out of the range representable in Noda Time.</exception> public static Instant FromUnixTimeSeconds(long seconds) { Preconditions.CheckArgumentRange(nameof(seconds), seconds, MinSeconds, MaxSeconds); return Instant.FromTrustedDuration(Duration.FromSeconds(seconds)); } /// <summary> /// Initializes a new instance of the <see cref="Instant" /> struct based /// on a number of milliseconds since the Unix epoch of (ISO) January 1st 1970, midnight, UTC. /// </summary> /// <param name="milliseconds">Number of milliseconds since the Unix epoch. May be negative (for instants before the epoch).</param> /// <returns>An <see cref="Instant"/> at exactly the given number of milliseconds since the Unix epoch.</returns> /// <exception cref="ArgumentOutOfRangeException">The constructed instant would be out of the range representable in Noda Time.</exception> public static Instant FromUnixTimeMilliseconds(long milliseconds) { Preconditions.CheckArgumentRange(nameof(milliseconds), milliseconds, MinMilliseconds, MaxMilliseconds); return Instant.FromTrustedDuration(Duration.FromMilliseconds(milliseconds)); } /// <summary> /// Initializes a new instance of the <see cref="Instant" /> struct based /// on a number of ticks since the Unix epoch of (ISO) January 1st 1970, midnight, UTC. /// </summary> /// <returns>An <see cref="Instant"/> at exactly the given number of ticks since the Unix epoch.</returns> /// <param name="ticks">Number of ticks since the Unix epoch. May be negative (for instants before the epoch).</param> public static Instant FromUnixTimeTicks(long ticks) { Preconditions.CheckArgumentRange(nameof(ticks), ticks, MinTicks, MaxTicks); return Instant.FromTrustedDuration(Duration.FromTicks(ticks)); } /// <summary> /// Gets the number of seconds since the Unix epoch. Negative values represent instants before the Unix epoch. /// </summary> /// <remarks> /// If the number of nanoseconds in this instant is not an exact number of seconds, the value is truncated towards the start of time. /// </remarks> /// <value>The number of seconds since the Unix epoch.</value> [Pure] [TestExemption(TestExemptionCategory.ConversionName)] public long ToUnixTimeSeconds() => duration.FloorDays * (long) SecondsPerDay + duration.NanosecondOfFloorDay / NanosecondsPerSecond; /// <summary> /// Gets the number of milliseconds since the Unix epoch. Negative values represent instants before the Unix epoch. /// </summary> /// <remarks> /// If the number of nanoseconds in this instant is not an exact number of milliseconds, the value is truncated towards the start of time. /// </remarks> /// <value>The number of milliseconds since the Unix epoch.</value> [Pure] [TestExemption(TestExemptionCategory.ConversionName)] public long ToUnixTimeMilliseconds() => duration.FloorDays * (long) MillisecondsPerDay + duration.NanosecondOfFloorDay / NanosecondsPerMillisecond; /// <summary> /// Gets the number of ticks since the Unix epoch. Negative values represent instants before the Unix epoch. /// </summary> /// <remarks> /// A tick is equal to 100 nanoseconds. There are 10,000 ticks in a millisecond. If the number of nanoseconds /// in this instant is not an exact number of ticks, the value is truncated towards the start of time. /// </remarks> /// <returns>The number of ticks since the Unix epoch.</returns> [Pure] [TestExemption(TestExemptionCategory.ConversionName)] public long ToUnixTimeTicks() => TickArithmetic.BoundedDaysAndTickOfDayToTicks(duration.FloorDays, duration.NanosecondOfFloorDay / NanosecondsPerTick); /// <summary> /// Returns the <see cref="ZonedDateTime"/> representing the same point in time as this instant, in the UTC time /// zone and ISO-8601 calendar. This is a shortcut for calling <see cref="InZone(DateTimeZone)" /> with an /// argument of <see cref="DateTimeZone.Utc"/>. /// </summary> /// <returns>A <see cref="ZonedDateTime"/> for the same instant, in the UTC time zone /// and the ISO-8601 calendar</returns> [Pure] public ZonedDateTime InUtc() { // Bypass any determination of offset and arithmetic, as we know the offset is zero. var offsetDateTime = new OffsetDateTime( new LocalDate(duration.FloorDays), new OffsetTime(nanosecondOfDayZeroOffset: duration.NanosecondOfFloorDay)); return new ZonedDateTime(offsetDateTime, DateTimeZone.Utc); } /// <summary> /// Returns the <see cref="ZonedDateTime"/> representing the same point in time as this instant, in the /// specified time zone and ISO-8601 calendar. /// </summary> /// <param name="zone">The time zone in which to represent this instant.</param> /// <returns>A <see cref="ZonedDateTime"/> for the same instant, in the given time zone /// and the ISO-8601 calendar</returns> [Pure] public ZonedDateTime InZone(DateTimeZone zone) => // zone is checked for nullity by the constructor. new ZonedDateTime(this, zone); /// <summary> /// Returns the <see cref="ZonedDateTime"/> representing the same point in time as this instant, in the /// specified time zone and calendar system. /// </summary> /// <param name="zone">The time zone in which to represent this instant.</param> /// <param name="calendar">The calendar system in which to represent this instant.</param> /// <returns>A <see cref="ZonedDateTime"/> for the same instant, in the given time zone /// and calendar</returns> [Pure] public ZonedDateTime InZone(DateTimeZone zone, CalendarSystem calendar) { Preconditions.CheckNotNull(zone, nameof(zone)); Preconditions.CheckNotNull(calendar, nameof(calendar)); return new ZonedDateTime(this, zone, calendar); } /// <summary> /// Returns the <see cref="OffsetDateTime"/> representing the same point in time as this instant, with /// the specified UTC offset in the ISO calendar system. /// </summary> /// <param name="offset">The offset from UTC with which to represent this instant.</param> /// <returns>An <see cref="OffsetDateTime"/> for the same instant, with the given offset /// in the ISO calendar system</returns> [Pure] public OffsetDateTime WithOffset(Offset offset) => new OffsetDateTime(this, offset); /// <summary> /// Returns the <see cref="OffsetDateTime"/> representing the same point in time as this instant, with /// the specified UTC offset and calendar system. /// </summary> /// <param name="offset">The offset from UTC with which to represent this instant.</param> /// <param name="calendar">The calendar system in which to represent this instant.</param> /// <returns>An <see cref="OffsetDateTime"/> for the same instant, with the given offset /// and calendar</returns> [Pure] public OffsetDateTime WithOffset(Offset offset, CalendarSystem calendar) { Preconditions.CheckNotNull(calendar, nameof(calendar)); return new OffsetDateTime(this, offset, calendar); } #region XML serialization /// <summary> /// Adds the XML schema type describing the structure of the <see cref="Instant"/> XML serialization to the given <paramref name="xmlSchemaSet"/>. /// </summary> /// <param name="xmlSchemaSet">The XML schema set provided by <see cref="XmlSchemaExporter"/>.</param> /// <returns>The qualified name of the schema type that was added to the <paramref name="xmlSchemaSet"/>.</returns> public static XmlQualifiedName AddSchema(XmlSchemaSet xmlSchemaSet) => Xml.XmlSchemaDefinition.AddInstantSchemaType(xmlSchemaSet); /// <inheritdoc /> XmlSchema IXmlSerializable.GetSchema() => null!; // TODO(nullable): Return XmlSchema? when docfx works with that /// <inheritdoc /> void IXmlSerializable.ReadXml(XmlReader reader) { Preconditions.CheckNotNull(reader, nameof(reader)); var pattern = InstantPattern.ExtendedIso; string text = reader.ReadElementContentAsString(); Unsafe.AsRef(this) = pattern.Parse(text).Value; } /// <inheritdoc /> void IXmlSerializable.WriteXml(XmlWriter writer) { Preconditions.CheckNotNull(writer, nameof(writer)); writer.WriteString(InstantPattern.ExtendedIso.Format(this)); } #endregion } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * 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 Rodrigo B. de Oliveira 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 // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class Module : TypeDefinition { protected NamespaceDeclaration _namespace; protected ImportCollection _imports; protected Block _globals; protected AttributeCollection _assemblyAttributes; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public Module CloneNode() { return (Module)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public Module CleanClone() { return (Module)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.Module; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnModule(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( Module)node; if (_modifiers != other._modifiers) return NoMatch("Module._modifiers"); if (_name != other._name) return NoMatch("Module._name"); if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("Module._attributes"); if (!Node.AllMatch(_members, other._members)) return NoMatch("Module._members"); if (!Node.AllMatch(_baseTypes, other._baseTypes)) return NoMatch("Module._baseTypes"); if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("Module._genericParameters"); if (!Node.Matches(_namespace, other._namespace)) return NoMatch("Module._namespace"); if (!Node.AllMatch(_imports, other._imports)) return NoMatch("Module._imports"); if (!Node.Matches(_globals, other._globals)) return NoMatch("Module._globals"); if (!Node.AllMatch(_assemblyAttributes, other._assemblyAttributes)) return NoMatch("Module._assemblyAttributes"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_attributes != null) { Attribute item = existing as Attribute; if (null != item) { Attribute newItem = (Attribute)newNode; if (_attributes.Replace(item, newItem)) { return true; } } } if (_members != null) { TypeMember item = existing as TypeMember; if (null != item) { TypeMember newItem = (TypeMember)newNode; if (_members.Replace(item, newItem)) { return true; } } } if (_baseTypes != null) { TypeReference item = existing as TypeReference; if (null != item) { TypeReference newItem = (TypeReference)newNode; if (_baseTypes.Replace(item, newItem)) { return true; } } } if (_genericParameters != null) { GenericParameterDeclaration item = existing as GenericParameterDeclaration; if (null != item) { GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode; if (_genericParameters.Replace(item, newItem)) { return true; } } } if (_namespace == existing) { this.Namespace = (NamespaceDeclaration)newNode; return true; } if (_imports != null) { Import item = existing as Import; if (null != item) { Import newItem = (Import)newNode; if (_imports.Replace(item, newItem)) { return true; } } } if (_globals == existing) { this.Globals = (Block)newNode; return true; } if (_assemblyAttributes != null) { Attribute item = existing as Attribute; if (null != item) { Attribute newItem = (Attribute)newNode; if (_assemblyAttributes.Replace(item, newItem)) { return true; } } } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { Module clone = new Module(); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); clone._modifiers = _modifiers; clone._name = _name; if (null != _attributes) { clone._attributes = _attributes.Clone() as AttributeCollection; clone._attributes.InitializeParent(clone); } if (null != _members) { clone._members = _members.Clone() as TypeMemberCollection; clone._members.InitializeParent(clone); } if (null != _baseTypes) { clone._baseTypes = _baseTypes.Clone() as TypeReferenceCollection; clone._baseTypes.InitializeParent(clone); } if (null != _genericParameters) { clone._genericParameters = _genericParameters.Clone() as GenericParameterDeclarationCollection; clone._genericParameters.InitializeParent(clone); } if (null != _namespace) { clone._namespace = _namespace.Clone() as NamespaceDeclaration; clone._namespace.InitializeParent(clone); } if (null != _imports) { clone._imports = _imports.Clone() as ImportCollection; clone._imports.InitializeParent(clone); } if (null != _globals) { clone._globals = _globals.Clone() as Block; clone._globals.InitializeParent(clone); } if (null != _assemblyAttributes) { clone._assemblyAttributes = _assemblyAttributes.Clone() as AttributeCollection; clone._assemblyAttributes.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _attributes) { _attributes.ClearTypeSystemBindings(); } if (null != _members) { _members.ClearTypeSystemBindings(); } if (null != _baseTypes) { _baseTypes.ClearTypeSystemBindings(); } if (null != _genericParameters) { _genericParameters.ClearTypeSystemBindings(); } if (null != _namespace) { _namespace.ClearTypeSystemBindings(); } if (null != _imports) { _imports.ClearTypeSystemBindings(); } if (null != _globals) { _globals.ClearTypeSystemBindings(); } if (null != _assemblyAttributes) { _assemblyAttributes.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public NamespaceDeclaration Namespace { get { return _namespace; } set { if (_namespace != value) { _namespace = value; if (null != _namespace) { _namespace.InitializeParent(this); } } } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(Import))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public ImportCollection Imports { get { return _imports ?? (_imports = new ImportCollection(this)); } set { if (_imports != value) { _imports = value; if (null != _imports) { _imports.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block Globals { get { if (_globals == null) { _globals = new Block(); _globals.InitializeParent(this); } return _globals; } set { if (_globals != value) { _globals = value; if (null != _globals) { _globals.InitializeParent(this); } } } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(Attribute))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public AttributeCollection AssemblyAttributes { get { return _assemblyAttributes ?? (_assemblyAttributes = new AttributeCollection(this)); } set { if (_assemblyAttributes != value) { _assemblyAttributes = value; if (null != _assemblyAttributes) { _assemblyAttributes.InitializeParent(this); } } } } } }
#define CATCHERROR using System; using System.Drawing; using System.IO; using System.Windows.Forms; using Engine; using Engine.Interfaces; using Engine.Xna; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using ButtonState = Microsoft.Xna.Framework.Input.ButtonState; using Keys = Microsoft.Xna.Framework.Input.Keys; using Point = Microsoft.Xna.Framework.Point; namespace Client.WindowsGame { public class GameClient : Game { SpriteBatch spriteBatch; GraphicsDeviceManager graphics; private BaseClient client; private IRenderer renderer; public GameClient() : base() { graphics = new GraphicsDeviceManager(this); var c = new ContentManager(this.Services); Content.RootDirectory = "Content"; IsMouseVisible = true; TouchPanel.EnableMouseTouchPoint = true; graphics.PreferredBackBufferWidth = 1536/2; graphics.PreferredBackBufferHeight = 2048/2; } protected override void Initialize() { base.Initialize(); } private void ExceptionOccured(Exception exc) { Form form = new Form(); form.Width = 1000; form.Height = 500; TextBox txt = new TextBox(); txt.Multiline = true; txt.Font = new Font(txt.Font.FontFamily, 15); txt.WordWrap = false; txt.ScrollBars = ScrollBars.Both; txt.Dock=DockStyle.Fill; txt.Text = exc.ToString(); form.Controls.Add(txt); form.FormClosed += (sender, args) => this.Exit(); form.Show(); failed = true; } protected override void LoadContent() { if (failed) return; #if CATCHERROR try { #endif spriteBatch = new SpriteBatch(GraphicsDevice); client = new XnaClient({{{projectName}}}, new XnaClientSettings(getKeyboardInput: (callback) => { callback(""); }, oneLayoutAtATime: false, loadFile: s => new StreamReader("Content/" + s), openAppStore: () => { }, rateApp: () => { }, sendEmail: (to, subject, message) => { }) { }, new WindowsUserPreferences(), Content); renderer = new XnaRenderer(GraphicsDevice, Content, graphics, client); client.LoadAssets(renderer); client.Init(renderer); #if CATCHERROR } catch (Exception ex) { ExceptionOccured(ex); } #endif } protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } private int mouseX; private int mouseY; private bool mouseIsDown; // private int currentIndex = 0; protected override void Update(GameTime gameTime) { if (failed) return; #if CATCHERROR try { #endif if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); if (Keyboard.GetState().IsKeyDown(Keys.Space)) { // currentIndex = currentIndex == 0 ? 1 : 0; // var screen = client.ScreenManager.Screens.ElementAt(currentIndex); // client.ScreenManager.ChangeScreen(screen); } var layoutManager = client.ScreenManager.CurrentScreen; if (Keyboard.GetState().IsKeyDown(Keys.Left)) { layoutManager.ChangeLayout(Direction.Left); } if (Keyboard.GetState().IsKeyDown(Keys.Right)) { layoutManager.ChangeLayout(Direction.Right); } if (Keyboard.GetState().IsKeyDown(Keys.Up)) { layoutManager.ChangeLayout(Direction.Up); } if (Keyboard.GetState().IsKeyDown(Keys.Down)) { layoutManager.ChangeLayout(Direction.Down); } MouseState mouseState = Mouse.GetState(); if (mouseX != mouseState.X || mouseY != mouseState.Y) { mouseX = mouseState.X; mouseY = mouseState.Y; client.TouchEvent(TouchType.TouchMove, (int)mouseState.X, (int)mouseState.Y); } /* switch (mouseState.LeftButton) { case ButtonState.Pressed: if (!mouseIsDown) { client.TouchEvent(TouchType.TouchDown, (int)mouseState.X, (int)mouseState.Y); } mouseIsDown = true; break; case ButtonState.Released: if (mouseIsDown) { client.TouchEvent(TouchType.TouchUp, (int)mouseState.X, (int)mouseState.Y); mouseIsDown = false; } break; }*/ TouchCollection touchCollection = TouchPanel.GetState(); foreach (var touch in touchCollection) { switch (touch.State) { case TouchLocationState.Moved: client.TouchEvent(TouchType.TouchMove, (int)touch.Position.X, (int)touch.Position.Y); break; case TouchLocationState.Pressed: client.TouchEvent(TouchType.TouchDown, (int)touch.Position.X, (int)touch.Position.Y); break; case TouchLocationState.Released: client.TouchEvent(TouchType.TouchUp, (int)touch.Position.X, (int)touch.Position.Y); break; } } client.Tick(gameTime.TotalGameTime); base.Update(gameTime); #if CATCHERROR } catch (Exception ex) { ExceptionOccured(ex); } #endif } private bool failed = false; protected override void Draw(GameTime gameTime) { if (failed) return; #if CATCHERROR try { #endif GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.CornflowerBlue); client.Draw(gameTime.TotalGameTime); client.DrawLetterbox(); base.Draw(gameTime); #if CATCHERROR } catch (Exception ex) { ExceptionOccured(ex); } #endif } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ServiceModel.Description; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; using System.Reflection; using System.Xml; using System.ServiceModel.Diagnostics; using System.ServiceModel.Channels; using System.Runtime.Diagnostics; using System.Runtime; using System.Threading.Tasks; namespace System.ServiceModel.Dispatcher { internal abstract class OperationFormatter : IClientMessageFormatter, IDispatchMessageFormatter { private MessageDescription _replyDescription; private MessageDescription _requestDescription; private XmlDictionaryString _action; private XmlDictionaryString _replyAction; protected StreamFormatter requestStreamFormatter, replyStreamFormatter; private XmlDictionary _dictionary; private string _operationName; public OperationFormatter(OperationDescription description, bool isRpc, bool isEncoded) { Validate(description, isRpc, isEncoded); _requestDescription = description.Messages[0]; if (description.Messages.Count == 2) _replyDescription = description.Messages[1]; int stringCount = 3 + _requestDescription.Body.Parts.Count; if (_replyDescription != null) stringCount += 2 + _replyDescription.Body.Parts.Count; _dictionary = new XmlDictionary(stringCount * 2); GetActions(description, _dictionary, out _action, out _replyAction); _operationName = description.Name; requestStreamFormatter = StreamFormatter.Create(_requestDescription, _operationName, true/*isRequest*/); if (_replyDescription != null) replyStreamFormatter = StreamFormatter.Create(_replyDescription, _operationName, false/*isResponse*/); } protected abstract void AddHeadersToMessage(Message message, MessageDescription messageDescription, object[] parameters, bool isRequest); protected abstract void SerializeBody(XmlDictionaryWriter writer, MessageVersion version, string action, MessageDescription messageDescription, object returnValue, object[] parameters, bool isRequest); protected virtual Task SerializeBodyAsync(XmlDictionaryWriter writer, MessageVersion version, string action, MessageDescription messageDescription, object returnValue, object[] parameters, bool isRequest) { SerializeBody(writer, version, action, messageDescription, returnValue, parameters, isRequest); return Task.CompletedTask; } protected abstract void GetHeadersFromMessage(Message message, MessageDescription messageDescription, object[] parameters, bool isRequest); protected abstract object DeserializeBody(XmlDictionaryReader reader, MessageVersion version, string action, MessageDescription messageDescription, object[] parameters, bool isRequest); protected virtual void WriteBodyAttributes(XmlDictionaryWriter writer, MessageVersion messageVersion) { } internal string RequestAction { get { if (_action != null) return _action.Value; return null; } } internal string ReplyAction { get { if (_replyAction != null) return _replyAction.Value; return null; } } protected XmlDictionary Dictionary { get { return _dictionary; } } protected string OperationName { get { return _operationName; } } protected MessageDescription ReplyDescription { get { return _replyDescription; } } protected MessageDescription RequestDescription { get { return _requestDescription; } } protected XmlDictionaryString AddToDictionary(string s) { return AddToDictionary(_dictionary, s); } public object DeserializeReply(Message message, object[] parameters) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); if (parameters == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("parameters"), message); try { object result = null; if (_replyDescription.IsTypedMessage) { object typeMessageInstance = CreateTypedMessageInstance(_replyDescription.MessageType); TypedMessageParts typedMessageParts = new TypedMessageParts(typeMessageInstance, _replyDescription); object[] parts = new object[typedMessageParts.Count]; GetPropertiesFromMessage(message, _replyDescription, parts); GetHeadersFromMessage(message, _replyDescription, parts, false/*isRequest*/); DeserializeBodyContents(message, parts, false/*isRequest*/); // copy values into the actual field/properties typedMessageParts.SetTypedMessageParts(parts); result = typeMessageInstance; } else { GetPropertiesFromMessage(message, _replyDescription, parameters); GetHeadersFromMessage(message, _replyDescription, parameters, false/*isRequest*/); result = DeserializeBodyContents(message, parameters, false/*isRequest*/); } return result; } catch (XmlException xe) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( SR.Format(SR.SFxErrorDeserializingReplyBodyMore, _operationName, xe.Message), xe)); } catch (FormatException fe) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( SR.Format(SR.SFxErrorDeserializingReplyBodyMore, _operationName, fe.Message), fe)); } catch (SerializationException se) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( SR.Format(SR.SFxErrorDeserializingReplyBodyMore, _operationName, se.Message), se)); } } private static object CreateTypedMessageInstance(Type messageContractType) { try { object typeMessageInstance = Activator.CreateInstance(messageContractType); return typeMessageInstance; } catch (MissingMethodException mme) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxMessageContractRequiresDefaultConstructor, messageContractType.FullName), mme)); } } public void DeserializeRequest(Message message, object[] parameters) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); if (parameters == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("parameters"), message); try { if (_requestDescription.IsTypedMessage) { object typeMessageInstance = CreateTypedMessageInstance(_requestDescription.MessageType); TypedMessageParts typedMessageParts = new TypedMessageParts(typeMessageInstance, _requestDescription); object[] parts = new object[typedMessageParts.Count]; GetPropertiesFromMessage(message, _requestDescription, parts); GetHeadersFromMessage(message, _requestDescription, parts, true/*isRequest*/); DeserializeBodyContents(message, parts, true/*isRequest*/); // copy values into the actual field/properties typedMessageParts.SetTypedMessageParts(parts); parameters[0] = typeMessageInstance; } else { GetPropertiesFromMessage(message, _requestDescription, parameters); GetHeadersFromMessage(message, _requestDescription, parameters, true/*isRequest*/); DeserializeBodyContents(message, parameters, true/*isRequest*/); } } catch (XmlException xe) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( OperationFormatter.CreateDeserializationFailedFault( SR.Format(SR.SFxErrorDeserializingRequestBodyMore, _operationName, xe.Message), xe)); } catch (FormatException fe) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( OperationFormatter.CreateDeserializationFailedFault( SR.Format(SR.SFxErrorDeserializingRequestBodyMore, _operationName, fe.Message), fe)); } catch (SerializationException se) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( SR.Format(SR.SFxErrorDeserializingRequestBodyMore, _operationName, se.Message), se)); } } private object DeserializeBodyContents(Message message, object[] parameters, bool isRequest) { MessageDescription messageDescription; StreamFormatter streamFormatter; SetupStreamAndMessageDescription(isRequest, out streamFormatter, out messageDescription); if (streamFormatter != null) { object retVal = null; streamFormatter.Deserialize(parameters, ref retVal, message); return retVal; } if (message.IsEmpty) { return null; } else { XmlDictionaryReader reader = message.GetReaderAtBodyContents(); using (reader) { object body = DeserializeBody(reader, message.Version, RequestAction, messageDescription, parameters, isRequest); message.ReadFromBodyContentsToEnd(reader); return body; } } } public Message SerializeRequest(MessageVersion messageVersion, object[] parameters) { object[] parts = null; if (messageVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion"); if (parameters == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters"); if (_requestDescription.IsTypedMessage) { TypedMessageParts typedMessageParts = new TypedMessageParts(parameters[0], _requestDescription); // copy values from the actual field/properties parts = new object[typedMessageParts.Count]; typedMessageParts.GetTypedMessageParts(parts); } else { parts = parameters; } Message msg = new OperationFormatterMessage(this, messageVersion, _action == null ? null : ActionHeader.Create(_action, messageVersion.Addressing), parts, null, true/*isRequest*/); AddPropertiesToMessage(msg, _requestDescription, parts); AddHeadersToMessage(msg, _requestDescription, parts, true /*isRequest*/); return msg; } public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result) { object[] parts = null; object resultPart = null; if (messageVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion"); if (parameters == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters"); if (_replyDescription.IsTypedMessage) { // If the response is a typed message then it must // be the response (as opposed to an out param). We will // serialize the response in the exact same way that we // would serialize a bunch of outs (with no return value). TypedMessageParts typedMessageParts = new TypedMessageParts(result, _replyDescription); // make a copy of the list so that we have the actual values of the field/properties parts = new object[typedMessageParts.Count]; typedMessageParts.GetTypedMessageParts(parts); } else { parts = parameters; resultPart = result; } Message msg = new OperationFormatterMessage(this, messageVersion, _replyAction == null ? null : ActionHeader.Create(_replyAction, messageVersion.Addressing), parts, resultPart, false/*isRequest*/); AddPropertiesToMessage(msg, _replyDescription, parts); AddHeadersToMessage(msg, _replyDescription, parts, false /*isRequest*/); return msg; } private void SetupStreamAndMessageDescription(bool isRequest, out StreamFormatter streamFormatter, out MessageDescription messageDescription) { if (isRequest) { streamFormatter = requestStreamFormatter; messageDescription = _requestDescription; } else { streamFormatter = replyStreamFormatter; messageDescription = _replyDescription; } } private void SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, object[] parameters, object returnValue, bool isRequest) { MessageDescription messageDescription; StreamFormatter streamFormatter; SetupStreamAndMessageDescription(isRequest, out streamFormatter, out messageDescription); if (streamFormatter != null) { streamFormatter.Serialize(writer, parameters, returnValue); return; } SerializeBody(writer, version, RequestAction, messageDescription, returnValue, parameters, isRequest); } private async Task SerializeBodyContentsAsync(XmlDictionaryWriter writer, MessageVersion version, object[] parameters, object returnValue, bool isRequest) { MessageDescription messageDescription; StreamFormatter streamFormatter; SetupStreamAndMessageDescription(isRequest, out streamFormatter, out messageDescription); if (streamFormatter != null) { await streamFormatter.SerializeAsync(writer, parameters, returnValue); return; } await SerializeBodyAsync(writer, version, RequestAction, messageDescription, returnValue, parameters, isRequest); } private IAsyncResult BeginSerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, object[] parameters, object returnValue, bool isRequest, AsyncCallback callback, object state) { return new SerializeBodyContentsAsyncResult(this, writer, version, parameters, returnValue, isRequest, callback, state); } private void EndSerializeBodyContents(IAsyncResult result) { SerializeBodyContentsAsyncResult.End(result); } internal class SerializeBodyContentsAsyncResult : AsyncResult { private static AsyncCompletion s_handleEndSerializeBodyContents = new AsyncCompletion(HandleEndSerializeBodyContents); private StreamFormatter _streamFormatter; internal SerializeBodyContentsAsyncResult(OperationFormatter operationFormatter, XmlDictionaryWriter writer, MessageVersion version, object[] parameters, object returnValue, bool isRequest, AsyncCallback callback, object state) : base(callback, state) { bool completeSelf = true; MessageDescription messageDescription; StreamFormatter streamFormatter; operationFormatter.SetupStreamAndMessageDescription(isRequest, out streamFormatter, out messageDescription); if (streamFormatter != null) { _streamFormatter = streamFormatter; IAsyncResult result = streamFormatter.BeginSerialize(writer, parameters, returnValue, PrepareAsyncCompletion(s_handleEndSerializeBodyContents), this); completeSelf = SyncContinue(result); } else { operationFormatter.SerializeBody(writer, version, operationFormatter.RequestAction, messageDescription, returnValue, parameters, isRequest); completeSelf = true; } if (completeSelf) { Complete(true); } } private static bool HandleEndSerializeBodyContents(IAsyncResult result) { SerializeBodyContentsAsyncResult thisPtr = (SerializeBodyContentsAsyncResult)result.AsyncState; thisPtr._streamFormatter.EndSerialize(result); return true; } public static void End(IAsyncResult result) { AsyncResult.End<SerializeBodyContentsAsyncResult>(result); } } private void AddPropertiesToMessage(Message message, MessageDescription messageDescription, object[] parameters) { if (messageDescription.Properties.Count > 0) { AddPropertiesToMessageCore(message, messageDescription, parameters); } } private void AddPropertiesToMessageCore(Message message, MessageDescription messageDescription, object[] parameters) { MessageProperties properties = message.Properties; MessagePropertyDescriptionCollection propertyDescriptions = messageDescription.Properties; for (int i = 0; i < propertyDescriptions.Count; i++) { MessagePropertyDescription propertyDescription = propertyDescriptions[i]; object parameter = parameters[propertyDescription.Index]; if (null != parameter) properties.Add(propertyDescription.Name, parameter); } } private void GetPropertiesFromMessage(Message message, MessageDescription messageDescription, object[] parameters) { if (messageDescription.Properties.Count > 0) { GetPropertiesFromMessageCore(message, messageDescription, parameters); } } private void GetPropertiesFromMessageCore(Message message, MessageDescription messageDescription, object[] parameters) { MessageProperties properties = message.Properties; MessagePropertyDescriptionCollection propertyDescriptions = messageDescription.Properties; for (int i = 0; i < propertyDescriptions.Count; i++) { MessagePropertyDescription propertyDescription = propertyDescriptions[i]; if (properties.ContainsKey(propertyDescription.Name)) { parameters[propertyDescription.Index] = properties[propertyDescription.Name]; } } } internal static object GetContentOfMessageHeaderOfT(MessageHeaderDescription headerDescription, object parameterValue, out bool mustUnderstand, out bool relay, out string actor) { actor = headerDescription.Actor; mustUnderstand = headerDescription.MustUnderstand; relay = headerDescription.Relay; if (headerDescription.TypedHeader && parameterValue != null) parameterValue = TypedHeaderManager.GetContent(headerDescription.Type, parameterValue, out mustUnderstand, out relay, out actor); return parameterValue; } internal static bool IsValidReturnValue(MessagePartDescription returnValue) { return (returnValue != null) && (returnValue.Type != typeof(void)); } internal static XmlDictionaryString AddToDictionary(XmlDictionary dictionary, string s) { XmlDictionaryString dictionaryString; if (!dictionary.TryLookup(s, out dictionaryString)) { dictionaryString = dictionary.Add(s); } return dictionaryString; } internal static void Validate(OperationDescription operation, bool isRpc, bool isEncoded) { if (isEncoded && !isRpc) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxDocEncodedNotSupported, operation.Name))); } bool hasVoid = false; bool hasTypedOrUntypedMessage = false; bool hasParameter = false; for (int i = 0; i < operation.Messages.Count; i++) { MessageDescription message = operation.Messages[i]; if (message.IsTypedMessage || message.IsUntypedMessage) { if (isRpc && operation.IsValidateRpcWrapperName) { if (!isEncoded) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxTypedMessageCannotBeRpcLiteral, operation.Name))); } hasTypedOrUntypedMessage = true; } else if (message.IsVoid) hasVoid = true; else hasParameter = true; } if (hasParameter && hasTypedOrUntypedMessage) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxTypedOrUntypedMessageCannotBeMixedWithParameters, operation.Name))); if (isRpc && hasTypedOrUntypedMessage && hasVoid) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxTypedOrUntypedMessageCannotBeMixedWithVoidInRpc, operation.Name))); } internal static void GetActions(OperationDescription description, XmlDictionary dictionary, out XmlDictionaryString action, out XmlDictionaryString replyAction) { string actionString, replyActionString; actionString = description.Messages[0].Action; if (actionString == MessageHeaders.WildcardAction) actionString = null; if (!description.IsOneWay) replyActionString = description.Messages[1].Action; else replyActionString = null; if (replyActionString == MessageHeaders.WildcardAction) replyActionString = null; action = replyAction = null; if (actionString != null) action = AddToDictionary(dictionary, actionString); if (replyActionString != null) replyAction = AddToDictionary(dictionary, replyActionString); } internal static NetDispatcherFaultException CreateDeserializationFailedFault(string reason, Exception innerException) { reason = SR.Format(SR.SFxDeserializationFailed1, reason); FaultCode code = new FaultCode(FaultCodeConstants.Codes.DeserializationFailed, FaultCodeConstants.Namespaces.NetDispatch); code = FaultCode.CreateSenderFaultCode(code); return new NetDispatcherFaultException(reason, code, innerException); } internal static void TraceAndSkipElement(XmlReader xmlReader) { xmlReader.Skip(); } internal class TypedMessageParts { private object _instance; private MemberInfo[] _members; public TypedMessageParts(object instance, MessageDescription description) { if (description == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("description")); } if (instance == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(SR.Format(SR.SFxTypedMessageCannotBeNull, description.Action))); } _members = new MemberInfo[description.Body.Parts.Count + description.Properties.Count + description.Headers.Count]; foreach (MessagePartDescription part in description.Headers) _members[part.Index] = part.MemberInfo; foreach (MessagePartDescription part in description.Properties) _members[part.Index] = part.MemberInfo; foreach (MessagePartDescription part in description.Body.Parts) _members[part.Index] = part.MemberInfo; _instance = instance; } private object GetValue(int index) { MemberInfo memberInfo = _members[index]; PropertyInfo propertyInfo = memberInfo as PropertyInfo; if (propertyInfo != null) { return propertyInfo.GetValue(_instance, null); } else { return ((FieldInfo)memberInfo).GetValue(_instance); } } private void SetValue(object value, int index) { MemberInfo memberInfo = _members[index]; PropertyInfo propertyInfo = memberInfo as PropertyInfo; if (propertyInfo != null) { propertyInfo.SetValue(_instance, value, null); } else { ((FieldInfo)memberInfo).SetValue(_instance, value); } } internal void GetTypedMessageParts(object[] values) { for (int i = 0; i < _members.Length; i++) { values[i] = GetValue(i); } } internal void SetTypedMessageParts(object[] values) { for (int i = 0; i < _members.Length; i++) { SetValue(values[i], i); } } internal int Count { get { return _members.Length; } } } internal class OperationFormatterMessage : BodyWriterMessage { private OperationFormatter _operationFormatter; public OperationFormatterMessage(OperationFormatter operationFormatter, MessageVersion version, ActionHeader action, object[] parameters, object returnValue, bool isRequest) : base(version, action, new OperationFormatterBodyWriter(operationFormatter, version, parameters, returnValue, isRequest)) { _operationFormatter = operationFormatter; } public OperationFormatterMessage(MessageVersion version, string action, BodyWriter bodyWriter) : base(version, action, bodyWriter) { } private OperationFormatterMessage(MessageHeaders headers, KeyValuePair<string, object>[] properties, OperationFormatterBodyWriter bodyWriter) : base(headers, properties, bodyWriter) { _operationFormatter = bodyWriter.OperationFormatter; } protected override void OnWriteStartBody(XmlDictionaryWriter writer) { base.OnWriteStartBody(writer); _operationFormatter.WriteBodyAttributes(writer, this.Version); } protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { BodyWriter bufferedBodyWriter; if (BodyWriter.IsBuffered) { bufferedBodyWriter = base.BodyWriter; } else { bufferedBodyWriter = base.BodyWriter.CreateBufferedCopy(maxBufferSize); } KeyValuePair<string, object>[] properties = new KeyValuePair<string, object>[base.Properties.Count]; ((ICollection<KeyValuePair<string, object>>)base.Properties).CopyTo(properties, 0); return new OperationFormatterMessageBuffer(base.Headers, properties, bufferedBodyWriter); } internal class OperationFormatterBodyWriter : BodyWriter { private bool _isRequest; private OperationFormatter _operationFormatter; private object[] _parameters; private object _returnValue; private MessageVersion _version; private bool _onBeginWriteBodyContentsCalled; public OperationFormatterBodyWriter(OperationFormatter operationFormatter, MessageVersion version, object[] parameters, object returnValue, bool isRequest) : base(AreParametersBuffered(isRequest, operationFormatter)) { _parameters = parameters; _returnValue = returnValue; _isRequest = isRequest; _operationFormatter = operationFormatter; _version = version; } private object ThisLock { get { return this; } } private static bool AreParametersBuffered(bool isRequest, OperationFormatter operationFormatter) { StreamFormatter streamFormatter = isRequest ? operationFormatter.requestStreamFormatter : operationFormatter.replyStreamFormatter; return streamFormatter == null; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { lock (ThisLock) { _operationFormatter.SerializeBodyContents(writer, _version, _parameters, _returnValue, _isRequest); } } protected override Task OnWriteBodyContentsAsync(XmlDictionaryWriter writer) { return _operationFormatter.SerializeBodyContentsAsync(writer, _version, _parameters, _returnValue, _isRequest); } protected override IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state) { Fx.Assert(!_onBeginWriteBodyContentsCalled, "OnBeginWriteBodyContents has already been called"); _onBeginWriteBodyContentsCalled = true; return new OnWriteBodyContentsAsyncResult(this, writer, callback, state); } protected override void OnEndWriteBodyContents(IAsyncResult result) { OnWriteBodyContentsAsyncResult.End(result); } internal OperationFormatter OperationFormatter { get { return _operationFormatter; } } internal class OnWriteBodyContentsAsyncResult : AsyncResult { private static AsyncCompletion s_handleEndOnWriteBodyContents = new AsyncCompletion(HandleEndOnWriteBodyContents); private OperationFormatter _operationFormatter; internal OnWriteBodyContentsAsyncResult(OperationFormatterBodyWriter operationFormatterBodyWriter, XmlDictionaryWriter writer, AsyncCallback callback, object state) : base(callback, state) { bool completeSelf = true; _operationFormatter = operationFormatterBodyWriter.OperationFormatter; IAsyncResult result = _operationFormatter.BeginSerializeBodyContents(writer, operationFormatterBodyWriter._version, operationFormatterBodyWriter._parameters, operationFormatterBodyWriter._returnValue, operationFormatterBodyWriter._isRequest, PrepareAsyncCompletion(s_handleEndOnWriteBodyContents), this); completeSelf = SyncContinue(result); if (completeSelf) { Complete(true); } } private static bool HandleEndOnWriteBodyContents(IAsyncResult result) { OnWriteBodyContentsAsyncResult thisPtr = (OnWriteBodyContentsAsyncResult)result.AsyncState; thisPtr._operationFormatter.EndSerializeBodyContents(result); return true; } public static void End(IAsyncResult result) { AsyncResult.End<OnWriteBodyContentsAsyncResult>(result); } } } private class OperationFormatterMessageBuffer : BodyWriterMessageBuffer { public OperationFormatterMessageBuffer(MessageHeaders headers, KeyValuePair<string, object>[] properties, BodyWriter bodyWriter) : base(headers, properties, bodyWriter) { } public override Message CreateMessage() { OperationFormatterBodyWriter operationFormatterBodyWriter = base.BodyWriter as OperationFormatterBodyWriter; if (operationFormatterBodyWriter == null) return base.CreateMessage(); lock (ThisLock) { if (base.Closed) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException()); return new OperationFormatterMessage(base.Headers, base.Properties, operationFormatterBodyWriter); } } } } internal abstract class OperationFormatterHeader : MessageHeader { protected MessageHeader innerHeader; //use innerHeader to handle versionSupported, actor/role handling etc. protected OperationFormatter operationFormatter; protected MessageVersion version; public OperationFormatterHeader(OperationFormatter operationFormatter, MessageVersion version, string name, string ns, bool mustUnderstand, string actor, bool relay) { this.operationFormatter = operationFormatter; this.version = version; if (actor != null) innerHeader = MessageHeader.CreateHeader(name, ns, null/*headerValue*/, mustUnderstand, actor, relay); else innerHeader = MessageHeader.CreateHeader(name, ns, null/*headerValue*/, mustUnderstand, "", relay); } public override bool IsMessageVersionSupported(MessageVersion messageVersion) { return innerHeader.IsMessageVersionSupported(messageVersion); } public override string Name { get { return innerHeader.Name; } } public override string Namespace { get { return innerHeader.Namespace; } } public override bool MustUnderstand { get { return innerHeader.MustUnderstand; } } public override bool Relay { get { return innerHeader.Relay; } } public override string Actor { get { return innerHeader.Actor; } } protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { //Prefix needed since there may be xsi:type attribute at toplevel with qname value where ns = "" writer.WriteStartElement((this.Namespace == null || this.Namespace.Length == 0) ? string.Empty : "h", this.Name, this.Namespace); OnWriteHeaderAttributes(writer, messageVersion); } protected virtual void OnWriteHeaderAttributes(XmlDictionaryWriter writer, MessageVersion messageVersion) { base.WriteHeaderAttributes(writer, messageVersion); } } internal class XmlElementMessageHeader : OperationFormatterHeader { protected XmlElement headerValue; public XmlElementMessageHeader(OperationFormatter operationFormatter, MessageVersion version, string name, string ns, bool mustUnderstand, string actor, bool relay, XmlElement headerValue) : base(operationFormatter, version, name, ns, mustUnderstand, actor, relay) { this.headerValue = headerValue; } protected override void OnWriteHeaderAttributes(XmlDictionaryWriter writer, MessageVersion messageVersion) { throw ExceptionHelper.PlatformNotSupported(); } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { headerValue.WriteContentTo(writer); } } internal struct QName { internal string Name; internal string Namespace; internal QName(string name, string ns) { Name = name; Namespace = ns; } } internal class QNameComparer : IEqualityComparer<QName> { static internal QNameComparer Singleton = new QNameComparer(); private QNameComparer() { } public bool Equals(QName x, QName y) { return x.Name == y.Name && x.Namespace == y.Namespace; } public int GetHashCode(QName obj) { return obj.Name.GetHashCode(); } } internal class MessageHeaderDescriptionTable : Dictionary<QName, MessageHeaderDescription> { internal MessageHeaderDescriptionTable() : base(QNameComparer.Singleton) { } internal void Add(string name, string ns, MessageHeaderDescription message) { base.Add(new QName(name, ns), message); } internal MessageHeaderDescription Get(string name, string ns) { MessageHeaderDescription message; if (base.TryGetValue(new QName(name, ns), out message)) return message; return null; } } } }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.IO; using System.Text; using Alachisoft.NCache.Serialization.Formatters; using Alachisoft.NCache.Serialization.Surrogates; using Alachisoft.NCache.Serialization; using Alachisoft.NCache.Runtime.Serialization.IO; namespace Alachisoft.NCache.IO { /// <summary> /// This class encapsulates a <see cref="BinaryWriter"/> object. It also provides an extra /// Write method for <see cref="System.Object"/> types. /// </summary> public class CompactBinaryWriter : CompactWriter, IDisposable { private SerializationContext context; private BinaryWriter writer; /// <summary> /// Constructs a compact writer over a <see cref="Stream"/> object. /// </summary> /// <param name="output"><see cref="Stream"/> object</param> public CompactBinaryWriter(Stream output) : this(output, new UTF8Encoding(true)) { } /// <summary> /// Constructs a compact writer over a <see cref="Stream"/> object. /// </summary> /// <param name="output"><see cref="Stream"/> object</param> /// <param name="encoding"><see cref="Encoding"/> object</param> public CompactBinaryWriter(Stream output, Encoding encoding) { context = new SerializationContext(); writer = new BinaryWriter(output, encoding); } /// <summary> Returns the underlying <see cref="BinaryWriter"/> object. </summary> internal BinaryWriter BaseWriter { get { return writer; } } /// <summary> Returns the current <see cref="SerializationContext"/> object. </summary> internal SerializationContext Context { get { return context; } } /// <summary> /// Close the underlying <see cref="BinaryWriter"/>. /// </summary> public void Dispose() { if (writer != null) writer.Close(); } /// <summary> /// Close the underlying <see cref="BinaryWriter"/>. /// </summary> public void Dispose(bool closeStream) { if (closeStream) writer.Close(); writer = null; } /// <summary> /// Writes <paramref name="graph"/> to the current stream and advances the stream position. /// </summary> /// <param name="graph">Object to write</param> public override void WriteObject(object graph) { // Find an appropriate surrogate for the object ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForObject(graph, context.CacheContext); // write type handle writer.Write(surrogate.TypeHandle); try { surrogate.Write(this, graph); } catch (CompactSerializationException) { throw; } catch (Exception e) { throw new CompactSerializationException(e.Message); } } public override void WriteObjectAs<T>(T graph) { if (graph == null) throw new ArgumentNullException("graph"); // Find an appropriate surrogate for the object ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForType(typeof(T), context.CacheContext); surrogate.Write(this, graph); } public string CacheContext { get { return context.CacheContext; } } #region / CompactBinaryWriter.Write(XXX) / /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> public override void Write(bool value) { writer.Write(value); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> public override void Write(byte value) { writer.Write(value); } /// <summary> /// Writes <paramref name="ch"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="ch">Object to write</param> public override void Write(char ch) { writer.Write(ch); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> public override void Write(short value) { writer.Write(value); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> public override void Write(int value) { writer.Write(value); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> public override void Write(long value) { writer.Write(value); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> public override void Write(decimal value) { writer.Write(value); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> public override void Write(float value) { writer.Write(value); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> public override void Write(double value) { writer.Write(value); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> public override void Write(DateTime value) { writer.Write(value.Ticks); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> public override void Write(Guid value) { writer.Write(value.ToByteArray()); } /// <summary> /// Writes <paramref name="buffer"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="buffer">Object to write</param> public override void Write(byte[] buffer) { if (buffer != null) writer.Write(buffer); else WriteObject(null); } /// <summary> /// Writes <paramref name="chars"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="chars">Object to write</param> public override void Write(char[] chars) { if (chars != null) writer.Write(chars); else WriteObject(null); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> public override void Write(string value) { if (value != null) writer.Write(value); else WriteObject(null); } /// <summary> /// Writes <paramref name="buffer"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="buffer">buffer to write</param> /// <param name="index">starting position in the buffer</param> /// <param name="count">number of bytes to write</param> public override void Write(byte[] buffer, int index, int count) { if (buffer != null) writer.Write(buffer, index, count); else WriteObject(null); } /// <summary> /// Writes <paramref name="chars"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="chars">buffer to write</param> /// <param name="index">starting position in the buffer</param> /// <param name="count">number of bytes to write</param> public override void Write(char[] chars, int index, int count) { if (chars != null) writer.Write(chars, index, count); else WriteObject(null); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> [CLSCompliant(false)] public override void Write(sbyte value) { writer.Write(value); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> [CLSCompliant(false)] public override void Write(ushort value) { writer.Write(value); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> [CLSCompliant(false)] public override void Write(uint value) { writer.Write(value); } /// <summary> /// Writes <paramref name="value"/> to the current stream and advances the stream position. /// This method writes directly to the underlying stream. /// </summary> /// <param name="value">Object to write</param> [CLSCompliant(false)] public override void Write(ulong value) { writer.Write(value); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor.Graphing; using UnityEditor.ShaderGraph; using UnityEngine.Rendering; using UnityEngine.Rendering.LWRP; namespace UnityEditor.Rendering.LWRP { [Serializable] [FormerName("UnityEditor.Experimental.Rendering.LightweightPipeline.LightWeightPBRSubShader")] [FormerName("UnityEditor.ShaderGraph.LightWeightPBRSubShader")] class LightWeightPBRSubShader : IPBRSubShader { static readonly NeededCoordinateSpace k_PixelCoordinateSpace = NeededCoordinateSpace.World; struct Pass { public string Name; public List<int> VertexShaderSlots; public List<int> PixelShaderSlots; } Pass m_ForwardPassMetallic = new Pass { Name = "LightweightForward", PixelShaderSlots = new List<int> { PBRMasterNode.AlbedoSlotId, PBRMasterNode.NormalSlotId, PBRMasterNode.EmissionSlotId, PBRMasterNode.MetallicSlotId, PBRMasterNode.SmoothnessSlotId, PBRMasterNode.OcclusionSlotId, PBRMasterNode.AlphaSlotId, PBRMasterNode.AlphaThresholdSlotId }, VertexShaderSlots = new List<int>() { PBRMasterNode.PositionSlotId } }; Pass m_ForwardPassSpecular = new Pass() { Name = "LightweightForward", PixelShaderSlots = new List<int>() { PBRMasterNode.AlbedoSlotId, PBRMasterNode.NormalSlotId, PBRMasterNode.EmissionSlotId, PBRMasterNode.SpecularSlotId, PBRMasterNode.SmoothnessSlotId, PBRMasterNode.OcclusionSlotId, PBRMasterNode.AlphaSlotId, PBRMasterNode.AlphaThresholdSlotId }, VertexShaderSlots = new List<int>() { PBRMasterNode.PositionSlotId } }; Pass m_DepthShadowPass = new Pass() { Name = "", PixelShaderSlots = new List<int>() { PBRMasterNode.AlbedoSlotId, PBRMasterNode.EmissionSlotId, PBRMasterNode.AlphaSlotId, PBRMasterNode.AlphaThresholdSlotId }, VertexShaderSlots = new List<int>() { PBRMasterNode.PositionSlotId } }; public int GetPreviewPassIndex() { return 0; } public string GetSubshader(IMasterNode masterNode, GenerationMode mode, List<string> sourceAssetDependencyPaths = null) { if (sourceAssetDependencyPaths != null) { // LightWeightPBRSubShader.cs sourceAssetDependencyPaths.Add(AssetDatabase.GUIDToAssetPath("ca91dbeb78daa054c9bbe15fef76361c")); } var templatePath = GetTemplatePath("lightweightPBRForwardPass.template"); var extraPassesTemplatePath = GetTemplatePath("lightweightPBRExtraPasses.template"); if (!File.Exists(templatePath) || !File.Exists(extraPassesTemplatePath)) return string.Empty; if (sourceAssetDependencyPaths != null) { sourceAssetDependencyPaths.Add(templatePath); sourceAssetDependencyPaths.Add(extraPassesTemplatePath); var relativePath = "Packages/com.unity.render-pipelines.lightweight/"; var fullPath = Path.GetFullPath(relativePath); var shaderFiles = Directory.GetFiles(Path.Combine(fullPath, "ShaderLibrary")).Select(x => Path.Combine(relativePath, x.Substring(fullPath.Length))); sourceAssetDependencyPaths.AddRange(shaderFiles); } string forwardTemplate = File.ReadAllText(templatePath); string extraTemplate = File.ReadAllText(extraPassesTemplatePath); var pbrMasterNode = masterNode as PBRMasterNode; var pass = pbrMasterNode.model == PBRMasterNode.Model.Metallic ? m_ForwardPassMetallic : m_ForwardPassSpecular; var subShader = new ShaderStringBuilder(); subShader.AppendLine("SubShader"); using (subShader.BlockScope()) { var materialTags = ShaderGenerator.BuildMaterialTags(pbrMasterNode.surfaceType); var tagsBuilder = new ShaderStringBuilder(0); materialTags.GetTags(tagsBuilder, LightweightRenderPipeline.k_ShaderTagName); subShader.AppendLines(tagsBuilder.ToString()); var materialOptions = ShaderGenerator.GetMaterialOptions(pbrMasterNode.surfaceType, pbrMasterNode.alphaMode, pbrMasterNode.twoSided.isOn); subShader.AppendLines(GetShaderPassFromTemplate( forwardTemplate, pbrMasterNode, pass, mode, materialOptions)); subShader.AppendLines(GetShaderPassFromTemplate( extraTemplate, pbrMasterNode, m_DepthShadowPass, mode, materialOptions)); } subShader.Append("CustomEditor \"UnityEditor.ShaderGraph.PBRMasterGUI\""); return subShader.ToString(); } public bool IsPipelineCompatible(RenderPipelineAsset renderPipelineAsset) { return renderPipelineAsset is LightweightRenderPipelineAsset; } static string GetTemplatePath(string templateName) { var basePath = "Packages/com.unity.render-pipelines.lightweight/Editor/ShaderGraph/"; string templatePath = Path.Combine(basePath, templateName); if (File.Exists(templatePath)) return templatePath; throw new FileNotFoundException(string.Format(@"Cannot find a template with name ""{0}"".", templateName)); } static string GetShaderPassFromTemplate(string template, PBRMasterNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions) { // ----------------------------------------------------- // // SETUP // // ----------------------------------------------------- // // ------------------------------------- // String builders var shaderProperties = new PropertyCollector(); var functionBuilder = new ShaderStringBuilder(1); var functionRegistry = new FunctionRegistry(functionBuilder); var defines = new ShaderStringBuilder(1); var graph = new ShaderStringBuilder(0); var vertexDescriptionInputStruct = new ShaderStringBuilder(1); var vertexDescriptionStruct = new ShaderStringBuilder(1); var vertexDescriptionFunction = new ShaderStringBuilder(1); var surfaceDescriptionInputStruct = new ShaderStringBuilder(1); var surfaceDescriptionStruct = new ShaderStringBuilder(1); var surfaceDescriptionFunction = new ShaderStringBuilder(1); var vertexInputStruct = new ShaderStringBuilder(1); var vertexOutputStruct = new ShaderStringBuilder(2); var vertexShader = new ShaderStringBuilder(2); var vertexShaderDescriptionInputs = new ShaderStringBuilder(2); var vertexShaderOutputs = new ShaderStringBuilder(2); var pixelShader = new ShaderStringBuilder(2); var pixelShaderSurfaceInputs = new ShaderStringBuilder(2); var pixelShaderSurfaceRemap = new ShaderStringBuilder(2); // ------------------------------------- // Get Slot and Node lists per stage var vertexSlots = pass.VertexShaderSlots.Select(masterNode.FindSlot<MaterialSlot>).ToList(); var vertexNodes = ListPool<AbstractMaterialNode>.Get(); NodeUtils.DepthFirstCollectNodesFromNode(vertexNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.VertexShaderSlots); var pixelSlots = pass.PixelShaderSlots.Select(masterNode.FindSlot<MaterialSlot>).ToList(); var pixelNodes = ListPool<AbstractMaterialNode>.Get(); NodeUtils.DepthFirstCollectNodesFromNode(pixelNodes, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots); // ------------------------------------- // Get Requirements var vertexRequirements = ShaderGraphRequirements.FromNodes(vertexNodes, ShaderStageCapability.Vertex, false); var pixelRequirements = ShaderGraphRequirements.FromNodes(pixelNodes, ShaderStageCapability.Fragment); var graphRequirements = pixelRequirements.Union(vertexRequirements); var surfaceRequirements = ShaderGraphRequirements.FromNodes(pixelNodes, ShaderStageCapability.Fragment, false); var modelRequiements = ShaderGraphRequirements.none; modelRequiements.requiresNormal |= k_PixelCoordinateSpace; modelRequiements.requiresTangent |= k_PixelCoordinateSpace; modelRequiements.requiresBitangent |= k_PixelCoordinateSpace; modelRequiements.requiresPosition |= k_PixelCoordinateSpace; modelRequiements.requiresViewDir |= k_PixelCoordinateSpace; modelRequiements.requiresMeshUVs.Add(UVChannel.UV1); // ----------------------------------------------------- // // START SHADER GENERATION // // ----------------------------------------------------- // // ------------------------------------- // Calculate material options var blendingBuilder = new ShaderStringBuilder(1); var cullingBuilder = new ShaderStringBuilder(1); var zTestBuilder = new ShaderStringBuilder(1); var zWriteBuilder = new ShaderStringBuilder(1); materialOptions.GetBlend(blendingBuilder); materialOptions.GetCull(cullingBuilder); materialOptions.GetDepthTest(zTestBuilder); materialOptions.GetDepthWrite(zWriteBuilder); // ------------------------------------- // Generate defines if (masterNode.IsSlotConnected(PBRMasterNode.NormalSlotId)) defines.AppendLine("#define _NORMALMAP 1"); if (masterNode.model == PBRMasterNode.Model.Specular) defines.AppendLine("#define _SPECULAR_SETUP 1"); if (masterNode.IsSlotConnected(PBRMasterNode.AlphaThresholdSlotId)) defines.AppendLine("#define _AlphaClip 1"); if (masterNode.surfaceType == SurfaceType.Transparent && masterNode.alphaMode == AlphaMode.Premultiply) defines.AppendLine("#define _ALPHAPREMULTIPLY_ON 1"); if (graphRequirements.requiresDepthTexture) defines.AppendLine("#define REQUIRE_DEPTH_TEXTURE"); if (graphRequirements.requiresCameraOpaqueTexture) defines.AppendLine("#define REQUIRE_OPAQUE_TEXTURE"); // ----------------------------------------------------- // // START VERTEX DESCRIPTION // // ----------------------------------------------------- // // ------------------------------------- // Generate Input structure for Vertex Description function // TODO - Vertex Description Input requirements are needed to exclude intermediate translation spaces vertexDescriptionInputStruct.AppendLine("struct VertexDescriptionInputs"); using (vertexDescriptionInputStruct.BlockSemicolonScope()) { ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresNormal, InterpolatorType.Normal, vertexDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresTangent, InterpolatorType.Tangent, vertexDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresBitangent, InterpolatorType.BiTangent, vertexDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresViewDir, InterpolatorType.ViewDirection, vertexDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(vertexRequirements.requiresPosition, InterpolatorType.Position, vertexDescriptionInputStruct); if (vertexRequirements.requiresVertexColor) vertexDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.VertexColor); if (vertexRequirements.requiresScreenPosition) vertexDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.ScreenPosition); foreach (var channel in vertexRequirements.requiresMeshUVs.Distinct()) vertexDescriptionInputStruct.AppendLine("half4 {0};", channel.GetUVName()); } // ------------------------------------- // Generate Output structure for Vertex Description function GraphUtil.GenerateVertexDescriptionStruct(vertexDescriptionStruct, vertexSlots); // ------------------------------------- // Generate Vertex Description function GraphUtil.GenerateVertexDescriptionFunction( masterNode.owner as GraphData, vertexDescriptionFunction, functionRegistry, shaderProperties, mode, vertexNodes, vertexSlots); // ----------------------------------------------------- // // START SURFACE DESCRIPTION // // ----------------------------------------------------- // // ------------------------------------- // Generate Input structure for Surface Description function // Surface Description Input requirements are needed to exclude intermediate translation spaces surfaceDescriptionInputStruct.AppendLine("struct SurfaceDescriptionInputs"); using (surfaceDescriptionInputStruct.BlockSemicolonScope()) { ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(surfaceRequirements.requiresNormal, InterpolatorType.Normal, surfaceDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(surfaceRequirements.requiresTangent, InterpolatorType.Tangent, surfaceDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(surfaceRequirements.requiresBitangent, InterpolatorType.BiTangent, surfaceDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(surfaceRequirements.requiresViewDir, InterpolatorType.ViewDirection, surfaceDescriptionInputStruct); ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(surfaceRequirements.requiresPosition, InterpolatorType.Position, surfaceDescriptionInputStruct); if (surfaceRequirements.requiresVertexColor) surfaceDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.VertexColor); if (surfaceRequirements.requiresScreenPosition) surfaceDescriptionInputStruct.AppendLine("float4 {0};", ShaderGeneratorNames.ScreenPosition); if (surfaceRequirements.requiresFaceSign) surfaceDescriptionInputStruct.AppendLine("float {0};", ShaderGeneratorNames.FaceSign); foreach (var channel in surfaceRequirements.requiresMeshUVs.Distinct()) surfaceDescriptionInputStruct.AppendLine("half4 {0};", channel.GetUVName()); } // ------------------------------------- // Generate Output structure for Surface Description function GraphUtil.GenerateSurfaceDescriptionStruct(surfaceDescriptionStruct, pixelSlots); // ------------------------------------- // Generate Surface Description function GraphUtil.GenerateSurfaceDescriptionFunction( pixelNodes, masterNode, masterNode.owner as GraphData, surfaceDescriptionFunction, functionRegistry, shaderProperties, pixelRequirements, mode, "PopulateSurfaceData", "SurfaceDescription", null, pixelSlots); // ----------------------------------------------------- // // GENERATE VERTEX > PIXEL PIPELINE // // ----------------------------------------------------- // // ------------------------------------- // Generate Input structure for Vertex shader GraphUtil.GenerateApplicationVertexInputs(vertexRequirements.Union(pixelRequirements.Union(modelRequiements)), vertexInputStruct); // ------------------------------------- // Generate standard transformations // This method ensures all required transform data is available in vertex and pixel stages ShaderGenerator.GenerateStandardTransforms( 3, 10, vertexOutputStruct, vertexShader, vertexShaderDescriptionInputs, vertexShaderOutputs, pixelShader, pixelShaderSurfaceInputs, pixelRequirements, surfaceRequirements, modelRequiements, vertexRequirements, CoordinateSpace.World); // ------------------------------------- // Generate pixel shader surface remap foreach (var slot in pixelSlots) { pixelShaderSurfaceRemap.AppendLine("{0} = surf.{0};", slot.shaderOutputName); } // ------------------------------------- // Extra pixel shader work var faceSign = new ShaderStringBuilder(); if (pixelRequirements.requiresFaceSign) faceSign.AppendLine(", half FaceSign : VFACE"); // ----------------------------------------------------- // // FINALIZE // // ----------------------------------------------------- // // ------------------------------------- // Combine Graph sections graph.AppendLine(shaderProperties.GetPropertiesDeclaration(1, mode)); graph.AppendLine(vertexDescriptionInputStruct.ToString()); graph.AppendLine(surfaceDescriptionInputStruct.ToString()); graph.AppendLine(functionBuilder.ToString()); graph.AppendLine(vertexDescriptionStruct.ToString()); graph.AppendLine(vertexDescriptionFunction.ToString()); graph.AppendLine(surfaceDescriptionStruct.ToString()); graph.AppendLine(surfaceDescriptionFunction.ToString()); graph.AppendLine(vertexInputStruct.ToString()); // ------------------------------------- // Generate final subshader var resultPass = template.Replace("${Tags}", string.Empty); resultPass = resultPass.Replace("${Blending}", blendingBuilder.ToString()); resultPass = resultPass.Replace("${Culling}", cullingBuilder.ToString()); resultPass = resultPass.Replace("${ZTest}", zTestBuilder.ToString()); resultPass = resultPass.Replace("${ZWrite}", zWriteBuilder.ToString()); resultPass = resultPass.Replace("${Defines}", defines.ToString()); resultPass = resultPass.Replace("${Graph}", graph.ToString()); resultPass = resultPass.Replace("${VertexOutputStruct}", vertexOutputStruct.ToString()); resultPass = resultPass.Replace("${VertexShader}", vertexShader.ToString()); resultPass = resultPass.Replace("${VertexShaderDescriptionInputs}", vertexShaderDescriptionInputs.ToString()); resultPass = resultPass.Replace("${VertexShaderOutputs}", vertexShaderOutputs.ToString()); resultPass = resultPass.Replace("${FaceSign}", faceSign.ToString()); resultPass = resultPass.Replace("${PixelShader}", pixelShader.ToString()); resultPass = resultPass.Replace("${PixelShaderSurfaceInputs}", pixelShaderSurfaceInputs.ToString()); resultPass = resultPass.Replace("${PixelShaderSurfaceRemap}", pixelShaderSurfaceRemap.ToString()); return resultPass; } } }
using System; using System.Linq; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; using Blueprint41.DatastoreTemplates; using q = Domain.Data.Query; namespace Domain.Data.Manipulation { public interface IMovieReviewOriginalData { string Uid { get; } string Review { get; } decimal? Rating { get; } Movie Movie { get; } } public partial class MovieReview : OGM<MovieReview, MovieReview.MovieReviewData, System.String>, IMovieReviewOriginalData { #region Initialize static MovieReview() { Register.Types(); } protected override void RegisterGeneratedStoredQueries() { #region LoadByKeys RegisterQuery(nameof(LoadByKeys), (query, alias) => query. Where(alias.Uid.In(Parameter.New<System.String>(Param0)))); #endregion #region LoadByUid RegisterQuery(nameof(LoadByUid), (query, alias) => query. Where(alias.Uid == Parameter.New<string>(Param0))); #endregion AdditionalGeneratedStoredQueries(); } public static MovieReview LoadByUid(string uid) { return FromQuery(nameof(LoadByUid), new Parameter(Param0, uid)).FirstOrDefault(); } partial void AdditionalGeneratedStoredQueries(); public static Dictionary<System.String, MovieReview> LoadByKeys(IEnumerable<System.String> uids) { return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item); } protected static void RegisterQuery(string name, Func<IMatchQuery, q.MovieReviewAlias, IWhereQuery> query) { q.MovieReviewAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.MovieReview.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"MovieReview => Uid : {this.Uid}, Review : {this.Review?.ToString() ?? "null"}, Rating : {this.Rating?.ToString() ?? "null"}"; } public override int GetHashCode() { return base.GetHashCode(); } protected override void LazySet() { base.LazySet(); if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged) { if ((object)InnerData == (object)OriginalData) OriginalData = new MovieReviewData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 #pragma warning restore CS0472 } protected override void ValidateDelete() { } #endregion #region Inner Data public class MovieReviewData : Data<System.String> { public MovieReviewData() { } public MovieReviewData(MovieReviewData data) { Uid = data.Uid; Review = data.Review; Rating = data.Rating; Movie = data.Movie; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "MovieReview"; Movie = new EntityCollection<Movie>(Wrapper, Members.Movie); } public string NodeType { get; private set; } sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); } sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); } #endregion #region Map Data sealed public override IDictionary<string, object> MapTo() { IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("Uid", Uid); dictionary.Add("Review", Review); dictionary.Add("Rating", Conversion<decimal?, long?>.Convert(Rating)); return dictionary; } sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties) { object value; if (properties.TryGetValue("Uid", out value)) Uid = (string)value; if (properties.TryGetValue("Review", out value)) Review = (string)value; if (properties.TryGetValue("Rating", out value)) Rating = Conversion<long, decimal>.Convert((long)value); } #endregion #region Members for interface IMovieReview public string Uid { get; set; } public string Review { get; set; } public decimal? Rating { get; set; } public EntityCollection<Movie> Movie { get; private set; } #endregion } #endregion #region Outer Data #region Members for interface IMovieReview public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } } public string Review { get { LazyGet(); return InnerData.Review; } set { if (LazySet(Members.Review, InnerData.Review, value)) InnerData.Review = value; } } public decimal? Rating { get { LazyGet(); return InnerData.Rating; } set { if (LazySet(Members.Rating, InnerData.Rating, value)) InnerData.Rating = value; } } public Movie Movie { get { return ((ILookupHelper<Movie>)InnerData.Movie).GetItem(null); } set { if (LazySet(Members.Movie, ((ILookupHelper<Movie>)InnerData.Movie).GetItem(null), value)) ((ILookupHelper<Movie>)InnerData.Movie).SetItem(value, null); } } #endregion #region Virtual Node Type public string NodeType { get { return InnerData.NodeType; } } #endregion #endregion #region Reflection private static MovieReviewMembers members = null; public static MovieReviewMembers Members { get { if (members == null) { lock (typeof(MovieReview)) { if (members == null) members = new MovieReviewMembers(); } } return members; } } public class MovieReviewMembers { internal MovieReviewMembers() { } #region Members for interface IMovieReview public Property Uid { get; } = MovieGraph.Model.Datastore.Model.Entities["MovieReview"].Properties["Uid"]; public Property Review { get; } = MovieGraph.Model.Datastore.Model.Entities["MovieReview"].Properties["Review"]; public Property Rating { get; } = MovieGraph.Model.Datastore.Model.Entities["MovieReview"].Properties["Rating"]; public Property Movie { get; } = MovieGraph.Model.Datastore.Model.Entities["MovieReview"].Properties["Movie"]; #endregion } private static MovieReviewFullTextMembers fullTextMembers = null; public static MovieReviewFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(MovieReview)) { if (fullTextMembers == null) fullTextMembers = new MovieReviewFullTextMembers(); } } return fullTextMembers; } } public class MovieReviewFullTextMembers { internal MovieReviewFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(MovieReview)) { if (entity == null) entity = MovieGraph.Model.Datastore.Model.Entities["MovieReview"]; } } return entity; } private static MovieReviewEvents events = null; public static MovieReviewEvents Events { get { if (events == null) { lock (typeof(MovieReview)) { if (events == null) events = new MovieReviewEvents(); } } return events; } } public class MovieReviewEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<MovieReview, EntityEventArgs> onNew; public event EventHandler<MovieReview, EntityEventArgs> OnNew { add { lock (this) { if (!onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; Entity.Events.OnNew += onNewProxy; onNewIsRegistered = true; } onNew += value; } } remove { lock (this) { onNew -= value; if (onNew == null && onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; onNewIsRegistered = false; } } } } private void onNewProxy(object sender, EntityEventArgs args) { EventHandler<MovieReview, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((MovieReview)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<MovieReview, EntityEventArgs> onDelete; public event EventHandler<MovieReview, EntityEventArgs> OnDelete { add { lock (this) { if (!onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; Entity.Events.OnDelete += onDeleteProxy; onDeleteIsRegistered = true; } onDelete += value; } } remove { lock (this) { onDelete -= value; if (onDelete == null && onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; onDeleteIsRegistered = false; } } } } private void onDeleteProxy(object sender, EntityEventArgs args) { EventHandler<MovieReview, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((MovieReview)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<MovieReview, EntityEventArgs> onSave; public event EventHandler<MovieReview, EntityEventArgs> OnSave { add { lock (this) { if (!onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; Entity.Events.OnSave += onSaveProxy; onSaveIsRegistered = true; } onSave += value; } } remove { lock (this) { onSave -= value; if (onSave == null && onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; onSaveIsRegistered = false; } } } } private void onSaveProxy(object sender, EntityEventArgs args) { EventHandler<MovieReview, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((MovieReview)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<MovieReview, PropertyEventArgs> onUid; public static event EventHandler<MovieReview, PropertyEventArgs> OnUid { add { lock (typeof(OnPropertyChange)) { if (!onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; Members.Uid.Events.OnChange += onUidProxy; onUidIsRegistered = true; } onUid += value; } } remove { lock (typeof(OnPropertyChange)) { onUid -= value; if (onUid == null && onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; onUidIsRegistered = false; } } } } private static void onUidProxy(object sender, PropertyEventArgs args) { EventHandler<MovieReview, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((MovieReview)sender, args); } #endregion #region OnReview private static bool onReviewIsRegistered = false; private static EventHandler<MovieReview, PropertyEventArgs> onReview; public static event EventHandler<MovieReview, PropertyEventArgs> OnReview { add { lock (typeof(OnPropertyChange)) { if (!onReviewIsRegistered) { Members.Review.Events.OnChange -= onReviewProxy; Members.Review.Events.OnChange += onReviewProxy; onReviewIsRegistered = true; } onReview += value; } } remove { lock (typeof(OnPropertyChange)) { onReview -= value; if (onReview == null && onReviewIsRegistered) { Members.Review.Events.OnChange -= onReviewProxy; onReviewIsRegistered = false; } } } } private static void onReviewProxy(object sender, PropertyEventArgs args) { EventHandler<MovieReview, PropertyEventArgs> handler = onReview; if ((object)handler != null) handler.Invoke((MovieReview)sender, args); } #endregion #region OnRating private static bool onRatingIsRegistered = false; private static EventHandler<MovieReview, PropertyEventArgs> onRating; public static event EventHandler<MovieReview, PropertyEventArgs> OnRating { add { lock (typeof(OnPropertyChange)) { if (!onRatingIsRegistered) { Members.Rating.Events.OnChange -= onRatingProxy; Members.Rating.Events.OnChange += onRatingProxy; onRatingIsRegistered = true; } onRating += value; } } remove { lock (typeof(OnPropertyChange)) { onRating -= value; if (onRating == null && onRatingIsRegistered) { Members.Rating.Events.OnChange -= onRatingProxy; onRatingIsRegistered = false; } } } } private static void onRatingProxy(object sender, PropertyEventArgs args) { EventHandler<MovieReview, PropertyEventArgs> handler = onRating; if ((object)handler != null) handler.Invoke((MovieReview)sender, args); } #endregion #region OnMovie private static bool onMovieIsRegistered = false; private static EventHandler<MovieReview, PropertyEventArgs> onMovie; public static event EventHandler<MovieReview, PropertyEventArgs> OnMovie { add { lock (typeof(OnPropertyChange)) { if (!onMovieIsRegistered) { Members.Movie.Events.OnChange -= onMovieProxy; Members.Movie.Events.OnChange += onMovieProxy; onMovieIsRegistered = true; } onMovie += value; } } remove { lock (typeof(OnPropertyChange)) { onMovie -= value; if (onMovie == null && onMovieIsRegistered) { Members.Movie.Events.OnChange -= onMovieProxy; onMovieIsRegistered = false; } } } } private static void onMovieProxy(object sender, PropertyEventArgs args) { EventHandler<MovieReview, PropertyEventArgs> handler = onMovie; if ((object)handler != null) handler.Invoke((MovieReview)sender, args); } #endregion } #endregion } #endregion #region IMovieReviewOriginalData public IMovieReviewOriginalData OriginalVersion { get { return this; } } #region Members for interface IMovieReview string IMovieReviewOriginalData.Uid { get { return OriginalData.Uid; } } string IMovieReviewOriginalData.Review { get { return OriginalData.Review; } } decimal? IMovieReviewOriginalData.Rating { get { return OriginalData.Rating; } } Movie IMovieReviewOriginalData.Movie { get { return ((ILookupHelper<Movie>)OriginalData.Movie).GetOriginalItem(null); } } #endregion #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Internal.TypeSystem; namespace Internal.TypeSystem.Ecma { public partial class EcmaModule : ModuleDesc { private PEReader _peReader; protected MetadataReader _metadataReader; internal interface IEntityHandleObject { EntityHandle Handle { get; } } private sealed class EcmaObjectLookupWrapper : IEntityHandleObject { private EntityHandle _handle; private object _obj; public EcmaObjectLookupWrapper(EntityHandle handle, object obj) { _obj = obj; _handle = handle; } public EntityHandle Handle { get { return _handle; } } public object Object { get { return _obj; } } } internal class EcmaObjectLookupHashtable : LockFreeReaderHashtable<EntityHandle, IEntityHandleObject> { private EcmaModule _module; public EcmaObjectLookupHashtable(EcmaModule module) { _module = module; } protected override int GetKeyHashCode(EntityHandle key) { return key.GetHashCode(); } protected override int GetValueHashCode(IEntityHandleObject value) { return value.Handle.GetHashCode(); } protected override bool CompareKeyToValue(EntityHandle key, IEntityHandleObject value) { return key.Equals(value.Handle); } protected override bool CompareValueToValue(IEntityHandleObject value1, IEntityHandleObject value2) { if (Object.ReferenceEquals(value1, value2)) return true; else return value1.Handle.Equals(value2.Handle); } protected override IEntityHandleObject CreateValueFromKey(EntityHandle handle) { object item; switch (handle.Kind) { case HandleKind.TypeDefinition: item = new EcmaType(_module, (TypeDefinitionHandle)handle); break; case HandleKind.MethodDefinition: { MethodDefinitionHandle methodDefinitionHandle = (MethodDefinitionHandle)handle; TypeDefinitionHandle typeDefinitionHandle = _module._metadataReader.GetMethodDefinition(methodDefinitionHandle).GetDeclaringType(); EcmaType type = (EcmaType)_module.GetObject(typeDefinitionHandle); item = new EcmaMethod(type, methodDefinitionHandle); } break; case HandleKind.FieldDefinition: { FieldDefinitionHandle fieldDefinitionHandle = (FieldDefinitionHandle)handle; TypeDefinitionHandle typeDefinitionHandle = _module._metadataReader.GetFieldDefinition(fieldDefinitionHandle).GetDeclaringType(); EcmaType type = (EcmaType)_module.GetObject(typeDefinitionHandle); item = new EcmaField(type, fieldDefinitionHandle); } break; case HandleKind.TypeReference: item = _module.ResolveTypeReference((TypeReferenceHandle)handle); break; case HandleKind.MemberReference: item = _module.ResolveMemberReference((MemberReferenceHandle)handle); break; case HandleKind.AssemblyReference: item = _module.ResolveAssemblyReference((AssemblyReferenceHandle)handle); break; case HandleKind.TypeSpecification: item = _module.ResolveTypeSpecification((TypeSpecificationHandle)handle); break; case HandleKind.MethodSpecification: item = _module.ResolveMethodSpecification((MethodSpecificationHandle)handle); break; case HandleKind.ExportedType: item = _module.ResolveExportedType((ExportedTypeHandle)handle); break; case HandleKind.StandaloneSignature: item = _module.ResolveStandaloneSignature((StandaloneSignatureHandle)handle); break; case HandleKind.ModuleDefinition: // ECMA-335 Partition 2 II.22.38 1d: This should not occur in a CLI ("compressed metadata") module, // but resolves to "current module". item = _module; break; default: throw new BadImageFormatException("Unknown metadata token type: " + handle.Kind); } switch (handle.Kind) { case HandleKind.TypeDefinition: case HandleKind.MethodDefinition: case HandleKind.FieldDefinition: // type/method/field definitions directly correspond to their target item. return (IEntityHandleObject)item; default: // Everything else is some form of reference which cannot be self-describing return new EcmaObjectLookupWrapper(handle, item); } } } private LockFreeReaderHashtable<EntityHandle, IEntityHandleObject> _resolvedTokens; internal EcmaModule(TypeSystemContext context, PEReader peReader, MetadataReader metadataReader) : base(context) { _peReader = peReader; _metadataReader = metadataReader; _resolvedTokens = new EcmaObjectLookupHashtable(this); } public static EcmaModule Create(TypeSystemContext context, PEReader peReader) { MetadataReader metadataReader = CreateMetadataReader(context, peReader); if (metadataReader.IsAssembly) return new EcmaAssembly(context, peReader, metadataReader); else return new EcmaModule(context, peReader, metadataReader); } private static MetadataReader CreateMetadataReader(TypeSystemContext context, PEReader peReader) { if (!peReader.HasMetadata) { throw new TypeSystemException.BadImageFormatException(); } var stringDecoderProvider = context as IMetadataStringDecoderProvider; MetadataReader metadataReader = peReader.GetMetadataReader(MetadataReaderOptions.None /* MetadataReaderOptions.ApplyWindowsRuntimeProjections */, (stringDecoderProvider != null) ? stringDecoderProvider.GetMetadataStringDecoder() : null); return metadataReader; } public PEReader PEReader { get { return _peReader; } } public MetadataReader MetadataReader { get { return _metadataReader; } } /// <summary> /// Gets the managed entrypoint method of this module or null if the module has no managed entrypoint. /// </summary> public MethodDesc EntryPoint { get { CorHeader corHeader = _peReader.PEHeaders.CorHeader; if ((corHeader.Flags & CorFlags.NativeEntryPoint) != 0) { // Entrypoint is an RVA to an unmanaged method return null; } int entryPointToken = corHeader.EntryPointTokenOrRelativeVirtualAddress; if (entryPointToken == 0) { // No entrypoint return null; } EntityHandle handle = MetadataTokens.EntityHandle(entryPointToken); if (handle.Kind == HandleKind.MethodDefinition) { return GetMethod(handle); } else if (handle.Kind == HandleKind.AssemblyFile) { // Entrypoint not in the manifest assembly throw new NotImplementedException(); } // Bad metadata throw new BadImageFormatException(); } } public sealed override MetadataType GetType(string nameSpace, string name, bool throwIfNotFound = true) { var stringComparer = _metadataReader.StringComparer; // TODO: More efficient implementation? foreach (var typeDefinitionHandle in _metadataReader.TypeDefinitions) { var typeDefinition = _metadataReader.GetTypeDefinition(typeDefinitionHandle); if (stringComparer.Equals(typeDefinition.Name, name) && stringComparer.Equals(typeDefinition.Namespace, nameSpace)) { return (MetadataType)GetType((EntityHandle)typeDefinitionHandle); } } foreach (var exportedTypeHandle in _metadataReader.ExportedTypes) { var exportedType = _metadataReader.GetExportedType(exportedTypeHandle); if (stringComparer.Equals(exportedType.Name, name) && stringComparer.Equals(exportedType.Namespace, nameSpace)) { if (exportedType.IsForwarder) { Object implementation = GetObject(exportedType.Implementation); if (implementation is ModuleDesc) { return ((ModuleDesc)(implementation)).GetType(nameSpace, name); } // TODO throw new NotImplementedException(); } // TODO: throw new NotImplementedException(); } } if (throwIfNotFound) throw new TypeSystemException.TypeLoadException(nameSpace, name, this); return null; } public TypeDesc GetType(EntityHandle handle) { TypeDesc type = GetObject(handle) as TypeDesc; if (type == null) throw new BadImageFormatException("Type expected"); return type; } public MethodDesc GetMethod(EntityHandle handle) { MethodDesc method = GetObject(handle) as MethodDesc; if (method == null) throw new BadImageFormatException("Method expected"); return method; } public FieldDesc GetField(EntityHandle handle) { FieldDesc field = GetObject(handle) as FieldDesc; if (field == null) throw new BadImageFormatException("Field expected"); return field; } public Object GetObject(EntityHandle handle) { IEntityHandleObject obj = _resolvedTokens.GetOrCreateValue(handle); if (obj is EcmaObjectLookupWrapper) { return ((EcmaObjectLookupWrapper)obj).Object; } else { return obj; } } private Object ResolveMethodSpecification(MethodSpecificationHandle handle) { MethodSpecification methodSpecification = _metadataReader.GetMethodSpecification(handle); MethodDesc methodDef = GetMethod(methodSpecification.Method); BlobReader signatureReader = _metadataReader.GetBlobReader(methodSpecification.Signature); EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader); TypeDesc[] instantiation = parser.ParseMethodSpecSignature(); return Context.GetInstantiatedMethod(methodDef, new Instantiation(instantiation)); } private Object ResolveStandaloneSignature(StandaloneSignatureHandle handle) { StandaloneSignature signature = _metadataReader.GetStandaloneSignature(handle); BlobReader signatureReader = _metadataReader.GetBlobReader(signature.Signature); EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader); MethodSignature methodSig = parser.ParseMethodSignature(); return methodSig; } private Object ResolveTypeSpecification(TypeSpecificationHandle handle) { TypeSpecification typeSpecification = _metadataReader.GetTypeSpecification(handle); BlobReader signatureReader = _metadataReader.GetBlobReader(typeSpecification.Signature); EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader); return parser.ParseType(); } private Object ResolveMemberReference(MemberReferenceHandle handle) { MemberReference memberReference = _metadataReader.GetMemberReference(handle); Object parent = GetObject(memberReference.Parent); TypeDesc parentTypeDesc = parent as TypeDesc; if (parentTypeDesc != null) { BlobReader signatureReader = _metadataReader.GetBlobReader(memberReference.Signature); EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader); string name = _metadataReader.GetString(memberReference.Name); if (parser.IsFieldSignature) { FieldDesc field = parentTypeDesc.GetField(name); if (field != null) return field; throw new TypeSystemException.MissingFieldException(parentTypeDesc, name); } else { MethodSignature sig = parser.ParseMethodSignature(); TypeDesc typeDescToInspect = parentTypeDesc; // Try to resolve the name and signature in the current type, or any of the base types. do { // TODO: handle substitutions MethodDesc method = typeDescToInspect.GetMethod(name, sig); if (method != null) { // If this resolved to one of the base types, make sure it's not a constructor. // Instance constructors are not inherited. if (typeDescToInspect != parentTypeDesc && method.IsConstructor) break; return method; } typeDescToInspect = typeDescToInspect.BaseType; } while (typeDescToInspect != null); throw new TypeSystemException.MissingMethodException(parentTypeDesc, name, sig); } } else if (parent is MethodDesc) { throw new TypeSystemException.InvalidProgramException(ExceptionStringID.InvalidProgramVararg, (MethodDesc)parent); } else if (parent is ModuleDesc) { throw new NotImplementedException("MemberRef to a global function or variable."); } throw new BadImageFormatException(); } private Object ResolveTypeReference(TypeReferenceHandle handle) { TypeReference typeReference = _metadataReader.GetTypeReference(handle); Object resolutionScope = GetObject(typeReference.ResolutionScope); if (resolutionScope is ModuleDesc) { return ((ModuleDesc)(resolutionScope)).GetType(_metadataReader.GetString(typeReference.Namespace), _metadataReader.GetString(typeReference.Name)); } else if (resolutionScope is MetadataType) { string typeName = _metadataReader.GetString(typeReference.Name); MetadataType result = ((MetadataType)(resolutionScope)).GetNestedType(typeName); if (result != null) return result; throw new TypeSystemException.TypeLoadException(typeName, ((MetadataType)resolutionScope).Module); } // TODO throw new NotImplementedException(); } private Object ResolveAssemblyReference(AssemblyReferenceHandle handle) { AssemblyReference assemblyReference = _metadataReader.GetAssemblyReference(handle); AssemblyName an = new AssemblyName(); an.Name = _metadataReader.GetString(assemblyReference.Name); an.Version = assemblyReference.Version; var publicKeyOrToken = _metadataReader.GetBlobBytes(assemblyReference.PublicKeyOrToken); if ((assemblyReference.Flags & AssemblyFlags.PublicKey) != 0) { an.SetPublicKey(publicKeyOrToken); } else { an.SetPublicKeyToken(publicKeyOrToken); } an.CultureName = _metadataReader.GetString(assemblyReference.Culture); an.ContentType = GetContentTypeFromAssemblyFlags(assemblyReference.Flags); return Context.ResolveAssembly(an); } private Object ResolveExportedType(ExportedTypeHandle handle) { ExportedType exportedType = _metadataReader.GetExportedType(handle); var implementation = GetObject(exportedType.Implementation); if (implementation is ModuleDesc) { var module = (ModuleDesc)implementation; string nameSpace = _metadataReader.GetString(exportedType.Namespace); string name = _metadataReader.GetString(exportedType.Name); return module.GetType(nameSpace, name); } else if (implementation is MetadataType) { var type = (MetadataType)implementation; string name = _metadataReader.GetString(exportedType.Name); var nestedType = type.GetNestedType(name); if (nestedType == null) throw new TypeSystemException.TypeLoadException(name, this); return nestedType; } else { throw new BadImageFormatException("Unknown metadata token type for exported type"); } } public sealed override IEnumerable<MetadataType> GetAllTypes() { foreach (var typeDefinitionHandle in _metadataReader.TypeDefinitions) { yield return (MetadataType)GetType(typeDefinitionHandle); } } public sealed override MetadataType GetGlobalModuleType() { int typeDefinitionsCount = _metadataReader.TypeDefinitions.Count; if (typeDefinitionsCount == 0) return null; return (MetadataType)GetType(MetadataTokens.EntityHandle(0x02000001 /* COR_GLOBAL_PARENT_TOKEN */)); } protected static AssemblyContentType GetContentTypeFromAssemblyFlags(AssemblyFlags flags) { return (AssemblyContentType)(((int)flags & 0x0E00) >> 9); } public string GetUserString(UserStringHandle userStringHandle) { // String literals are not cached return _metadataReader.GetUserString(userStringHandle); } public override string ToString() { ModuleDefinition moduleDefinition = _metadataReader.GetModuleDefinition(); return _metadataReader.GetString(moduleDefinition.Name); } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; using RestSharp; using RestSharp.Deserializers; using RestSharpMethod = RestSharp.Method; using Polly; namespace Org.OpenAPITools.Client { /// <summary> /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// </summary> internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer { private readonly IReadableConfiguration _configuration; private static readonly string _contentType = "application/json"; private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings { // OpenAPI generated types generally hide default constructors. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy { OverrideSpecifiedNames = false } } }; public CustomJsonCodec(IReadableConfiguration configuration) { _configuration = configuration; } public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) { _serializerSettings = serializerSettings; _configuration = configuration; } /// <summary> /// Serialize the object into a JSON string. /// </summary> /// <param name="obj">Object to be serialized.</param> /// <returns>A JSON string.</returns> public string Serialize(object obj) { if (obj != null && obj is Org.OpenAPITools.Models.AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema return ((Org.OpenAPITools.Models.AbstractOpenAPISchema)obj).ToJson(); } else { return JsonConvert.SerializeObject(obj, _serializerSettings); } } public T Deserialize<T>(IRestResponse response) { var result = (T)Deserialize(response, typeof(T)); return result; } /// <summary> /// Deserialize the JSON string into a proper object. /// </summary> /// <param name="response">The HTTP response.</param> /// <param name="type">Object type.</param> /// <returns>Object representation of the JSON string.</returns> internal object Deserialize(IRestResponse response, Type type) { if (type == typeof(byte[])) // return byte array { return response.RawBytes; } // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) if (type == typeof(Stream)) { var bytes = response.RawBytes; if (response.Headers != null) { var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); foreach (var header in response.Headers) { var match = regex.Match(header.ToString()); if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); File.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } } var stream = new MemoryStream(bytes); return stream; } if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); } if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type { return Convert.ChangeType(response.Content, type); } // at this point, it must be a model (json) try { return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings); } catch (Exception e) { throw new ApiException(500, e.Message); } } public string RootElement { get; set; } public string Namespace { get; set; } public string DateFormat { get; set; } public string ContentType { get { return _contentType; } set { throw new InvalidOperationException("Not allowed to set content type."); } } } /// <summary> /// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios), /// encapsulating general REST accessor use cases. /// </summary> public partial class ApiClient : ISynchronousClient, IAsynchronousClient { private readonly string _baseUrl; /// <summary> /// Specifies the settings on a <see cref="JsonSerializer" /> object. /// These settings can be adjusted to accomodate custom serialization rules. /// </summary> public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings { // OpenAPI generated types generally hide default constructors. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy { OverrideSpecifiedNames = false } } }; /// <summary> /// Allows for extending request processing for <see cref="ApiClient"/> generated code. /// </summary> /// <param name="request">The RestSharp request object</param> partial void InterceptRequest(IRestRequest request); /// <summary> /// Allows for extending response processing for <see cref="ApiClient"/> generated code. /// </summary> /// <param name="request">The RestSharp request object</param> /// <param name="response">The RestSharp response object</param> partial void InterceptResponse(IRestRequest request, IRestResponse response); /// <summary> /// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url. /// </summary> public ApiClient() { _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; } /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> /// </summary> /// <param name="basePath">The target service's base path in URL format.</param> /// <exception cref="ArgumentException"></exception> public ApiClient(string basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); _baseUrl = basePath; } /// <summary> /// Constructs the RestSharp version of an http method /// </summary> /// <param name="method">Swagger Client Custom HttpMethod</param> /// <returns>RestSharp's HttpMethod instance.</returns> /// <exception cref="ArgumentOutOfRangeException"></exception> private RestSharpMethod Method(HttpMethod method) { RestSharpMethod other; switch (method) { case HttpMethod.Get: other = RestSharpMethod.GET; break; case HttpMethod.Post: other = RestSharpMethod.POST; break; case HttpMethod.Put: other = RestSharpMethod.PUT; break; case HttpMethod.Delete: other = RestSharpMethod.DELETE; break; case HttpMethod.Head: other = RestSharpMethod.HEAD; break; case HttpMethod.Options: other = RestSharpMethod.OPTIONS; break; case HttpMethod.Patch: other = RestSharpMethod.PATCH; break; default: throw new ArgumentOutOfRangeException("method", method, null); } return other; } /// <summary> /// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>. /// At this point, all information for querying the service is known. Here, it is simply /// mapped into the RestSharp request. /// </summary> /// <param name="method">The http verb.</param> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>[private] A new RestRequest instance.</returns> /// <exception cref="ArgumentNullException"></exception> private RestRequest NewRequest( HttpMethod method, string path, RequestOptions options, IReadableConfiguration configuration) { if (path == null) throw new ArgumentNullException("path"); if (options == null) throw new ArgumentNullException("options"); if (configuration == null) throw new ArgumentNullException("configuration"); RestRequest request = new RestRequest(Method(method)) { Resource = path, JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) }; if (options.PathParameters != null) { foreach (var pathParam in options.PathParameters) { request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); } } if (options.QueryParameters != null) { foreach (var queryParam in options.QueryParameters) { foreach (var value in queryParam.Value) { request.AddQueryParameter(queryParam.Key, value); } } } if (configuration.DefaultHeaders != null) { foreach (var headerParam in configuration.DefaultHeaders) { request.AddHeader(headerParam.Key, headerParam.Value); } } if (options.HeaderParameters != null) { foreach (var headerParam in options.HeaderParameters) { foreach (var value in headerParam.Value) { request.AddHeader(headerParam.Key, value); } } } if (options.FormParameters != null) { foreach (var formParam in options.FormParameters) { request.AddParameter(formParam.Key, formParam.Value); } } if (options.Data != null) { if (options.Data is Stream stream) { var contentType = "application/octet-stream"; if (options.HeaderParameters != null) { var contentTypes = options.HeaderParameters["Content-Type"]; contentType = contentTypes[0]; } var bytes = ClientUtils.ReadAsBytes(stream); request.AddParameter(contentType, bytes, ParameterType.RequestBody); } else { if (options.HeaderParameters != null) { var contentTypes = options.HeaderParameters["Content-Type"]; if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) { request.RequestFormat = DataFormat.Json; } else { // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. } } else { // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. request.RequestFormat = DataFormat.Json; } request.AddJsonBody(options.Data); } } if (options.FileParameters != null) { foreach (var fileParam in options.FileParameters) { var bytes = ClientUtils.ReadAsBytes(fileParam.Value); var fileStream = fileParam.Value as FileStream; if (fileStream != null) request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); else request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); } } if (options.Cookies != null && options.Cookies.Count > 0) { foreach (var cookie in options.Cookies) { request.AddCookie(cookie.Name, cookie.Value); } } return request; } private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response) { T result = response.Data; string rawContent = response.Content; var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>(), result, rawContent) { ErrorText = response.ErrorMessage, Cookies = new List<Cookie>() }; if (response.Headers != null) { foreach (var responseHeader in response.Headers) { transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); } } if (response.Cookies != null) { foreach (var responseCookies in response.Cookies) { transformed.Cookies.Add( new Cookie( responseCookies.Name, responseCookies.Value, responseCookies.Path, responseCookies.Domain) ); } } return transformed; } private ApiResponse<T> Exec<T>(RestRequest req, IReadableConfiguration configuration) { RestClient client = new RestClient(_baseUrl); client.ClearHandlers(); var existingDeserializer = req.JsonSerializer as IDeserializer; if (existingDeserializer != null) { client.AddHandler("application/json", () => existingDeserializer); client.AddHandler("text/json", () => existingDeserializer); client.AddHandler("text/x-json", () => existingDeserializer); client.AddHandler("text/javascript", () => existingDeserializer); client.AddHandler("*+json", () => existingDeserializer); } else { var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); client.AddHandler("application/json", () => customDeserializer); client.AddHandler("text/json", () => customDeserializer); client.AddHandler("text/x-json", () => customDeserializer); client.AddHandler("text/javascript", () => customDeserializer); client.AddHandler("*+json", () => customDeserializer); } var xmlDeserializer = new XmlDeserializer(); client.AddHandler("application/xml", () => xmlDeserializer); client.AddHandler("text/xml", () => xmlDeserializer); client.AddHandler("*+xml", () => xmlDeserializer); client.AddHandler("*", () => xmlDeserializer); client.Timeout = configuration.Timeout; if (configuration.Proxy != null) { client.Proxy = configuration.Proxy; } if (configuration.UserAgent != null) { client.UserAgent = configuration.UserAgent; } if (configuration.ClientCertificates != null) { client.ClientCertificates = configuration.ClientCertificates; } InterceptRequest(req); IRestResponse<T> response; if (RetryConfiguration.RetryPolicy != null) { var policy = RetryConfiguration.RetryPolicy; var policyResult = policy.ExecuteAndCapture(() => client.Execute(req)); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T> { Request = req, ErrorException = policyResult.FinalException }; } else { response = client.Execute<T>(req); } // if the response type is oneOf/anyOf, call FromJSON to deserialize the data if (typeof(Org.OpenAPITools.Models.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) { response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); } else if (typeof(T).Name == "Stream") // for binary response { response.Data = (T)(object)new MemoryStream(response.RawBytes); } InterceptResponse(req, response); var result = ToApiResponse(response); if (response.ErrorMessage != null) { result.ErrorText = response.ErrorMessage; } if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List<Cookie>(); foreach (var restResponseCookie in response.Cookies) { var cookie = new Cookie( restResponseCookie.Name, restResponseCookie.Value, restResponseCookie.Path, restResponseCookie.Domain ) { Comment = restResponseCookie.Comment, CommentUri = restResponseCookie.CommentUri, Discard = restResponseCookie.Discard, Expired = restResponseCookie.Expired, Expires = restResponseCookie.Expires, HttpOnly = restResponseCookie.HttpOnly, Port = restResponseCookie.Port, Secure = restResponseCookie.Secure, Version = restResponseCookie.Version }; result.Cookies.Add(cookie); } } return result; } private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { RestClient client = new RestClient(_baseUrl); client.ClearHandlers(); var existingDeserializer = req.JsonSerializer as IDeserializer; if (existingDeserializer != null) { client.AddHandler("application/json", () => existingDeserializer); client.AddHandler("text/json", () => existingDeserializer); client.AddHandler("text/x-json", () => existingDeserializer); client.AddHandler("text/javascript", () => existingDeserializer); client.AddHandler("*+json", () => existingDeserializer); } else { var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); client.AddHandler("application/json", () => customDeserializer); client.AddHandler("text/json", () => customDeserializer); client.AddHandler("text/x-json", () => customDeserializer); client.AddHandler("text/javascript", () => customDeserializer); client.AddHandler("*+json", () => customDeserializer); } var xmlDeserializer = new XmlDeserializer(); client.AddHandler("application/xml", () => xmlDeserializer); client.AddHandler("text/xml", () => xmlDeserializer); client.AddHandler("*+xml", () => xmlDeserializer); client.AddHandler("*", () => xmlDeserializer); client.Timeout = configuration.Timeout; if (configuration.Proxy != null) { client.Proxy = configuration.Proxy; } if (configuration.UserAgent != null) { client.UserAgent = configuration.UserAgent; } if (configuration.ClientCertificates != null) { client.ClientCertificates = configuration.ClientCertificates; } InterceptRequest(req); IRestResponse<T> response; if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T> { Request = req, ErrorException = policyResult.FinalException }; } else { response = await client.ExecuteAsync<T>(req, cancellationToken).ConfigureAwait(false); } // if the response type is oneOf/anyOf, call FromJSON to deserialize the data if (typeof(Org.OpenAPITools.Models.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) { response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); } else if (typeof(T).Name == "Stream") // for binary response { response.Data = (T)(object)new MemoryStream(response.RawBytes); } InterceptResponse(req, response); var result = ToApiResponse(response); if (response.ErrorMessage != null) { result.ErrorText = response.ErrorMessage; } if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List<Cookie>(); foreach (var restResponseCookie in response.Cookies) { var cookie = new Cookie( restResponseCookie.Name, restResponseCookie.Value, restResponseCookie.Path, restResponseCookie.Domain ) { Comment = restResponseCookie.Comment, CommentUri = restResponseCookie.CommentUri, Discard = restResponseCookie.Discard, Expired = restResponseCookie.Expired, Expires = restResponseCookie.Expires, HttpOnly = restResponseCookie.HttpOnly, Port = restResponseCookie.Port, Secure = restResponseCookie.Secure, Version = restResponseCookie.Version }; result.Cookies.Add(cookie); } } return result; } #region IAsynchronousClient /// <summary> /// Make a HTTP GET request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> GetAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP POST request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> PostAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP PUT request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> PutAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP DELETE request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> DeleteAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP HEAD request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> HeadAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP OPTION request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> OptionsAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP PATCH request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> PatchAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Patch, path, options, config), config, cancellationToken); } #endregion IAsynchronousClient #region ISynchronousClient /// <summary> /// Make a HTTP GET request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Get<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Get, path, options, config), config); } /// <summary> /// Make a HTTP POST request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Post<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Post, path, options, config), config); } /// <summary> /// Make a HTTP PUT request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Put<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Put, path, options, config), config); } /// <summary> /// Make a HTTP DELETE request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Delete<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Delete, path, options, config), config); } /// <summary> /// Make a HTTP HEAD request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Head<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Head, path, options, config), config); } /// <summary> /// Make a HTTP OPTION request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Options<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Options, path, options, config), config); } /// <summary> /// Make a HTTP PATCH request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Patch<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Patch, path, options, config), config); } #endregion ISynchronousClient } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Drawing; using System.ComponentModel; using System.Windows.Forms; using HtmlRenderer.Entities; using HtmlRenderer.Parse; using HtmlRenderer.Utils; namespace HtmlRenderer { /// <summary> /// Provides HTML rendering using the text property.<br/> /// WinForms control that will render html content in it's client rectangle.<br/> /// If <see cref="AutoScroll"/> is true and the layout of the html resulted in its content beyond the client bounds /// of the panel it will show scrollbars (horizontal/vertical) allowing to scroll the content.<br/> /// If <see cref="AutoScroll"/> is false html content outside the client bounds will be clipped.<br/> /// The control will handle mouse and keyboard events on it to support html text selection, copy-paste and mouse clicks.<br/> /// <para> /// The major differential to use HtmlPanel or HtmlLabel is size and scrollbars.<br/> /// If the size of the control depends on the html content the HtmlLabel should be used.<br/> /// If the size is set by some kind of layout then HtmlPanel is more suitable, also shows scrollbars if the html contents is larger than the control client rectangle.<br/> /// </para> /// <para> /// <h4>AutoScroll:</h4> /// Allows showing scrollbars if html content is placed outside the visible boundaries of the panel. /// </para> /// <para> /// <h4>LinkClicked event:</h4> /// Raised when the user clicks on a link in the html.<br/> /// Allows canceling the execution of the link. /// </para> /// <para> /// <h4>StylesheetLoad event:</h4> /// Raised when a stylesheet is about to be loaded by file path or URI by link element.<br/> /// This event allows to provide the stylesheet manually or provide new source (file or uri) to load from.<br/> /// If no alternative data is provided the original source will be used.<br/> /// </para> /// <para> /// <h4>ImageLoad event:</h4> /// Raised when an image is about to be loaded by file path or URI.<br/> /// This event allows to provide the image manually, if not handled the image will be loaded from file or download from URI. /// </para> /// <para> /// <h4>RenderError event:</h4> /// Raised when an error occurred during html rendering.<br/> /// </para> /// </summary> public class HtmlPanel : ScrollableControl { #region Fields and Consts /// <summary> /// /// </summary> private HtmlContainer _htmlContainer; /// <summary> /// the raw base stylesheet data used in the control /// </summary> private string _baseRawCssData; /// <summary> /// the base stylesheet data used in the control /// </summary> private CssData _baseCssData; #endregion /// <summary> /// Creates a new HtmlPanel and sets a basic css for it's styling. /// </summary> public HtmlPanel() { AutoScroll = true; BackColor = SystemColors.Window; DoubleBuffered = true; SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.SupportsTransparentBackColor, true); _htmlContainer = new HtmlContainer(); _htmlContainer.LinkClicked += OnLinkClicked; _htmlContainer.RenderError += OnRenderError; _htmlContainer.Refresh += OnRefresh; _htmlContainer.ScrollChange += OnScrollChange; _htmlContainer.StylesheetLoad += OnStylesheetLoad; _htmlContainer.ImageLoad += OnImageLoad; } /// <summary> /// Raised when the user clicks on a link in the html.<br/> /// Allows canceling the execution of the link. /// </summary> public event EventHandler<HtmlLinkClickedEventArgs> LinkClicked; /// <summary> /// Raised when an error occurred during html rendering.<br/> /// </summary> public event EventHandler<HtmlRenderErrorEventArgs> RenderError; /// <summary> /// Raised when a stylesheet is about to be loaded by file path or URI by link element.<br/> /// This event allows to provide the stylesheet manually or provide new source (file or uri) to load from.<br/> /// If no alternative data is provided the original source will be used.<br/> /// </summary> public event EventHandler<HtmlStylesheetLoadEventArgs> StylesheetLoad; /// <summary> /// Raised when an image is about to be loaded by file path or URI.<br/> /// This event allows to provide the image manually, if not handled the image will be loaded from file or download from URI. /// </summary> public event EventHandler<HtmlImageLoadEventArgs> ImageLoad; /// <summary> /// Gets or sets a value indicating if anti-aliasing should be avoided for geometry like backgrounds and borders (default - false). /// </summary> public bool AvoidGeometryAntialias { get { return _htmlContainer.AvoidGeometryAntialias; } set { _htmlContainer.AvoidGeometryAntialias = value; } } /// <summary> /// Gets or sets a value indicating if image loading only when visible should be avoided (default - false).<br/> /// True - images are loaded as soon as the html is parsed.<br/> /// False - images that are not visible because of scroll location are not loaded until they are scrolled to. /// </summary> /// <remarks> /// Images late loading improve performance if the page contains image outside the visible scroll area, especially if there is large /// amount of images, as all image loading is delayed (downloading and loading into memory).<br/> /// Late image loading may effect the layout and actual size as image without set size will not have actual size until they are loaded /// resulting in layout change during user scroll.<br/> /// Early image loading may also effect the layout if image without known size above the current scroll location are loaded as they /// will push the html elements down. /// </remarks> public bool AvoidImagesLateLoading { get { return _htmlContainer.AvoidImagesLateLoading; } set { _htmlContainer.AvoidImagesLateLoading = value; } } /// <summary> /// Is content selection is enabled for the rendered html (default - true).<br/> /// If set to 'false' the rendered html will be static only with ability to click on links. /// </summary> [Browsable(true)] [DefaultValue(true)] [Category("Behavior")] [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Description("Is content selection is enabled for the rendered html.")] public bool IsSelectionEnabled { get { return _htmlContainer.IsSelectionEnabled; } set { _htmlContainer.IsSelectionEnabled = value; } } /// <summary> /// Is the build-in context menu enabled and will be shown on mouse right click (default - true) /// </summary> [Browsable(true)] [DefaultValue(true)] [Category("Behavior")] [EditorBrowsable(EditorBrowsableState.Always)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] [Description("Is the build-in context menu enabled and will be shown on mouse right click.")] public bool IsContextMenuEnabled { get { return _htmlContainer.IsContextMenuEnabled; } set { _htmlContainer.IsContextMenuEnabled = value; } } /// <summary> /// Set base stylesheet to be used by html rendered in the panel. /// </summary> [Browsable(true)] [Category("Appearance")] [Description("Set base stylesheet to be used by html rendered in the control.")] public string BaseStylesheet { get { return _baseRawCssData; } set { _baseRawCssData = value; _baseCssData = CssParser.ParseStyleSheet(value, true); } } /// <summary> /// Gets or sets a value indicating whether the container enables the user to scroll to any controls placed outside of its visible boundaries. /// </summary> [Browsable(true)] [Description("Sets a value indicating whether the container enables the user to scroll to any controls placed outside of its visible boundaries.")] public override bool AutoScroll { get{return base.AutoScroll;} set{base.AutoScroll = value;} } /// <summary> /// Gets or sets the text of this panel /// </summary> [Browsable(true)] [Description("Sets the html of this control.")] public override string Text { get { return base.Text; } set { base.Text = value; if (!IsDisposed) { VerticalScroll.Value = VerticalScroll.Minimum; _htmlContainer.SetHtml(Text, _baseCssData); PerformLayout(); Invalidate(); } } } /// <summary> /// Get the currently selected text segment in the html. /// </summary> [Browsable(false)] public string SelectedText { get { return _htmlContainer.SelectedText; } } /// <summary> /// Copy the currently selected html segment with style. /// </summary> [Browsable(false)] public string SelectedHtml { get { return _htmlContainer.SelectedHtml; } } /// <summary> /// Get html from the current DOM tree with inline style. /// </summary> /// <returns>generated html</returns> public string GetHtml() { return _htmlContainer != null ? _htmlContainer.GetHtml() : null; } /// <summary> /// Adjust the scrollbar of the panel on html element by the given id.<br/> /// The top of the html element rectangle will be at the top of the panel, if there /// is not enough height to scroll to the top the scroll will be at maximum.<br/> /// </summary> /// <param name="elementId">the id of the element to scroll to</param> public void ScrollToElement(string elementId) { ArgChecker.AssertArgNotNullOrEmpty(elementId, "elementId"); if( _htmlContainer != null ) { var rect = _htmlContainer.GetElementRectangle(elementId); if (rect.HasValue) { UpdateScroll(Point.Round(rect.Value.Location)); _htmlContainer.HandleMouseMove(this, new MouseEventArgs(MouseButtons, 0, MousePosition.X, MousePosition.Y, 0)); } } } #region Private methods /// <summary> /// Perform the layout of the html in the control. /// </summary> protected override void OnLayout(LayoutEventArgs levent) { PerformHtmlLayout(); base.OnLayout(levent); // to handle if vertical scrollbar is appearing or disappearing if (_htmlContainer != null && Math.Abs(_htmlContainer.MaxSize.Width - ClientSize.Width) > 0.1) { PerformHtmlLayout(); base.OnLayout(levent); } } /// <summary> /// Perform html container layout by the current panel client size. /// </summary> private void PerformHtmlLayout() { if (_htmlContainer != null) { _htmlContainer.MaxSize = new SizeF(ClientSize.Width, 0); using (var g = CreateGraphics()) { _htmlContainer.PerformLayout(g); } AutoScrollMinSize = Size.Round(_htmlContainer.ActualSize); } } /// <summary> /// Perform paint of the html in the control. /// </summary> protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (_htmlContainer != null) { _htmlContainer.ScrollOffset = AutoScrollPosition; _htmlContainer.PerformPaint(e.Graphics); // call mouse move to handle paint after scroll or html change affecting mouse cursor. var mp = PointToClient(MousePosition); _htmlContainer.HandleMouseMove(this, new MouseEventArgs(MouseButtons.None, 0, mp.X, mp.Y, 0)); } } /// <summary> /// Set focus on the control for keyboard scrrollbars handling. /// </summary> protected override void OnClick(EventArgs e) { base.OnClick(e); Focus(); } /// <summary> /// Handle mouse move to handle hover cursor and text selection. /// </summary> protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if( _htmlContainer != null ) _htmlContainer.HandleMouseMove(this, e); } /// <summary> /// Handle mouse leave to handle cursor change. /// </summary> protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); if (_htmlContainer != null) _htmlContainer.HandleMouseLeave(this); } /// <summary> /// Handle mouse down to handle selection. /// </summary> protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (_htmlContainer != null) _htmlContainer.HandleMouseDown(this, e); } /// <summary> /// Handle mouse up to handle selection and link click. /// </summary> protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseClick(e); if (_htmlContainer != null) _htmlContainer.HandleMouseUp(this, e); } /// <summary> /// Handle mouse double click to select word under the mouse. /// </summary> protected override void OnMouseDoubleClick(MouseEventArgs e) { base.OnMouseDoubleClick(e); if (_htmlContainer != null) _htmlContainer.HandleMouseDoubleClick(this, e); } /// <summary> /// Handle key down event for selection, copy and scrollbars handling. /// </summary> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (_htmlContainer != null) _htmlContainer.HandleKeyDown(this, e); if (e.KeyCode == Keys.Up) { VerticalScroll.Value = Math.Max(VerticalScroll.Value - 70, VerticalScroll.Minimum); PerformLayout(); } else if (e.KeyCode == Keys.Down) { VerticalScroll.Value = Math.Min(VerticalScroll.Value + 70, VerticalScroll.Maximum); PerformLayout(); } else if (e.KeyCode == Keys.PageDown) { VerticalScroll.Value = Math.Min(VerticalScroll.Value + 400, VerticalScroll.Maximum); PerformLayout(); } else if (e.KeyCode == Keys.PageUp) { VerticalScroll.Value = Math.Max(VerticalScroll.Value - 400, VerticalScroll.Minimum); PerformLayout(); } else if (e.KeyCode == Keys.End) { VerticalScroll.Value = VerticalScroll.Maximum; PerformLayout(); } else if (e.KeyCode == Keys.Home) { VerticalScroll.Value = VerticalScroll.Minimum; PerformLayout(); } } /// <summary> /// Propagate the LinkClicked event from root container. /// </summary> private void OnLinkClicked(object sender, HtmlLinkClickedEventArgs e) { if (LinkClicked != null) { LinkClicked(this, e); } } /// <summary> /// Propagate the Render Error event from root container. /// </summary> private void OnRenderError(object sender, HtmlRenderErrorEventArgs e) { if(RenderError != null) { if (InvokeRequired) Invoke(RenderError, this, e); else RenderError(this, e); } } /// <summary> /// Propagate the stylesheet load event from root container. /// </summary> private void OnStylesheetLoad(object sender, HtmlStylesheetLoadEventArgs e) { if (StylesheetLoad != null) { StylesheetLoad(this, e); } } /// <summary> /// Propagate the image load event from root container. /// </summary> private void OnImageLoad(object sender, HtmlImageLoadEventArgs e) { if (ImageLoad != null) { ImageLoad(this, e); } } /// <summary> /// Handle html renderer invalidate and re-layout as requested. /// </summary> private void OnRefresh(object sender, HtmlRefreshEventArgs e) { if(e.Layout) { if (InvokeRequired) Invoke(new MethodInvoker(PerformLayout)); else PerformLayout(); } if (InvokeRequired) Invoke(new MethodInvoker(Invalidate)); else Invalidate(); } /// <summary> /// On html renderer scroll request adjust the scrolling of the panel to the requested location. /// </summary> private void OnScrollChange(object sender, HtmlScrollEventArgs e) { UpdateScroll(e.Location); } /// <summary> /// Adjust the scrolling of the panel to the requested location. /// </summary> /// <param name="location">the location to adjust the scroll to</param> private void UpdateScroll(Point location) { AutoScrollPosition = location; _htmlContainer.ScrollOffset = AutoScrollPosition; } /// <summary> /// Used to add arrow keys to the handled keys in <see cref="OnKeyDown"/>. /// </summary> protected override bool IsInputKey(Keys keyData) { switch (keyData) { case Keys.Right: case Keys.Left: case Keys.Up: case Keys.Down: return true; case Keys.Shift | Keys.Right: case Keys.Shift | Keys.Left: case Keys.Shift | Keys.Up: case Keys.Shift | Keys.Down: return true; } return base.IsInputKey(keyData); } /// <summary> /// Release the html container resources. /// </summary> protected override void Dispose(bool disposing) { if(_htmlContainer != null) { _htmlContainer.LinkClicked -= OnLinkClicked; _htmlContainer.RenderError -= OnRenderError; _htmlContainer.Refresh -= OnRefresh; _htmlContainer.ScrollChange -= OnScrollChange; _htmlContainer.StylesheetLoad -= OnStylesheetLoad; _htmlContainer.ImageLoad -= OnImageLoad; _htmlContainer.Dispose(); _htmlContainer = null; } base.Dispose(disposing); } #region Hide not relevant properties from designer /// <summary> /// Not applicable. /// </summary> [Browsable(false)] public override Font Font { get { return base.Font; } set { base.Font = value; } } /// <summary> /// Not applicable. /// </summary> [Browsable(false)] public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; } } /// <summary> /// Not applicable. /// </summary> [Browsable(false)] public override bool AllowDrop { get { return base.AllowDrop; } set { base.AllowDrop = value; } } /// <summary> /// Not applicable. /// </summary> [Browsable(false)] public override RightToLeft RightToLeft { get { return base.RightToLeft; } set { base.RightToLeft = value; } } /// <summary> /// Not applicable. /// </summary> [Browsable(false)] public override Cursor Cursor { get { return base.Cursor; } set { base.Cursor = value; } } /// <summary> /// Not applicable. /// </summary> [Browsable(false)] public new bool UseWaitCursor { get { return base.UseWaitCursor; } set { base.UseWaitCursor = value; } } #endregion #endregion } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using QuantConnect.Configuration; using QuantConnect.Data; using QuantConnect.Data.Auxiliary; using QuantConnect.Interfaces; using QuantConnect.Util; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Regression algorithm to test volume adjusted behavior /// </summary> public class AdjustedVolumeRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private Symbol _aapl; private const string Ticker = "AAPL"; private FactorFile _factorFile; private readonly IEnumerator<decimal> _expectedAdjustedVolume = new List<decimal> { 6164842, 3044047, 3680347, 3468303, 2169943, 2652523, 1499707, 1518215, 1655219, 1510487 }.GetEnumerator(); private readonly IEnumerator<decimal> _expectedAdjustedAskSize = new List<decimal> { 215600, 5600, 25200, 8400, 5600, 5600, 2800, 8400, 14000, 2800 }.GetEnumerator(); private readonly IEnumerator<decimal> _expectedAdjustedBidSize = new List<decimal> { 2800, 11200, 2800, 2800, 2800, 5600, 11200, 8400, 30800, 2800 }.GetEnumerator(); public override void Initialize() { SetStartDate(2014, 6, 5); //Set Start Date SetEndDate(2014, 6, 5); //Set End Date UniverseSettings.DataNormalizationMode = DataNormalizationMode.SplitAdjusted; _aapl = AddEquity(Ticker, Resolution.Minute).Symbol; var dataProvider = Composer.Instance.GetExportedValueByTypeName<IDataProvider>(Config.Get("data-provider", "DefaultDataProvider")); var mapFileProvider = new LocalDiskMapFileProvider(); mapFileProvider.Initialize(dataProvider); var factorFileProvider = new LocalDiskFactorFileProvider(); factorFileProvider.Initialize(mapFileProvider, dataProvider); _factorFile = factorFileProvider.Get(_aapl); } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { if (!Portfolio.Invested) { SetHoldings(_aapl, 1); } if (data.Splits.ContainsKey(_aapl)) { Log(data.Splits[_aapl].ToString()); } if (data.Bars.ContainsKey(_aapl)) { var aaplData = data.Bars[_aapl]; // Assert our volume matches what we expect if (_expectedAdjustedVolume.MoveNext() && _expectedAdjustedVolume.Current != aaplData.Volume) { // Our values don't match lets try and give a reason why var dayFactor = _factorFile.GetSplitFactor(aaplData.Time); var probableAdjustedVolume = aaplData.Volume / dayFactor; if (_expectedAdjustedVolume.Current == probableAdjustedVolume) { throw new ArgumentException($"Volume was incorrect; but manually adjusted value is correct." + $" Adjustment by multiplying volume by {1 / dayFactor} is not occurring."); } else { throw new ArgumentException($"Volume was incorrect; even when adjusted manually by" + $" multiplying volume by {1 / dayFactor}. Data may have changed."); } } } if (data.QuoteBars.ContainsKey(_aapl)) { var aaplQuoteData = data.QuoteBars[_aapl]; // Assert our askSize matches what we expect if (_expectedAdjustedAskSize.MoveNext() && _expectedAdjustedAskSize.Current != aaplQuoteData.LastAskSize) { // Our values don't match lets try and give a reason why var dayFactor = _factorFile.GetSplitFactor(aaplQuoteData.Time); var probableAdjustedAskSize = aaplQuoteData.LastAskSize / dayFactor; if (_expectedAdjustedAskSize.Current == probableAdjustedAskSize) { throw new ArgumentException($"Ask size was incorrect; but manually adjusted value is correct." + $" Adjustment by multiplying size by {1 / dayFactor} is not occurring."); } else { throw new ArgumentException($"Ask size was incorrect; even when adjusted manually by" + $" multiplying size by {1 / dayFactor}. Data may have changed."); } } // Assert our bidSize matches what we expect if (_expectedAdjustedBidSize.MoveNext() && _expectedAdjustedBidSize.Current != aaplQuoteData.LastBidSize) { // Our values don't match lets try and give a reason why var dayFactor = _factorFile.GetSplitFactor(aaplQuoteData.Time); var probableAdjustedBidSize = aaplQuoteData.LastBidSize / dayFactor; if (_expectedAdjustedBidSize.Current == probableAdjustedBidSize) { throw new ArgumentException($"Bid size was incorrect; but manually adjusted value is correct." + $" Adjustment by multiplying size by {1 / dayFactor} is not occurring."); } else { throw new ArgumentException($"Bid size was incorrect; even when adjusted manually by" + $" multiplying size by {1 / dayFactor}. Data may have changed."); } } } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "1"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "0%"}, {"Drawdown", "0%"}, {"Expectancy", "0"}, {"Net Profit", "0%"}, {"Sharpe Ratio", "0"}, {"Probabilistic Sharpe Ratio", "0%"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0"}, {"Beta", "0"}, {"Annual Standard Deviation", "0"}, {"Annual Variance", "0"}, {"Information Ratio", "0"}, {"Tracking Error", "0"}, {"Treynor Ratio", "0"}, {"Total Fees", "$21.60"}, {"Estimated Strategy Capacity", "$42000000.00"}, {"Lowest Capacity Asset", "AAPL R735QTJ8XC9X"}, {"Fitness Score", "0"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "0"}, {"Return Over Maximum Drawdown", "0"}, {"Portfolio Turnover", "0"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "18e41dded4f8cee548ee02b03ffb0814"} }; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Windows.System; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace MetroCollage.Common { /// <summary> /// NavigationManager aids in navigation between pages. It provides commands used to /// navigate back and forward as well as registers for standard mouse and keyboard /// shortcuts used to go back and forward. In addition it integrates SuspensionManger /// to handle process lifetime management and state management when navigating between /// pages. /// </summary> /// <example> /// To make use of NavigationManager, follow these two steps or /// start with a BasicPage or any other Page item template other than BlankPage. /// /// 1) Create an instance of the NaivgationHelper somewhere such as in the /// constructor for the page and register a callback for the LoadState and /// SaveState events. /// <code> /// public MyPage() /// { /// this.InitializeComponent(); /// var navigationHelper = new NavigationHelper(this); /// this.navigationHelper.LoadState += navigationHelper_LoadState; /// this.navigationHelper.SaveState += navigationHelper_SaveState; /// } /// /// private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e) /// { } /// private async void navigationHelper_SaveState(object sender, LoadStateEventArgs e) /// { } /// </code> /// /// 2) Register the page to call into the NavigationManager whenever the page participates /// in navigation by overriding the <see cref="Windows.UI.Xaml.Controls.Page.OnNavigatedTo"/> /// and <see cref="Windows.UI.Xaml.Controls.Page.OnNavigatedFrom"/> events. /// <code> /// protected override void OnNavigatedTo(NavigationEventArgs e) /// { /// navigationHelper.OnNavigatedTo(e); /// } /// /// protected override void OnNavigatedFrom(NavigationEventArgs e) /// { /// navigationHelper.OnNavigatedFrom(e); /// } /// </code> /// </example> [Windows.Foundation.Metadata.WebHostHidden] public class NavigationHelper : DependencyObject { private Page Page { get; set; } private Frame Frame { get { return this.Page.Frame; } } /// <summary> /// Initializes a new instance of the <see cref="NavigationHelper"/> class. /// </summary> /// <param name="page">A reference to the current page used for navigation. /// This reference allows for frame manipulation and to ensure that keyboard /// navigation requests only occur when the page is occupying the entire window.</param> public NavigationHelper(Page page) { this.Page = page; // When this page is part of the visual tree make two changes: // 1) Map application view state to visual state for the page // 2) Handle keyboard and mouse navigation requests this.Page.Loaded += (sender, e) => { // Keyboard and mouse navigation only apply when occupying the entire window if (this.Page.ActualHeight == Window.Current.Bounds.Height && this.Page.ActualWidth == Window.Current.Bounds.Width) { // Listen to the window directly so focus isn't required Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += CoreDispatcher_AcceleratorKeyActivated; Window.Current.CoreWindow.PointerPressed += this.CoreWindow_PointerPressed; } }; // Undo the same changes when the page is no longer visible this.Page.Unloaded += (sender, e) => { Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated -= CoreDispatcher_AcceleratorKeyActivated; Window.Current.CoreWindow.PointerPressed -= this.CoreWindow_PointerPressed; }; } #region Navigation support RelayCommand _goBackCommand; RelayCommand _goForwardCommand; /// <summary> /// <see cref="RelayCommand"/> used to bind to the back Button's Command property /// for navigating to the most recent item in back navigation history, if a Frame /// manages its own navigation history. /// /// The <see cref="RelayCommand"/> is set up to use the virtual method <see cref="GoBack"/> /// as the Execute Action and <see cref="CanGoBack"/> for CanExecute. /// </summary> public RelayCommand GoBackCommand { get { if (_goBackCommand == null) { _goBackCommand = new RelayCommand( () => this.GoBack(), () => this.CanGoBack()); } return _goBackCommand; } set { _goBackCommand = value; } } /// <summary> /// <see cref="RelayCommand"/> used for navigating to the most recent item in /// the forward navigation history, if a Frame manages its own navigation history. /// /// The <see cref="RelayCommand"/> is set up to use the virtual method <see cref="GoForward"/> /// as the Execute Action and <see cref="CanGoForward"/> for CanExecute. /// </summary> public RelayCommand GoForwardCommand { get { if (_goForwardCommand == null) { _goForwardCommand = new RelayCommand( () => this.GoForward(), () => this.CanGoForward()); } return _goForwardCommand; } } /// <summary> /// Virtual method used by the <see cref="GoBackCommand"/> property /// to determine if the <see cref="Frame"/> can go back. /// </summary> /// <returns> /// true if the <see cref="Frame"/> has at least one entry /// in the back navigation history. /// </returns> public virtual bool CanGoBack() { return this.Frame != null && this.Frame.CanGoBack; } /// <summary> /// Virtual method used by the <see cref="GoForwardCommand"/> property /// to determine if the <see cref="Frame"/> can go forward. /// </summary> /// <returns> /// true if the <see cref="Frame"/> has at least one entry /// in the forward navigation history. /// </returns> public virtual bool CanGoForward() { return this.Frame != null && this.Frame.CanGoForward; } /// <summary> /// Virtual method used by the <see cref="GoBackCommand"/> property /// to invoke the <see cref="Windows.UI.Xaml.Controls.Frame.GoBack"/> method. /// </summary> public virtual void GoBack() { if (this.Frame != null && this.Frame.CanGoBack) this.Frame.GoBack(); } /// <summary> /// Virtual method used by the <see cref="GoForwardCommand"/> property /// to invoke the <see cref="Windows.UI.Xaml.Controls.Frame.GoForward"/> method. /// </summary> public virtual void GoForward() { if (this.Frame != null && this.Frame.CanGoForward) this.Frame.GoForward(); } /// <summary> /// Invoked on every keystroke, including system keys such as Alt key combinations, when /// this page is active and occupies the entire window. Used to detect keyboard navigation /// between pages even when the page itself doesn't have focus. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs e) { var virtualKey = e.VirtualKey; // Only investigate further when Left, Right, or the dedicated Previous or Next keys // are pressed if ((e.EventType == CoreAcceleratorKeyEventType.SystemKeyDown || e.EventType == CoreAcceleratorKeyEventType.KeyDown) && (virtualKey == VirtualKey.Left || virtualKey == VirtualKey.Right || (int)virtualKey == 166 || (int)virtualKey == 167)) { var coreWindow = Window.Current.CoreWindow; var downState = CoreVirtualKeyStates.Down; bool menuKey = (coreWindow.GetKeyState(VirtualKey.Menu) & downState) == downState; bool controlKey = (coreWindow.GetKeyState(VirtualKey.Control) & downState) == downState; bool shiftKey = (coreWindow.GetKeyState(VirtualKey.Shift) & downState) == downState; bool noModifiers = !menuKey && !controlKey && !shiftKey; bool onlyAlt = menuKey && !controlKey && !shiftKey; if (((int)virtualKey == 166 && noModifiers) || (virtualKey == VirtualKey.Left && onlyAlt)) { // When the previous key or Alt+Left are pressed navigate back e.Handled = true; this.GoBackCommand.Execute(null); } else if (((int)virtualKey == 167 && noModifiers) || (virtualKey == VirtualKey.Right && onlyAlt)) { // When the next key or Alt+Right are pressed navigate forward e.Handled = true; this.GoForwardCommand.Execute(null); } } } /// <summary> /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this /// page is active and occupies the entire window. Used to detect browser-style next and /// previous mouse button clicks to navigate between pages. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private void CoreWindow_PointerPressed(CoreWindow sender, PointerEventArgs e) { var properties = e.CurrentPoint.Properties; // Ignore button chords with the left, right, and middle buttons if (properties.IsLeftButtonPressed || properties.IsRightButtonPressed || properties.IsMiddleButtonPressed) return; // If back or foward are pressed (but not both) navigate appropriately bool backPressed = properties.IsXButton1Pressed; bool forwardPressed = properties.IsXButton2Pressed; if (backPressed ^ forwardPressed) { e.Handled = true; if (backPressed) this.GoBackCommand.Execute(null); if (forwardPressed) this.GoForwardCommand.Execute(null); } } #endregion #region Process lifetime management private String _pageKey; /// <summary> /// Register this event on the current page to populate the page /// with content passed during navigation as well as any saved /// state provided when recreating a page from a prior session. /// </summary> public event LoadStateEventHandler LoadState; /// <summary> /// Register this event on the current page to preserve /// state associated with the current page in case the /// application is suspended or the page is discarded from /// the navigaqtion cache. /// </summary> public event SaveStateEventHandler SaveState; /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// This method calls <see cref="LoadState"/>, where all page specific /// navigation and process lifetime management logic should be placed. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property provides the group to be displayed.</param> public void OnNavigatedTo(NavigationEventArgs e) { var frameState = SuspensionManager.SessionStateForFrame(this.Frame); this._pageKey = "Page-" + this.Frame.BackStackDepth; if (e.NavigationMode == NavigationMode.New) { // Clear existing state for forward navigation when adding a new page to the // navigation stack var nextPageKey = this._pageKey; int nextPageIndex = this.Frame.BackStackDepth; while (frameState.Remove(nextPageKey)) { nextPageIndex++; nextPageKey = "Page-" + nextPageIndex; } // Pass the navigation parameter to the new page if (this.LoadState != null) { this.LoadState(this, new LoadStateEventArgs(e.Parameter, null)); } } else { // Pass the navigation parameter and preserved page state to the page, using // the same strategy for loading suspended state and recreating pages discarded // from cache if (this.LoadState != null) { this.LoadState(this, new LoadStateEventArgs(e.Parameter, (Dictionary<String, Object>)frameState[this._pageKey])); } } } /// <summary> /// Invoked when this page will no longer be displayed in a Frame. /// This method calls <see cref="SaveState"/>, where all page specific /// navigation and process lifetime management logic should be placed. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property provides the group to be displayed.</param> public void OnNavigatedFrom(NavigationEventArgs e) { var frameState = SuspensionManager.SessionStateForFrame(this.Frame); var pageState = new Dictionary<String, Object>(); if (this.SaveState != null) { this.SaveState(this, new SaveStateEventArgs(pageState)); } frameState[_pageKey] = pageState; } #endregion } /// <summary> /// Represents the method that will handle the <see cref="NavigationHelper.LoadState"/>event /// </summary> public delegate void LoadStateEventHandler(object sender, LoadStateEventArgs e); /// <summary> /// Represents the method that will handle the <see cref="NavigationHelper.SaveState"/>event /// </summary> public delegate void SaveStateEventHandler(object sender, SaveStateEventArgs e); /// <summary> /// Class used to hold the event data required when a page attempts to load state. /// </summary> public class LoadStateEventArgs : EventArgs { /// <summary> /// The parameter value passed to <see cref="Frame.Navigate(Type, Object)"/> /// when this page was initially requested. /// </summary> public Object NavigationParameter { get; private set; } /// <summary> /// A dictionary of state preserved by this page during an earlier /// session. This will be null the first time a page is visited. /// </summary> public Dictionary<string, Object> PageState { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="LoadStateEventArgs"/> class. /// </summary> /// <param name="navigationParameter"> /// The parameter value passed to <see cref="Frame.Navigate(Type, Object)"/> /// when this page was initially requested. /// </param> /// <param name="pageState"> /// A dictionary of state preserved by this page during an earlier /// session. This will be null the first time a page is visited. /// </param> public LoadStateEventArgs(Object navigationParameter, Dictionary<string, Object> pageState) : base() { this.NavigationParameter = navigationParameter; this.PageState = pageState; } } /// <summary> /// Class used to hold the event data required when a page attempts to save state. /// </summary> public class SaveStateEventArgs : EventArgs { /// <summary> /// An empty dictionary to be populated with serializable state. /// </summary> public Dictionary<string, Object> PageState { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="SaveStateEventArgs"/> class. /// </summary> /// <param name="pageState">An empty dictionary to be populated with serializable state.</param> public SaveStateEventArgs(Dictionary<string, Object> pageState) : base() { this.PageState = pageState; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using BTDB.KVDBLayer; using BTDB.ODBLayer; using BTDBTest; namespace SimpleTester { public class RelationSpeedTest { public class Person { [PrimaryKey(1)] public ulong Id { get; set; } [SecondaryKey("Email")] public string? Email { get; set; } } static ObjectDB CreateInMemoryDb() { var lowDb = new InMemoryKeyValueDB(); var db = new ObjectDB(); db.Open(lowDb, true); return db; } static ObjectDB CreateDb(IFileCollection fc) { var lowDb = new KeyValueDB(fc); var db = new ObjectDB(); db.Open(lowDb, true); return db; } static ObjectDB CreateBTreeDb(IFileCollection fc) { var lowDb = new BTreeKeyValueDB(fc); var db = new ObjectDB(); db.Open(lowDb, true); return db; } static IEnumerable<string> GenerateEmails(int count) { var rnd = new Random(); while (count-- > 0) yield return $"a{rnd.Next(999)}@b{count}.com"; } interface IMeasureOperations { void Insert(); void List(); void Update(); void Remove(); } //definitions for relations public interface IPersonTable : IRelation<Person> { void Insert(Person person); void Update(Person person); Person FindById(ulong id); void RemoveById(ulong id); IEnumerator<Person> ListByEmail(AdvancedEnumeratorParam<string> param); } // class RelationPersonTest : IMeasureOperations { readonly int _count; readonly ObjectDB _db; readonly Func<IObjectDBTransaction, IPersonTable> _creator; public RelationPersonTest(ObjectDB db, int count) { _count = count; _db = db; using var tr = _db.StartTransaction(); _creator = tr.InitRelation<IPersonTable>("Job"); tr.Commit(); } public void Insert() { ulong idx = 0; foreach (var email in GenerateEmails(_count)) { using var tr = _db.StartTransaction(); var personTable = _creator(tr); personTable.Insert(new Person { Email = email, Id = idx++ }); tr.Commit(); } } public void List() { ulong sum = 0; using var tr = _db.StartTransaction(); var personTable = _creator(tr); var en = personTable.ListByEmail(AdvancedEnumeratorParam<string>.Instance); while (en.MoveNext()) { sum += en.Current.Id; } } public void Update() { for (var id = 0ul; id < (ulong)_count; id++) { using var tr = _db.StartTransaction(); var personTable = _creator(tr); var p = personTable.FindById(id); p.Email += "a"; personTable.Update(p); tr.Commit(); } } public void Remove() { for (var id = 0ul; id < (ulong)_count; id++) { using var tr = _db.StartTransaction(); var personTable = _creator(tr); personTable.RemoveById(id); tr.Commit(); } } } //definitions for singletons public class PersonMap { public IDictionary<ulong, Person>? Items { get; set; } } public class PersonNameIndex { public IOrderedDictionary<string, ulong>? Items { get; set; } } // class SingletonPersonTest : IMeasureOperations { readonly int _count; readonly ObjectDB _db; public SingletonPersonTest(ObjectDB db, int count) { _db = db; _count = count; } public void Insert() { ulong idx = 0; foreach (var email in GenerateEmails(_count)) { using var tr = _db.StartTransaction(); var persons = tr.Singleton<PersonMap>(); var emails = tr.Singleton<PersonNameIndex>(); persons.Items![idx] = new Person { Email = email, Id = idx }; emails.Items![email] = idx; idx++; tr.Commit(); } } public void List() { using var tr = _db.StartReadOnlyTransaction(); var persons = tr.Singleton<PersonMap>(); var emails = tr.Singleton<PersonNameIndex>(); ulong sum = 0; foreach (var e in emails.Items!) { var p = persons.Items![e.Value]; sum += p.Id; } } public void Update() { for (var id = 0ul; id < (ulong)_count; id++) { using var tr = _db.StartTransaction(); var persons = tr.Singleton<PersonMap>(); var emails = tr.Singleton<PersonNameIndex>(); var p = persons.Items![id]; emails.Items!.Remove(p.Email!); p.Email += "a"; emails.Items[p.Email] = id; persons.Items[id] = p; tr.Commit(); } } public void Remove() { for (var id = 0ul; id < (ulong)_count; id++) { using var tr = _db.StartTransaction(); var persons = tr.Singleton<PersonMap>(); var emails = tr.Singleton<PersonNameIndex>(); var p = persons.Items![id]; emails.Items!.Remove(p.Email!); persons.Items.Remove(id); tr.Commit(); } } public void Dispose() { _db.Dispose(); } } void Measure(string name, IMeasureOperations testImpl) { GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine($"Measure {name}"); var sw = new Stopwatch(); sw.Start(); Do("Insert", testImpl.Insert); Do("Update", testImpl.Update); Do("List ", testImpl.List); Do("Remove", testImpl.Remove); sw.Stop(); Console.WriteLine($"Total : {TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds)}"); Console.WriteLine(); } void Do(string operationName, Action action) { var sw = new Stopwatch(); sw.Start(); action(); sw.Stop(); Console.WriteLine($"{operationName}: {TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds)}"); } public void Run() { var cnt = 500000; using (var fc = new InMemoryFileCollection()) using (var db = CreateDb(fc)) { Measure("Relation: ", new RelationPersonTest(db, cnt)); } using (var fc = new InMemoryFileCollection()) using (var db = CreateDb(fc)) { Measure("2 Maps: ", new SingletonPersonTest(db, cnt)); } using (var fc = new InMemoryFileCollection()) using (var db = CreateBTreeDb(fc)) { Measure("Relation (BTree): ", new RelationPersonTest(db, cnt)); } using (var fc = new InMemoryFileCollection()) using (var db = CreateBTreeDb(fc)) { Measure("2 Maps (BTree): ", new SingletonPersonTest(db, cnt)); } using (var db = CreateInMemoryDb()) { Measure("Relation (mem): ", new RelationPersonTest(db, cnt)); } using (var db = CreateInMemoryDb()) { Measure("2 Maps (mem): ", new SingletonPersonTest(db, cnt)); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// Operations for managing Groups. /// </summary> internal partial class GroupsOperations : IServiceOperations<ApiManagementClient>, IGroupsOperations { /// <summary> /// Initializes a new instance of the GroupsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal GroupsOperations(ApiManagementClient client) { this._client = client; } private ApiManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.ApiManagement.ApiManagementClient. /// </summary> public ApiManagementClient Client { get { return this._client; } } /// <summary> /// Creates new group. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='gid'> /// Required. Identifier of the group. /// </param> /// <param name='parameters'> /// Required. Create parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateAsync(string resourceGroupName, string serviceName, string gid, GroupCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (gid == null) { throw new ArgumentNullException("gid"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.Name.Length > 300) { throw new ArgumentOutOfRangeException("parameters.Name"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("gid", gid); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/groups/"; url = url + Uri.EscapeDataString(gid); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject groupCreateParametersValue = new JObject(); requestDoc = groupCreateParametersValue; groupCreateParametersValue["name"] = parameters.Name; if (parameters.Description != null) { groupCreateParametersValue["description"] = parameters.Description; } if (parameters.Type != null) { groupCreateParametersValue["type"] = parameters.Type.Value.ToString(); } if (parameters.ExternalId != null) { groupCreateParametersValue["externalId"] = parameters.ExternalId; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Deletes specific group of the Api Management service instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='gid'> /// Required. Identifier of the group. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string gid, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (gid == null) { throw new ArgumentNullException("gid"); } if (etag == null) { throw new ArgumentNullException("etag"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("gid", gid); tracingParameters.Add("etag", etag); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/groups/"; url = url + Uri.EscapeDataString(gid); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", etag); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets specific group. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='gid'> /// Required. Identifier of the group. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Get Group operation response details. /// </returns> public async Task<GroupGetResponse> GetAsync(string resourceGroupName, string serviceName, string gid, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (gid == null) { throw new ArgumentNullException("gid"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("gid", gid); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/groups/"; url = url + Uri.EscapeDataString(gid); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GroupGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GroupGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { GroupContract valueInstance = new GroupContract(); result.Value = valueInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); valueInstance.IdPath = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); valueInstance.Name = nameInstance; } JToken descriptionValue = responseDoc["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); valueInstance.Description = descriptionInstance; } JToken builtInValue = responseDoc["builtIn"]; if (builtInValue != null && builtInValue.Type != JTokenType.Null) { bool builtInInstance = ((bool)builtInValue); valueInstance.System = builtInInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true)); valueInstance.Type = typeInstance; } JToken externalIdValue = responseDoc["externalId"]; if (externalIdValue != null && externalIdValue.Type != JTokenType.Null) { string externalIdInstance = ((string)externalIdValue); valueInstance.ExternalId = externalIdInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ETag")) { result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// List all groups. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='query'> /// Optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List Groups operation response details. /// </returns> public async Task<GroupListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("query", query); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/groups"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); List<string> odataFilter = new List<string>(); if (query != null && query.Filter != null) { odataFilter.Add(Uri.EscapeDataString(query.Filter)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (query != null && query.Top != null) { queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString())); } if (query != null && query.Skip != null) { queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString())); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GroupListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GroupListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { GroupPaged resultInstance = new GroupPaged(); result.Result = resultInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { GroupContract groupContractInstance = new GroupContract(); resultInstance.Values.Add(groupContractInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); groupContractInstance.IdPath = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); groupContractInstance.Name = nameInstance; } JToken descriptionValue = valueValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); groupContractInstance.Description = descriptionInstance; } JToken builtInValue = valueValue["builtIn"]; if (builtInValue != null && builtInValue.Type != JTokenType.Null) { bool builtInInstance = ((bool)builtInValue); groupContractInstance.System = builtInInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true)); groupContractInstance.Type = typeInstance; } JToken externalIdValue = valueValue["externalId"]; if (externalIdValue != null && externalIdValue.Type != JTokenType.Null) { string externalIdInstance = ((string)externalIdValue); groupContractInstance.ExternalId = externalIdInstance; } } } JToken countValue = responseDoc["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); resultInstance.TotalCount = countInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); resultInstance.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// List next groups page. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List Groups operation response details. /// </returns> public async Task<GroupListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GroupListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GroupListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { GroupPaged resultInstance = new GroupPaged(); result.Result = resultInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { GroupContract groupContractInstance = new GroupContract(); resultInstance.Values.Add(groupContractInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); groupContractInstance.IdPath = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); groupContractInstance.Name = nameInstance; } JToken descriptionValue = valueValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); groupContractInstance.Description = descriptionInstance; } JToken builtInValue = valueValue["builtIn"]; if (builtInValue != null && builtInValue.Type != JTokenType.Null) { bool builtInInstance = ((bool)builtInValue); groupContractInstance.System = builtInInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true)); groupContractInstance.Type = typeInstance; } JToken externalIdValue = valueValue["externalId"]; if (externalIdValue != null && externalIdValue.Type != JTokenType.Null) { string externalIdInstance = ((string)externalIdValue); groupContractInstance.ExternalId = externalIdInstance; } } } JToken countValue = responseDoc["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); resultInstance.TotalCount = countInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); resultInstance.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Patches specific group. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='gid'> /// Required. Identifier of the group. /// </param> /// <param name='parameters'> /// Required. Update parameters. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> UpdateAsync(string resourceGroupName, string serviceName, string gid, GroupUpdateParameters parameters, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (gid == null) { throw new ArgumentNullException("gid"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name != null && parameters.Name.Length > 300) { throw new ArgumentOutOfRangeException("parameters.Name"); } if (etag == null) { throw new ArgumentNullException("etag"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("gid", gid); tracingParameters.Add("parameters", parameters); tracingParameters.Add("etag", etag); TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/groups/"; url = url + Uri.EscapeDataString(gid); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", etag); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject groupUpdateParametersValue = new JObject(); requestDoc = groupUpdateParametersValue; if (parameters.Name != null) { groupUpdateParametersValue["name"] = parameters.Name; } if (parameters.Description != null) { groupUpdateParametersValue["description"] = parameters.Description; } if (parameters.Type != null) { groupUpdateParametersValue["type"] = parameters.Type.Value.ToString(); } if (parameters.ExternalId != null) { groupUpdateParametersValue["externalId"] = parameters.ExternalId; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Data.Entity.ModelConfiguration.Conventions; using Abp.Application.Editions; using Abp.Application.Features; using Abp.Auditing; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.BackgroundJobs; using Abp.Domain.Entities; using Abp.EntityFramework.Extensions; using Abp.MultiTenancy; using Abp.Notifications; namespace Abp.Zero.EntityFramework { /// <summary> /// Base DbContext for ABP zero. /// Derive your DbContext from this class to have base entities. /// </summary> public abstract class AbpZeroDbContext<TTenant, TRole, TUser> : AbpZeroCommonDbContext<TRole, TUser> where TTenant : AbpTenant<TUser> where TRole : AbpRole<TUser> where TUser : AbpUser<TUser> { /// <summary> /// Tenants /// </summary> public virtual IDbSet<TTenant> Tenants { get; set; } /// <summary> /// Editions. /// </summary> public virtual IDbSet<Edition> Editions { get; set; } /// <summary> /// FeatureSettings. /// </summary> public virtual IDbSet<FeatureSetting> FeatureSettings { get; set; } /// <summary> /// TenantFeatureSetting. /// </summary> public virtual IDbSet<TenantFeatureSetting> TenantFeatureSettings { get; set; } /// <summary> /// EditionFeatureSettings. /// </summary> public virtual IDbSet<EditionFeatureSetting> EditionFeatureSettings { get; set; } /// <summary> /// Background jobs. /// </summary> public virtual IDbSet<BackgroundJobInfo> BackgroundJobs { get; set; } /// <summary> /// User accounts /// </summary> public virtual IDbSet<UserAccount> UserAccounts { get; set; } protected AbpZeroDbContext() { } protected AbpZeroDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { } protected AbpZeroDbContext(DbCompiledModel model) : base(model) { } protected AbpZeroDbContext(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { } protected AbpZeroDbContext(string nameOrConnectionString, DbCompiledModel model) : base(nameOrConnectionString, model) { } protected AbpZeroDbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) { } protected AbpZeroDbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); #region BackgroundJobInfo.IX_IsAbandoned_NextTryTime modelBuilder.Entity<BackgroundJobInfo>() .Property(j => j.IsAbandoned) .CreateIndex("IX_IsAbandoned_NextTryTime", 1); modelBuilder.Entity<BackgroundJobInfo>() .Property(j => j.NextTryTime) .CreateIndex("IX_IsAbandoned_NextTryTime", 2); modelBuilder.Entity<BackgroundJobInfo>() .Property(j => j.Priority) .CreateIndex("IX_Priority_TryCount_NextTryTime", 1); modelBuilder.Entity<BackgroundJobInfo>() .Property(j => j.TryCount) .CreateIndex("IX_Priority_TryCount_NextTryTime", 2); modelBuilder.Entity<BackgroundJobInfo>() .Property(j => j.NextTryTime) .CreateIndex("IX_Priority_TryCount_NextTryTime", 3); #endregion #region NotificationSubscriptionInfo.IX_NotificationName_EntityTypeName_EntityId_UserId modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(ns => ns.NotificationName) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 1); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(ns => ns.EntityTypeName) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 2); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(ns => ns.EntityId) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 3); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(ns => ns.UserId) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 4); #endregion #region UserNotificationInfo.IX_UserId_State_CreationTime modelBuilder.Entity<UserNotificationInfo>() .Property(un => un.UserId) .CreateIndex("IX_UserId_State_CreationTime", 1); modelBuilder.Entity<UserNotificationInfo>() .Property(un => un.State) .CreateIndex("IX_UserId_State_CreationTime", 2); modelBuilder.Entity<UserNotificationInfo>() .Property(un => un.CreationTime) .CreateIndex("IX_UserId_State_CreationTime", 3); #endregion #region UserLoginAttempt.IX_TenancyName_UserNameOrEmailAddress_Result modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.TenancyName) .CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 1); modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.UserNameOrEmailAddress) .CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 2); modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.Result) .CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 3); #endregion #region UserLoginAttempt.IX_UserId_TenantId modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.UserId) .CreateIndex("IX_UserId_TenantId", 1); modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.TenantId) .CreateIndex("IX_UserId_TenantId", 2); #endregion #region AuditLog.Set_MaxLengths modelBuilder.Entity<AuditLog>() .Property(e => e.ServiceName) .HasMaxLength(AuditLog.MaxServiceNameLength); modelBuilder.Entity<AuditLog>() .Property(e => e.MethodName) .HasMaxLength(AuditLog.MaxMethodNameLength); modelBuilder.Entity<AuditLog>() .Property(e => e.Parameters) .HasMaxLength(AuditLog.MaxParametersLength); modelBuilder.Entity<AuditLog>() .Property(e => e.ClientIpAddress) .HasMaxLength(AuditLog.MaxClientIpAddressLength); modelBuilder.Entity<AuditLog>() .Property(e => e.ClientName) .HasMaxLength(AuditLog.MaxClientNameLength); modelBuilder.Entity<AuditLog>() .Property(e => e.BrowserInfo) .HasMaxLength(AuditLog.MaxBrowserInfoLength); modelBuilder.Entity<AuditLog>() .Property(e => e.ExceptionMessage) .HasMaxLength(AuditLog.MaxExceptionMessageLength); modelBuilder.Entity<AuditLog>() .Property(e => e.Exception) .HasMaxLength(AuditLog.MaxExceptionLength); modelBuilder.Entity<AuditLog>() .Property(e => e.CustomData) .HasMaxLength(AuditLog.MaxCustomDataLength); #endregion #region Common Indexes modelBuilder.Conventions.AddAfter<IndexAttributeConvention>(new IndexingPropertyConvention<ISoftDelete, bool>(m => m.IsDeleted)); modelBuilder.Conventions.AddAfter<IndexAttributeConvention>(new IndexingPropertyConvention<IMayHaveTenant, int?>(m => m.TenantId)); modelBuilder.Conventions.AddAfter<IndexAttributeConvention>(new IndexingPropertyConvention<IMustHaveTenant, int>(m => m.TenantId)); #endregion #region UserLogin.ProviderKey_TenantId modelBuilder.Entity<UserLogin>() .HasIndex(e => new {e.ProviderKey, e.TenantId}) .IsUnique(); #endregion } } }
// Copyright (c) 2021 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License using Alachisoft.NCache.Common.DataStructures; using System; using System.Collections; using System.Collections.Generic; namespace Alachisoft.NCache.Client { internal class WebCacheEnumerator<T> : IDictionaryEnumerator, IDisposable { private Cache _cache; private List<EnumerationDataChunk> _currentChunks; private IEnumerator<string> _currentChunkEnumerator; private object _currentValue; private string _serializationContext; private DictionaryEntry _de; internal WebCacheEnumerator(string serializationContext, Cache cache) { _cache = cache; _serializationContext = serializationContext; _de = new DictionaryEntry(); Initialize(); } public void Initialize() { List<EnumerationPointer> pointers = new List<EnumerationPointer>(); pointers.Add(new EnumerationPointer()); _currentChunks = _cache.GetNextChunk(pointers); List<string> data = new List<string>(); for (int i = 0; i < _currentChunks.Count; i++) { if (_currentChunks[i] != null && _currentChunks[i].Data != null) { data.AddRange(_currentChunks[i].Data); } } _currentChunkEnumerator = data.GetEnumerator(); } #region / --- IEnumerator --- / /// <summary> /// Set the enumerator to its initial position. which is before the first element in the collection /// </summary> public void Reset() { if (_currentChunks != null && _currentChunks.Count > 0) { for (int i = 0; i < _currentChunks.Count; i++) { _currentChunks[i].Pointer.Reset(); } } if (_currentChunkEnumerator != null) _currentChunkEnumerator.Reset(); } /// <summary> /// Advance the enumerator to the next element of the collection /// </summary> /// <returns></returns> public bool MoveNext() { bool result = false; if (_currentChunkEnumerator != null) { result = _currentChunkEnumerator.MoveNext(); if (!result) { if (_currentChunks != null && !IsLastChunk(_currentChunks)) { _currentChunks = _cache.GetNextChunk(GetPointerList(_currentChunks)); List<string> data = new List<string>(); for (int i = 0; i < _currentChunks.Count; i++) { if (_currentChunks[i] != null && _currentChunks[i].Data != null) { data.AddRange(_currentChunks[i].Data); } } if (data != null && data.Count > 0) { _currentChunkEnumerator = data.GetEnumerator(); result = _currentChunkEnumerator.MoveNext(); } } else if (_currentChunks != null && _currentChunks.Count > 0) { List<EnumerationPointer> pointers = GetPointerList(_currentChunks); if (pointers.Count > 0) _cache.GetNextChunk(pointers); //just an empty call to dispose enumerator for this particular list of pointer } } } return result; } private List<EnumerationPointer> GetPointerList(List<EnumerationDataChunk> chunks) { List<EnumerationPointer> pointers = new List<EnumerationPointer>(); for (int i = 0; i < chunks.Count; i++) { if (!chunks[i].IsLastChunk) pointers.Add(chunks[i].Pointer); } return pointers; } private bool IsLastChunk(List<EnumerationDataChunk> chunks) { for (int i = 0; i < chunks.Count; i++) { if (!chunks[i].IsLastChunk) { return false; } } return true; } /// <summary> /// Gets the current element in the collection /// </summary> public object Current { get { return Entry; } } #endregion #region / --- IDictionaryEnumerator --- / /// <summary> /// Gets the key and value of the current dictionary entry. /// </summary> public DictionaryEntry Entry { get { _de.Key = Key; _de.Value = Value; return _de; } } /// <summary> /// Gets the key of the current dictionary entry /// </summary> public object Key { get { object key = null; if (_currentChunkEnumerator != null) key = _currentChunkEnumerator.Current; return key; } } /// <summary> /// Gets the value of the current dictionary entry /// </summary> public object Value { get { try { return _cache.Get<T>(Key as string); } catch (Exception ex) { if (ex.Message.StartsWith("Connection with server lost")) { try { return _cache.Get<T>(Key as string); } catch (Exception inner) { throw inner; } } throw ex; } } } #endregion #region IDisposable Members public void Dispose() { if (_cache != null && _currentChunks != null) { List<EnumerationPointer> pointerlist = GetPointerList(_currentChunks); if (pointerlist.Count > 0) { _cache.GetNextChunk(pointerlist); //just an empty call to dispose enumerator for this particular pointer } } _cache = null; _serializationContext = null; } #endregion } }
using System; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; using NUnit.Framework; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Infrastructure.Persistence; using Umbraco.Cms.Tests.Common.Builders; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Scoping { [TestFixture] public class ScopeEventDispatcherTests { [SetUp] public void Setup() { // remove all handlers first DoThing1 = null; DoThing2 = null; DoThing3 = null; } [TestCase(false, true, true)] [TestCase(false, true, false)] [TestCase(false, false, true)] [TestCase(false, false, false)] [TestCase(true, true, true)] [TestCase(true, true, false)] [TestCase(true, false, true)] [TestCase(true, false, false)] public void EventsHandling(bool passive, bool cancel, bool complete) { var counter1 = 0; var counter2 = 0; DoThing1 += (sender, args) => { counter1++; if (cancel) args.Cancel = true; }; DoThing2 += (sender, args) => { counter2++; }; var scopeProvider = GetScopeProvider(NullLoggerFactory.Instance); using (var scope = scopeProvider.CreateScope(eventDispatcher: passive ? new PassiveEventDispatcher() : null)) { var cancelled = scope.Events.DispatchCancelable(DoThing1, this, new SaveEventArgs<string>("test")); if (cancelled == false) scope.Events.Dispatch(DoThing2, this, new SaveEventArgs<int>(0)); if (complete) scope.Complete(); } var expected1 = passive ? 0 : 1; Assert.AreEqual(expected1, counter1); int expected2; if (passive) expected2 = 0; else expected2 = cancel ? 0 : (complete ? 1 : 0); Assert.AreEqual(expected2, counter2); } private ScopeProvider GetScopeProvider(NullLoggerFactory instance) { var fileSystems = new FileSystems( instance, Mock.Of<IIOHelper>(), Options.Create(new GlobalSettings()), Mock.Of<IHostingEnvironment>()); var mediaFileManager = new MediaFileManager( Mock.Of<IFileSystem>(), Mock.Of<IMediaPathScheme>(), instance.CreateLogger<MediaFileManager>(), Mock.Of<IShortStringHelper>(), Mock.Of<IServiceProvider>(), Options.Create(new ContentSettings())); return new ScopeProvider( Mock.Of<IUmbracoDatabaseFactory>(), fileSystems, Options.Create(new CoreDebugSettings()), mediaFileManager, Mock.Of<ILogger<ScopeProvider>>(), instance, Mock.Of<IRequestCache>(), Mock.Of<IEventAggregator>() ); } [Test] public void QueueEvents() { DoThing1 += OnDoThingFail; DoThing2 += OnDoThingFail; DoThing3 += OnDoThingFail; var scopeProvider = GetScopeProvider(NullLoggerFactory.Instance); using (var scope = scopeProvider.CreateScope(eventDispatcher: new PassiveEventDispatcher())) { scope.Events.Dispatch(DoThing1, this, new SaveEventArgs<string>("test")); scope.Events.Dispatch(DoThing2, this, new SaveEventArgs<int>(0)); scope.Events.Dispatch(DoThing3, this, new SaveEventArgs<decimal>(0)); // events have been queued Assert.AreEqual(3, scope.Events.GetEvents(EventDefinitionFilter.All).Count()); var events = scope.Events.GetEvents(EventDefinitionFilter.All).ToArray(); var knownNames = new[] { "DoThing1", "DoThing2", "DoThing3" }; var knownArgTypes = new[] { typeof(SaveEventArgs<string>), typeof(SaveEventArgs<int>), typeof(SaveEventArgs<decimal>) }; for (var i = 0; i < events.Length; i++) { Assert.AreEqual(knownNames[i], events[i].EventName); Assert.AreEqual(knownArgTypes[i], events[i].Args.GetType()); } } } [Test] public void SupersededEvents() { DoSaveForContent += OnDoThingFail; DoDeleteForContent += OnDoThingFail; DoForTestArgs += OnDoThingFail; DoForTestArgs2 += OnDoThingFail; var contentType = ContentTypeBuilder.CreateBasicContentType(); var content1 = ContentBuilder.CreateBasicContent(contentType); content1.Id = 123; var content2 = ContentBuilder.CreateBasicContent(contentType); content2.Id = 456; var content3 = ContentBuilder.CreateBasicContent(contentType); content3.Id = 789; var scopeProvider = GetScopeProvider(NullLoggerFactory.Instance); using (var scope = scopeProvider.CreateScope(eventDispatcher: new PassiveEventDispatcher())) { //content1 will be filtered from the args scope.Events.Dispatch(DoSaveForContent, this, new SaveEventArgs<IContent>(new[] { content1, content3 })); scope.Events.Dispatch(DoDeleteForContent, this, new DeleteEventArgs<IContent>(content1), "DoDeleteForContent"); scope.Events.Dispatch(DoSaveForContent, this, new SaveEventArgs<IContent>(content2)); //this entire event will be filtered scope.Events.Dispatch(DoForTestArgs, this, new TestEventArgs(content1)); scope.Events.Dispatch(DoForTestArgs2, this, new TestEventArgs2(content1)); // events have been queued var events = scope.Events.GetEvents(EventDefinitionFilter.All).ToArray(); Assert.AreEqual(4, events.Length); Assert.AreEqual(typeof(SaveEventArgs<IContent>), events[0].Args.GetType()); Assert.AreEqual(1, ((SaveEventArgs<IContent>)events[0].Args).SavedEntities.Count()); Assert.AreEqual(content3.Id, ((SaveEventArgs<IContent>)events[0].Args).SavedEntities.First().Id); Assert.AreEqual(typeof(DeleteEventArgs<IContent>), events[1].Args.GetType()); Assert.AreEqual(content1.Id, ((DeleteEventArgs<IContent>)events[1].Args).DeletedEntities.First().Id); Assert.AreEqual(typeof(SaveEventArgs<IContent>), events[2].Args.GetType()); Assert.AreEqual(content2.Id, ((SaveEventArgs<IContent>)events[2].Args).SavedEntities.First().Id); Assert.AreEqual(typeof(TestEventArgs2), events[3].Args.GetType()); } } [Test] public void SupersededEvents2() { Test_Unpublished += OnDoThingFail; Test_Deleted += OnDoThingFail; var contentService = Mock.Of<IContentService>(); var content = Mock.Of<IContent>(); var scopeProvider = GetScopeProvider(NullLoggerFactory.Instance); using (var scope = scopeProvider.CreateScope(eventDispatcher: new PassiveEventDispatcher())) { scope.Events.Dispatch(Test_Unpublished, contentService, new PublishEventArgs<IContent>(new[] { content }), "Unpublished"); scope.Events.Dispatch(Test_Deleted, contentService, new DeleteEventArgs<IContent>(new[] { content }), "Deleted"); // see U4-10764 var events = scope.Events.GetEvents(EventDefinitionFilter.All).ToArray(); Assert.AreEqual(2, events.Length); } } /// <summary> /// This will test that when we track events that before we Get the events we normalize all of the /// event entities to be the latest one (most current) found amongst the event so that there is /// no 'stale' entities in any of the args /// </summary> [Test] public void LatestEntities() { DoSaveForContent += OnDoThingFail; var now = DateTime.Now; var contentType = ContentTypeBuilder.CreateBasicContentType(); var content1 = ContentBuilder.CreateBasicContent(contentType); content1.Id = 123; content1.UpdateDate = now.AddMinutes(1); var content2 = ContentBuilder.CreateBasicContent(contentType); content2.Id = 123; content2.UpdateDate = now.AddMinutes(2); var content3 = ContentBuilder.CreateBasicContent(contentType); content3.Id = 123; content3.UpdateDate = now.AddMinutes(3); var scopeProvider = GetScopeProvider(NullLoggerFactory.Instance); using (var scope = scopeProvider.CreateScope(eventDispatcher: new PassiveEventDispatcher())) { scope.Events.Dispatch(DoSaveForContent, this, new SaveEventArgs<IContent>(content1)); scope.Events.Dispatch(DoSaveForContent, this, new SaveEventArgs<IContent>(content2)); scope.Events.Dispatch(DoSaveForContent, this, new SaveEventArgs<IContent>(content3)); // events have been queued var events = scope.Events.GetEvents(EventDefinitionFilter.All).ToArray(); Assert.AreEqual(3, events.Length); foreach (var t in events) { var args = (SaveEventArgs<IContent>)t.Args; foreach (var entity in args.SavedEntities) { Assert.AreEqual(content3, entity); Assert.IsTrue(object.ReferenceEquals(content3, entity)); } } } } [Test] public void FirstIn() { DoSaveForContent += OnDoThingFail; var now = DateTime.Now; var contentType = ContentTypeBuilder.CreateBasicContentType(); var content1 = ContentBuilder.CreateBasicContent(contentType); content1.Id = 123; content1.UpdateDate = now.AddMinutes(1); var content2 = ContentBuilder.CreateBasicContent(contentType); content2.Id = 123; content1.UpdateDate = now.AddMinutes(2); var content3 = ContentBuilder.CreateBasicContent(contentType); content3.Id = 123; content1.UpdateDate = now.AddMinutes(3); var scopeProvider = GetScopeProvider(NullLoggerFactory.Instance); using (var scope = scopeProvider.CreateScope(eventDispatcher: new PassiveEventDispatcher())) { scope.Events.Dispatch(DoSaveForContent, this, new SaveEventArgs<IContent>(content1)); scope.Events.Dispatch(DoSaveForContent, this, new SaveEventArgs<IContent>(content2)); scope.Events.Dispatch(DoSaveForContent, this, new SaveEventArgs<IContent>(content3)); // events have been queued var events = scope.Events.GetEvents(EventDefinitionFilter.FirstIn).ToArray(); Assert.AreEqual(1, events.Length); Assert.AreEqual(content1, ((SaveEventArgs<IContent>)events[0].Args).SavedEntities.First()); Assert.IsTrue(object.ReferenceEquals(content1, ((SaveEventArgs<IContent>)events[0].Args).SavedEntities.First())); Assert.AreEqual(content1.UpdateDate, ((SaveEventArgs<IContent>)events[0].Args).SavedEntities.First().UpdateDate); } } [Test] public void LastIn() { DoSaveForContent += OnDoThingFail; var now = DateTime.Now; var contentType = ContentTypeBuilder.CreateBasicContentType(); var content1 = ContentBuilder.CreateBasicContent(contentType); content1.Id = 123; content1.UpdateDate = now.AddMinutes(1); var content2 = ContentBuilder.CreateBasicContent(contentType); content2.Id = 123; content2.UpdateDate = now.AddMinutes(2); var content3 = ContentBuilder.CreateBasicContent(contentType); content3.Id = 123; content3.UpdateDate = now.AddMinutes(3); var scopeProvider = GetScopeProvider(NullLoggerFactory.Instance); using (var scope = scopeProvider.CreateScope(eventDispatcher: new PassiveEventDispatcher())) { scope.Events.Dispatch(DoSaveForContent, this, new SaveEventArgs<IContent>(content1)); scope.Events.Dispatch(DoSaveForContent, this, new SaveEventArgs<IContent>(content2)); scope.Events.Dispatch(DoSaveForContent, this, new SaveEventArgs<IContent>(content3)); // events have been queued var events = scope.Events.GetEvents(EventDefinitionFilter.LastIn).ToArray(); Assert.AreEqual(1, events.Length); Assert.AreEqual(content3, ((SaveEventArgs<IContent>)events[0].Args).SavedEntities.First()); Assert.IsTrue(object.ReferenceEquals(content3, ((SaveEventArgs<IContent>)events[0].Args).SavedEntities.First())); Assert.AreEqual(content3.UpdateDate, ((SaveEventArgs<IContent>)events[0].Args).SavedEntities.First().UpdateDate); } } [TestCase(true)] [TestCase(false)] public void EventsDispatching_Passive(bool complete) { DoThing1 += OnDoThingFail; DoThing2 += OnDoThingFail; DoThing3 += OnDoThingFail; var scopeProvider = GetScopeProvider(NullLoggerFactory.Instance); using (var scope = scopeProvider.CreateScope(eventDispatcher: new PassiveEventDispatcher())) { scope.Events.Dispatch(DoThing1, this, new SaveEventArgs<string>("test")); scope.Events.Dispatch(DoThing2, this, new SaveEventArgs<int>(0)); scope.Events.Dispatch(DoThing3, this, new SaveEventArgs<decimal>(0)); // events have been queued Assert.AreEqual(3, scope.Events.GetEvents(EventDefinitionFilter.All).Count()); if (complete) scope.Complete(); } // no event has been raised (else OnDoThingFail would have failed) } [TestCase(true)] [TestCase(false)] public void EventsDispatching_Scope(bool complete) { var counter = 0; IScope ambientScope = null; IScopeContext ambientContext = null; Guid value = Guid.Empty; var scopeProvider = GetScopeProvider(NullLoggerFactory.Instance) as ScopeProvider; DoThing1 += (sender, args) => { counter++; }; DoThing2 += (sender, args) => { counter++; }; DoThing3 += (sender, args) => { ambientScope = scopeProvider.AmbientScope; ambientContext = scopeProvider.AmbientContext; value = scopeProvider.Context.Enlist("value", Guid.NewGuid, (c, o) => { }); counter++; }; Guid guid; using (var scope = scopeProvider.CreateScope()) { Assert.IsNotNull(scopeProvider.AmbientContext); guid = scopeProvider.Context.Enlist("value", Guid.NewGuid, (c, o) => { }); scope.Events.Dispatch(DoThing1, this, new SaveEventArgs<string>("test")); scope.Events.Dispatch(DoThing2, this, new SaveEventArgs<int>(0)); scope.Events.Dispatch(DoThing3, this, new SaveEventArgs<decimal>(0)); // events have been queued Assert.AreEqual(3, scope.Events.GetEvents(EventDefinitionFilter.All).Count()); Assert.AreEqual(0, counter); if (complete) scope.Complete(); } if (complete) { // events have been raised Assert.AreEqual(3, counter); Assert.IsNull(ambientScope); // scope was gone Assert.IsNotNull(ambientContext); // but not context Assert.AreEqual(guid, value); // so we got the same value! } else { // else, no event has been raised Assert.AreEqual(0, counter); } // everything's gone Assert.IsNull(scopeProvider.AmbientScope); Assert.IsNull(scopeProvider.AmbientContext); } private static void OnDoThingFail(object sender, EventArgs eventArgs) { Assert.Fail(); } public static event EventHandler<SaveEventArgs<IContent>> DoSaveForContent; public static event EventHandler<DeleteEventArgs<IContent>> DoDeleteForContent; public static event EventHandler<TestEventArgs> DoForTestArgs; public static event EventHandler<TestEventArgs2> DoForTestArgs2; public static event EventHandler<SaveEventArgs<string>> DoThing1; public static event EventHandler<SaveEventArgs<int>> DoThing2; public static event TypedEventHandler<ScopeEventDispatcherTests, SaveEventArgs<decimal>> DoThing3; public static event TypedEventHandler<IContentService, PublishEventArgs<IContent>> Test_Unpublished; public static event TypedEventHandler<IContentService, DeleteEventArgs<IContent>> Test_Deleted; public class TestEventArgs : CancellableObjectEventArgs { public TestEventArgs(object eventObject) : base(eventObject) { } public object MyEventObject { get { return EventObject; } } } [SupersedeEvent(typeof(TestEventArgs))] public class TestEventArgs2 : CancellableObjectEventArgs { public TestEventArgs2(object eventObject) : base(eventObject) { } public object MyEventObject { get { return EventObject; } } } public class PassiveEventDispatcher : QueuingEventDispatcherBase { public PassiveEventDispatcher() : base(false) { } protected override void ScopeExitCompleted() { // do nothing } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using Microsoft.WindowsAzure; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// A virtual machine image associated with your subscription. /// </summary> public partial class VirtualMachineOSImageGetResponse : OperationResponse { private string _affinityGroup; /// <summary> /// Optional. The affinity in which the media is located. The /// AffinityGroup value is derived from storage account that contains /// the blob in which the media is located. If the storage account /// does not belong to an affinity group the value is NULL and the /// element is not displayed in the response. This value is NULL for /// platform images. /// </summary> public string AffinityGroup { get { return this._affinityGroup; } set { this._affinityGroup = value; } } private string _category; /// <summary> /// Optional. The repository classification of the image. All user /// images have the category User. /// </summary> public string Category { get { return this._category; } set { this._category = value; } } private string _description; /// <summary> /// Optional. Specifies the description of the image. /// </summary> public string Description { get { return this._description; } set { this._description = value; } } private string _eula; /// <summary> /// Optional. Specifies the End User License Agreement that is /// associated with the image. The value for this element is a string, /// but it is recommended that the value be a URL that points to a /// EULA. /// </summary> public string Eula { get { return this._eula; } set { this._eula = value; } } private Uri _iconUri; /// <summary> /// Optional. Provides the URI to the icon for this Operating System /// Image. /// </summary> public Uri IconUri { get { return this._iconUri; } set { this._iconUri = value; } } private string _imageFamily; /// <summary> /// Optional. Specifies a value that can be used to group images. /// </summary> public string ImageFamily { get { return this._imageFamily; } set { this._imageFamily = value; } } private string _iOType; /// <summary> /// Optional. Gets or sets the IO type. /// </summary> public string IOType { get { return this._iOType; } set { this._iOType = value; } } private bool? _isPremium; /// <summary> /// Optional. Indicates whether the image contains software or /// associated services that will incur charges above the core price /// for the virtual machine. For additional details, see the /// PricingDetailLink element. /// </summary> public bool? IsPremium { get { return this._isPremium; } set { this._isPremium = value; } } private string _label; /// <summary> /// Optional. An identifier for the image. /// </summary> public string Label { get { return this._label; } set { this._label = value; } } private string _language; /// <summary> /// Optional. Specifies the language of the image. The Language element /// is only available using version 2013-03-01 or higher. /// </summary> public string Language { get { return this._language; } set { this._language = value; } } private string _location; /// <summary> /// Optional. The geo-location in which this media is located. The /// Location value is derived from storage account that contains the /// blob in which the media is located. If the storage account belongs /// to an affinity group the value is NULL. If the version is set to /// 2012-08-01 or later, the locations are returned for platform /// images; otherwise, this value is NULL for platform images. /// </summary> public string Location { get { return this._location; } set { this._location = value; } } private double _logicalSizeInGB; /// <summary> /// Optional. The size, in GB, of the image. /// </summary> public double LogicalSizeInGB { get { return this._logicalSizeInGB; } set { this._logicalSizeInGB = value; } } private Uri _mediaLinkUri; /// <summary> /// Optional. The location of the blob in Azure storage. The blob /// location belongs to a storage account in the subscription /// specified by the SubscriptionId value in the operation call. /// Example: http://example.blob.core.windows.net/disks/myimage.vhd. /// </summary> public Uri MediaLinkUri { get { return this._mediaLinkUri; } set { this._mediaLinkUri = value; } } private string _name; /// <summary> /// Optional. The name of the operating system image. This is the name /// that is used when creating one or more virtual machines using the /// image. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _operatingSystemType; /// <summary> /// Optional. The operating system type of the OS image. Possible /// values are: Linux or Windows. /// </summary> public string OperatingSystemType { get { return this._operatingSystemType; } set { this._operatingSystemType = value; } } private Uri _privacyUri; /// <summary> /// Optional. Specifies the URI that points to a document that contains /// the privacy policy related to the image. /// </summary> public Uri PrivacyUri { get { return this._privacyUri; } set { this._privacyUri = value; } } private DateTime _publishedDate; /// <summary> /// Optional. Specifies the date when the image was added to the image /// repository. /// </summary> public DateTime PublishedDate { get { return this._publishedDate; } set { this._publishedDate = value; } } private string _publisherName; /// <summary> /// Optional. The name of the publisher of this OS Image in Azure. /// </summary> public string PublisherName { get { return this._publisherName; } set { this._publisherName = value; } } private string _recommendedVMSize; /// <summary> /// Optional. Specifies the size to use for the virtual machine that is /// created from the OS image. /// </summary> public string RecommendedVMSize { get { return this._recommendedVMSize; } set { this._recommendedVMSize = value; } } private bool? _showInGui; /// <summary> /// Optional. Indicates whether the image should be shown in the Azure /// portal. /// </summary> public bool? ShowInGui { get { return this._showInGui; } set { this._showInGui = value; } } private Uri _smallIconUri; /// <summary> /// Optional. Specifies the URI to the small icon that is displayed /// when the image is presented in the Azure Management Portal. The /// SmallIconUri element is only available using version 2013-03-01 or /// higher. /// </summary> public Uri SmallIconUri { get { return this._smallIconUri; } set { this._smallIconUri = value; } } /// <summary> /// Initializes a new instance of the VirtualMachineOSImageGetResponse /// class. /// </summary> public VirtualMachineOSImageGetResponse() { } } }
// 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.Drawing.Internal; using System.Runtime.InteropServices; namespace System.Drawing.Printing { /// <summary> /// Specifies settings that apply to a single page. /// </summary> public partial class PageSettings : ICloneable { internal PrinterSettings printerSettings; private TriState _color = TriState.Default; private PaperSize _paperSize; private PaperSource _paperSource; private PrinterResolution _printerResolution; private TriState _landscape = TriState.Default; private Margins _margins = new Margins(); /// <summary> /// Initializes a new instance of the <see cref='PageSettings'/> class using the default printer. /// </summary> public PageSettings() : this(new PrinterSettings()) { } /// <summary> /// Initializes a new instance of the <see cref='PageSettings'/> class using the specified printer. /// </summary> public PageSettings(PrinterSettings printerSettings) { Debug.Assert(printerSettings != null, "printerSettings == null"); this.printerSettings = printerSettings; } /// <summary> /// Gets the bounds of the page, taking into account the Landscape property. /// </summary> public Rectangle Bounds { get { IntPtr modeHandle = printerSettings.GetHdevmode(); Rectangle pageBounds = GetBounds(modeHandle); SafeNativeMethods.GlobalFree(new HandleRef(this, modeHandle)); return pageBounds; } } /// <summary> /// Gets or sets a value indicating whether the page is printed in color. /// </summary> public bool Color { get { if (_color.IsDefault) return printerSettings.GetModeField(ModeField.Color, SafeNativeMethods.DMCOLOR_MONOCHROME) == SafeNativeMethods.DMCOLOR_COLOR; else return (bool)_color; } set { _color = value; } } /// <summary> /// Returns the x dimension of the hard margin /// </summary> public float HardMarginX { get { float hardMarginX = 0; DeviceContext dc = printerSettings.CreateDeviceContext(this); try { int dpiX = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), SafeNativeMethods.LOGPIXELSX); int hardMarginX_DU = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), SafeNativeMethods.PHYSICALOFFSETX); hardMarginX = hardMarginX_DU * 100 / dpiX; } finally { dc.Dispose(); } return hardMarginX; } } /// <summary> /// Returns the y dimension of the hard margin. /// </summary> public float HardMarginY { get { float hardMarginY = 0; DeviceContext dc = printerSettings.CreateDeviceContext(this); try { int dpiY = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), SafeNativeMethods.LOGPIXELSY); int hardMarginY_DU = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(dc, dc.Hdc), SafeNativeMethods.PHYSICALOFFSETY); hardMarginY = hardMarginY_DU * 100 / dpiY; } finally { dc.Dispose(); } return hardMarginY; } } /// <summary> /// Gets or sets a value indicating whether the page should be printed in landscape or portrait orientation. /// </summary> public bool Landscape { get { if (_landscape.IsDefault) return printerSettings.GetModeField(ModeField.Orientation, SafeNativeMethods.DMORIENT_PORTRAIT) == SafeNativeMethods.DMORIENT_LANDSCAPE; else return (bool)_landscape; } set { _landscape = value; } } /// <summary> /// Gets or sets a value indicating the margins for this page. /// </summary> public Margins Margins { get { return _margins; } set { _margins = value; } } /// <summary> /// Gets or sets the paper size. /// </summary> public PaperSize PaperSize { get { return GetPaperSize(IntPtr.Zero); } set { _paperSize = value; } } /// <summary> /// Gets or sets a value indicating the paper source (i.e. upper bin). /// </summary> public PaperSource PaperSource { get { if (_paperSource == null) { IntPtr modeHandle = printerSettings.GetHdevmode(); IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle)); SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE)); PaperSource result = PaperSourceFromMode(mode); SafeNativeMethods.GlobalUnlock(new HandleRef(this, modeHandle)); SafeNativeMethods.GlobalFree(new HandleRef(this, modeHandle)); return result; } else return _paperSource; } set { _paperSource = value; } } /// <summary> /// Gets the PrintableArea for the printer. Units = 100ths of an inch. /// </summary> public RectangleF PrintableArea { get { RectangleF printableArea = new RectangleF(); DeviceContext dc = printerSettings.CreateInformationContext(this); HandleRef hdc = new HandleRef(dc, dc.Hdc); try { int dpiX = UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.LOGPIXELSX); int dpiY = UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.LOGPIXELSY); if (!Landscape) { // // Need to convert the printable area to 100th of an inch from the device units printableArea.X = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.PHYSICALOFFSETX) * 100 / dpiX; printableArea.Y = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.PHYSICALOFFSETY) * 100 / dpiY; printableArea.Width = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.HORZRES) * 100 / dpiX; printableArea.Height = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.VERTRES) * 100 / dpiY; } else { // // Need to convert the printable area to 100th of an inch from the device units printableArea.Y = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.PHYSICALOFFSETX) * 100 / dpiX; printableArea.X = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.PHYSICALOFFSETY) * 100 / dpiY; printableArea.Height = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.HORZRES) * 100 / dpiX; printableArea.Width = (float)UnsafeNativeMethods.GetDeviceCaps(hdc, SafeNativeMethods.VERTRES) * 100 / dpiY; } } finally { dc.Dispose(); } return printableArea; } } /// <summary> /// Gets or sets the printer resolution for the page. /// </summary> public PrinterResolution PrinterResolution { get { if (_printerResolution == null) { IntPtr modeHandle = printerSettings.GetHdevmode(); IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle)); SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE)); PrinterResolution result = PrinterResolutionFromMode(mode); SafeNativeMethods.GlobalUnlock(new HandleRef(this, modeHandle)); SafeNativeMethods.GlobalFree(new HandleRef(this, modeHandle)); return result; } else return _printerResolution; } set { _printerResolution = value; } } /// <summary> /// Gets or sets the associated printer settings. /// </summary> public PrinterSettings PrinterSettings { get { return printerSettings; } set { if (value == null) value = new PrinterSettings(); printerSettings = value; } } /// <summary> /// Copies the settings and margins. /// </summary> public object Clone() { PageSettings result = (PageSettings)MemberwiseClone(); result._margins = (Margins)_margins.Clone(); return result; } /// <summary> /// Copies the relevant information out of the PageSettings and into the handle. /// </summary> public void CopyToHdevmode(IntPtr hdevmode) { IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(null, hdevmode)); SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE)); if (_color.IsNotDefault && ((mode.dmFields & SafeNativeMethods.DM_COLOR) == SafeNativeMethods.DM_COLOR)) mode.dmColor = unchecked((short)(((bool)_color) ? SafeNativeMethods.DMCOLOR_COLOR : SafeNativeMethods.DMCOLOR_MONOCHROME)); if (_landscape.IsNotDefault && ((mode.dmFields & SafeNativeMethods.DM_ORIENTATION) == SafeNativeMethods.DM_ORIENTATION)) mode.dmOrientation = unchecked((short)(((bool)_landscape) ? SafeNativeMethods.DMORIENT_LANDSCAPE : SafeNativeMethods.DMORIENT_PORTRAIT)); if (_paperSize != null) { if ((mode.dmFields & SafeNativeMethods.DM_PAPERSIZE) == SafeNativeMethods.DM_PAPERSIZE) { mode.dmPaperSize = unchecked((short)_paperSize.RawKind); } bool setWidth = false; bool setLength = false; if ((mode.dmFields & SafeNativeMethods.DM_PAPERLENGTH) == SafeNativeMethods.DM_PAPERLENGTH) { // dmPaperLength is always in tenths of millimeter but paperSizes are in hundredth of inch .. // so we need to convert :: use PrinterUnitConvert.Convert(value, PrinterUnit.TenthsOfAMillimeter /*fromUnit*/, PrinterUnit.Display /*ToUnit*/) int length = PrinterUnitConvert.Convert(_paperSize.Height, PrinterUnit.Display, PrinterUnit.TenthsOfAMillimeter); mode.dmPaperLength = unchecked((short)length); setLength = true; } if ((mode.dmFields & SafeNativeMethods.DM_PAPERWIDTH) == SafeNativeMethods.DM_PAPERWIDTH) { int width = PrinterUnitConvert.Convert(_paperSize.Width, PrinterUnit.Display, PrinterUnit.TenthsOfAMillimeter); mode.dmPaperWidth = unchecked((short)width); setWidth = true; } if (_paperSize.Kind == PaperKind.Custom) { if (!setLength) { mode.dmFields |= SafeNativeMethods.DM_PAPERLENGTH; int length = PrinterUnitConvert.Convert(_paperSize.Height, PrinterUnit.Display, PrinterUnit.TenthsOfAMillimeter); mode.dmPaperLength = unchecked((short)length); } if (!setWidth) { mode.dmFields |= SafeNativeMethods.DM_PAPERWIDTH; int width = PrinterUnitConvert.Convert(_paperSize.Width, PrinterUnit.Display, PrinterUnit.TenthsOfAMillimeter); mode.dmPaperWidth = unchecked((short)width); } } } if (_paperSource != null && ((mode.dmFields & SafeNativeMethods.DM_DEFAULTSOURCE) == SafeNativeMethods.DM_DEFAULTSOURCE)) { mode.dmDefaultSource = unchecked((short)_paperSource.RawKind); } if (_printerResolution != null) { if (_printerResolution.Kind == PrinterResolutionKind.Custom) { if ((mode.dmFields & SafeNativeMethods.DM_PRINTQUALITY) == SafeNativeMethods.DM_PRINTQUALITY) { mode.dmPrintQuality = unchecked((short)_printerResolution.X); } if ((mode.dmFields & SafeNativeMethods.DM_YRESOLUTION) == SafeNativeMethods.DM_YRESOLUTION) { mode.dmYResolution = unchecked((short)_printerResolution.Y); } } else { if ((mode.dmFields & SafeNativeMethods.DM_PRINTQUALITY) == SafeNativeMethods.DM_PRINTQUALITY) { mode.dmPrintQuality = unchecked((short)_printerResolution.Kind); } } } Marshal.StructureToPtr(mode, modePointer, false); // It's possible this page has a DEVMODE for a different printer than the DEVMODE passed in here // (Ex: occurs when Doc.DefaultPageSettings.PrinterSettings.PrinterName != Doc.PrinterSettings.PrinterName) // // if the passed in devmode has fewer bytes than our buffer for the extrainfo, we want to skip the merge as it will cause // a buffer overrun if (mode.dmDriverExtra >= ExtraBytes) { int retCode = SafeNativeMethods.DocumentProperties(NativeMethods.NullHandleRef, NativeMethods.NullHandleRef, printerSettings.PrinterName, modePointer, modePointer, SafeNativeMethods.DM_IN_BUFFER | SafeNativeMethods.DM_OUT_BUFFER); if (retCode < 0) { SafeNativeMethods.GlobalFree(new HandleRef(null, modePointer)); } } SafeNativeMethods.GlobalUnlock(new HandleRef(null, hdevmode)); } private short ExtraBytes { get { IntPtr modeHandle = printerSettings.GetHdevmodeInternal(); IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle)); SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE)); short result = mode?.dmDriverExtra ?? 0; SafeNativeMethods.GlobalUnlock(new HandleRef(this, modeHandle)); SafeNativeMethods.GlobalFree(new HandleRef(this, modeHandle)); return result; } } // This function shows up big on profiles, so we need to make it fast internal Rectangle GetBounds(IntPtr modeHandle) { Rectangle pageBounds; PaperSize size = GetPaperSize(modeHandle); if (GetLandscape(modeHandle)) pageBounds = new Rectangle(0, 0, size.Height, size.Width); else pageBounds = new Rectangle(0, 0, size.Width, size.Height); return pageBounds; } private bool GetLandscape(IntPtr modeHandle) { if (_landscape.IsDefault) return printerSettings.GetModeField(ModeField.Orientation, SafeNativeMethods.DMORIENT_PORTRAIT, modeHandle) == SafeNativeMethods.DMORIENT_LANDSCAPE; else return (bool)_landscape; } private PaperSize GetPaperSize(IntPtr modeHandle) { if (_paperSize == null) { bool ownHandle = false; if (modeHandle == IntPtr.Zero) { modeHandle = printerSettings.GetHdevmode(); ownHandle = true; } IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(null, modeHandle)); SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE)); PaperSize result = PaperSizeFromMode(mode); SafeNativeMethods.GlobalUnlock(new HandleRef(null, modeHandle)); if (ownHandle) SafeNativeMethods.GlobalFree(new HandleRef(null, modeHandle)); return result; } else return _paperSize; } private PaperSize PaperSizeFromMode(SafeNativeMethods.DEVMODE mode) { PaperSize[] sizes = printerSettings.Get_PaperSizes(); if ((mode.dmFields & SafeNativeMethods.DM_PAPERSIZE) == SafeNativeMethods.DM_PAPERSIZE) { for (int i = 0; i < sizes.Length; i++) { if ((int)sizes[i].RawKind == mode.dmPaperSize) return sizes[i]; } } return new PaperSize(PaperKind.Custom, "custom", //mode.dmPaperWidth, mode.dmPaperLength); PrinterUnitConvert.Convert(mode.dmPaperWidth, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display), PrinterUnitConvert.Convert(mode.dmPaperLength, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display)); } private PaperSource PaperSourceFromMode(SafeNativeMethods.DEVMODE mode) { PaperSource[] sources = printerSettings.Get_PaperSources(); if ((mode.dmFields & SafeNativeMethods.DM_DEFAULTSOURCE) == SafeNativeMethods.DM_DEFAULTSOURCE) { for (int i = 0; i < sources.Length; i++) { // the dmDefaultSource == to the RawKind in the Papersource.. and Not the Kind... // if the PaperSource is populated with CUSTOM values... if (unchecked((short)sources[i].RawKind) == mode.dmDefaultSource) { return sources[i]; } } } return new PaperSource((PaperSourceKind)mode.dmDefaultSource, "unknown"); } private PrinterResolution PrinterResolutionFromMode(SafeNativeMethods.DEVMODE mode) { PrinterResolution[] resolutions = printerSettings.Get_PrinterResolutions(); for (int i = 0; i < resolutions.Length; i++) { if (mode.dmPrintQuality >= 0 && ((mode.dmFields & SafeNativeMethods.DM_PRINTQUALITY) == SafeNativeMethods.DM_PRINTQUALITY) && ((mode.dmFields & SafeNativeMethods.DM_YRESOLUTION) == SafeNativeMethods.DM_YRESOLUTION)) { if (resolutions[i].X == unchecked((int)(PrinterResolutionKind)mode.dmPrintQuality) && resolutions[i].Y == unchecked((int)(PrinterResolutionKind)mode.dmYResolution)) return resolutions[i]; } else { if ((mode.dmFields & SafeNativeMethods.DM_PRINTQUALITY) == SafeNativeMethods.DM_PRINTQUALITY) { if (resolutions[i].Kind == (PrinterResolutionKind)mode.dmPrintQuality) return resolutions[i]; } } } return new PrinterResolution(PrinterResolutionKind.Custom, mode.dmPrintQuality, mode.dmYResolution); } /// <summary> /// Copies the relevant information out of the handle and into the PageSettings. /// </summary> public void SetHdevmode(IntPtr hdevmode) { if (hdevmode == IntPtr.Zero) throw new ArgumentException(SR.Format(SR.InvalidPrinterHandle, hdevmode)); IntPtr pointer = SafeNativeMethods.GlobalLock(new HandleRef(null, hdevmode)); SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(pointer, typeof(SafeNativeMethods.DEVMODE)); if ((mode.dmFields & SafeNativeMethods.DM_COLOR) == SafeNativeMethods.DM_COLOR) { _color = (mode.dmColor == SafeNativeMethods.DMCOLOR_COLOR); } if ((mode.dmFields & SafeNativeMethods.DM_ORIENTATION) == SafeNativeMethods.DM_ORIENTATION) { _landscape = (mode.dmOrientation == SafeNativeMethods.DMORIENT_LANDSCAPE); } _paperSize = PaperSizeFromMode(mode); _paperSource = PaperSourceFromMode(mode); _printerResolution = PrinterResolutionFromMode(mode); SafeNativeMethods.GlobalUnlock(new HandleRef(null, hdevmode)); } /// <summary> /// Provides some interesting information about the PageSettings in String form. /// </summary> public override string ToString() { return "[PageSettings:" + " Color=" + Color.ToString() + ", Landscape=" + Landscape.ToString() + ", Margins=" + Margins.ToString() + ", PaperSize=" + PaperSize.ToString() + ", PaperSource=" + PaperSource.ToString() + ", PrinterResolution=" + PrinterResolution.ToString() + "]"; } } }
using System; using System.Collections.Generic; using System.Collections; using System.IO; namespace CardGenerator { public class CardOutput { public CardOutput () { } public enum eCARDORDERTYPE { eCARDORDERVOCAB, eCARDORDERTYPES, eCARDORDERRANDOM, }; public static void saveToKLEIOFile(String fileName) { StreamWriter fileout = new StreamWriter(fileName); fileout.Write(textFromKLEIOOutput ()); fileout.Close (); } public static String textFromKLEIOOutput () { StringWriter fileout = new StringWriter(); List<Dictionary<String, String>> outputTable = CardGeneratorDB.Instance.getDataFromTable(CardGeneratorDB.TABLECardOutput); foreach (Dictionary<String, String> outputEntry in outputTable) { String CardDataID = outputEntry[CardGeneratorDB.COLUMNCardDataID]; String CardDefinitionID = outputEntry[CardGeneratorDB.COLUMNCardDefinitionID]; // ("+COLUMNCardOutputID+" INTEGER NOT NULL, "+COLUMNCardDefinitionID+" INTEGER, "+COLUMNCardDataID+" INTEGER)", Dictionary<String, String> cardDefinition = CardGeneratorDB.Instance.getRowFromTable(CardGeneratorDB.TABLECardDefinitions, CardGeneratorDB.COLUMNCardDefinitionID, CardDefinitionID); Dictionary<String, String> cardData = CardGeneratorDB.Instance.getRowFromTable(CardGeneratorDB.TABLECardData, CardGeneratorDB.COLUMNCardDataID, CardDataID); StringWriter faceOutput = new StringWriter(); int iFace = 1; bool bFirstFaceRun = true; bool bContinue = true; while (bContinue) { String faceColumn = "Face"+(iFace++); if (cardDefinition.ContainsKey(faceColumn)) { if (!bFirstFaceRun) { faceOutput.Write(","); } else { bFirstFaceRun = false; } String faceDefinition = cardDefinition[faceColumn]; List<CardDefinitions.CardDefClass> faceLanguages = CardDefinitions.faceCardStructureFromJSONString(faceDefinition); bool bFirstRun = true; // first entry in a face foreach (CardDefinitions.CardDefClass item in faceLanguages) { if (item.TYPE == false) { if (!bFirstRun) { faceOutput.Write(" - "); } else { bFirstRun = false; } if (item.TYPE == false) { faceOutput.Write(cardData[item.COLUMNSOURCE]); } else { // a sound, get the sound instead //String filename = AudioFiles.generateFilename(item.LANGUAGECODE, cardData[item.COLUMNSOURCE]); //faceOutput.Write("[sound:" + filename + "]"); } } } } else { bContinue = false; } } String outLn = faceOutput.ToString(); fileout.WriteLine(outLn); // ok, now build the faces from each // get faces data // DE-JSON into class data // build string for each JSON context } fileout.Close(); return fileout.ToString(); } public static void saveToAnkiFile(String fileName) { StreamWriter fileout = new StreamWriter(fileName); List<Dictionary<String, String>> outputTable = CardGeneratorDB.Instance.getDataFromTable(CardGeneratorDB.TABLECardOutput); foreach (Dictionary<String, String> outputEntry in outputTable) { String CardDataID = outputEntry[CardGeneratorDB.COLUMNCardDataID]; String CardDefinitionID = outputEntry[CardGeneratorDB.COLUMNCardDefinitionID]; // ("+COLUMNCardOutputID+" INTEGER NOT NULL, "+COLUMNCardDefinitionID+" INTEGER, "+COLUMNCardDataID+" INTEGER)", Dictionary<String, String> cardDefinition = CardGeneratorDB.Instance.getRowFromTable(CardGeneratorDB.TABLECardDefinitions, CardGeneratorDB.COLUMNCardDefinitionID, CardDefinitionID); Dictionary<String, String> cardData = CardGeneratorDB.Instance.getRowFromTable(CardGeneratorDB.TABLECardData, CardGeneratorDB.COLUMNCardDataID, CardDataID); StringWriter faceOutput = new StringWriter(); int iFace = 1; bool bFirstFaceRun = true; bool bContinue = true; while (bContinue) { String faceColumn = "Face"+(iFace++); if (cardDefinition.ContainsKey(faceColumn)) { if (!bFirstFaceRun) { faceOutput.Write(";"); } else { bFirstFaceRun = false; } String faceDefinition = cardDefinition[faceColumn]; List<CardDefinitions.CardDefClass> faceLanguages = CardDefinitions.faceCardStructureFromJSONString(faceDefinition); bool bFirstRun = true; // first entry in a face foreach (CardDefinitions.CardDefClass item in faceLanguages) { if (!bFirstRun) { faceOutput.Write("<BR>"); } else { bFirstRun = false; } if (item.TYPE == false) { faceOutput.Write(cardData[item.COLUMNSOURCE]); } else { // a sound, get the sound instead String filename = AudioFiles.generateFilename(item.LANGUAGECODE, cardData[item.COLUMNSOURCE]); faceOutput.Write("[sound:" + filename + "]"); } } } else { bContinue = false; } } String outLn = faceOutput.ToString(); fileout.WriteLine(outLn); // ok, now build the faces from each // get faces data // DE-JSON into class data // build string for each JSON context } fileout.Close(); } public static void BuildCardOutputTable(List<String> cardTypeNames, eCARDORDERTYPE order) { // build every permutation of carddata and carddefinitions justnow. // use the permutations to build the face card data later CardGeneratorDB.Instance.removeDataFromTable(CardGeneratorDB.TABLECardOutput); List<String> cardDataIDs = CardGeneratorDB.Instance.getSingleColumnDataFromTable(CardGeneratorDB.TABLECardData, CardGeneratorDB.COLUMNCardDataID); List<String> cardDefinitionIDs = new List<String>(); { List<Dictionary<String, String>> cardDefinitions = CardGeneratorDB.Instance.getDataFromTable(CardGeneratorDB.TABLECardDefinitions); foreach(Dictionary<String, String> item in cardDefinitions) { if (cardTypeNames.Contains(item[CardGeneratorDB.COLUMNCardDefinitionName])) { cardDefinitionIDs.Add(item[CardGeneratorDB.COLUMNCardDefinitionID]); } } //List<String> cardDefinitionIDs = CardGeneratorDB.Instance.getSingleColumnDataFromTable(CardGeneratorDB.TABLECardDefinitions, CardGeneratorDB.COLUMNCardDefinitionID); } if (order == eCARDORDERTYPE.eCARDORDERRANDOM) { // any output will be randomized //cardDataIDs = ShuffleList(cardDataIDs); //cardDefinitionIDs = ShuffleList(cardDefinitionIDs); List<String[]> dataout = new List<string[]>(); foreach (String cardDataID in cardDataIDs) { foreach (String cardDefinitionID in cardDefinitionIDs) { String[] data = {CardGeneratorDB.COLUMNCardOutputID, "0", CardGeneratorDB.COLUMNCardDefinitionID , cardDefinitionID, CardGeneratorDB.COLUMNCardDataID , cardDataID}; dataout.Add(data); } } dataout = ShuffleList(dataout); int iID = 0; foreach (String[] data in dataout) { iID++; data[1] = iID.ToString(); CardGeneratorDB.Instance.addRowToTable(CardGeneratorDB.TABLECardOutput, data); } } else if (order == eCARDORDERTYPE.eCARDORDERVOCAB) { // order by data int iID = 0; foreach (String cardDataID in cardDataIDs) { foreach (String cardDefinitionID in cardDefinitionIDs) { iID++; String[] data = {CardGeneratorDB.COLUMNCardOutputID, iID.ToString(), CardGeneratorDB.COLUMNCardDefinitionID , cardDefinitionID, CardGeneratorDB.COLUMNCardDataID , cardDataID}; CardGeneratorDB.Instance.addRowToTable(CardGeneratorDB.TABLECardOutput, data); } } } else { // order by type int iID = 0; foreach (String cardDefinitionID in cardDefinitionIDs) { foreach (String cardDataID in cardDataIDs) { iID++; String[] data = {CardGeneratorDB.COLUMNCardOutputID, iID.ToString(), CardGeneratorDB.COLUMNCardDefinitionID , cardDefinitionID, CardGeneratorDB.COLUMNCardDataID , cardDataID}; CardGeneratorDB.Instance.addRowToTable(CardGeneratorDB.TABLECardOutput, data); } } } } private static List<T> ShuffleList<T>(List<T> source) { List<T> sortedList = new List<T>(); Random generator = new Random(); while (source.Count > 0) { int position = generator.Next(source.Count); sortedList.Add(source[position]); source.RemoveAt(position); } return sortedList; } } }
namespace EIDSS.Reports.BaseControls { partial class ReportView { /// <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() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ReportView)); this.printingSystemReports = new DevExpress.XtraPrinting.PrintingSystem(this.components); this.printControlReport = new EIDSS.Reports.BaseControls.ReportPrintControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.printBarManager = new DevExpress.XtraPrinting.Preview.PrintBarManager(this.components); this.previewBar1 = new DevExpress.XtraPrinting.Preview.PreviewBar(); this.biLoadDefault = new DevExpress.XtraBars.BarButtonItem(); this.biEdit = new DevExpress.XtraBars.BarButtonItem(); this.biFind = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biPrint = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biPrintDirect = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biPageSetup = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biScale = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biHandTool = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biMagnifier = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biZoomOut = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biZoom = new DevExpress.XtraPrinting.Preview.ZoomBarEditItem(); this.printPreviewRepositoryItemComboBox1 = new DevExpress.XtraPrinting.Preview.PrintPreviewRepositoryItemComboBox(); this.ZoomIn = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biShowFirstPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biShowPrevPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biShowNextPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biShowLastPage = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biMultiplePages = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biFillBackground = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.biExportFile = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.barStatus = new DevExpress.XtraPrinting.Preview.PreviewBar(); this.biPage = new DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem(); this.barStaticItem1 = new DevExpress.XtraBars.BarStaticItem(); this.biProgressBar = new DevExpress.XtraPrinting.Preview.ProgressBarEditItem(); this.repositoryItemProgressBar1 = new DevExpress.XtraEditors.Repository.RepositoryItemProgressBar(); this.biStatusStatus = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem(); this.biStatusZoom = new DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem(); this.barMainMenu = new DevExpress.XtraPrinting.Preview.PreviewBar(); this.printPreviewSubItem4 = new DevExpress.XtraPrinting.Preview.PrintPreviewSubItem(); this.printPreviewBarItem27 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.printPreviewBarItem28 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.barToolbarsListItem1 = new DevExpress.XtraBars.BarToolbarsListItem(); this.biExportPdf = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem(); this.biExportHtm = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem(); this.biExportMht = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem(); this.biExportRtf = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem(); this.biExportXls = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem(); this.biExportCsv = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem(); this.biExportTxt = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem(); this.biExportGraphic = new DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem(); this.printPreviewBarItem2 = new DevExpress.XtraPrinting.Preview.PrintPreviewBarItem(); this.timerScroll = new System.Windows.Forms.Timer(this.components); ((System.ComponentModel.ISupportInitialize)(this.printingSystemReports)).BeginInit(); this.printControlReport.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.printBarManager)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.printPreviewRepositoryItemComboBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemProgressBar1)).BeginInit(); this.SuspendLayout(); bv.common.Resources.BvResourceManagerChanger.GetResourceManager(typeof(ReportView), out resources); // Form Is Localizable: True // // printControlReport // resources.ApplyResources(this.printControlReport, "printControlReport"); this.printControlReport.Controls.Add(this.barDockControlLeft); this.printControlReport.Controls.Add(this.barDockControlRight); this.printControlReport.Controls.Add(this.barDockControlBottom); this.printControlReport.Controls.Add(this.barDockControlTop); this.printControlReport.LookAndFeel.SkinName = "Blue"; this.printControlReport.Name = "printControlReport"; this.printControlReport.PrintingSystem = this.printingSystemReports; // // barDockControlLeft // this.barDockControlLeft.CausesValidation = false; resources.ApplyResources(this.barDockControlLeft, "barDockControlLeft"); // // barDockControlRight // this.barDockControlRight.CausesValidation = false; resources.ApplyResources(this.barDockControlRight, "barDockControlRight"); // // barDockControlBottom // this.barDockControlBottom.CausesValidation = false; resources.ApplyResources(this.barDockControlBottom, "barDockControlBottom"); // // barDockControlTop // this.barDockControlTop.CausesValidation = false; resources.ApplyResources(this.barDockControlTop, "barDockControlTop"); // // printBarManager // this.printBarManager.AllowCustomization = false; this.printBarManager.AllowQuickCustomization = false; this.printBarManager.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.previewBar1, this.barStatus, this.barMainMenu}); this.printBarManager.DockControls.Add(this.barDockControlTop); this.printBarManager.DockControls.Add(this.barDockControlBottom); this.printBarManager.DockControls.Add(this.barDockControlLeft); this.printBarManager.DockControls.Add(this.barDockControlRight); this.printBarManager.Form = this.printControlReport; this.printBarManager.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("printBarManager.ImageStream"))); this.printBarManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.biPage, this.barStaticItem1, this.biProgressBar, this.biStatusStatus, this.barButtonItem1, this.biStatusZoom, this.biFind, this.biPrint, this.biPrintDirect, this.biPageSetup, this.biScale, this.biHandTool, this.biMagnifier, this.biZoomOut, this.biZoom, this.ZoomIn, this.biShowFirstPage, this.biShowPrevPage, this.biShowNextPage, this.biShowLastPage, this.biMultiplePages, this.biFillBackground, this.biExportFile, this.printPreviewSubItem4, this.printPreviewBarItem27, this.printPreviewBarItem28, this.barToolbarsListItem1, this.biExportPdf, this.biExportHtm, this.biExportMht, this.biExportRtf, this.biExportXls, this.biExportCsv, this.biExportTxt, this.biExportGraphic, this.biEdit, this.biLoadDefault}); this.printBarManager.MainMenu = this.barMainMenu; this.printBarManager.MaxItemId = 60; this.printBarManager.PreviewBar = this.previewBar1; this.printBarManager.PrintControl = this.printControlReport; this.printBarManager.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] { this.repositoryItemProgressBar1, this.printPreviewRepositoryItemComboBox1}); this.printBarManager.StatusBar = this.barStatus; // // previewBar1 // this.previewBar1.BarName = "Toolbar"; this.previewBar1.DockCol = 0; this.previewBar1.DockRow = 1; this.previewBar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.previewBar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.biLoadDefault, true), new DevExpress.XtraBars.LinkPersistInfo(this.biEdit), new DevExpress.XtraBars.LinkPersistInfo(this.biFind, true), new DevExpress.XtraBars.LinkPersistInfo(this.biPrint), new DevExpress.XtraBars.LinkPersistInfo(this.biPrintDirect), new DevExpress.XtraBars.LinkPersistInfo(this.biPageSetup), new DevExpress.XtraBars.LinkPersistInfo(this.biScale), new DevExpress.XtraBars.LinkPersistInfo(this.biHandTool, true), new DevExpress.XtraBars.LinkPersistInfo(this.biMagnifier), new DevExpress.XtraBars.LinkPersistInfo(this.biZoomOut, true), new DevExpress.XtraBars.LinkPersistInfo(DevExpress.XtraBars.BarLinkUserDefines.Width, this.biZoom, "", false, true, true, 70), new DevExpress.XtraBars.LinkPersistInfo(this.ZoomIn), new DevExpress.XtraBars.LinkPersistInfo(this.biShowFirstPage, true), new DevExpress.XtraBars.LinkPersistInfo(this.biShowPrevPage), new DevExpress.XtraBars.LinkPersistInfo(this.biShowNextPage), new DevExpress.XtraBars.LinkPersistInfo(this.biShowLastPage), new DevExpress.XtraBars.LinkPersistInfo(this.biMultiplePages, true), new DevExpress.XtraBars.LinkPersistInfo(this.biFillBackground), new DevExpress.XtraBars.LinkPersistInfo(this.biExportFile, true)}); this.previewBar1.OptionsBar.AllowQuickCustomization = false; this.previewBar1.OptionsBar.DisableClose = true; this.previewBar1.OptionsBar.DisableCustomization = true; this.previewBar1.OptionsBar.DrawDragBorder = false; resources.ApplyResources(this.previewBar1, "previewBar1"); // // biLoadDefault // resources.ApplyResources(this.biLoadDefault, "biLoadDefault"); this.biLoadDefault.Enabled = false; this.biLoadDefault.Glyph = global::EIDSS.Reports.Properties.Resources.restore; this.biLoadDefault.Id = 59; this.biLoadDefault.Name = "biLoadDefault"; this.biLoadDefault.Visibility = DevExpress.XtraBars.BarItemVisibility.Never; this.biLoadDefault.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biLoadDefault_ItemClick); // // biEdit // resources.ApplyResources(this.biEdit, "biEdit"); this.biEdit.Enabled = false; this.biEdit.Glyph = global::EIDSS.Reports.Properties.Resources.msg_edit; this.biEdit.Id = 58; this.biEdit.Name = "biEdit"; this.biEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Never; this.biEdit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.biEdit_ItemClick); // // biFind // resources.ApplyResources(this.biFind, "biFind"); this.biFind.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Find; this.biFind.Enabled = false; this.biFind.Id = 8; this.biFind.ImageIndex = 20; this.biFind.Name = "biFind"; // // biPrint // this.biPrint.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check; resources.ApplyResources(this.biPrint, "biPrint"); this.biPrint.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Print; this.biPrint.Enabled = false; this.biPrint.Id = 12; this.biPrint.ImageIndex = 0; this.biPrint.Name = "biPrint"; // // biPrintDirect // resources.ApplyResources(this.biPrintDirect, "biPrintDirect"); this.biPrintDirect.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PrintDirect; this.biPrintDirect.Enabled = false; this.biPrintDirect.Id = 13; this.biPrintDirect.ImageIndex = 1; this.biPrintDirect.Name = "biPrintDirect"; // // biPageSetup // this.biPageSetup.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check; resources.ApplyResources(this.biPageSetup, "biPageSetup"); this.biPageSetup.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageSetup; this.biPageSetup.Enabled = false; this.biPageSetup.Id = 14; this.biPageSetup.ImageIndex = 2; this.biPageSetup.Name = "biPageSetup"; // // biScale // this.biScale.ActAsDropDown = true; this.biScale.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown; resources.ApplyResources(this.biScale, "biScale"); this.biScale.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Scale; this.biScale.Enabled = false; this.biScale.Id = 16; this.biScale.ImageIndex = 25; this.biScale.Name = "biScale"; // // biHandTool // this.biHandTool.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check; resources.ApplyResources(this.biHandTool, "biHandTool"); this.biHandTool.Command = DevExpress.XtraPrinting.PrintingSystemCommand.HandTool; this.biHandTool.Enabled = false; this.biHandTool.Id = 17; this.biHandTool.ImageIndex = 16; this.biHandTool.Name = "biHandTool"; // // biMagnifier // this.biMagnifier.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check; resources.ApplyResources(this.biMagnifier, "biMagnifier"); this.biMagnifier.Command = DevExpress.XtraPrinting.PrintingSystemCommand.Magnifier; this.biMagnifier.Enabled = false; this.biMagnifier.Id = 18; this.biMagnifier.ImageIndex = 3; this.biMagnifier.Name = "biMagnifier"; // // biZoomOut // resources.ApplyResources(this.biZoomOut, "biZoomOut"); this.biZoomOut.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ZoomOut; this.biZoomOut.Enabled = false; this.biZoomOut.Id = 19; this.biZoomOut.ImageIndex = 5; this.biZoomOut.Name = "biZoomOut"; // // biZoom // resources.ApplyResources(this.biZoom, "biZoom"); this.biZoom.Edit = this.printPreviewRepositoryItemComboBox1; this.biZoom.EditValue = "100%"; this.biZoom.Enabled = false; this.biZoom.Id = 20; this.biZoom.Name = "biZoom"; // // printPreviewRepositoryItemComboBox1 // this.printPreviewRepositoryItemComboBox1.AutoComplete = false; this.printPreviewRepositoryItemComboBox1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("printPreviewRepositoryItemComboBox1.Buttons"))))}); this.printPreviewRepositoryItemComboBox1.DropDownRows = 11; this.printPreviewRepositoryItemComboBox1.Name = "printPreviewRepositoryItemComboBox1"; // // ZoomIn // resources.ApplyResources(this.ZoomIn, "ZoomIn"); this.ZoomIn.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ZoomIn; this.ZoomIn.Enabled = false; this.ZoomIn.Id = 21; this.ZoomIn.ImageIndex = 4; this.ZoomIn.Name = "ZoomIn"; // // biShowFirstPage // resources.ApplyResources(this.biShowFirstPage, "biShowFirstPage"); this.biShowFirstPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowFirstPage; this.biShowFirstPage.Enabled = false; this.biShowFirstPage.Id = 22; this.biShowFirstPage.ImageIndex = 7; this.biShowFirstPage.Name = "biShowFirstPage"; // // biShowPrevPage // resources.ApplyResources(this.biShowPrevPage, "biShowPrevPage"); this.biShowPrevPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowPrevPage; this.biShowPrevPage.Enabled = false; this.biShowPrevPage.Id = 23; this.biShowPrevPage.ImageIndex = 8; this.biShowPrevPage.Name = "biShowPrevPage"; // // biShowNextPage // resources.ApplyResources(this.biShowNextPage, "biShowNextPage"); this.biShowNextPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowNextPage; this.biShowNextPage.Enabled = false; this.biShowNextPage.Id = 24; this.biShowNextPage.ImageIndex = 9; this.biShowNextPage.Name = "biShowNextPage"; // // biShowLastPage // resources.ApplyResources(this.biShowLastPage, "biShowLastPage"); this.biShowLastPage.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ShowLastPage; this.biShowLastPage.Enabled = false; this.biShowLastPage.Id = 25; this.biShowLastPage.ImageIndex = 10; this.biShowLastPage.Name = "biShowLastPage"; // // biMultiplePages // this.biMultiplePages.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown; resources.ApplyResources(this.biMultiplePages, "biMultiplePages"); this.biMultiplePages.Command = DevExpress.XtraPrinting.PrintingSystemCommand.MultiplePages; this.biMultiplePages.Enabled = false; this.biMultiplePages.Id = 26; this.biMultiplePages.ImageIndex = 11; this.biMultiplePages.Name = "biMultiplePages"; // // biFillBackground // this.biFillBackground.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown; resources.ApplyResources(this.biFillBackground, "biFillBackground"); this.biFillBackground.Command = DevExpress.XtraPrinting.PrintingSystemCommand.FillBackground; this.biFillBackground.Enabled = false; this.biFillBackground.Id = 27; this.biFillBackground.ImageIndex = 12; this.biFillBackground.Name = "biFillBackground"; // // biExportFile // this.biExportFile.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.DropDown; resources.ApplyResources(this.biExportFile, "biExportFile"); this.biExportFile.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportFile; this.biExportFile.Enabled = false; this.biExportFile.Id = 29; this.biExportFile.ImageIndex = 18; this.biExportFile.Name = "biExportFile"; // // barStatus // this.barStatus.BarName = "Status Bar"; this.barStatus.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom; this.barStatus.DockCol = 0; this.barStatus.DockRow = 0; this.barStatus.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom; this.barStatus.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.biPage), new DevExpress.XtraBars.LinkPersistInfo(this.barStaticItem1, true), new DevExpress.XtraBars.LinkPersistInfo(this.biProgressBar), new DevExpress.XtraBars.LinkPersistInfo(this.biStatusStatus), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem1), new DevExpress.XtraBars.LinkPersistInfo(this.biStatusZoom, true)}); this.barStatus.OptionsBar.AllowQuickCustomization = false; this.barStatus.OptionsBar.DrawDragBorder = false; this.barStatus.OptionsBar.UseWholeRow = true; resources.ApplyResources(this.barStatus, "barStatus"); // // biPage // this.biPage.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder; resources.ApplyResources(this.biPage, "biPage"); this.biPage.Id = 0; this.biPage.LeftIndent = 1; this.biPage.Name = "biPage"; this.biPage.RightIndent = 1; this.biPage.TextAlignment = System.Drawing.StringAlignment.Near; this.biPage.Type = "PageOfPages"; // // barStaticItem1 // this.barStaticItem1.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder; this.barStaticItem1.Id = 1; this.barStaticItem1.Name = "barStaticItem1"; this.barStaticItem1.TextAlignment = System.Drawing.StringAlignment.Near; // // biProgressBar // this.biProgressBar.Edit = this.repositoryItemProgressBar1; this.biProgressBar.EditHeight = 12; this.biProgressBar.Id = 2; this.biProgressBar.Name = "biProgressBar"; this.biProgressBar.Visibility = DevExpress.XtraBars.BarItemVisibility.Never; resources.ApplyResources(this.biProgressBar, "biProgressBar"); // // repositoryItemProgressBar1 // this.repositoryItemProgressBar1.Name = "repositoryItemProgressBar1"; // // biStatusStatus // resources.ApplyResources(this.biStatusStatus, "biStatusStatus"); this.biStatusStatus.Command = DevExpress.XtraPrinting.PrintingSystemCommand.StopPageBuilding; this.biStatusStatus.Enabled = false; this.biStatusStatus.Id = 3; this.biStatusStatus.Name = "biStatusStatus"; this.biStatusStatus.Visibility = DevExpress.XtraBars.BarItemVisibility.Never; // // barButtonItem1 // this.barButtonItem1.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Left; this.barButtonItem1.Enabled = false; this.barButtonItem1.Id = 4; this.barButtonItem1.Name = "barButtonItem1"; // // biStatusZoom // this.biStatusZoom.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Right; this.biStatusZoom.Border = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder; resources.ApplyResources(this.biStatusZoom, "biStatusZoom"); this.biStatusZoom.Id = 5; this.biStatusZoom.Name = "biStatusZoom"; this.biStatusZoom.TextAlignment = System.Drawing.StringAlignment.Near; this.biStatusZoom.Type = "ZoomFactor"; // // barMainMenu // this.barMainMenu.BarName = "Main Menu"; this.barMainMenu.DockCol = 0; this.barMainMenu.DockRow = 0; this.barMainMenu.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.barMainMenu.OptionsBar.MultiLine = true; this.barMainMenu.OptionsBar.UseWholeRow = true; resources.ApplyResources(this.barMainMenu, "barMainMenu"); this.barMainMenu.Visible = false; // // printPreviewSubItem4 // resources.ApplyResources(this.printPreviewSubItem4, "printPreviewSubItem4"); this.printPreviewSubItem4.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageLayout; this.printPreviewSubItem4.Id = 35; this.printPreviewSubItem4.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewBarItem27), new DevExpress.XtraBars.LinkPersistInfo(this.printPreviewBarItem28)}); this.printPreviewSubItem4.Name = "printPreviewSubItem4"; // // printPreviewBarItem27 // this.printPreviewBarItem27.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check; resources.ApplyResources(this.printPreviewBarItem27, "printPreviewBarItem27"); this.printPreviewBarItem27.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageLayoutFacing; this.printPreviewBarItem27.Enabled = false; this.printPreviewBarItem27.GroupIndex = 100; this.printPreviewBarItem27.Id = 36; this.printPreviewBarItem27.Name = "printPreviewBarItem27"; // // printPreviewBarItem28 // this.printPreviewBarItem28.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check; resources.ApplyResources(this.printPreviewBarItem28, "printPreviewBarItem28"); this.printPreviewBarItem28.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageLayoutContinuous; this.printPreviewBarItem28.Enabled = false; this.printPreviewBarItem28.GroupIndex = 100; this.printPreviewBarItem28.Id = 37; this.printPreviewBarItem28.Name = "printPreviewBarItem28"; // // barToolbarsListItem1 // resources.ApplyResources(this.barToolbarsListItem1, "barToolbarsListItem1"); this.barToolbarsListItem1.Id = 38; this.barToolbarsListItem1.Name = "barToolbarsListItem1"; // // biExportPdf // resources.ApplyResources(this.biExportPdf, "biExportPdf"); this.biExportPdf.Checked = true; this.biExportPdf.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportPdf; this.biExportPdf.Enabled = false; this.biExportPdf.GroupIndex = 1; this.biExportPdf.Id = 39; this.biExportPdf.Name = "biExportPdf"; // // biExportHtm // resources.ApplyResources(this.biExportHtm, "biExportHtm"); this.biExportHtm.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportHtm; this.biExportHtm.Enabled = false; this.biExportHtm.GroupIndex = 1; this.biExportHtm.Id = 40; this.biExportHtm.Name = "biExportHtm"; // // biExportMht // resources.ApplyResources(this.biExportMht, "biExportMht"); this.biExportMht.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportMht; this.biExportMht.Enabled = false; this.biExportMht.GroupIndex = 1; this.biExportMht.Id = 41; this.biExportMht.Name = "biExportMht"; // // biExportRtf // resources.ApplyResources(this.biExportRtf, "biExportRtf"); this.biExportRtf.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportRtf; this.biExportRtf.Enabled = false; this.biExportRtf.GroupIndex = 1; this.biExportRtf.Id = 42; this.biExportRtf.Name = "biExportRtf"; // // biExportXls // resources.ApplyResources(this.biExportXls, "biExportXls"); this.biExportXls.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportXls; this.biExportXls.Enabled = false; this.biExportXls.GroupIndex = 1; this.biExportXls.Id = 43; this.biExportXls.Name = "biExportXls"; // // biExportCsv // resources.ApplyResources(this.biExportCsv, "biExportCsv"); this.biExportCsv.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportCsv; this.biExportCsv.Enabled = false; this.biExportCsv.GroupIndex = 1; this.biExportCsv.Id = 44; this.biExportCsv.Name = "biExportCsv"; // // biExportTxt // resources.ApplyResources(this.biExportTxt, "biExportTxt"); this.biExportTxt.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportTxt; this.biExportTxt.Enabled = false; this.biExportTxt.GroupIndex = 1; this.biExportTxt.Id = 45; this.biExportTxt.Name = "biExportTxt"; // // biExportGraphic // resources.ApplyResources(this.biExportGraphic, "biExportGraphic"); this.biExportGraphic.Command = DevExpress.XtraPrinting.PrintingSystemCommand.ExportGraphic; this.biExportGraphic.Enabled = false; this.biExportGraphic.GroupIndex = 1; this.biExportGraphic.Id = 46; this.biExportGraphic.Name = "biExportGraphic"; // // printPreviewBarItem2 // this.printPreviewBarItem2.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check; resources.ApplyResources(this.printPreviewBarItem2, "printPreviewBarItem2"); this.printPreviewBarItem2.Command = DevExpress.XtraPrinting.PrintingSystemCommand.PageSetup; this.printPreviewBarItem2.Enabled = false; this.printPreviewBarItem2.Id = 14; this.printPreviewBarItem2.ImageIndex = 2; this.printPreviewBarItem2.Name = "printPreviewBarItem2"; // // timerScroll // this.timerScroll.Interval = 300; this.timerScroll.Tick += new System.EventHandler(this.timerScroll_Tick); // // ReportView // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.printControlReport); this.DoubleBuffered = true; this.Name = "ReportView"; ((System.ComponentModel.ISupportInitialize)(this.printingSystemReports)).EndInit(); this.printControlReport.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.printBarManager)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.printPreviewRepositoryItemComboBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemProgressBar1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraPrinting.PrintingSystem printingSystemReports; private ReportPrintControl printControlReport; private DevExpress.XtraPrinting.Preview.PrintBarManager printBarManager; private DevExpress.XtraPrinting.Preview.PreviewBar previewBar1; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biFind; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biPrint; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biPrintDirect; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biPageSetup; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biScale; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biHandTool; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biMagnifier; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biZoomOut; private DevExpress.XtraPrinting.Preview.ZoomBarEditItem biZoom; private DevExpress.XtraPrinting.Preview.PrintPreviewRepositoryItemComboBox printPreviewRepositoryItemComboBox1; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem ZoomIn; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowFirstPage; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowPrevPage; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowNextPage; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biShowLastPage; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biMultiplePages; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biFillBackground; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biExportFile; private DevExpress.XtraPrinting.Preview.PreviewBar barStatus; private DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem biPage; private DevExpress.XtraBars.BarStaticItem barStaticItem1; private DevExpress.XtraPrinting.Preview.ProgressBarEditItem biProgressBar; private DevExpress.XtraEditors.Repository.RepositoryItemProgressBar repositoryItemProgressBar1; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem biStatusStatus; private DevExpress.XtraBars.BarButtonItem barButtonItem1; private DevExpress.XtraPrinting.Preview.PrintPreviewStaticItem biStatusZoom; private DevExpress.XtraPrinting.Preview.PreviewBar barMainMenu; private DevExpress.XtraPrinting.Preview.PrintPreviewSubItem printPreviewSubItem4; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem27; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem28; private DevExpress.XtraBars.BarToolbarsListItem barToolbarsListItem1; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportPdf; private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportHtm; private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportMht; private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportRtf; private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportXls; private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportCsv; private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportTxt; private DevExpress.XtraPrinting.Preview.PrintPreviewBarCheckItem biExportGraphic; private DevExpress.XtraPrinting.Preview.PrintPreviewBarItem printPreviewBarItem2; private DevExpress.XtraBars.BarButtonItem biEdit; private DevExpress.XtraBars.BarButtonItem biLoadDefault; private System.Windows.Forms.Timer timerScroll; } }
// 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 { using System; using System.Globalization; using System.IO; using System.Collections.Generic; using System.Xml.Schema; using System.Diagnostics; /// <summary> /// This writer wraps an XmlRawWriter and inserts additional lexical information into the resulting /// Xml 1.0 document: /// 1. CData sections /// 2. DocType declaration /// /// It also performs well-formed document checks if standalone="yes" and/or a doc-type-decl is output. /// </summary> internal class QueryOutputWriter : XmlRawWriter { private XmlRawWriter _wrapped; private bool _inCDataSection; private Dictionary<XmlQualifiedName, int> _lookupCDataElems; private BitStack _bitsCData; private XmlQualifiedName _qnameCData; private bool _outputDocType, _checkWellFormedDoc, _hasDocElem, _inAttr; private string _systemId, _publicId; private int _depth; public QueryOutputWriter(XmlRawWriter writer, XmlWriterSettings settings) { _wrapped = writer; _systemId = settings.DocTypeSystem; _publicId = settings.DocTypePublic; if (settings.OutputMethod == XmlOutputMethod.Xml) { // Xml output method shouldn't output doc-type-decl if system ID is not defined (even if public ID is) // Only check for well-formed document if output method is xml if (_systemId != null) { _outputDocType = true; _checkWellFormedDoc = true; } // Check for well-formed document if standalone="yes" in an auto-generated xml declaration if (settings.AutoXmlDeclaration && settings.Standalone == XmlStandalone.Yes) _checkWellFormedDoc = true; if (settings.CDataSectionElements.Count > 0) { _bitsCData = new BitStack(); _lookupCDataElems = new Dictionary<XmlQualifiedName, int>(); _qnameCData = new XmlQualifiedName(); // Add each element name to the lookup table foreach (XmlQualifiedName name in settings.CDataSectionElements) { _lookupCDataElems[name] = 0; } _bitsCData.PushBit(false); } } else if (settings.OutputMethod == XmlOutputMethod.Html) { // Html output method should output doc-type-decl if system ID or public ID is defined if (_systemId != null || _publicId != null) _outputDocType = true; } } //----------------------------------------------- // XmlWriter interface //----------------------------------------------- /// <summary> /// Get and set the namespace resolver that's used by this RawWriter to resolve prefixes. /// </summary> internal override IXmlNamespaceResolver NamespaceResolver { get { return this.resolver; } set { this.resolver = value; _wrapped.NamespaceResolver = value; } } /// <summary> /// Write the xml declaration. This must be the first call. /// </summary> internal override void WriteXmlDeclaration(XmlStandalone standalone) { _wrapped.WriteXmlDeclaration(standalone); } internal override void WriteXmlDeclaration(string xmldecl) { _wrapped.WriteXmlDeclaration(xmldecl); } /// <summary> /// Return settings provided to factory. /// </summary> public override XmlWriterSettings Settings { get { XmlWriterSettings settings = _wrapped.Settings; settings.ReadOnly = false; settings.DocTypeSystem = _systemId; settings.DocTypePublic = _publicId; settings.ReadOnly = true; return settings; } } /// <summary> /// Suppress this explicit call to WriteDocType if information was provided by XmlWriterSettings. /// </summary> public override void WriteDocType(string name, string pubid, string sysid, string subset) { if (_publicId == null && _systemId == null) { Debug.Assert(!_outputDocType); _wrapped.WriteDocType(name, pubid, sysid, subset); } } /// <summary> /// Check well-formedness, possibly output doc-type-decl, and determine whether this element is a /// CData section element. /// </summary> public override void WriteStartElement(string prefix, string localName, string ns) { EndCDataSection(); if (_checkWellFormedDoc) { // Don't allow multiple document elements if (_depth == 0 && _hasDocElem) throw new XmlException(SR.Xml_NoMultipleRoots, string.Empty); _depth++; _hasDocElem = true; } // Output doc-type declaration immediately before first element is output if (_outputDocType) { _wrapped.WriteDocType( prefix.Length != 0 ? prefix + ":" + localName : localName, _publicId, _systemId, null); _outputDocType = false; } _wrapped.WriteStartElement(prefix, localName, ns); if (_lookupCDataElems != null) { // Determine whether this element is a CData section element _qnameCData.Init(localName, ns); _bitsCData.PushBit(_lookupCDataElems.ContainsKey(_qnameCData)); } } internal override void WriteEndElement(string prefix, string localName, string ns) { EndCDataSection(); _wrapped.WriteEndElement(prefix, localName, ns); if (_checkWellFormedDoc) _depth--; if (_lookupCDataElems != null) _bitsCData.PopBit(); } internal override void WriteFullEndElement(string prefix, string localName, string ns) { EndCDataSection(); _wrapped.WriteFullEndElement(prefix, localName, ns); if (_checkWellFormedDoc) _depth--; if (_lookupCDataElems != null) _bitsCData.PopBit(); } internal override void StartElementContent() { _wrapped.StartElementContent(); } public override void WriteStartAttribute(string prefix, string localName, string ns) { _inAttr = true; _wrapped.WriteStartAttribute(prefix, localName, ns); } public override void WriteEndAttribute() { _inAttr = false; _wrapped.WriteEndAttribute(); } internal override void WriteNamespaceDeclaration(string prefix, string ns) { _wrapped.WriteNamespaceDeclaration(prefix, ns); } internal override bool SupportsNamespaceDeclarationInChunks { get { return _wrapped.SupportsNamespaceDeclarationInChunks; } } internal override void WriteStartNamespaceDeclaration(string prefix) { _wrapped.WriteStartNamespaceDeclaration(prefix); } internal override void WriteEndNamespaceDeclaration() { _wrapped.WriteEndNamespaceDeclaration(); } public override void WriteCData(string text) { _wrapped.WriteCData(text); } public override void WriteComment(string text) { EndCDataSection(); _wrapped.WriteComment(text); } public override void WriteProcessingInstruction(string name, string text) { EndCDataSection(); _wrapped.WriteProcessingInstruction(name, text); } public override void WriteWhitespace(string ws) { if (!_inAttr && (_inCDataSection || StartCDataSection())) _wrapped.WriteCData(ws); else _wrapped.WriteWhitespace(ws); } public override void WriteString(string text) { if (!_inAttr && (_inCDataSection || StartCDataSection())) _wrapped.WriteCData(text); else _wrapped.WriteString(text); } public override void WriteChars(char[] buffer, int index, int count) { if (!_inAttr && (_inCDataSection || StartCDataSection())) _wrapped.WriteCData(new string(buffer, index, count)); else _wrapped.WriteChars(buffer, index, count); } public override void WriteEntityRef(string name) { EndCDataSection(); _wrapped.WriteEntityRef(name); } public override void WriteCharEntity(char ch) { EndCDataSection(); _wrapped.WriteCharEntity(ch); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { EndCDataSection(); _wrapped.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteRaw(char[] buffer, int index, int count) { if (!_inAttr && (_inCDataSection || StartCDataSection())) _wrapped.WriteCData(new string(buffer, index, count)); else _wrapped.WriteRaw(buffer, index, count); } public override void WriteRaw(string data) { if (!_inAttr && (_inCDataSection || StartCDataSection())) _wrapped.WriteCData(data); else _wrapped.WriteRaw(data); } public override void Close() { _wrapped.Close(); if (_checkWellFormedDoc && !_hasDocElem) { // Need at least one document element throw new XmlException(SR.Xml_NoRoot, string.Empty); } } public override void Flush() { _wrapped.Flush(); } //----------------------------------------------- // Helper methods //----------------------------------------------- /// <summary> /// Write CData text if element is a CData element. Return true if text should be written /// within a CData section. /// </summary> private bool StartCDataSection() { Debug.Assert(!_inCDataSection); if (_lookupCDataElems != null && _bitsCData.PeekBit()) { _inCDataSection = true; return true; } return false; } /// <summary> /// No longer write CData text. /// </summary> private void EndCDataSection() { _inCDataSection = false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Threading; using Xunit; namespace System.IO.Tests { public class ChangedTests : FileSystemWatcherTest { [Fact] [ActiveIssue(2011, PlatformID.OSX)] public void FileSystemWatcher_Changed_LastWrite_File() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var watcher = new FileSystemWatcher(testDirectory.Path)) { watcher.Filter = Path.GetFileName(file.Path); AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); ExpectEvent(eventOccurred, "changed"); } } [Fact] [ActiveIssue(2011, PlatformID.OSX)] public void FileSystemWatcher_Changed_LastWrite_Directory() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var watcher = new FileSystemWatcher(testDirectory.Path)) { watcher.Filter = Path.GetFileName(dir.Path); AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; Directory.SetLastWriteTime(dir.Path, DateTime.Now + TimeSpan.FromSeconds(10)); ExpectEvent(eventOccurred, "changed"); } } [Fact] public void FileSystemWatcher_Changed_Negative() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var watcher = new FileSystemWatcher()) { // put everything in our own directory to avoid collisions watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*.*"; AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Changed); // run all scenarios together to avoid unnecessary waits, // assert information is verbose enough to trace to failure cause watcher.EnableRaisingEvents = true; // create a file using (var testFile = new TempFile(Path.Combine(dir.Path, "file"))) using (var testDir = new TempDirectory(Path.Combine(dir.Path, "dir"))) { // rename a file in the same directory File.Move(testFile.Path, testFile.Path + "_rename"); // renaming a directory Directory.Move(testDir.Path, testDir.Path + "_rename"); // deleting a file & directory by leaving the using block } ExpectNoEvent(eventOccurred, "changed"); } } [Fact, ActiveIssue(2279)] public void FileSystemWatcher_Changed_WatchedFolder() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var watcher = new FileSystemWatcher()) { watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; Directory.SetLastAccessTime(watcher.Path, DateTime.Now); ExpectEvent(eventOccurred, "changed"); } } [Fact] public void FileSystemWatcher_Changed_NestedDirectories() { TestNestedDirectoriesHelper(GetTestFilePath(), WatcherChangeTypes.Changed, (AutoResetEvent are, TempDirectory ttd) => { Directory.SetLastAccessTime(ttd.Path, DateTime.Now); ExpectEvent(are, "changed"); }, NotifyFilters.DirectoryName | NotifyFilters.LastAccess); } [Fact] public void FileSystemWatcher_Changed_FileInNestedDirectory() { TestNestedDirectoriesHelper(GetTestFilePath(), WatcherChangeTypes.Changed, (AutoResetEvent are, TempDirectory ttd) => { using (var nestedFile = new TempFile(Path.Combine(ttd.Path, "nestedFile"))) { Directory.SetLastAccessTime(nestedFile.Path, DateTime.Now); ExpectEvent(are, "changed"); } }, NotifyFilters.DirectoryName | NotifyFilters.LastAccess | NotifyFilters.FileName); } [Fact] public void FileSystemWatcher_Changed_FileDataChange() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var watcher = new FileSystemWatcher()) { AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Changed); // Attach the FSW to the existing structure watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; using (var file = File.Create(Path.Combine(dir.Path, "testfile.txt"))) { watcher.EnableRaisingEvents = true; // Change the nested file and verify we get the changed event byte[] bt = new byte[4096]; file.Write(bt, 0, bt.Length); file.Flush(); } ExpectEvent(eventOccurred, "file changed"); } } [Theory] [InlineData(true)] [InlineData(false)] public void FileSystemWatcher_Changed_PreSeededNestedStructure(bool includeSubdirectories) { // Make a nested structure before the FSW is setup using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var watcher = new FileSystemWatcher()) using (var dir1 = new TempDirectory(Path.Combine(dir.Path, "dir1"))) using (var dir2 = new TempDirectory(Path.Combine(dir1.Path, "dir2"))) using (var dir3 = new TempDirectory(Path.Combine(dir2.Path, "dir3"))) { string filePath = Path.Combine(dir3.Path, "testfile.txt"); File.WriteAllBytes(filePath, new byte[4096]); // Attach the FSW to the existing structure AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.Attributes; watcher.IncludeSubdirectories = includeSubdirectories; watcher.EnableRaisingEvents = true; File.SetAttributes(filePath, FileAttributes.ReadOnly); File.SetAttributes(filePath, FileAttributes.Normal); if (includeSubdirectories) ExpectEvent(eventOccurred, "file changed"); else ExpectNoEvent(eventOccurred, "file changed"); // Restart the FSW watcher.EnableRaisingEvents = false; watcher.EnableRaisingEvents = true; File.SetAttributes(filePath, FileAttributes.ReadOnly); File.SetAttributes(filePath, FileAttributes.Normal); if (includeSubdirectories) ExpectEvent(eventOccurred, "second file change"); else ExpectNoEvent(eventOccurred, "second file change"); } } [ConditionalFact(nameof(CanCreateSymbolicLinks))] public void FileSystemWatcher_Changed_SymLinkFileDoesntFireEvent() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var watcher = new FileSystemWatcher()) { AutoResetEvent are = WatchForEvents(watcher, WatcherChangeTypes.Changed); // Setup the watcher watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; using (var file = new TempFile(GetTestFilePath())) { CreateSymLink(file.Path, Path.Combine(dir.Path, "link"), false); watcher.EnableRaisingEvents = true; // Changing the temp file should not fire an event through the symlink byte[] bt = new byte[4096]; File.WriteAllBytes(file.Path, bt); } ExpectNoEvent(are, "symlink'd file change"); } } [ConditionalFact(nameof(CanCreateSymbolicLinks))] public void FileSystemWatcher_Changed_SymLinkFolderDoesntFireEvent() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var tempDir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFilePath()))) using (var watcher = new FileSystemWatcher()) { AutoResetEvent are = WatchForEvents(watcher, WatcherChangeTypes.Changed); // Setup the watcher watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; watcher.IncludeSubdirectories = true; using (var file = new TempFile(Path.Combine(tempDir.Path, "test"))) { // Create the symlink first CreateSymLink(tempDir.Path, Path.Combine(dir.Path, "link"), true); watcher.EnableRaisingEvents = true; // Changing the temp file should not fire an event through the symlink byte[] bt = new byte[4096]; File.WriteAllBytes(file.Path, bt); } ExpectNoEvent(are, "symlink'd file change"); } } [Fact] public void FileSystemWatcher_Changed_RootFolderChangeDoesNotFireEvent() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var watcher = new FileSystemWatcher()) { AutoResetEvent are = WatchForEvents(watcher, WatcherChangeTypes.Changed); // Setup the watcher watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.EnableRaisingEvents = true; Directory.SetLastWriteTime(dir.Path, DateTime.Now.AddSeconds(10)); ExpectNoEvent(are, "Root Directory Change"); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class HoistedThisTests : ExpressionCompilerTestBase { [WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")] [Fact] public void InstanceIterator_NoCapturing() { var source = @" class C { System.Collections.IEnumerable F() { yield break; } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<F>d__0.MoveNext", "C", expectedIL); } [WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")] [Fact] public void InstanceAsync_NoCapturing() { var source = @" using System; using System.Threading.Tasks; class C { async Task F() { await Console.Out.WriteLineAsync('a'); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.<F>d__0 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<F>d__0.MoveNext", "C", expectedIL); } [WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")] [Fact] public void InstanceLambda_NoCapturing() { var source = @" class C { void M() { System.Action a = () => 1.Equals(2); a(); } } "; // This test documents the fact that, as in dev12, "this" // is unavailable while stepping through the lambda. It // would be preferable if it were. VerifyNoThis(source, "C.<>c.<M>b__0_0"); } [Fact] public void InstanceLambda_NoCapturingExceptThis() { var source = @" class C { void M() { System.Action a = () => this.ToString(); a(); } } "; var expectedIL = @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"; VerifyHasThis(source, "C.<M>b__0_0", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceIterator_CapturedThis() { var source = @" class C { System.Collections.IEnumerable F() { yield return this; } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceAsync_CapturedThis() { var source = @" using System; using System.Threading.Tasks; class C { async Task F() { await Console.Out.WriteLineAsync(this.ToString()); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.<F>d__0 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceLambda_CapturedThis_DisplayClass() { var source = @" class C { int x; void M(int y) { System.Action a = () => x.Equals(y); a(); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<>c__DisplayClass1_0.<M>b__0", "C", expectedIL, thisCanBeElided: false); } [WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")] [Fact] public void InstanceLambda_CapturedThis_NoDisplayClass() { var source = @" class C { int x; void M(int y) { System.Action a = () => x.Equals(1); a(); } } "; var expectedIL = @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"; VerifyHasThis(source, "C.<M>b__1_0", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceIterator_Generic() { var source = @" class C<T> { System.Collections.IEnumerable F<U>() { yield return this; } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C<T> C<T>.<F>d__0<U>.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<F>d__0.MoveNext", "C<T>", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceAsync_Generic() { var source = @" using System; using System.Threading.Tasks; class C<T> { async Task F<U>() { await Console.Out.WriteLineAsync(this.ToString()); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C<T>.<F>d__0<U> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C<T> C<T>.<F>d__0<U>.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<F>d__0.MoveNext", "C<T>", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceLambda_Generic() { var source = @" class C<T> { int x; void M<U>(int y) { System.Action a = () => x.Equals(y); a(); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C<T> C<T>.<>c__DisplayClass1_0<U>.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<>c__DisplayClass1_0.<M>b__0", "C<T>", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceIterator_ExplicitInterfaceImplementation() { var source = @" interface I { System.Collections.IEnumerable F(); } class C : I { System.Collections.IEnumerable I.F() { yield return this; } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<I-F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<I-F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceAsync_ExplicitInterfaceImplementation() { var source = @" using System; using System.Threading.Tasks; interface I { Task F(); } class C : I { async Task I.F() { await Console.Out.WriteLineAsync(this.ToString()); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.<I-F>d__0 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<I-F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<I-F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceLambda_ExplicitInterfaceImplementation() { var source = @" interface I { void M(int y); } class C : I { int x; void I.M(int y) { System.Action a = () => x.Equals(y); a(); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<>c__DisplayClass1_0.<I.M>b__0", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceIterator_ExplicitGenericInterfaceImplementation() { var source = @" interface I<T> { System.Collections.IEnumerable F(); } class C : I<int> { System.Collections.IEnumerable I<int>.F() { yield return this; } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<I<System-Int32>-F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<I<System-Int32>-F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceAsync_ExplicitGenericInterfaceImplementation() { var source = @" using System; using System.Threading.Tasks; interface I<T> { Task F(); } class C : I<int> { async Task I<int>.F() { await Console.Out.WriteLineAsync(this.ToString()); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.<I<System-Int32>-F>d__0 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<I<System-Int32>-F>d__0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<I<System-Int32>-F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false); } [Fact] public void InstanceLambda_ExplicitGenericInterfaceImplementation() { var source = @" interface I<T> { void M(int y); } class C : I<int> { int x; void I<int>.M(int y) { System.Action a = () => x.Equals(y); a(); } } "; var expectedIL = @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ret }"; VerifyHasThis(source, "C.<>c__DisplayClass1_0.<I<System.Int32>.M>b__0", "C", expectedIL, thisCanBeElided: false); } [WorkItem(1066489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066489")] [Fact] public void InstanceIterator_ExplicitInterfaceImplementation_OldName() { var ilSource = @" .class interface public abstract auto ansi I`1<T> { .method public hidebysig newslot abstract virtual instance class [mscorlib]System.Collections.IEnumerable F() cil managed { } // end of method I`1::F } // end of class I`1 .class public auto ansi beforefieldinit C extends [mscorlib]System.Object implements class I`1<int32> { .class auto ansi sealed nested private beforefieldinit '<I<System.Int32>'.'F>d__0' extends [mscorlib]System.Object implements class [mscorlib]System.Collections.Generic.IEnumerable`1<object>, [mscorlib]System.Collections.IEnumerable, class [mscorlib]System.Collections.Generic.IEnumerator`1<object>, [mscorlib]System.Collections.IEnumerator, [mscorlib]System.IDisposable { .field private object '<>2__current' .field private int32 '<>1__state' .field private int32 '<>l__initialThreadId' .field public class C '<>4__this' .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.Generic.IEnumerator`1<object> 'System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator'() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance bool MoveNext() cil managed { ldnull throw } .method private hidebysig newslot specialname virtual final instance object 'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance void System.Collections.IEnumerator.Reset() cil managed { ldnull throw } .method private hidebysig newslot virtual final instance void System.IDisposable.Dispose() cil managed { ldnull throw } .method private hidebysig newslot specialname virtual final instance object System.Collections.IEnumerator.get_Current() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor(int32 '<>1__state') cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .property instance object 'System.Collections.Generic.IEnumerator<System.Object>.Current'() { .get instance object C/'<I<System.Int32>'.'F>d__0'::'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() } .property instance object System.Collections.IEnumerator.Current() { .get instance object C/'<I<System.Int32>'.'F>d__0'::System.Collections.IEnumerator.get_Current() } } // end of class '<I<System.Int32>'.'F>d__0' .method private hidebysig newslot virtual final instance class [mscorlib]System.Collections.IEnumerable 'I<System.Int32>.F'() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class C "; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var context = CreateMethodContext(runtime, "C.<I<System.Int32>.F>d__0.MoveNext"); VerifyHasThis(context, "C", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C C.<I<System.Int32>.F>d__0.<>4__this"" IL_0006: ret }"); } [Fact] public void StaticIterator() { var source = @" class C { static System.Collections.IEnumerable F() { yield break; } } "; VerifyNoThis(source, "C.<F>d__0.MoveNext"); } [Fact] public void StaticAsync() { var source = @" using System; using System.Threading.Tasks; class C<T> { static async Task F<U>() { await Console.Out.WriteLineAsync('a'); } } "; VerifyNoThis(source, "C.<F>d__0.MoveNext"); } [Fact] public void StaticLambda() { var source = @" using System; class C<T> { static void F<U>(int x) { Action a = () => x.ToString(); a(); } } "; VerifyNoThis(source, "C.<>c__DisplayClass0_0.<F>b__0"); } [Fact] public void ExtensionIterator() { var source = @" static class C { static System.Collections.IEnumerable F(this int x) { yield return x; } } "; VerifyNoThis(source, "C.<F>d__0.MoveNext"); } [Fact] public void ExtensionAsync() { var source = @" using System; using System.Threading.Tasks; static class C { static async Task F(this int x) { await Console.Out.WriteLineAsync(x.ToString()); } } "; VerifyNoThis(source, "C.<F>d__0.MoveNext"); } [Fact] public void ExtensionLambda() { var source = @" using System; static class C { static void F(this int x) { Action a = () => x.ToString(); a(); } } "; VerifyNoThis(source, "C.<>c__DisplayClass0_0.<F>b__0"); } [WorkItem(1072296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072296")] [Fact] public void OldStyleNonCapturingLambda() { var ilSource = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig instance void M() cil managed { ldnull throw } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method private hidebysig static int32 '<M>b__0'() cil managed { ldnull throw } } // end of class C "; var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var context = CreateMethodContext(runtime, "C.<M>b__0"); VerifyNoThis(context); } [WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")] [Fact] public void LambdaLocations_Instance() { var source = @" using System; class C { int _toBeCaptured; C() { int l = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 4))() + x))(1); } ~C() { int l = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 6))() + x))(1); } int P { get { return ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 7))() + x))(1); } set { value = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 8))() + x))(1); } } int this[int p] { get { return ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 9))() + x))(1); } set { value = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 10))() + x))(1); } } event Action E { add { int l = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 11))() + x))(1); } remove { int l = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 12))() + x))(1); } } } "; var expectedILTemplate = @" {{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""C C.{0}.<>4__this"" IL_0006: ret }}"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); WithRuntimeInstance(comp, runtime => { var dummyComp = CreateCompilationWithMscorlib("", new[] { comp.EmitToImageReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var typeC = dummyComp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var displayClassTypes = typeC.GetMembers().OfType<NamedTypeSymbol>(); Assert.True(displayClassTypes.Any()); foreach (var displayClassType in displayClassTypes) { var displayClassName = displayClassType.Name; Assert.Equal(GeneratedNameKind.LambdaDisplayClass, GeneratedNames.GetKind(displayClassName)); foreach (var displayClassMethod in displayClassType.GetMembers().OfType<MethodSymbol>().Where(m => GeneratedNames.GetKind(m.Name) == GeneratedNameKind.LambdaMethod)) { var lambdaMethodName = string.Format("C.{0}.{1}", displayClassName, displayClassMethod.Name); var context = CreateMethodContext(runtime, lambdaMethodName); var expectedIL = string.Format(expectedILTemplate, displayClassName); VerifyHasThis(context, "C", expectedIL); } } }); } [Fact] public void LambdaLocations_Static() { var source = @" using System; class C { static int f = ((Func<int, int>)(x => ((Func<int>)(() => x + 2))() + x))(1); static C() { int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 4))() + x))(1); } static int P { get { return ((Func<int, int>)(x => ((Func<int>)(() => x + 7))() + x))(1); } set { value = ((Func<int, int>)(x => ((Func<int>)(() => x + 8))() + x))(1); } } static event Action E { add { int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 11))() + x))(1); } remove { int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 12))() + x))(1); } } } "; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); WithRuntimeInstance(comp, runtime => { var dummyComp = CreateCompilationWithMscorlib("", new[] { comp.EmitToImageReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var typeC = dummyComp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var displayClassTypes = typeC.GetMembers().OfType<NamedTypeSymbol>(); Assert.True(displayClassTypes.Any()); foreach (var displayClassType in displayClassTypes) { var displayClassName = displayClassType.Name; Assert.Equal(GeneratedNameKind.LambdaDisplayClass, GeneratedNames.GetKind(displayClassName)); foreach (var displayClassMethod in displayClassType.GetMembers().OfType<MethodSymbol>().Where(m => GeneratedNames.GetKind(m.Name) == GeneratedNameKind.LambdaMethod)) { var lambdaMethodName = string.Format("C.{0}.{1}", displayClassName, displayClassMethod.Name); var context = CreateMethodContext(runtime, lambdaMethodName); VerifyNoThis(context); } } }); } private void VerifyHasThis(string source, string methodName, string expectedType, string expectedIL, bool thisCanBeElided = true) { var sourceCompilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); WithRuntimeInstance(sourceCompilation, runtime => { var context = CreateMethodContext(runtime, methodName); VerifyHasThis(context, expectedType, expectedIL); }); // Now recompile and test CompileExpression with optimized code. sourceCompilation = sourceCompilation.WithOptions(sourceCompilation.Options.WithOptimizationLevel(OptimizationLevel.Release)); WithRuntimeInstance(sourceCompilation, runtime => { var context = CreateMethodContext(runtime, methodName); // In C#, "this" may be optimized away. if (thisCanBeElided) { VerifyNoThis(context); } else { VerifyHasThis(context, expectedType, expectedIL: null); } // Verify that binding a trivial expression succeeds. string error; var testData = new CompilationTestData(); context.CompileExpression("42", out error, testData); Assert.Null(error); Assert.Equal(1, testData.Methods.Count); }); } private static void VerifyHasThis(EvaluationContext context, string expectedType, string expectedIL) { var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var testData = new CompilationTestData(); var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.NotNull(assembly); Assert.NotEqual(assembly.Count, 0); var localAndMethod = locals.Single(l => l.LocalName == "this"); if (expectedIL != null) { VerifyMethodData(testData.Methods.Single(m => m.Key.Contains(localAndMethod.MethodName)).Value, expectedType, expectedIL); } locals.Free(); string error; testData = new CompilationTestData(); context.CompileExpression("this", out error, testData); Assert.Null(error); if (expectedIL != null) { VerifyMethodData(testData.Methods.Single(m => m.Key.Contains("<>m0")).Value, expectedType, expectedIL); } } private static void VerifyMethodData(CompilationTestData.MethodData methodData, string expectedType, string expectedIL) { methodData.VerifyIL(expectedIL); var method = (MethodSymbol)methodData.Method; VerifyTypeParameters(method); Assert.Equal(expectedType, method.ReturnType.ToTestDisplayString()); } private void VerifyNoThis(string source, string methodName) { var comp = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => VerifyNoThis(CreateMethodContext(runtime, methodName))); } private static void VerifyNoThis(EvaluationContext context) { string error; var testData = new CompilationTestData(); context.CompileExpression("this", out error, testData); Assert.Contains(error, new[] { "error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer", "error CS0027: Keyword 'this' is not available in the current context", }); testData = new CompilationTestData(); context.CompileExpression("base.ToString()", out error, testData); Assert.Contains(error, new[] { "error CS1511: Keyword 'base' is not available in a static method", "error CS1512: Keyword 'base' is not available in the current context", }); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; testData = new CompilationTestData(); var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.NotNull(assembly); AssertEx.None(locals, l => l.LocalName.Contains("this")); locals.Free(); } [WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")] [Fact] public void InstanceMembersInIterator() { var source = @"class C { object x; System.Collections.IEnumerable F() { yield return this.x; } }"; var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>d__1.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("this.x", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<F>d__1.<>4__this"" IL_0006: ldfld ""object C.x"" IL_000b: ret }"); }); } [WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")] [Fact] public void InstanceMembersInAsync() { var source = @" using System; using System.Threading.Tasks; class C { object x; async Task F() { await Console.Out.WriteLineAsync(this.ToString()); } }"; var compilation0 = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>d__1.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("this.x", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, C.<F>d__1 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""C C.<F>d__1.<>4__this"" IL_0006: ldfld ""object C.x"" IL_000b: ret }"); }); } [WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")] [Fact] public void InstanceMembersInLambda() { var source = @"class C { object x; void F() { System.Action a = () => this.x.ToString(); a(); } }"; var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>b__1_0"); string error; var testData = new CompilationTestData(); context.CompileExpression("this.x", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""object C.x"" IL_0006: ret }"); }); } [Fact] public void BaseMembersInIterator() { var source = @" class Base { protected int x; } class Derived : Base { new protected object x; System.Collections.IEnumerable M() { yield return base.x; } }"; var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "Derived.<M>d__1.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("base.x", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""Derived Derived.<M>d__1.<>4__this"" IL_0006: ldfld ""int Base.x"" IL_000b: ret }"); }); } [Fact] public void BaseMembersInAsync() { var source = @" using System; using System.Threading.Tasks; class Base { protected int x; } class Derived : Base { new protected object x; async Task M() { await Console.Out.WriteLineAsync(this.ToString()); } }"; var compilation0 = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "Derived.<M>d__1.MoveNext"); string error; var testData = new CompilationTestData(); context.CompileExpression("base.x", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, Derived.<M>d__1 V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""Derived Derived.<M>d__1.<>4__this"" IL_0006: ldfld ""int Base.x"" IL_000b: ret }"); }); } [Fact] public void BaseMembersInLambda() { var source = @" class Base { protected int x; } class Derived : Base { new protected object x; void F() { System.Action a = () => this.x.ToString(); a(); } }"; var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "Derived.<F>b__1_0"); string error; var testData = new CompilationTestData(); context.CompileExpression("this.x", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""object Derived.x"" IL_0006: ret }"); }); } [Fact] public void IteratorOverloading_Parameters1() { var source = @" public class C { public System.Collections.IEnumerable M() { yield return this; } public System.Collections.IEnumerable M(int x) { return null; } }"; CheckIteratorOverloading(source, m => m.ParameterCount == 0); } [Fact] public void IteratorOverloading_Parameters2() // Same as above, but declarations reversed. { var source = @" public class C { public System.Collections.IEnumerable M(int x) { return null; } public System.Collections.IEnumerable M() { yield return this; } }"; // NB: We pick the wrong overload, but it doesn't matter because // the methods have the same characteristics. // Also, we don't require this behavior, we're just documenting it. CheckIteratorOverloading(source, m => m.ParameterCount == 1); } [Fact] public void IteratorOverloading_Staticness() { var source = @" public class C { public static System.Collections.IEnumerable M(int x) { return null; } // NB: We declare the interesting overload last so we know we're not // just picking the first one by mistake. public System.Collections.IEnumerable M() { yield return this; } }"; CheckIteratorOverloading(source, m => !m.IsStatic); } [Fact] public void IteratorOverloading_Abstractness() { var source = @" public abstract class C { public abstract System.Collections.IEnumerable M(int x); // NB: We declare the interesting overload last so we know we're not // just picking the first one by mistake. public System.Collections.IEnumerable M() { yield return this; } }"; CheckIteratorOverloading(source, m => !m.IsAbstract); } [Fact] public void IteratorOverloading_Arity1() { var source = @" public class C { public System.Collections.IEnumerable M<T>(int x) { return null; } // NB: We declare the interesting overload last so we know we're not // just picking the first one by mistake. public System.Collections.IEnumerable M() { yield return this; } }"; CheckIteratorOverloading(source, m => m.Arity == 0); } [Fact] public void IteratorOverloading_Arity2() { var source = @" public class C { public System.Collections.IEnumerable M(int x) { return null; } // NB: We declare the interesting overload last so we know we're not // just picking the first one by mistake. public System.Collections.IEnumerable M<T>() { yield return this; } }"; CheckIteratorOverloading(source, m => m.Arity == 1); } [Fact] public void IteratorOverloading_Constraints1() { var source = @" public class C { public System.Collections.IEnumerable M<T>(int x) where T : struct { return null; } // NB: We declare the interesting overload last so we know we're not // just picking the first one by mistake. public System.Collections.IEnumerable M<T>() where T : class { yield return this; } }"; CheckIteratorOverloading(source, m => m.TypeParameters.Single().HasReferenceTypeConstraint); } [Fact] public void IteratorOverloading_Constraints2() { var source = @" using System.Collections.Generic; public class C { public System.Collections.IEnumerable M<T, U>(int x) where T : class where U : IEnumerable<T> { return null; } // NB: We declare the interesting overload last so we know we're not // just picking the first one by mistake. public System.Collections.IEnumerable M<T, U>() where U : class where T : IEnumerable<U> { yield return this; } }"; // NOTE: This isn't the feature we're switching on, but it is a convenient // differentiator. CheckIteratorOverloading(source, m => m.ParameterCount == 0); } private static void CheckIteratorOverloading(string source, Func<MethodSymbol, bool> isDesiredOverload) { var comp1 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); var ref1 = comp1.EmitToImageReference(); var comp2 = CreateCompilationWithMscorlib("", new[] { ref1 }, options: TestOptions.DebugDll); var originalType = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var iteratorMethod = originalType.GetMembers("M").OfType<MethodSymbol>().Single(isDesiredOverload); var stateMachineType = originalType.GetMembers().OfType<NamedTypeSymbol>().Single(t => GeneratedNames.GetKind(t.Name) == GeneratedNameKind.StateMachineType); var moveNextMethod = stateMachineType.GetMember<MethodSymbol>("MoveNext"); var guessedIterator = CompilationContext.GetSubstitutedSourceMethod(moveNextMethod, sourceMethodMustBeInstance: true); Assert.Equal(iteratorMethod, guessedIterator.OriginalDefinition); } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; /// <summary> /// A <see cref="Rescorer"/> that uses a provided <see cref="Query"/> to assign /// scores to the first-pass hits. /// <para/> /// @lucene.experimental /// </summary> public abstract class QueryRescorer : Rescorer { private readonly Query query; /// <summary> /// Sole constructor, passing the 2nd pass query to /// assign scores to the 1st pass hits. /// </summary> public QueryRescorer(Query query) { this.query = query; } /// <summary> /// Implement this in a subclass to combine the first pass and /// second pass scores. If <paramref name="secondPassMatches"/> is <c>false</c> then /// the second pass query failed to match a hit from the /// first pass query, and you should ignore the /// <paramref name="secondPassScore"/>. /// </summary> protected abstract float Combine(float firstPassScore, bool secondPassMatches, float secondPassScore); public override TopDocs Rescore(IndexSearcher searcher, TopDocs firstPassTopDocs, int topN) { ScoreDoc[] hits = (ScoreDoc[])firstPassTopDocs.ScoreDocs.Clone(); Array.Sort(hits, Comparer<ScoreDoc>.Create((a, b) => a.Doc - b.Doc)); IList<AtomicReaderContext> leaves = searcher.IndexReader.Leaves; Weight weight = searcher.CreateNormalizedWeight(query); // Now merge sort docIDs from hits, with reader's leaves: int hitUpto = 0; int readerUpto = -1; int endDoc = 0; int docBase = 0; Scorer scorer = null; while (hitUpto < hits.Length) { ScoreDoc hit = hits[hitUpto]; int docID = hit.Doc; AtomicReaderContext readerContext = null; while (docID >= endDoc) { readerUpto++; readerContext = leaves[readerUpto]; endDoc = readerContext.DocBase + readerContext.Reader.MaxDoc; } if (readerContext != null) { // We advanced to another segment: docBase = readerContext.DocBase; scorer = weight.GetScorer(readerContext, null); } int targetDoc = docID - docBase; int actualDoc = scorer.DocID; if (actualDoc < targetDoc) { actualDoc = scorer.Advance(targetDoc); } if (actualDoc == targetDoc) { // Query did match this doc: hit.Score = Combine(hit.Score, true, scorer.GetScore()); } else { // Query did not match this doc: Debug.Assert(actualDoc > targetDoc); hit.Score = Combine(hit.Score, false, 0.0f); } hitUpto++; } // TODO: we should do a partial sort (of only topN) // instead, but typically the number of hits is // smallish: Array.Sort(hits, Comparer<ScoreDoc>.Create((a, b) => { // Sort by score descending, then docID ascending: if (a.Score > b.Score) { return -1; } else if (a.Score < b.Score) { return 1; } else { // this subtraction can't overflow int // because docIDs are >= 0: return a.Doc - b.Doc; } })); if (topN < hits.Length) { ScoreDoc[] subset = new ScoreDoc[topN]; Array.Copy(hits, 0, subset, 0, topN); hits = subset; } return new TopDocs(firstPassTopDocs.TotalHits, hits, hits[0].Score); } public override Explanation Explain(IndexSearcher searcher, Explanation firstPassExplanation, int docID) { Explanation secondPassExplanation = searcher.Explain(query, docID); float? secondPassScore = secondPassExplanation.IsMatch ? (float?)secondPassExplanation.Value : null; float score; if (secondPassScore == null) { score = Combine(firstPassExplanation.Value, false, 0.0f); } else { score = Combine(firstPassExplanation.Value, true, (float)secondPassScore); } Explanation result = new Explanation(score, "combined first and second pass score using " + this.GetType()); Explanation first = new Explanation(firstPassExplanation.Value, "first pass score"); first.AddDetail(firstPassExplanation); result.AddDetail(first); Explanation second; if (secondPassScore == null) { second = new Explanation(0.0f, "no second pass score"); } else { second = new Explanation((float)secondPassScore, "second pass score"); } second.AddDetail(secondPassExplanation); result.AddDetail(second); return result; } /// <summary> /// Sugar API, calling <see cref="QueryRescorer.Rescore(IndexSearcher, TopDocs, int)"/> using a simple linear /// combination of firstPassScore + <paramref name="weight"/> * secondPassScore /// </summary> public static TopDocs Rescore(IndexSearcher searcher, TopDocs topDocs, Query query, double weight, int topN) { return new QueryRescorerAnonymousInnerClassHelper(query, weight).Rescore(searcher, topDocs, topN); } private class QueryRescorerAnonymousInnerClassHelper : QueryRescorer { private double weight; public QueryRescorerAnonymousInnerClassHelper(Lucene.Net.Search.Query query, double weight) : base(query) { this.weight = weight; } protected override float Combine(float firstPassScore, bool secondPassMatches, float secondPassScore) { float score = firstPassScore; if (secondPassMatches) { score += (float)(weight * secondPassScore); } return score; } } } }
// 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.Linq; using System.Numerics; using Xunit; namespace System.Security.Cryptography.Rsa.Tests { public partial class ImportExport { private static bool EphemeralKeysAreExportable => !PlatformDetection.IsFullFramework || PlatformDetection.IsNetfx462OrNewer(); [ConditionalFact(nameof(EphemeralKeysAreExportable))] public static void ExportAutoKey() { RSAParameters privateParams; RSAParameters publicParams; int keySize; using (RSA rsa = RSAFactory.Create()) { keySize = rsa.KeySize; // We've not done anything with this instance yet, but it should automatically // create the key, because we'll now asked about it. privateParams = rsa.ExportParameters(true); publicParams = rsa.ExportParameters(false); // It shouldn't be changing things when it generated the key. Assert.Equal(keySize, rsa.KeySize); } Assert.Null(publicParams.D); Assert.NotNull(privateParams.D); ValidateParameters(ref publicParams); ValidateParameters(ref privateParams); Assert.Equal(privateParams.Modulus, publicParams.Modulus); Assert.Equal(privateParams.Exponent, publicParams.Exponent); } [ActiveIssue(20214, TargetFrameworkMonikers.NetFramework)] [ConditionalFact(nameof(EphemeralKeysAreExportable))] public static void PaddedExport() { // OpenSSL's numeric type for the storage of RSA key parts disregards zero-valued // prefix bytes. // // The .NET 4.5 RSACryptoServiceProvider type verifies that all of the D breakdown // values (P, DP, Q, DQ, InverseQ) are exactly half the size of D (which is itself // the same size as Modulus). // // These two things, in combination, suggest that we ensure that all .NET // implementations of RSA export their keys to the fixed array size suggested by their // KeySize property. RSAParameters diminishedDPParameters = TestData.DiminishedDPParameters; RSAParameters exported; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(diminishedDPParameters); exported = rsa.ExportParameters(true); } // DP is the most likely to fail, the rest just otherwise ensure that Export // isn't losing data. AssertKeyEquals(ref diminishedDPParameters, ref exported); } [ActiveIssue(20214, TargetFrameworkMonikers.NetFramework)] [ConditionalFact(nameof(EphemeralKeysAreExportable))] public static void LargeKeyImportExport() { RSAParameters imported = TestData.RSA16384Params; using (RSA rsa = RSAFactory.Create()) { try { rsa.ImportParameters(imported); } catch (CryptographicException) { // The key is pretty big, perhaps it was refused. return; } RSAParameters exported = rsa.ExportParameters(false); Assert.Equal(exported.Modulus, imported.Modulus); Assert.Equal(exported.Exponent, imported.Exponent); Assert.Null(exported.D); exported = rsa.ExportParameters(true); AssertKeyEquals(ref imported, ref exported); } } [ActiveIssue(20214, TargetFrameworkMonikers.NetFramework)] [ConditionalFact(nameof(EphemeralKeysAreExportable))] public static void UnusualExponentImportExport() { // Most choices for the Exponent value in an RSA key use a Fermat prime. // Since a Fermat prime is 2^(2^m) + 1, it always only has two bits set, and // frequently has the form { 0x01, [some number of 0x00s], 0x01 }, which has the same // representation in both big- and little-endian. // // The only real requirement for an Exponent value is that it be coprime to (p-1)(q-1). // So here we'll use the (non-Fermat) prime value 433 (0x01B1) to ensure big-endian export. RSAParameters unusualExponentParameters = TestData.UnusualExponentParameters; RSAParameters exported; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(unusualExponentParameters); exported = rsa.ExportParameters(true); } // Exponent is the most likely to fail, the rest just otherwise ensure that Export // isn't losing data. AssertKeyEquals(ref unusualExponentParameters, ref exported); } [ActiveIssue(20214, TargetFrameworkMonikers.NetFramework)] [ConditionalFact(nameof(EphemeralKeysAreExportable))] public static void ImportExport1032() { RSAParameters imported = TestData.RSA1032Parameters; RSAParameters exported; RSAParameters exportedPublic; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); exported = rsa.ExportParameters(true); exportedPublic = rsa.ExportParameters(false); } AssertKeyEquals(ref imported, ref exported); Assert.Equal(exportedPublic.Modulus, imported.Modulus); Assert.Equal(exportedPublic.Exponent, imported.Exponent); Assert.Null(exportedPublic.D); } [ActiveIssue(20214, TargetFrameworkMonikers.NetFramework)] [ConditionalFact(nameof(EphemeralKeysAreExportable))] public static void ImportReset() { using (RSA rsa = RSAFactory.Create()) { RSAParameters exported = rsa.ExportParameters(true); RSAParameters imported; // Ensure that we cause the KeySize value to change. if (rsa.KeySize == 1024) { imported = TestData.RSA2048Params; } else { imported = TestData.RSA1024Params; } Assert.NotEqual(imported.Modulus.Length * 8, rsa.KeySize); Assert.NotEqual(imported.Modulus, exported.Modulus); rsa.ImportParameters(imported); Assert.Equal(imported.Modulus.Length * 8, rsa.KeySize); exported = rsa.ExportParameters(true); AssertKeyEquals(ref imported, ref exported); } } [Fact] public static void ImportPrivateExportPublic() { RSAParameters imported = TestData.RSA1024Params; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); RSAParameters exportedPublic = rsa.ExportParameters(false); Assert.Equal(imported.Modulus, exportedPublic.Modulus); Assert.Equal(imported.Exponent, exportedPublic.Exponent); Assert.Null(exportedPublic.D); ValidateParameters(ref exportedPublic); } } [ActiveIssue(20214, TargetFrameworkMonikers.NetFramework)] [ConditionalFact(nameof(EphemeralKeysAreExportable))] public static void MultiExport() { RSAParameters imported = TestData.RSA1024Params; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); RSAParameters exportedPrivate = rsa.ExportParameters(true); RSAParameters exportedPrivate2 = rsa.ExportParameters(true); RSAParameters exportedPublic = rsa.ExportParameters(false); RSAParameters exportedPublic2 = rsa.ExportParameters(false); RSAParameters exportedPrivate3 = rsa.ExportParameters(true); RSAParameters exportedPublic3 = rsa.ExportParameters(false); AssertKeyEquals(ref imported, ref exportedPrivate); Assert.Equal(imported.Modulus, exportedPublic.Modulus); Assert.Equal(imported.Exponent, exportedPublic.Exponent); Assert.Null(exportedPublic.D); ValidateParameters(ref exportedPublic); AssertKeyEquals(ref exportedPrivate, ref exportedPrivate2); AssertKeyEquals(ref exportedPrivate, ref exportedPrivate3); AssertKeyEquals(ref exportedPublic, ref exportedPublic2); AssertKeyEquals(ref exportedPublic, ref exportedPublic3); } } [Fact] public static void PublicOnlyPrivateExport() { RSAParameters imported = new RSAParameters { Modulus = TestData.RSA1024Params.Modulus, Exponent = TestData.RSA1024Params.Exponent, }; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); Assert.ThrowsAny<CryptographicException>(() => rsa.ExportParameters(true)); } } [Fact] public static void ImportNoExponent() { RSAParameters imported = new RSAParameters { Modulus = TestData.RSA1024Params.Modulus, }; using (RSA rsa = RSAFactory.Create()) { if (rsa is RSACng && PlatformDetection.IsFullFramework) Assert.Throws<ArgumentException>(() => rsa.ImportParameters(imported)); else Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported)); } } [Fact] public static void ImportNoModulus() { RSAParameters imported = new RSAParameters { Exponent = TestData.RSA1024Params.Exponent, }; using (RSA rsa = RSAFactory.Create()) { if (rsa is RSACng && PlatformDetection.IsFullFramework) Assert.Throws<ArgumentException>(() => rsa.ImportParameters(imported)); else Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported)); } } [Fact] #if TESTING_CNG_IMPLEMENTATION [ActiveIssue(18882, TargetFrameworkMonikers.NetFramework)] #endif public static void ImportNoDP() { // Because RSAParameters is a struct, this is a copy, // so assigning DP is not destructive to other tests. RSAParameters imported = TestData.RSA1024Params; imported.DP = null; using (RSA rsa = RSAFactory.Create()) { Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported)); } } internal static void AssertKeyEquals(ref RSAParameters expected, ref RSAParameters actual) { Assert.Equal(expected.Modulus, actual.Modulus); Assert.Equal(expected.Exponent, actual.Exponent); Assert.Equal(expected.P, actual.P); Assert.Equal(expected.DP, actual.DP); Assert.Equal(expected.Q, actual.Q); Assert.Equal(expected.DQ, actual.DQ); Assert.Equal(expected.InverseQ, actual.InverseQ); if (expected.D == null) { Assert.Null(actual.D); } else { Assert.NotNull(actual.D); // If the value matched expected, take that as valid and shortcut the math. // If it didn't, we'll test that the value is at least legal. if (!expected.D.SequenceEqual(actual.D)) { VerifyDValue(ref actual); } } } internal static void ValidateParameters(ref RSAParameters rsaParams) { Assert.NotNull(rsaParams.Modulus); Assert.NotNull(rsaParams.Exponent); // Key compatibility: RSA as an algorithm is achievable using just N (Modulus), // E (public Exponent) and D (private exponent). Having all of the breakdowns // of D make the algorithm faster, and shipped versions of RSACryptoServiceProvider // have thrown if D is provided and the rest of the private key values are not. // So, here we're going to assert that none of them were null for private keys. if (rsaParams.D == null) { Assert.Null(rsaParams.P); Assert.Null(rsaParams.DP); Assert.Null(rsaParams.Q); Assert.Null(rsaParams.DQ); Assert.Null(rsaParams.InverseQ); } else { Assert.NotNull(rsaParams.P); Assert.NotNull(rsaParams.DP); Assert.NotNull(rsaParams.Q); Assert.NotNull(rsaParams.DQ); Assert.NotNull(rsaParams.InverseQ); } } private static void VerifyDValue(ref RSAParameters rsaParams) { if (rsaParams.P == null) { return; } // Verify that the formula (D * E) % LCM(p - 1, q - 1) == 1 // is true. // // This is NOT the same as saying D = ModInv(E, LCM(p - 1, q - 1)), // because D = ModInv(E, (p - 1) * (q - 1)) is a valid choice, but will // still work through this formula. BigInteger p = PositiveBigInteger(rsaParams.P); BigInteger q = PositiveBigInteger(rsaParams.Q); BigInteger e = PositiveBigInteger(rsaParams.Exponent); BigInteger d = PositiveBigInteger(rsaParams.D); BigInteger lambda = LeastCommonMultiple(p - 1, q - 1); BigInteger modProduct = (d * e) % lambda; Assert.Equal(BigInteger.One, modProduct); } private static BigInteger LeastCommonMultiple(BigInteger a, BigInteger b) { BigInteger gcd = BigInteger.GreatestCommonDivisor(a, b); return BigInteger.Abs(a) / gcd * BigInteger.Abs(b); } private static BigInteger PositiveBigInteger(byte[] bigEndianBytes) { byte[] littleEndianBytes; if (bigEndianBytes[0] >= 0x80) { // Insert a padding 00 byte so the number is treated as positive. littleEndianBytes = new byte[bigEndianBytes.Length + 1]; Buffer.BlockCopy(bigEndianBytes, 0, littleEndianBytes, 1, bigEndianBytes.Length); } else { littleEndianBytes = (byte[])bigEndianBytes.Clone(); } Array.Reverse(littleEndianBytes); return new BigInteger(littleEndianBytes); } } }
//Copyright (C) 2005 Richard J. Northedge // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //This file is based on the SentenceDetectorME.java source file found in the //original java implementation of OpenNLP. That source file contains the following header: // Copyright (C) 2004 Jason Baldridge, Gann Bierner and Tom Morton // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using SharpEntropy; namespace OpenNLP.Tools.SentenceDetect { /// <summary> /// A sentence detector for splitting up raw text into sentences. A maximum /// entropy model is used to evaluate the characters ".", "!", and "?" in a /// string to determine if they signify the end of a sentence. /// </summary> public class MaximumEntropySentenceDetector : ISentenceDetector { // Properties --------------- /// <summary> /// The maximum entropy model to use to evaluate contexts. /// </summary> private readonly IMaximumEntropyModel _model; /// <summary> /// The feature context generator. /// </summary> private readonly IContextGenerator<Tuple<StringBuilder, int>> _contextGenerator; /// <summary> /// The EndOfSentenceScanner to use when scanning for end of /// sentence offsets. /// </summary> private readonly IEndOfSentenceScanner _scanner; // Constructors ------------------ /// <summary> /// Constructor which takes a IMaximumEntropyModel and calls the three-arg /// constructor with that model, a SentenceDetectionContextGenerator, and the /// default end of sentence scanner. /// </summary> /// <param name="model"> /// The MaxentModel which this SentenceDetectorME will use to /// evaluate end-of-sentence decisions. /// </param> public MaximumEntropySentenceDetector(IMaximumEntropyModel model): this(model, new DefaultEndOfSentenceScanner()){} public MaximumEntropySentenceDetector(IMaximumEntropyModel model, IEndOfSentenceScanner scanner): this(model, new SentenceDetectionContextGenerator(scanner.GetPotentialEndOfSentenceCharacters().ToArray()), scanner){ } /// <summary> /// Constructor which takes a IMaximumEntropyModel and a IContextGenerator. /// calls the three-arg constructor with a default ed of sentence scanner. /// </summary> /// <param name="model"> /// The MaxentModel which this SentenceDetectorME will use to /// evaluate end-of-sentence decisions. /// </param> /// <param name="contextGenerator"> /// The IContextGenerator object which this MaximumEntropySentenceDetector /// will use to turn strings into contexts for the model to /// evaluate. /// </param> public MaximumEntropySentenceDetector(IMaximumEntropyModel model, IContextGenerator<Tuple<StringBuilder, int>> contextGenerator): this(model, contextGenerator, new DefaultEndOfSentenceScanner()){} /// <summary> /// Creates a new <code>MaximumEntropySentenceDetector</code> instance. /// </summary> /// <param name="model"> /// The IMaximumEntropyModel which this MaximumEntropySentenceDetector will use to /// evaluate end-of-sentence decisions. /// </param> /// <param name="contextGenerator">The IContextGenerator object which this MaximumEntropySentenceDetector /// will use to turn strings into contexts for the model to /// evaluate. /// </param> /// <param name="scanner">the EndOfSentenceScanner which this MaximumEntropySentenceDetector /// will use to locate end of sentence indexes. /// </param> public MaximumEntropySentenceDetector(IMaximumEntropyModel model, IContextGenerator<Tuple<StringBuilder, int>> contextGenerator, IEndOfSentenceScanner scanner) { _model = model; _contextGenerator = contextGenerator; _scanner = scanner; } /// <summary> /// Detect sentences in a string. /// </summary> /// <param name="input"> /// The string to be processed. /// </param> /// <returns> /// A string array containing individual sentences as elements. /// </returns> public virtual string[] SentenceDetect(string input) { int[] startsList = SentencePositionDetect(input); if (startsList.Length == 0) { return new string[] {input}; } bool isLeftover = startsList[startsList.Length - 1] != input.Length; var sentences = new string[isLeftover ? startsList.Length + 1 : startsList.Length]; sentences[0] = input.Substring(0, (startsList[0]) - (0)).Trim(); for (int currentStart = 1; currentStart < startsList.Length; currentStart++) { sentences[currentStart] = input.Substring(startsList[currentStart - 1], (startsList[currentStart]) - (startsList[currentStart - 1])).Trim(); } if (isLeftover) { sentences[sentences.Length - 1] = input.Substring(startsList[startsList.Length - 1]).Trim(); } return sentences; } private int GetFirstWhitespace(string input, int position) { while (position < input.Length && !char.IsWhiteSpace(input[position])) { position++; } return position; } private int GetFirstNonWhitespace(string input, int position) { while (position < input.Length && char.IsWhiteSpace(input[position])) { position++; } return position; } /// <summary> /// Detect the position of the first words of sentences in a string. /// </summary> /// <param name="input"> /// The string to be processed. /// </param> /// <returns> /// A integer array containing the positions of the end index of /// every sentence /// </returns> public virtual int[] SentencePositionDetect(string input) { if (string.IsNullOrEmpty(input)){ return new int[] {}; } var buffer = new StringBuilder(input); List<int> endersList = _scanner.GetPositions(input); var positions = new List<int>(endersList.Count); for (int currentEnder = 0, enderCount = endersList.Count, index = 0; currentEnder < enderCount; currentEnder++) { int candidate = endersList[currentEnder]; int cInt = candidate; // skip over the leading parts of non-token final delimiters int firstWhiteSpace = GetFirstWhitespace(input, cInt + 1); if (((currentEnder + 1) < enderCount) && ((endersList[currentEnder + 1]) < firstWhiteSpace)) { continue; } var pair = new Tuple<StringBuilder, int>(buffer, candidate); var context = _contextGenerator.GetContext(pair); double[] probabilities = _model.Evaluate(context); string bestOutcome = _model.GetBestOutcome(probabilities); if (bestOutcome.Equals("T") && IsAcceptableBreak(input, index, cInt)) { if (index != cInt) { positions.Add(GetFirstNonWhitespace(input, GetFirstWhitespace(input, cInt + 1))); } index = cInt + 1; } } return positions.ToArray(); } /// <summary> /// Allows subclasses to check an overzealous (read: poorly /// trained) model from flagging obvious non-breaks as breaks based /// on some boolean determination of a break's acceptability. /// /// <p>The implementation here always returns true, which means /// that the IMaximumEntropyModel's outcome is taken as is.</p> /// </summary> /// <param name="input"> /// the string in which the break occured. /// </param> /// <param name="fromIndex"> /// the start of the segment currently being evaluated /// </param> /// <param name="candidateIndex"> /// the index of the candidate sentence ending /// </param> /// <returns> true if the break is acceptable /// </returns> protected internal virtual bool IsAcceptableBreak(string input, int fromIndex, int candidateIndex) { return true; } // Utilities ---------------------------- /// <summary> /// Use this training method if you wish to supply an end of /// sentence scanner which provides a different set of ending chars /// other than the default ones. They are "\\.|!|\\?|\\\"|\\)". /// </summary> public static GisModel TrainModel(string filePath, int iterations, int cut, IEndOfSentenceScanner scanner) { return TrainModel(new List<string>() {filePath}, iterations, cut, scanner); } public static GisModel TrainModel(IEnumerable<string> filePaths, int iterations, int cut, IEndOfSentenceScanner scanner) { var trainer = new GisTrainer(); var readers = filePaths.Select(path => new StreamReader(path)).ToList(); // train the model ITrainingDataReader<string> dataReader = new MultipleFilesPlainTextByLineDataReader(readers); ITrainingEventReader eventReader = new SentenceDetectionEventReader(dataReader, scanner); trainer.TrainModel(eventReader, iterations, cut); return new GisModel(trainer); } } }
/* Generated SBE (Simple Binary Encoding) message codec */ #pragma warning disable 1591 // disable warning on missing comments using System; using Adaptive.SimpleBinaryEncoding; namespace Adaptive.SimpleBinaryEncoding.PerfTests.Bench.SBE.FIX { public sealed partial class MarketDataIncrementalRefreshTrades { public const ushort BlockLength = (ushort)11; public const ushort TemplateId = (ushort)2; public const ushort SchemaId = (ushort)2; public const ushort Schema_Version = (ushort)0; public const string SematicType = "X"; private readonly MarketDataIncrementalRefreshTrades _parentMessage; private DirectBuffer _buffer; private int _offset; private int _limit; private int _actingBlockLength; private int _actingVersion; public int Offset { get { return _offset; } } public MarketDataIncrementalRefreshTrades() { _parentMessage = this; } public void WrapForEncode(DirectBuffer buffer, int offset) { _buffer = buffer; _offset = offset; _actingBlockLength = BlockLength; _actingVersion = Schema_Version; Limit = offset + _actingBlockLength; } public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { _buffer = buffer; _offset = offset; _actingBlockLength = actingBlockLength; _actingVersion = actingVersion; Limit = offset + _actingBlockLength; } public int Size { get { return _limit - _offset; } } public int Limit { get { return _limit; } set { _buffer.CheckLimit(value); _limit = value; } } public const int TransactTimeId = 60; public static string TransactTimeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanossecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const ulong TransactTimeNullValue = 0xffffffffffffffffUL; public const ulong TransactTimeMinValue = 0x0UL; public const ulong TransactTimeMaxValue = 0xfffffffffffffffeUL; public ulong TransactTime { get { return _buffer.Uint64GetLittleEndian(_offset + 0); } set { _buffer.Uint64PutLittleEndian(_offset + 0, value); } } public const int EventTimeDeltaId = 37704; public static string EventTimeDeltaMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const ushort EventTimeDeltaNullValue = (ushort)65535; public const ushort EventTimeDeltaMinValue = (ushort)0; public const ushort EventTimeDeltaMaxValue = (ushort)65534; public ushort EventTimeDelta { get { return _buffer.Uint16GetLittleEndian(_offset + 8); } set { _buffer.Uint16PutLittleEndian(_offset + 8, value); } } public const int MatchEventIndicatorId = 5799; public static string MatchEventIndicatorMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public MatchEventIndicator MatchEventIndicator { get { return (MatchEventIndicator)_buffer.CharGet(_offset + 10); } set { _buffer.CharPut(_offset + 10, (byte)value); } } private readonly MdIncGrpGroup _mdIncGrp = new MdIncGrpGroup(); public const long MdIncGrpId = 268; public MdIncGrpGroup MdIncGrp { get { _mdIncGrp.WrapForDecode(_parentMessage, _buffer, _actingVersion); return _mdIncGrp; } } public MdIncGrpGroup MdIncGrpCount(int count) { _mdIncGrp.WrapForEncode(_parentMessage, _buffer, count); return _mdIncGrp; } public sealed partial class MdIncGrpGroup { private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding(); private MarketDataIncrementalRefreshTrades _parentMessage; private DirectBuffer _buffer; private int _blockLength; private int _actingVersion; private int _count; private int _index; private int _offset; public void WrapForDecode(MarketDataIncrementalRefreshTrades parentMessage, DirectBuffer buffer, int actingVersion) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, actingVersion); _blockLength = _dimensions.BlockLength; _count = _dimensions.NumInGroup; _actingVersion = actingVersion; _index = -1; _parentMessage.Limit = parentMessage.Limit + SbeHeaderSize; } public void WrapForEncode(MarketDataIncrementalRefreshTrades parentMessage, DirectBuffer buffer, int count) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion); _dimensions.BlockLength = (ushort)34; _dimensions.NumInGroup = (byte)count; _index = -1; _count = count; _blockLength = 34; parentMessage.Limit = parentMessage.Limit + SbeHeaderSize; } public const int SbeBlockLength = 34; public const int SbeHeaderSize = 3; public int ActingBlockLength { get { return _blockLength; } } public int Count { get { return _count; } } public bool HasNext { get { return (_index + 1) < _count; } } public MdIncGrpGroup Next() { if (_index + 1 >= _count) { throw new InvalidOperationException(); } _offset = _parentMessage.Limit; _parentMessage.Limit = _offset + _blockLength; ++_index; return this; } public const int TradeIdId = 1003; public static string TradeIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const ulong TradeIdNullValue = 0xffffffffffffffffUL; public const ulong TradeIdMinValue = 0x0UL; public const ulong TradeIdMaxValue = 0xfffffffffffffffeUL; public ulong TradeId { get { return _buffer.Uint64GetLittleEndian(_offset + 0); } set { _buffer.Uint64PutLittleEndian(_offset + 0, value); } } public const int SecurityIdId = 48; public static string SecurityIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const ulong SecurityIdNullValue = 0xffffffffffffffffUL; public const ulong SecurityIdMinValue = 0x0UL; public const ulong SecurityIdMaxValue = 0xfffffffffffffffeUL; public ulong SecurityId { get { return _buffer.Uint64GetLittleEndian(_offset + 8); } set { _buffer.Uint64PutLittleEndian(_offset + 8, value); } } public const int MdEntryPxId = 270; public static string MdEntryPxMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } private readonly Decimal64 _mdEntryPx = new Decimal64(); public Decimal64 MdEntryPx { get { _mdEntryPx.Wrap(_buffer, _offset + 16, _actingVersion); return _mdEntryPx; } } public const int MdEntrySizeId = 271; public static string MdEntrySizeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } private readonly IntQty32 _mdEntrySize = new IntQty32(); public IntQty32 MdEntrySize { get { _mdEntrySize.Wrap(_buffer, _offset + 24, _actingVersion); return _mdEntrySize; } } public const int NumberOfOrdersId = 346; public static string NumberOfOrdersMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const ushort NumberOfOrdersNullValue = (ushort)65535; public const ushort NumberOfOrdersMinValue = (ushort)0; public const ushort NumberOfOrdersMaxValue = (ushort)65534; public ushort NumberOfOrders { get { return _buffer.Uint16GetLittleEndian(_offset + 28); } set { _buffer.Uint16PutLittleEndian(_offset + 28, value); } } public const int MdUpdateActionId = 279; public static string MdUpdateActionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public MDUpdateAction MdUpdateAction { get { return (MDUpdateAction)_buffer.Uint8Get(_offset + 30); } set { _buffer.Uint8Put(_offset + 30, (byte)value); } } public const int RptSeqId = 83; public static string RptSeqMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public const byte RptSeqNullValue = (byte)255; public const byte RptSeqMinValue = (byte)0; public const byte RptSeqMaxValue = (byte)254; public byte RptSeq { get { return _buffer.Uint8Get(_offset + 31); } set { _buffer.Uint8Put(_offset + 31, value); } } public const int AggressorSideId = 5797; public static string AggressorSideMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public Side AggressorSide { get { return (Side)_buffer.CharGet(_offset + 32); } set { _buffer.CharPut(_offset + 32, (byte)value); } } public const int MdEntryTypeId = 269; public static string MdEntryTypeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return ""; } return ""; } public MDEntryType MdEntryType { get { return (MDEntryType)_buffer.CharGet(_offset + 33); } set { _buffer.CharPut(_offset + 33, (byte)value); } } } } }
using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using NFluent; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; using WireMock.Server; using Xunit; namespace WireMock.Net.Tests { public class StatefulBehaviorTests { [Fact] public async Task Scenarios_Should_skip_non_relevant_states() { // given string path = $"/foo_{Guid.NewGuid()}"; var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path).UsingGet()) .InScenario("s") .WhenStateIs("Test state") .RespondWith(Response.Create()); // when var response = await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); // then Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); server.Stop(); } [Fact] public async Task Scenarios_Should_process_request_if_equals_state_and_single_state_defined() { // given string path = $"/foo_{Guid.NewGuid()}"; var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path).UsingGet()) .InScenario("s") .WillSetStateTo("Test state") .RespondWith(Response.Create().WithBody("No state msg")); server .Given(Request.Create().WithPath(path).UsingGet()) .InScenario("s") .WhenStateIs("Test state") .RespondWith(Response.Create().WithBody("Test state msg")); // when var responseNoState = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); var responseWithState = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); // then Check.That(responseNoState).Equals("No state msg"); Check.That(responseWithState).Equals("Test state msg"); server.Stop(); } [Fact] public async Task Scenarios_With_Same_Path_Should_Use_Times_When_Moving_To_Next_State() { // given const int times = 2; string path = $"/foo_{Guid.NewGuid()}"; string body1 = "Scenario S1, No State, Setting State T2"; string body2 = "Scenario S1, State T2, End"; var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path).UsingGet()) .InScenario(1) .WillSetStateTo(2, times) .RespondWith(Response.Create().WithBody(body1)); server .Given(Request.Create().WithPath(path).UsingGet()) .InScenario(1) .WhenStateIs(2) .RespondWith(Response.Create().WithBody(body2)); // when var client = new HttpClient(); var responseScenario1 = await client.GetStringAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); var responseScenario2 = await client.GetStringAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); var responseWithState = await client.GetStringAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); // then responseScenario1.Should().Be(body1); responseScenario2.Should().Be(body1); responseWithState.Should().Be(body2); server.Stop(); } [Fact] public async Task Scenarios_With_Different_Paths_Should_Use_Times_When_Moving_To_Next_State() { // given const int times = 2; string path1 = $"/a_{Guid.NewGuid()}"; string path2 = $"/b_{Guid.NewGuid()}"; string path3 = $"/c_{Guid.NewGuid()}"; string body1 = "Scenario S1, No State, Setting State T2"; string body2 = "Scenario S1, State T2, Setting State T3"; string body3 = "Scenario S1, State T3, End"; var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path1).UsingGet()) .InScenario("S1") .WillSetStateTo("T2", times) .RespondWith(Response.Create().WithBody(body1)); server .Given(Request.Create().WithPath(path2).UsingGet()) .InScenario("S1") .WhenStateIs("T2") .WillSetStateTo("T3", times) .RespondWith(Response.Create().WithBody(body2)); server .Given(Request.Create().WithPath(path3).UsingGet()) .InScenario("S1") .WhenStateIs("T3") .RespondWith(Response.Create().WithBody(body3)); // when var client = new HttpClient(); var t1a = await client.GetStringAsync("http://localhost:" + server.Ports[0] + path1).ConfigureAwait(false); var t1b = await client.GetStringAsync("http://localhost:" + server.Ports[0] + path1).ConfigureAwait(false); var t2a = await client.GetStringAsync("http://localhost:" + server.Ports[0] + path2).ConfigureAwait(false); var t2b = await client.GetStringAsync("http://localhost:" + server.Ports[0] + path2).ConfigureAwait(false); var t3 = await client.GetStringAsync("http://localhost:" + server.Ports[0] + path3).ConfigureAwait(false); // then t1a.Should().Be(body1); t1b.Should().Be(body1); t2a.Should().Be(body2); t2b.Should().Be(body2); t3.Should().Be(body3); server.Stop(); } [Fact] public async Task Scenarios_Should_Respect_Int_Valued_Scenarios_and_States() { // given string path = $"/foo_{Guid.NewGuid()}"; var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path).UsingGet()) .InScenario(1) .WillSetStateTo(2) .RespondWith(Response.Create().WithBody("Scenario 1, Setting State 2")); server .Given(Request.Create().WithPath(path).UsingGet()) .InScenario(1) .WhenStateIs(2) .RespondWith(Response.Create().WithBody("Scenario 1, State 2")); // when var responseIntScenario = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); var responseWithIntState = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); // then Check.That(responseIntScenario).Equals("Scenario 1, Setting State 2"); Check.That(responseWithIntState).Equals("Scenario 1, State 2"); server.Stop(); } [Fact] public async Task Scenarios_Should_Respect_Mixed_String_Scenario_and_Int_State() { // given string path = $"/foo_{Guid.NewGuid()}"; var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path).UsingGet()) .InScenario("state string") .WillSetStateTo(1) .RespondWith(Response.Create().WithBody("string state, Setting State 2")); server .Given(Request.Create().WithPath(path).UsingGet()) .InScenario("state string") .WhenStateIs(1) .RespondWith(Response.Create().WithBody("string state, State 2")); // when var responseIntScenario = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); var responseWithIntState = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); // then Check.That(responseIntScenario).Equals("string state, Setting State 2"); Check.That(responseWithIntState).Equals("string state, State 2"); server.Stop(); } [Fact] public async Task Scenarios_Should_Respect_Mixed_Int_Scenario_and_String_Scenario_and_String_State() { // given string path = $"/foo_{Guid.NewGuid()}"; var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path).UsingGet()) .InScenario(1) .WillSetStateTo("Next State") .RespondWith(Response.Create().WithBody("int state, Setting State 2")); server .Given(Request.Create().WithPath(path).UsingGet()) .InScenario("1") .WhenStateIs("Next State") .RespondWith(Response.Create().WithBody("string state, State 2")); // when var responseIntScenario = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); var responseWithIntState = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); // then Check.That(responseIntScenario).Equals("int state, Setting State 2"); Check.That(responseWithIntState).Equals("string state, State 2"); server.Stop(); } [Fact] public async Task Scenarios_TodoList_Example() { // Assign var server = WireMockServer.Start(); server .Given(Request.Create().WithPath("/todo/items").UsingGet()) .InScenario("To do list") .WillSetStateTo("TodoList State Started") .RespondWith(Response.Create().WithBody("Buy milk")); server .Given(Request.Create().WithPath("/todo/items").UsingPost()) .InScenario("To do list") .WhenStateIs("TodoList State Started") .WillSetStateTo("Cancel newspaper item added") .RespondWith(Response.Create().WithStatusCode(201)); server .Given(Request.Create().WithPath("/todo/items").UsingGet()) .InScenario("To do list") .WhenStateIs("Cancel newspaper item added") .RespondWith(Response.Create().WithBody("Buy milk;Cancel newspaper subscription")); Check.That(server.Scenarios.Any()).IsFalse(); // Act and Assert string url = "http://localhost:" + server.Ports[0]; string getResponse1 = new HttpClient().GetStringAsync(url + "/todo/items").Result; Check.That(getResponse1).Equals("Buy milk"); Check.That(server.Scenarios["To do list"].Name).IsEqualTo("To do list"); Check.That(server.Scenarios["To do list"].NextState).IsEqualTo("TodoList State Started"); Check.That(server.Scenarios["To do list"].Started).IsTrue(); Check.That(server.Scenarios["To do list"].Finished).IsFalse(); var postResponse = await new HttpClient().PostAsync(url + "/todo/items", new StringContent("Cancel newspaper subscription")).ConfigureAwait(false); Check.That(postResponse.StatusCode).Equals(HttpStatusCode.Created); Check.That(server.Scenarios["To do list"].Name).IsEqualTo("To do list"); Check.That(server.Scenarios["To do list"].NextState).IsEqualTo("Cancel newspaper item added"); Check.That(server.Scenarios["To do list"].Started).IsTrue(); Check.That(server.Scenarios["To do list"].Finished).IsFalse(); string getResponse2 = await new HttpClient().GetStringAsync(url + "/todo/items").ConfigureAwait(false); Check.That(getResponse2).Equals("Buy milk;Cancel newspaper subscription"); Check.That(server.Scenarios["To do list"].Name).IsEqualTo("To do list"); Check.That(server.Scenarios["To do list"].NextState).IsNull(); Check.That(server.Scenarios["To do list"].Started).IsTrue(); Check.That(server.Scenarios["To do list"].Finished).IsTrue(); server.Stop(); } [Fact] public async Task Scenarios_Should_process_request_if_equals_state_and_multiple_state_defined() { // Assign var server = WireMockServer.Start(); server .Given(Request.Create().WithPath("/state1").UsingGet()) .InScenario("s1") .WillSetStateTo("Test state 1") .RespondWith(Response.Create().WithBody("No state msg 1")); server .Given(Request.Create().WithPath("/foo1X").UsingGet()) .InScenario("s1") .WhenStateIs("Test state 1") .RespondWith(Response.Create().WithBody("Test state msg 1")); server .Given(Request.Create().WithPath("/state2").UsingGet()) .InScenario("s2") .WillSetStateTo("Test state 2") .RespondWith(Response.Create().WithBody("No state msg 2")); server .Given(Request.Create().WithPath("/foo2X").UsingGet()) .InScenario("s2") .WhenStateIs("Test state 2") .RespondWith(Response.Create().WithBody("Test state msg 2")); // Act and Assert string url = "http://localhost:" + server.Ports[0]; var responseNoState1 = await new HttpClient().GetStringAsync(url + "/state1").ConfigureAwait(false); Check.That(responseNoState1).Equals("No state msg 1"); var responseNoState2 = await new HttpClient().GetStringAsync(url + "/state2").ConfigureAwait(false); Check.That(responseNoState2).Equals("No state msg 2"); var responseWithState1 = await new HttpClient().GetStringAsync(url + "/foo1X").ConfigureAwait(false); Check.That(responseWithState1).Equals("Test state msg 1"); var responseWithState2 = await new HttpClient().GetStringAsync(url + "/foo2X").ConfigureAwait(false); Check.That(responseWithState2).Equals("Test state msg 2"); server.Stop(); } } }
// 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; namespace System.IO.Pipelines.Samples.Models { public static class BigModels { public static readonly Model About100Fields = new Model() { CreatedDate = DateTime.Now, UpdateBy = Guid.NewGuid().ToString(), UpdatedDate = DateTime.Now, Provider = new HealthCareProvider() { CreatedDate = DateTime.Now, Name = Guid.NewGuid().ToString(), UpdateBy = Guid.NewGuid().ToString(), UpdatedDate = DateTime.Now, Services = new List<Service>() { new Service() { Code = "abcd", CreatedDate = DateTime.Now, Name = Guid.NewGuid().ToString(), SubName = Guid.NewGuid().ToString(), UpdateBy = Guid.NewGuid().ToString(), UpdatedDate = DateTime.Now, }, new Service() { Code = "abcd", CreatedDate = DateTime.Now, Name = Guid.NewGuid().ToString(), SubName = Guid.NewGuid().ToString(), UpdateBy = Guid.NewGuid().ToString(), UpdatedDate = DateTime.Now, }, new Service() { Code = "abcd", CreatedDate = DateTime.Now, Name = Guid.NewGuid().ToString(), SubName = Guid.NewGuid().ToString(), UpdateBy = Guid.NewGuid().ToString(), UpdatedDate = DateTime.Now, } } }, Enrollment = new Enrollment() { CreatedDate = DateTime.Now, UpdateBy = Guid.NewGuid().ToString(), UpdatedDate = DateTime.Now, Client = new Client() { CreatedDate = DateTime.Now, UpdateBy = Guid.NewGuid().ToString(), UpdatedDate = DateTime.Now, HomeAddress = new Address() { City = "Seattle", State = "WA", Street1 = Guid.NewGuid().ToString(), Zip = 98004, }, }, Program = new Program() { CreatedDate = DateTime.Now, UpdateBy = Guid.NewGuid().ToString(), UpdatedDate = DateTime.Now, Services = new List<Service>() { new Service() { Code = "abcd", CreatedDate = DateTime.Now, Name = Guid.NewGuid().ToString(), SubName = Guid.NewGuid().ToString(), UpdateBy = Guid.NewGuid().ToString(), UpdatedDate = DateTime.Now, }, new Service() { Code = "abcd", CreatedDate = DateTime.Now, Name = Guid.NewGuid().ToString(), SubName = Guid.NewGuid().ToString(), UpdateBy = Guid.NewGuid().ToString(), UpdatedDate = DateTime.Now, }, new Service() { Code = "abcd", CreatedDate = DateTime.Now, Name = Guid.NewGuid().ToString(), SubName = Guid.NewGuid().ToString(), UpdateBy = Guid.NewGuid().ToString(), UpdatedDate = DateTime.Now, } } }, }, Service = new Service() { Code = "abcd", CreatedDate = DateTime.Now, Name = Guid.NewGuid().ToString(), SubName = Guid.NewGuid().ToString(), UpdateBy = Guid.NewGuid().ToString(), UpdatedDate = DateTime.Now, }, }; } public abstract class BaseEntity<TId> { public abstract TId Id { get; } public DateTime CreatedDate { get; set; } public DateTime UpdatedDate { get; set; } public string UpdateBy { get; set; } public virtual bool IsTransient() { return Id.Equals(default); } } public class Model : BaseEntity<int> { public override int Id => EnrollmentServiceId; public int EnrollmentServiceId { get; set; } public int EnrollmentId { get; set; } public int ServiceId { get; set; } public int ProviderId { get; set; } public virtual Enrollment Enrollment { get; set; } public virtual Service Service { get; set; } public virtual HealthCareProvider Provider { get; set; } } public class Enrollment : BaseEntity<int> { public override int Id => EnrollmentId; public int EnrollmentId { get; set; } public int ClientId { get; set; } public virtual User PrimaryCaseManager { get; set; } public virtual User SecondaryCaseManager { get; set; } public int ProgramId { get; set; } public virtual Program Program { get; set; } public virtual Client Client { get; set; } public virtual ICollection<Model> EnrollmentServices { get; set; } public virtual ICollection<Doc> Documents { get; set; } public virtual ICollection<Note> Notes { get; set; } } public class Service : BaseEntity<int> { public override int Id => ServiceId; public int ServiceId { get; set; } public int ProgramId { get; set; } public string Code { get; set; } public string Name { get; set; } public string SubName { get; set; } public ICollection<HealthCareProvider> Providers { get; set; } public Program Program { get; set; } } public class HealthCareProvider : BaseEntity<int> { public override int Id => ProviderId; public int ProviderId { get; set; } public string Name { get; set; } public virtual ICollection<Service> Services { get; set; } } public class Client : BaseEntity<int> { public override int Id => ClientId; public int ClientId { get; set; } public virtual Address HomeAddress { get; set; } public virtual ICollection<Doc> Docs { get; set; } public virtual ICollection<Note> Notes { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } public virtual ICollection<Contact> Contacts { get; set; } public virtual ICollection<ClientCareSetting> CareSettings { get; set; } } public class Program : BaseEntity<int> { public override int Id => ProgramId; public int ProgramId { get; set; } public string Name { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } public virtual ICollection<Service> Services { get; set; } } public class Note : BaseEntity<int> { public override int Id => NoteId; public int NoteId { get; set; } public string Content { get; set; } } public class Doc : BaseEntity<int> { public override int Id => DocId; public int DocId { get; set; } public string Filename { get; set; } } public class Contact : BaseEntity<int> { public override int Id => ContactId; public int ContactId { get; set; } } public class User : BaseEntity<int> { public override int Id => UserId; public int UserId { get; set; } } public class ClientCareSetting : BaseEntity<int> { public override int Id => ClientCareSettingId; public int ClientCareSettingId { get; set; } public string Key { get; set; } public string Value { get; set; } } public class Address { public string Street1 { get; set; } public string Street2 { get; set; } public int Zip { get; set; } public string City { get; set; } public string State { get; set; } } }
/* * Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ using System; using System.Data; using System.Collections.Generic; using System.Linq; using System.Text; using AdoNetTest.BIN.BusinessObjects; using AdoNetTest.BIN.DataObjects; using Pivotal.Data.GemFireXD; namespace AdoNetTest.BIN { /// <summary> /// Common facade for data object interfaces. /// </summary> class DbController { public GFXDClientConnection Connection { get; set; } public String SchemaName { get; set; } public DbController(GFXDClientConnection connection) { Connection = connection; SchemaName = String.Empty; } public DbController(GFXDClientConnection connection, String schemaName) { Connection = connection; SchemaName = schemaName; } public void ProcessNewCustomerOrder(IList<BusinessObject> bObjects) { foreach (BusinessObject bObject in bObjects) { if (bObject is Address) AddAddress((Address)bObject); else if (bObject is Supplier) AddSupplier((Supplier)bObject); else if (bObject is Category) AddCategory((Category)bObject); else if (bObject is Customer) AddCustomer((Customer)bObject); else if (bObject is Product) AddProduct((Product)bObject); else if (bObject is Order) AddOrder((Order)bObject); else if (bObject is OrderDetail) AddOrderDetail((OrderDetail)bObject); else throw new Exception("Unrecognized business object type"); } } public bool ValidateTransaction(IList<BusinessObject> bObjects) { bool isValid = true; foreach (BusinessObject bObject in bObjects) { if (bObject is Address) isValid = ValidateAddress(bObject); else if (bObject is Supplier) isValid = ValidateSupplier(bObject); else if (bObject is Category) isValid = ValidateCategory(bObject); else if (bObject is Customer) isValid = ValidateCustomer(bObject); else if (bObject is Product) isValid = ValidateProduct(bObject); else if (bObject is Order) isValid = ValidateOrder(bObject); else if (bObject is OrderDetail) isValid = ValidateOrderDetail(bObject); else throw new Exception("Unrecognized business object type"); } return isValid; } public String GetValidationErrors(IList<BusinessObject> bObjects) { StringBuilder errors = new StringBuilder(); errors.Append("Transaction validation failed. Errors: "); foreach (BusinessObject bObject in bObjects) { foreach(String error in bObject.ValidationErrors) errors.AppendFormat("Type: {0}, Error: {1}; ", bObject.GetType().Name, error); } return errors.ToString(); } public bool ValidateAddress(BusinessObject bObject) { Address address = (Address)bObject; return address.Validate(GetAddress(address.AddressId)); } public bool ValidateSupplier(BusinessObject bObject) { Supplier supplier = (Supplier)bObject; return supplier.Validate(GetSupplier(supplier.SupplierId)); } public bool ValidateCategory(BusinessObject bObject) { Category category = (Category)bObject; return category.Validate(GetCategory(category.CategoryId)); } public bool ValidateCustomer(BusinessObject bObject) { Customer customer = (Customer)bObject; return customer.Validate(GetCustomer(customer.CustomerId)); } public bool ValidateProduct(BusinessObject bObject) { Product product = (Product)bObject; return product.Validate(GetProduct(product.ProductId)); } public bool ValidateOrder(BusinessObject bObject) { Order order = (Order)bObject; return order.Validate(GetOrder(order.OrderId)); } public bool ValidateOrderDetail(BusinessObject bObject) { OrderDetail ordDetail = (OrderDetail)bObject; return ordDetail.Validate(GetOrderDetail(ordDetail.OrderId, ordDetail.ProductId)); } public long AddAddress(Address address) { return (new AddressDao(Connection, SchemaName)).Insert(address); } public long AddSupplier(Supplier supplier) { return (new SupplierDao(Connection, SchemaName)).Insert(supplier); } public long AddCategory(Category category) { return (new CategoryDao(Connection, SchemaName)).Insert(category); } public long AddProduct(Product product) { return (new ProductDao(Connection, SchemaName)).Insert(product); } public long AddCustomer(Customer customer) { return (new CustomerDao(Connection, SchemaName)).Insert(customer); } public long AddOrder(Order order) { return (new OrderDao(Connection, SchemaName)).Insert(order); } public long AddOrderDetail(OrderDetail ordDetail) { return (new OrderDetailDao(Connection, SchemaName)).Insert(ordDetail); } public long UpdateAddress(Address address) { return (new AddressDao(Connection, SchemaName)).Update(address); } public long UpdateSupplier(Supplier supplier) { return (new SupplierDao(Connection, SchemaName)).Update(supplier); } public long UpdateCategory(Category category) { return (new CategoryDao(Connection, SchemaName)).Update(category); } public long UpdateProduct(Product product) { return (new ProductDao(Connection, SchemaName)).Update(product); } public long UpdateCustomer(Customer customer) { return (new CustomerDao(Connection, SchemaName)).Update(customer); } public long UpdateOrder(Order order) { return (new OrderDao(Connection, SchemaName)).Update(order); } public long UpdateOrderDetail(OrderDetail ordDetail) { return (new OrderDetailDao(Connection, SchemaName)).Update(ordDetail); } public int DeleteAddress(long addressId) { return (new AddressDao(Connection, SchemaName)).Delete(addressId); } public int DeleteSupplier(long supplierId) { return (new SupplierDao(Connection, SchemaName)).Delete(supplierId); } public int DeleteCategory(long categoryId) { return (new CategoryDao(Connection, SchemaName)).Delete(categoryId); } public int DeleteProduct(long productId) { return (new ProductDao(Connection, SchemaName)).Delete(productId); } public int DeleteCustomer(long customerId) { return (new CustomerDao(Connection, SchemaName)).Delete(customerId); } public int DeleteOrder(long orderId) { return (new OrderDao(Connection, SchemaName)).Delete(orderId); } public int DeleteOrderDetail(long orderId, long productId) { return (new OrderDetailDao(Connection, SchemaName)).Delete(orderId, productId); } public Address GetAddress(long addressId) { return (new AddressDao(Connection, SchemaName)).Select(addressId); } public Supplier GetSupplier(long supplierId) { return (new SupplierDao(Connection, SchemaName)).Select(supplierId); } public Category GetCategory(long categoryId) { return (new CategoryDao(Connection, SchemaName)).Select(categoryId); } public Product GetProduct(long productId) { return (new ProductDao(Connection, SchemaName)).Select(productId); } public Customer GetCustomer(long customerId) { return (new CustomerDao(Connection, SchemaName)).Select(customerId); } public Order GetOrder(long orderId) { return (new OrderDao(Connection, SchemaName)).Select(orderId); } public IList<Order> GetOrdersByCustomer(long customerId) { return (new OrderDao(Connection, SchemaName)).SelectByCustomer(customerId); } public OrderDetail GetOrderDetail(long orderId, long productId) { return (new OrderDetailDao(Connection, SchemaName)).Select(orderId, productId); } public IList<Address> GetAddresses() { return (new AddressDao(Connection, SchemaName)).Select(); } public IList<Supplier> GetSuppliers() { return (new SupplierDao(Connection, SchemaName)).Select(); } public IList<Category> GetCategories() { return (new CategoryDao(Connection, SchemaName)).Select(); } public IList<Product> GetProducts() { return (new ProductDao(Connection, SchemaName)).Select(); } public IList<Customer> GetCustomers() { return (new CustomerDao(Connection, SchemaName)).Select(); } public IList<Order> GetOrders() { return (new OrderDao(Connection, SchemaName)).Select(); } public IList<OrderDetail> GetOrderDetails() { return (new OrderDetailDao(Connection, SchemaName)).Select(); } public IList<OrderDetail> GetOrderDetails(long orderId) { return (new OrderDetailDao(Connection, SchemaName)).Select(orderId); } public Address GetRandomAddress() { return (new AddressDao(Connection, SchemaName)).SelectRandom(); } public IList<Address> GetRandomAddresses(int numRecords) { return (new AddressDao(Connection, SchemaName)).SelectRandom(numRecords); } public Supplier GetRandomSupplier() { return (new SupplierDao(Connection, SchemaName)).SelectRandom(); } public IList<Supplier> GetRandomSuppliers(int numRecords) { return (new SupplierDao(Connection, SchemaName)).SelectRandom(numRecords); } public Category GetRandomCategory() { return (new CategoryDao(Connection, SchemaName)).SelectRandom(); } public IList<Category> GetRandomCategories(int numRecords) { return (new CategoryDao(Connection, SchemaName)).SelectRandom(numRecords); } public Product GetRandomProduct() { return (new ProductDao(Connection, SchemaName)).SelectRandom(); } public IList<Product> GetRandomProducts(int numRecords) { return (new ProductDao(Connection, SchemaName)).SelectRandom(numRecords); } public Customer GetRandomCustomer() { return (new CustomerDao(Connection, SchemaName)).SelectRandom(); } public IList<Customer> GetRandomCustomers(int numRecords) { return (new CustomerDao(Connection, SchemaName)).SelectRandom(numRecords); } public Order GetRandomOrder() { return (new OrderDao(Connection, SchemaName)).SelectRandom(); } public IList<Order> GetRandomOrders(int numRecords) { return (new OrderDao(Connection, SchemaName)).SelectRandom(numRecords); } public OrderDetail GetRandomOrderDetail() { return (new OrderDetailDao(Connection, SchemaName)).SelectRandom(); } public IList<OrderDetail> GetRandomOrderDetails(int numRecord) { return (new OrderDetailDao(Connection, SchemaName)).SelectRandom(numRecord); } public long GetAddressCount() { return (new AddressDao(Connection, SchemaName)).SelectCount(); } public long GetSupplierCount() { return (new SupplierDao(Connection, SchemaName)).SelectCount(); } public long GetCategoryCount() { return (new CategoryDao(Connection, SchemaName)).SelectCount(); } public long GetProductCount() { return (new ProductDao(Connection, SchemaName)).SelectCount(); } public long GetCustomerCount() { return (new CustomerDao(Connection, SchemaName)).SelectCount(); } public long GetOrderCount() { return (new OrderDao(Connection, SchemaName)).SelectCount(); } public long GetOrderDetailCount() { return (new OrderDetailDao(Connection, SchemaName)).SelectCount(); } public int CreateView(Relation relation) { return GFXDDbi.Create(Connection, DbDefault.GetCreateViewStatement(relation)); } public DataTable GetView(String viewName) { return (DataTable)GFXDDbi.Select(Connection, "SElECT * FROM " + viewName, QueryTypes.DATATABLE); } public int DropView(String viewName) { return GFXDDbi.Drop(Connection, "DROP VIEW " + viewName); } } }
// File generated from our OpenAPI spec namespace Stripe { using Newtonsoft.Json; public class DisputeEvidenceOptions : INestedOptions { /// <summary> /// Any server or activity logs showing proof that the customer accessed or downloaded the /// purchased digital product. This information should include IP addresses, corresponding /// timestamps, and any detailed recorded activity. Has a maximum character count of 20,000. /// </summary> [JsonProperty("access_activity_log")] public string AccessActivityLog { get; set; } /// <summary> /// The billing address provided by the customer. /// </summary> [JsonProperty("billing_address")] public string BillingAddress { get; set; } /// <summary> /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Your /// subscription cancellation policy, as shown to the customer. /// </summary> [JsonProperty("cancellation_policy")] public string CancellationPolicy { get; set; } /// <summary> /// An explanation of how and when the customer was shown your refund policy prior to /// purchase. Has a maximum character count of 20,000. /// </summary> [JsonProperty("cancellation_policy_disclosure")] public string CancellationPolicyDisclosure { get; set; } /// <summary> /// A justification for why the customer's subscription was not canceled. Has a maximum /// character count of 20,000. /// </summary> [JsonProperty("cancellation_rebuttal")] public string CancellationRebuttal { get; set; } /// <summary> /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Any /// communication with the customer that you feel is relevant to your case. Examples include /// emails proving that the customer received the product or service, or demonstrating their /// use of or satisfaction with the product or service. /// </summary> [JsonProperty("customer_communication")] public string CustomerCommunication { get; set; } /// <summary> /// The email address of the customer. /// </summary> [JsonProperty("customer_email_address")] public string CustomerEmailAddress { get; set; } /// <summary> /// The name of the customer. /// </summary> [JsonProperty("customer_name")] public string CustomerName { get; set; } /// <summary> /// The IP address that the customer used when making the purchase. /// </summary> [JsonProperty("customer_purchase_ip")] public string CustomerPurchaseIp { get; set; } /// <summary> /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) A /// relevant document or contract showing the customer's signature. /// </summary> [JsonProperty("customer_signature")] public string CustomerSignature { get; set; } /// <summary> /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) /// Documentation for the prior charge that can uniquely identify the charge, such as a /// receipt, shipping label, work order, etc. This document should be paired with a similar /// document from the disputed payment that proves the two payments are separate. /// </summary> [JsonProperty("duplicate_charge_documentation")] public string DuplicateChargeDocumentation { get; set; } /// <summary> /// An explanation of the difference between the disputed charge versus the prior charge /// that appears to be a duplicate. Has a maximum character count of 20,000. /// </summary> [JsonProperty("duplicate_charge_explanation")] public string DuplicateChargeExplanation { get; set; } /// <summary> /// The Stripe ID for the prior charge which appears to be a duplicate of the disputed /// charge. /// </summary> [JsonProperty("duplicate_charge_id")] public string DuplicateChargeId { get; set; } /// <summary> /// A description of the product or service that was sold. Has a maximum character count of /// 20,000. /// </summary> [JsonProperty("product_description")] public string ProductDescription { get; set; } /// <summary> /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Any /// receipt or message sent to the customer notifying them of the charge. /// </summary> [JsonProperty("receipt")] public string Receipt { get; set; } /// <summary> /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Your /// refund policy, as shown to the customer. /// </summary> [JsonProperty("refund_policy")] public string RefundPolicy { get; set; } /// <summary> /// Documentation demonstrating that the customer was shown your refund policy prior to /// purchase. Has a maximum character count of 20,000. /// </summary> [JsonProperty("refund_policy_disclosure")] public string RefundPolicyDisclosure { get; set; } /// <summary> /// A justification for why the customer is not entitled to a refund. Has a maximum /// character count of 20,000. /// </summary> [JsonProperty("refund_refusal_explanation")] public string RefundRefusalExplanation { get; set; } /// <summary> /// The date on which the customer received or began receiving the purchased service, in a /// clear human-readable format. /// </summary> [JsonProperty("service_date")] public string ServiceDate { get; set; } /// <summary> /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) /// Documentation showing proof that a service was provided to the customer. This could /// include a copy of a signed contract, work order, or other form of written agreement. /// </summary> [JsonProperty("service_documentation")] public string ServiceDocumentation { get; set; } /// <summary> /// The address to which a physical product was shipped. You should try to include as /// complete address information as possible. /// </summary> [JsonProperty("shipping_address")] public string ShippingAddress { get; set; } /// <summary> /// The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. If /// multiple carriers were used for this purchase, please separate them with commas. /// </summary> [JsonProperty("shipping_carrier")] public string ShippingCarrier { get; set; } /// <summary> /// The date on which a physical product began its route to the shipping address, in a clear /// human-readable format. /// </summary> [JsonProperty("shipping_date")] public string ShippingDate { get; set; } /// <summary> /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) /// Documentation showing proof that a product was shipped to the customer at the same /// address the customer provided to you. This could include a copy of the shipment receipt, /// shipping label, etc. It should show the customer's full shipping address, if possible. /// </summary> [JsonProperty("shipping_documentation")] public string ShippingDocumentation { get; set; } /// <summary> /// The tracking number for a physical product, obtained from the delivery service. If /// multiple tracking numbers were generated for this purchase, please separate them with /// commas. /// </summary> [JsonProperty("shipping_tracking_number")] public string ShippingTrackingNumber { get; set; } /// <summary> /// (ID of a <a href="https://stripe.com/docs/guides/file-upload">file upload</a>) Any /// additional evidence or statements. /// </summary> [JsonProperty("uncategorized_file")] public string UncategorizedFile { get; set; } /// <summary> /// Any additional evidence or statements. Has a maximum character count of 20,000. /// </summary> [JsonProperty("uncategorized_text")] public string UncategorizedText { get; set; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnNino class. /// </summary> [Serializable] public partial class PnNinoCollection : ActiveList<PnNino, PnNinoCollection> { public PnNinoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnNinoCollection</returns> public PnNinoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnNino o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_nino table. /// </summary> [Serializable] public partial class PnNino : ActiveRecord<PnNino>, IActiveRecord { #region .ctors and Default Settings public PnNino() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnNino(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnNino(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnNino(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_nino", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdNino = new TableSchema.TableColumn(schema); colvarIdNino.ColumnName = "id_nino"; colvarIdNino.DataType = DbType.Int32; colvarIdNino.MaxLength = 0; colvarIdNino.AutoIncrement = true; colvarIdNino.IsNullable = false; colvarIdNino.IsPrimaryKey = true; colvarIdNino.IsForeignKey = false; colvarIdNino.IsReadOnly = false; colvarIdNino.DefaultSetting = @""; colvarIdNino.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdNino); TableSchema.TableColumn colvarCuie = new TableSchema.TableColumn(schema); colvarCuie.ColumnName = "cuie"; colvarCuie.DataType = DbType.AnsiString; colvarCuie.MaxLength = 10; colvarCuie.AutoIncrement = false; colvarCuie.IsNullable = false; colvarCuie.IsPrimaryKey = false; colvarCuie.IsForeignKey = false; colvarCuie.IsReadOnly = false; colvarCuie.DefaultSetting = @""; colvarCuie.ForeignKeyTableName = ""; schema.Columns.Add(colvarCuie); TableSchema.TableColumn colvarClave = new TableSchema.TableColumn(schema); colvarClave.ColumnName = "clave"; colvarClave.DataType = DbType.AnsiString; colvarClave.MaxLength = 50; colvarClave.AutoIncrement = false; colvarClave.IsNullable = true; colvarClave.IsPrimaryKey = false; colvarClave.IsForeignKey = false; colvarClave.IsReadOnly = false; colvarClave.DefaultSetting = @""; colvarClave.ForeignKeyTableName = ""; schema.Columns.Add(colvarClave); TableSchema.TableColumn colvarClaseDoc = new TableSchema.TableColumn(schema); colvarClaseDoc.ColumnName = "clase_doc"; colvarClaseDoc.DataType = DbType.AnsiString; colvarClaseDoc.MaxLength = -1; colvarClaseDoc.AutoIncrement = false; colvarClaseDoc.IsNullable = true; colvarClaseDoc.IsPrimaryKey = false; colvarClaseDoc.IsForeignKey = false; colvarClaseDoc.IsReadOnly = false; colvarClaseDoc.DefaultSetting = @""; colvarClaseDoc.ForeignKeyTableName = ""; schema.Columns.Add(colvarClaseDoc); TableSchema.TableColumn colvarTipoDoc = new TableSchema.TableColumn(schema); colvarTipoDoc.ColumnName = "tipo_doc"; colvarTipoDoc.DataType = DbType.AnsiString; colvarTipoDoc.MaxLength = -1; colvarTipoDoc.AutoIncrement = false; colvarTipoDoc.IsNullable = true; colvarTipoDoc.IsPrimaryKey = false; colvarTipoDoc.IsForeignKey = false; colvarTipoDoc.IsReadOnly = false; colvarTipoDoc.DefaultSetting = @""; colvarTipoDoc.ForeignKeyTableName = ""; schema.Columns.Add(colvarTipoDoc); TableSchema.TableColumn colvarNumDoc = new TableSchema.TableColumn(schema); colvarNumDoc.ColumnName = "num_doc"; colvarNumDoc.DataType = DbType.Decimal; colvarNumDoc.MaxLength = 0; colvarNumDoc.AutoIncrement = false; colvarNumDoc.IsNullable = true; colvarNumDoc.IsPrimaryKey = false; colvarNumDoc.IsForeignKey = false; colvarNumDoc.IsReadOnly = false; colvarNumDoc.DefaultSetting = @""; colvarNumDoc.ForeignKeyTableName = ""; schema.Columns.Add(colvarNumDoc); TableSchema.TableColumn colvarApellido = new TableSchema.TableColumn(schema); colvarApellido.ColumnName = "apellido"; colvarApellido.DataType = DbType.AnsiString; colvarApellido.MaxLength = -1; colvarApellido.AutoIncrement = false; colvarApellido.IsNullable = true; colvarApellido.IsPrimaryKey = false; colvarApellido.IsForeignKey = false; colvarApellido.IsReadOnly = false; colvarApellido.DefaultSetting = @""; colvarApellido.ForeignKeyTableName = ""; schema.Columns.Add(colvarApellido); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = -1; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = true; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarFechaNac = new TableSchema.TableColumn(schema); colvarFechaNac.ColumnName = "fecha_nac"; colvarFechaNac.DataType = DbType.DateTime; colvarFechaNac.MaxLength = 0; colvarFechaNac.AutoIncrement = false; colvarFechaNac.IsNullable = true; colvarFechaNac.IsPrimaryKey = false; colvarFechaNac.IsForeignKey = false; colvarFechaNac.IsReadOnly = false; colvarFechaNac.DefaultSetting = @""; colvarFechaNac.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaNac); TableSchema.TableColumn colvarFechaControl = new TableSchema.TableColumn(schema); colvarFechaControl.ColumnName = "fecha_control"; colvarFechaControl.DataType = DbType.DateTime; colvarFechaControl.MaxLength = 0; colvarFechaControl.AutoIncrement = false; colvarFechaControl.IsNullable = true; colvarFechaControl.IsPrimaryKey = false; colvarFechaControl.IsForeignKey = false; colvarFechaControl.IsReadOnly = false; colvarFechaControl.DefaultSetting = @""; colvarFechaControl.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaControl); TableSchema.TableColumn colvarPeso = new TableSchema.TableColumn(schema); colvarPeso.ColumnName = "peso"; colvarPeso.DataType = DbType.Decimal; colvarPeso.MaxLength = 0; colvarPeso.AutoIncrement = false; colvarPeso.IsNullable = true; colvarPeso.IsPrimaryKey = false; colvarPeso.IsForeignKey = false; colvarPeso.IsReadOnly = false; colvarPeso.DefaultSetting = @""; colvarPeso.ForeignKeyTableName = ""; schema.Columns.Add(colvarPeso); TableSchema.TableColumn colvarTalla = new TableSchema.TableColumn(schema); colvarTalla.ColumnName = "talla"; colvarTalla.DataType = DbType.Decimal; colvarTalla.MaxLength = 0; colvarTalla.AutoIncrement = false; colvarTalla.IsNullable = true; colvarTalla.IsPrimaryKey = false; colvarTalla.IsForeignKey = false; colvarTalla.IsReadOnly = false; colvarTalla.DefaultSetting = @""; colvarTalla.ForeignKeyTableName = ""; schema.Columns.Add(colvarTalla); TableSchema.TableColumn colvarPerimCefalico = new TableSchema.TableColumn(schema); colvarPerimCefalico.ColumnName = "perim_cefalico"; colvarPerimCefalico.DataType = DbType.Decimal; colvarPerimCefalico.MaxLength = 0; colvarPerimCefalico.AutoIncrement = false; colvarPerimCefalico.IsNullable = true; colvarPerimCefalico.IsPrimaryKey = false; colvarPerimCefalico.IsForeignKey = false; colvarPerimCefalico.IsReadOnly = false; colvarPerimCefalico.DefaultSetting = @""; colvarPerimCefalico.ForeignKeyTableName = ""; schema.Columns.Add(colvarPerimCefalico); TableSchema.TableColumn colvarPercenPesoEdad = new TableSchema.TableColumn(schema); colvarPercenPesoEdad.ColumnName = "percen_peso_edad"; colvarPercenPesoEdad.DataType = DbType.AnsiString; colvarPercenPesoEdad.MaxLength = -1; colvarPercenPesoEdad.AutoIncrement = false; colvarPercenPesoEdad.IsNullable = true; colvarPercenPesoEdad.IsPrimaryKey = false; colvarPercenPesoEdad.IsForeignKey = false; colvarPercenPesoEdad.IsReadOnly = false; colvarPercenPesoEdad.DefaultSetting = @""; colvarPercenPesoEdad.ForeignKeyTableName = ""; schema.Columns.Add(colvarPercenPesoEdad); TableSchema.TableColumn colvarPercenTallaEdad = new TableSchema.TableColumn(schema); colvarPercenTallaEdad.ColumnName = "percen_talla_edad"; colvarPercenTallaEdad.DataType = DbType.AnsiString; colvarPercenTallaEdad.MaxLength = -1; colvarPercenTallaEdad.AutoIncrement = false; colvarPercenTallaEdad.IsNullable = true; colvarPercenTallaEdad.IsPrimaryKey = false; colvarPercenTallaEdad.IsForeignKey = false; colvarPercenTallaEdad.IsReadOnly = false; colvarPercenTallaEdad.DefaultSetting = @""; colvarPercenTallaEdad.ForeignKeyTableName = ""; schema.Columns.Add(colvarPercenTallaEdad); TableSchema.TableColumn colvarPercenPerimCefaliEdad = new TableSchema.TableColumn(schema); colvarPercenPerimCefaliEdad.ColumnName = "percen_perim_cefali_edad"; colvarPercenPerimCefaliEdad.DataType = DbType.AnsiString; colvarPercenPerimCefaliEdad.MaxLength = -1; colvarPercenPerimCefaliEdad.AutoIncrement = false; colvarPercenPerimCefaliEdad.IsNullable = true; colvarPercenPerimCefaliEdad.IsPrimaryKey = false; colvarPercenPerimCefaliEdad.IsForeignKey = false; colvarPercenPerimCefaliEdad.IsReadOnly = false; colvarPercenPerimCefaliEdad.DefaultSetting = @""; colvarPercenPerimCefaliEdad.ForeignKeyTableName = ""; schema.Columns.Add(colvarPercenPerimCefaliEdad); TableSchema.TableColumn colvarPercenPesoTalla = new TableSchema.TableColumn(schema); colvarPercenPesoTalla.ColumnName = "percen_peso_talla"; colvarPercenPesoTalla.DataType = DbType.AnsiString; colvarPercenPesoTalla.MaxLength = -1; colvarPercenPesoTalla.AutoIncrement = false; colvarPercenPesoTalla.IsNullable = true; colvarPercenPesoTalla.IsPrimaryKey = false; colvarPercenPesoTalla.IsForeignKey = false; colvarPercenPesoTalla.IsReadOnly = false; colvarPercenPesoTalla.DefaultSetting = @""; colvarPercenPesoTalla.ForeignKeyTableName = ""; schema.Columns.Add(colvarPercenPesoTalla); TableSchema.TableColumn colvarTripleViral = new TableSchema.TableColumn(schema); colvarTripleViral.ColumnName = "triple_viral"; colvarTripleViral.DataType = DbType.DateTime; colvarTripleViral.MaxLength = 0; colvarTripleViral.AutoIncrement = false; colvarTripleViral.IsNullable = true; colvarTripleViral.IsPrimaryKey = false; colvarTripleViral.IsForeignKey = false; colvarTripleViral.IsReadOnly = false; colvarTripleViral.DefaultSetting = @""; colvarTripleViral.ForeignKeyTableName = ""; schema.Columns.Add(colvarTripleViral); TableSchema.TableColumn colvarNinoEdad = new TableSchema.TableColumn(schema); colvarNinoEdad.ColumnName = "nino_edad"; colvarNinoEdad.DataType = DbType.Int32; colvarNinoEdad.MaxLength = 0; colvarNinoEdad.AutoIncrement = false; colvarNinoEdad.IsNullable = true; colvarNinoEdad.IsPrimaryKey = false; colvarNinoEdad.IsForeignKey = false; colvarNinoEdad.IsReadOnly = false; colvarNinoEdad.DefaultSetting = @""; colvarNinoEdad.ForeignKeyTableName = ""; schema.Columns.Add(colvarNinoEdad); TableSchema.TableColumn colvarObservaciones = new TableSchema.TableColumn(schema); colvarObservaciones.ColumnName = "observaciones"; colvarObservaciones.DataType = DbType.AnsiString; colvarObservaciones.MaxLength = -1; colvarObservaciones.AutoIncrement = false; colvarObservaciones.IsNullable = true; colvarObservaciones.IsPrimaryKey = false; colvarObservaciones.IsForeignKey = false; colvarObservaciones.IsReadOnly = false; colvarObservaciones.DefaultSetting = @""; colvarObservaciones.ForeignKeyTableName = ""; schema.Columns.Add(colvarObservaciones); TableSchema.TableColumn colvarFechaCarga = new TableSchema.TableColumn(schema); colvarFechaCarga.ColumnName = "fecha_carga"; colvarFechaCarga.DataType = DbType.DateTime; colvarFechaCarga.MaxLength = 0; colvarFechaCarga.AutoIncrement = false; colvarFechaCarga.IsNullable = true; colvarFechaCarga.IsPrimaryKey = false; colvarFechaCarga.IsForeignKey = false; colvarFechaCarga.IsReadOnly = false; colvarFechaCarga.DefaultSetting = @""; colvarFechaCarga.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaCarga); TableSchema.TableColumn colvarUsuario = new TableSchema.TableColumn(schema); colvarUsuario.ColumnName = "usuario"; colvarUsuario.DataType = DbType.AnsiString; colvarUsuario.MaxLength = -1; colvarUsuario.AutoIncrement = false; colvarUsuario.IsNullable = true; colvarUsuario.IsPrimaryKey = false; colvarUsuario.IsForeignKey = false; colvarUsuario.IsReadOnly = false; colvarUsuario.DefaultSetting = @""; colvarUsuario.ForeignKeyTableName = ""; schema.Columns.Add(colvarUsuario); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_nino",schema); } } #endregion #region Props [XmlAttribute("IdNino")] [Bindable(true)] public int IdNino { get { return GetColumnValue<int>(Columns.IdNino); } set { SetColumnValue(Columns.IdNino, value); } } [XmlAttribute("Cuie")] [Bindable(true)] public string Cuie { get { return GetColumnValue<string>(Columns.Cuie); } set { SetColumnValue(Columns.Cuie, value); } } [XmlAttribute("Clave")] [Bindable(true)] public string Clave { get { return GetColumnValue<string>(Columns.Clave); } set { SetColumnValue(Columns.Clave, value); } } [XmlAttribute("ClaseDoc")] [Bindable(true)] public string ClaseDoc { get { return GetColumnValue<string>(Columns.ClaseDoc); } set { SetColumnValue(Columns.ClaseDoc, value); } } [XmlAttribute("TipoDoc")] [Bindable(true)] public string TipoDoc { get { return GetColumnValue<string>(Columns.TipoDoc); } set { SetColumnValue(Columns.TipoDoc, value); } } [XmlAttribute("NumDoc")] [Bindable(true)] public decimal? NumDoc { get { return GetColumnValue<decimal?>(Columns.NumDoc); } set { SetColumnValue(Columns.NumDoc, value); } } [XmlAttribute("Apellido")] [Bindable(true)] public string Apellido { get { return GetColumnValue<string>(Columns.Apellido); } set { SetColumnValue(Columns.Apellido, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("FechaNac")] [Bindable(true)] public DateTime? FechaNac { get { return GetColumnValue<DateTime?>(Columns.FechaNac); } set { SetColumnValue(Columns.FechaNac, value); } } [XmlAttribute("FechaControl")] [Bindable(true)] public DateTime? FechaControl { get { return GetColumnValue<DateTime?>(Columns.FechaControl); } set { SetColumnValue(Columns.FechaControl, value); } } [XmlAttribute("Peso")] [Bindable(true)] public decimal? Peso { get { return GetColumnValue<decimal?>(Columns.Peso); } set { SetColumnValue(Columns.Peso, value); } } [XmlAttribute("Talla")] [Bindable(true)] public decimal? Talla { get { return GetColumnValue<decimal?>(Columns.Talla); } set { SetColumnValue(Columns.Talla, value); } } [XmlAttribute("PerimCefalico")] [Bindable(true)] public decimal? PerimCefalico { get { return GetColumnValue<decimal?>(Columns.PerimCefalico); } set { SetColumnValue(Columns.PerimCefalico, value); } } [XmlAttribute("PercenPesoEdad")] [Bindable(true)] public string PercenPesoEdad { get { return GetColumnValue<string>(Columns.PercenPesoEdad); } set { SetColumnValue(Columns.PercenPesoEdad, value); } } [XmlAttribute("PercenTallaEdad")] [Bindable(true)] public string PercenTallaEdad { get { return GetColumnValue<string>(Columns.PercenTallaEdad); } set { SetColumnValue(Columns.PercenTallaEdad, value); } } [XmlAttribute("PercenPerimCefaliEdad")] [Bindable(true)] public string PercenPerimCefaliEdad { get { return GetColumnValue<string>(Columns.PercenPerimCefaliEdad); } set { SetColumnValue(Columns.PercenPerimCefaliEdad, value); } } [XmlAttribute("PercenPesoTalla")] [Bindable(true)] public string PercenPesoTalla { get { return GetColumnValue<string>(Columns.PercenPesoTalla); } set { SetColumnValue(Columns.PercenPesoTalla, value); } } [XmlAttribute("TripleViral")] [Bindable(true)] public DateTime? TripleViral { get { return GetColumnValue<DateTime?>(Columns.TripleViral); } set { SetColumnValue(Columns.TripleViral, value); } } [XmlAttribute("NinoEdad")] [Bindable(true)] public int? NinoEdad { get { return GetColumnValue<int?>(Columns.NinoEdad); } set { SetColumnValue(Columns.NinoEdad, value); } } [XmlAttribute("Observaciones")] [Bindable(true)] public string Observaciones { get { return GetColumnValue<string>(Columns.Observaciones); } set { SetColumnValue(Columns.Observaciones, value); } } [XmlAttribute("FechaCarga")] [Bindable(true)] public DateTime? FechaCarga { get { return GetColumnValue<DateTime?>(Columns.FechaCarga); } set { SetColumnValue(Columns.FechaCarga, value); } } [XmlAttribute("Usuario")] [Bindable(true)] public string Usuario { get { return GetColumnValue<string>(Columns.Usuario); } set { SetColumnValue(Columns.Usuario, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varCuie,string varClave,string varClaseDoc,string varTipoDoc,decimal? varNumDoc,string varApellido,string varNombre,DateTime? varFechaNac,DateTime? varFechaControl,decimal? varPeso,decimal? varTalla,decimal? varPerimCefalico,string varPercenPesoEdad,string varPercenTallaEdad,string varPercenPerimCefaliEdad,string varPercenPesoTalla,DateTime? varTripleViral,int? varNinoEdad,string varObservaciones,DateTime? varFechaCarga,string varUsuario) { PnNino item = new PnNino(); item.Cuie = varCuie; item.Clave = varClave; item.ClaseDoc = varClaseDoc; item.TipoDoc = varTipoDoc; item.NumDoc = varNumDoc; item.Apellido = varApellido; item.Nombre = varNombre; item.FechaNac = varFechaNac; item.FechaControl = varFechaControl; item.Peso = varPeso; item.Talla = varTalla; item.PerimCefalico = varPerimCefalico; item.PercenPesoEdad = varPercenPesoEdad; item.PercenTallaEdad = varPercenTallaEdad; item.PercenPerimCefaliEdad = varPercenPerimCefaliEdad; item.PercenPesoTalla = varPercenPesoTalla; item.TripleViral = varTripleViral; item.NinoEdad = varNinoEdad; item.Observaciones = varObservaciones; item.FechaCarga = varFechaCarga; item.Usuario = varUsuario; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdNino,string varCuie,string varClave,string varClaseDoc,string varTipoDoc,decimal? varNumDoc,string varApellido,string varNombre,DateTime? varFechaNac,DateTime? varFechaControl,decimal? varPeso,decimal? varTalla,decimal? varPerimCefalico,string varPercenPesoEdad,string varPercenTallaEdad,string varPercenPerimCefaliEdad,string varPercenPesoTalla,DateTime? varTripleViral,int? varNinoEdad,string varObservaciones,DateTime? varFechaCarga,string varUsuario) { PnNino item = new PnNino(); item.IdNino = varIdNino; item.Cuie = varCuie; item.Clave = varClave; item.ClaseDoc = varClaseDoc; item.TipoDoc = varTipoDoc; item.NumDoc = varNumDoc; item.Apellido = varApellido; item.Nombre = varNombre; item.FechaNac = varFechaNac; item.FechaControl = varFechaControl; item.Peso = varPeso; item.Talla = varTalla; item.PerimCefalico = varPerimCefalico; item.PercenPesoEdad = varPercenPesoEdad; item.PercenTallaEdad = varPercenTallaEdad; item.PercenPerimCefaliEdad = varPercenPerimCefaliEdad; item.PercenPesoTalla = varPercenPesoTalla; item.TripleViral = varTripleViral; item.NinoEdad = varNinoEdad; item.Observaciones = varObservaciones; item.FechaCarga = varFechaCarga; item.Usuario = varUsuario; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdNinoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CuieColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn ClaveColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn ClaseDocColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn TipoDocColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn NumDocColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn ApellidoColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn FechaNacColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn FechaControlColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn PesoColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn TallaColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn PerimCefalicoColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn PercenPesoEdadColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn PercenTallaEdadColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn PercenPerimCefaliEdadColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn PercenPesoTallaColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn TripleViralColumn { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn NinoEdadColumn { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn ObservacionesColumn { get { return Schema.Columns[19]; } } public static TableSchema.TableColumn FechaCargaColumn { get { return Schema.Columns[20]; } } public static TableSchema.TableColumn UsuarioColumn { get { return Schema.Columns[21]; } } #endregion #region Columns Struct public struct Columns { public static string IdNino = @"id_nino"; public static string Cuie = @"cuie"; public static string Clave = @"clave"; public static string ClaseDoc = @"clase_doc"; public static string TipoDoc = @"tipo_doc"; public static string NumDoc = @"num_doc"; public static string Apellido = @"apellido"; public static string Nombre = @"nombre"; public static string FechaNac = @"fecha_nac"; public static string FechaControl = @"fecha_control"; public static string Peso = @"peso"; public static string Talla = @"talla"; public static string PerimCefalico = @"perim_cefalico"; public static string PercenPesoEdad = @"percen_peso_edad"; public static string PercenTallaEdad = @"percen_talla_edad"; public static string PercenPerimCefaliEdad = @"percen_perim_cefali_edad"; public static string PercenPesoTalla = @"percen_peso_talla"; public static string TripleViral = @"triple_viral"; public static string NinoEdad = @"nino_edad"; public static string Observaciones = @"observaciones"; public static string FechaCarga = @"fecha_carga"; public static string Usuario = @"usuario"; } #endregion #region Update PK Collections #endregion #region Deep Save #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 Xunit; namespace System.IO.Compression.Tests { public partial class ZipFileTest_Invalid : ZipFileTestBase { private static void ConstructorThrows<TException>(Func<ZipArchive> constructor, string Message = "") where TException : Exception { Assert.Throws<TException>(() => { using (ZipArchive archive = constructor()) { } }); } [Fact] public void InvalidInstanceMethods() { using (TempFile testArchive = CreateTempCopyFile(zfile("normal.zip"), GetTestFilePath())) using (ZipArchive archive = ZipFile.Open(testArchive.Path, ZipArchiveMode.Update)) { //non-existent entry Assert.True(null == archive.GetEntry("nonExistentEntry")); //null/empty string Assert.Throws<ArgumentNullException>(() => archive.GetEntry(null)); ZipArchiveEntry entry = archive.GetEntry("first.txt"); //null/empty string Assert.Throws<ArgumentException>(() => archive.CreateEntry("")); Assert.Throws<ArgumentNullException>(() => archive.CreateEntry(null)); } } [Fact] public void InvalidConstructors() { //out of range enum values ConstructorThrows<ArgumentOutOfRangeException>(() => ZipFile.Open("bad file", (ZipArchiveMode)(10))); } [Fact] public void InvalidFiles() { ConstructorThrows<InvalidDataException>(() => ZipFile.OpenRead(bad("EOCDmissing.zip"))); ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("EOCDmissing.zip"), ZipArchiveMode.Update)); ConstructorThrows<InvalidDataException>(() => ZipFile.OpenRead(bad("CDoffsetOutOfBounds.zip"))); ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("CDoffsetOutOfBounds.zip"), ZipArchiveMode.Update)); using (ZipArchive archive = ZipFile.OpenRead(bad("CDoffsetInBoundsWrong.zip"))) { Assert.Throws<InvalidDataException>(() => { var x = archive.Entries; }); } ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("CDoffsetInBoundsWrong.zip"), ZipArchiveMode.Update)); using (ZipArchive archive = ZipFile.OpenRead(bad("numberOfEntriesDifferent.zip"))) { Assert.Throws<InvalidDataException>(() => { var x = archive.Entries; }); } ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("numberOfEntriesDifferent.zip"), ZipArchiveMode.Update)); //read mode on empty file ConstructorThrows<InvalidDataException>(() => new ZipArchive(new MemoryStream())); //offset out of bounds using (ZipArchive archive = ZipFile.OpenRead(bad("localFileOffsetOutOfBounds.zip"))) { ZipArchiveEntry e = archive.Entries[0]; Assert.Throws<InvalidDataException>(() => e.Open()); } ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("localFileOffsetOutOfBounds.zip"), ZipArchiveMode.Update)); //compressed data offset + compressed size out of bounds using (ZipArchive archive = ZipFile.OpenRead(bad("compressedSizeOutOfBounds.zip"))) { ZipArchiveEntry e = archive.Entries[0]; Assert.Throws<InvalidDataException>(() => e.Open()); } ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("compressedSizeOutOfBounds.zip"), ZipArchiveMode.Update)); //signature wrong using (ZipArchive archive = ZipFile.OpenRead(bad("localFileHeaderSignatureWrong.zip"))) { ZipArchiveEntry e = archive.Entries[0]; Assert.Throws<InvalidDataException>(() => e.Open()); } ConstructorThrows<InvalidDataException>(() => ZipFile.Open(bad("localFileHeaderSignatureWrong.zip"), ZipArchiveMode.Update)); } [Theory] [InlineData("LZMA.zip", true)] [InlineData("invalidDeflate.zip", false)] public void UnsupportedCompressionRoutine(string zipName, Boolean throwsOnOpen) { string filename = bad(zipName); using (ZipArchive archive = ZipFile.OpenRead(filename)) { ZipArchiveEntry e = archive.Entries[0]; if (throwsOnOpen) { Assert.Throws<InvalidDataException>(() => e.Open()); } else { using (Stream s = e.Open()) { Assert.Throws<InvalidDataException>(() => s.ReadByte()); } } } using (TempFile updatedCopy = CreateTempCopyFile(filename, GetTestFilePath())) { string name; Int64 length, compressedLength; DateTimeOffset lastWriteTime; using (ZipArchive archive = ZipFile.Open(updatedCopy.Path, ZipArchiveMode.Update)) { ZipArchiveEntry e = archive.Entries[0]; name = e.FullName; lastWriteTime = e.LastWriteTime; length = e.Length; compressedLength = e.CompressedLength; Assert.Throws<InvalidDataException>(() => e.Open()); } //make sure that update mode preserves that unreadable file using (ZipArchive archive = ZipFile.Open(updatedCopy.Path, ZipArchiveMode.Update)) { ZipArchiveEntry e = archive.Entries[0]; Assert.Equal(name, e.FullName); Assert.Equal(lastWriteTime, e.LastWriteTime); Assert.Equal(length, e.Length); Assert.Equal(compressedLength, e.CompressedLength); Assert.Throws<InvalidDataException>(() => e.Open()); } } } [Fact] public void InvalidDates() { using (ZipArchive archive = ZipFile.OpenRead(bad("invaliddate.zip"))) { Assert.Equal(new DateTime(1980, 1, 1, 0, 0, 0), archive.Entries[0].LastWriteTime.DateTime); } FileInfo fileWithBadDate = new FileInfo(GetTestFilePath()); fileWithBadDate.Create().Dispose(); fileWithBadDate.LastWriteTimeUtc = new DateTime(1970, 1, 1, 1, 1, 1); string archivePath = GetTestFilePath(); using (FileStream output = File.Open(archivePath, FileMode.Create)) using (ZipArchive archive = new ZipArchive(output, ZipArchiveMode.Create)) { archive.CreateEntryFromFile(fileWithBadDate.FullName, "SomeEntryName"); } using (ZipArchive archive = ZipFile.OpenRead(archivePath)) { Assert.Equal(new DateTime(1980, 1, 1, 0, 0, 0), archive.Entries[0].LastWriteTime.DateTime); } } [Fact] public void FilesOutsideDirectory() { string archivePath = GetTestFilePath(); using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create)) using (StreamWriter writer = new StreamWriter(archive.CreateEntry(Path.Combine("..", "entry1"), CompressionLevel.Optimal).Open())) { writer.Write("This is a test."); } Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(archivePath, GetTestFilePath())); } [Fact] public void DirectoryEntryWithData() { string archivePath = GetTestFilePath(); using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create)) using (StreamWriter writer = new StreamWriter(archive.CreateEntry("testdir" + Path.DirectorySeparatorChar, CompressionLevel.Optimal).Open())) { writer.Write("This is a test."); } Assert.Throws<IOException>(() => ZipFile.ExtractToDirectory(archivePath, GetTestFilePath())); } /// <summary> /// This test ensures that a zipfile with path names that are invalid to this OS will throw errors /// when an attempt is made to extract them. /// </summary> [Theory] [InlineData("NullCharFileName_FromWindows")] [InlineData("NullCharFileName_FromUnix")] [PlatformSpecific(PlatformID.AnyUnix)] public void Unix_ZipWithInvalidFileNames_ThrowsArgumentException(string zipName) { Assert.Throws<ArgumentException>(() => ZipFile.ExtractToDirectory(compat(zipName) + ".zip", GetTestFilePath())); } [Theory] [InlineData("backslashes_FromUnix", "aa\\bb\\cc\\dd")] [InlineData("backslashes_FromWindows", "aa\\bb\\cc\\dd")] [InlineData("WindowsInvalid_FromUnix", "aa<b>d")] [InlineData("WindowsInvalid_FromWindows", "aa<b>d")] [PlatformSpecific(PlatformID.AnyUnix)] public void Unix_ZipWithOSSpecificFileNames(string zipName, string fileName) { string tempDir = GetTestFilePath(); ZipFile.ExtractToDirectory(compat(zipName) + ".zip", tempDir); string[] results = Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories); Assert.Equal(1, results.Length); Assert.Equal(fileName, Path.GetFileName(results[0])); } /// <summary> /// This test ensures that a zipfile with path names that are invalid to this OS will throw errors /// when an attempt is made to extract them. /// </summary> [Theory] [InlineData("WindowsInvalid_FromUnix")] [InlineData("WindowsInvalid_FromWindows")] [InlineData("NullCharFileName_FromWindows")] [InlineData("NullCharFileName_FromUnix")] [PlatformSpecific(PlatformID.Windows)] public void Windows_ZipWithInvalidFileNames_ThrowsArgumentException(string zipName) { Assert.Throws<ArgumentException>(() => ZipFile.ExtractToDirectory(compat(zipName) + ".zip", GetTestFilePath())); } [Theory] [InlineData("backslashes_FromUnix", "dd")] [InlineData("backslashes_FromWindows", "dd")] [PlatformSpecific(PlatformID.Windows)] public void Windows_ZipWithOSSpecificFileNames(string zipName, string fileName) { string tempDir = GetTestFilePath(); ZipFile.ExtractToDirectory(compat(zipName) + ".zip", tempDir); string[] results = Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories); Assert.Equal(1, results.Length); Assert.Equal(fileName, Path.GetFileName(results[0])); } } }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using Microsoft.Win32; using System.IO; using System.Reflection; using Alachisoft.NCache.Common; using log4net.Appender; using System.Diagnostics; using System.Text; using log4net.Filter; namespace Alachisoft.NCache.Common.Util { /// <summary> /// Summary description for Log. /// </summary> public sealed class Log4net { static string _cacheserver="NCache"; /// <summary>Configuration file folder name</summary> private const string DIRNAME = @"log-files"; private static byte[] log4netXML = Encoding.ASCII.GetBytes("<?xml version=\"1.0\"?> <configuration> <configSections> <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, Culture = neutral, PublicKeyToken=1b44e1d426115821 \"/> </configSections> <log4net> </log4net> </configuration>"); public static log4net.Core.Level criticalInfo = new log4net.Core.Level(5000000, "CRIT", "INFO"); /// <summary>Path of the configuration folder.</summary> static private string s_configDir = ""; static private string path = ""; static object lockObj = new Object(); /// <summary> /// Scans the registry and locates the configuration file. /// </summary> static Log4net() { s_configDir = AppUtil.InstallDir; try { s_configDir = System.IO.Path.Combine(s_configDir, DIRNAME); } catch { } if (s_configDir == null && s_configDir.Length > 0) { s_configDir = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName; s_configDir = System.IO.Path.Combine(s_configDir, DIRNAME); } } internal static string GetLogPath() { if (path.Length < 1) { path = s_configDir; } try { log4net.LogManager.GetRepository().LevelMap.Add(criticalInfo); if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); } catch (Exception e) { AppUtil.LogEvent(_cacheserver, e.ToString(), System.Diagnostics.EventLogEntryType.Error, EventCategories.Error, EventID.GeneralError); } return path; } /// <summary> /// Start the cache logging functionality. /// </summary> public static string Initialize(IDictionary properties, string partitionID, string cacheName) { return Initialize(properties, partitionID, cacheName, false, false); } /// <summary> /// Start the cache logging functionality. /// </summary> public static string Initialize(IDictionary properties, string partitionID, string cacheName, bool isStartedAsMirror, bool inproc) { lock (lockObj) { MemoryStream logStream = new MemoryStream(log4netXML); log4net.Config.XmlConfigurator.Configure(logStream); string logger_name = ""; try { logger_name = cacheName; if (partitionID != null && partitionID.Length > 0) logger_name += "-" + partitionID; if (isStartedAsMirror) logger_name += "-" + "replica"; if (inproc && !isStartedAsMirror) logger_name += "." + System.Diagnostics.Process.GetCurrentProcess().Id; //Add loggerName to be accessed w.r.t the cache Name if (!LoggingInformation.cacheLogger.Contains(logger_name)) { LoggingInformation.cacheLogger.Add(logger_name, logger_name); string LogExceptions = ""; if (logger_name == "LogExceptions") LogExceptions = "\\LogExceptions"; string fileName = GetLogPath() + LogExceptions + "\\" + logger_name + "_" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + ".txt"; ; AddAppender(logger_name, CreateBufferAppender(logger_name, fileName)); if (properties != null) { if (properties.Contains("trace-errors")) { if (Convert.ToBoolean(properties["trace-errors"])) { SetLevel(logger_name, "ERROR"); } } if (properties.Contains("trace-notices")) { if (Convert.ToBoolean(properties["trace-notices"])) { SetLevel(logger_name, "INFO"); } } if (properties.Contains("trace-warnings")) if (Convert.ToBoolean(properties["trace-warnings"])) { SetLevel(logger_name, "WARN"); } if (properties.Contains("trace-debug")) if (Convert.ToBoolean(properties["trace-debug"])) { SetLevel(logger_name, "ALL"); } if (properties.Contains("enabled")) { if (!Convert.ToBoolean(properties["trace-errors"])) { SetLevel(logger_name, "OFF"); } } } else { SetLevel(logger_name, "WARN"); } return logger_name; } else { if (properties != null) { if (properties.Contains("trace-errors")) { if (Convert.ToBoolean(properties["trace-errors"])) { SetLevel(logger_name, "ERROR"); } } if (properties.Contains("trace-notices")) { if (Convert.ToBoolean(properties["trace-notices"])) { SetLevel(logger_name, "INFO"); } } if (properties.Contains("trace-warnings")) if (Convert.ToBoolean(properties["trace-warnings"])) { SetLevel(logger_name, "WARN"); } if (properties.Contains("trace-debug")) if (Convert.ToBoolean(properties["trace-debug"])) { SetLevel(logger_name, "ALL"); } if (properties.Contains("enabled")) { if (!Convert.ToBoolean(properties["trace-errors"])) { SetLevel(logger_name, "OFF"); } } } else { SetLevel(logger_name, "WARN"); } return logger_name; } } catch (Exception e) { AppUtil.LogEvent(_cacheserver, "Failed to open log. " + e, System.Diagnostics.EventLogEntryType.Error, EventCategories.Error, EventID.GeneralError); } return logger_name; } } /// <summary> /// intitializes Known name based log files (will not log License Logs at service Startup /// </summary> /// <param name="loggerName">Enum of Known loggerNames</param> public static void Initialize(NCacheLog.LoggerNames loggerName) { if (loggerName != NCacheLog.LoggerNames.Licence) { Initialize(loggerName, null); } } /// <summary> /// intitializes Known name based log files /// </summary> /// <param name="loggerName">Enum of Known loggerNames</param> /// <param name="cacheName">cacheName use the other override</param> public static void Initialize(NCacheLog.LoggerNames loggerNameEnum, string cacheName) { lock (lockObj) { MemoryStream logStream = new MemoryStream(log4netXML); log4net.Config.XmlConfigurator.Configure(logStream); string logName = loggerNameEnum.ToString(); string filename = logName; if (loggerNameEnum == NCacheLog.LoggerNames.ClientLogs && (cacheName != null && cacheName.Length > 0)) { filename = filename + "." + cacheName + "." + System.Diagnostics.Process.GetCurrentProcess().Id; // changing the name here will invalidate static log checks automatically since LoggerName == ClientLogs logName = cacheName + System.Diagnostics.Process.GetCurrentProcess().Id; } else { if (cacheName != null && cacheName.Length > 0) filename = cacheName; } //If Logger is already present, can either be a cache or Client if (LoggingInformation.GetLoggerName(logName) != null) { if (loggerNameEnum == NCacheLog.LoggerNames.ClientLogs) return; // clientLogs alread initiated else { if (LoggingInformation.GetStaticLoggerName(logName) != null) return; // Log already initiated else { logName = logName + DateTime.Now; } } } else { if (loggerNameEnum != NCacheLog.LoggerNames.ClientLogs) { if (LoggingInformation.GetStaticLoggerName(logName) != null) return; // Log already initiated else { logName = logName + DateTime.Now; } } } filename = filename + "." + Environment.MachineName.ToLower() + "." + DateTime.Now.ToString("dd-MM-yy HH-mm-ss") + @".logs.txt"; string filepath = ""; if (!DirectoryUtil.SearchGlobalDirectory("log-files", false, out filepath)) { try { DirectoryUtil.SearchLocalDirectory("log-files", true, out filepath); } catch (Exception ex) { throw new Exception("Unable to initialize the log file", ex); } } try { filepath = Path.Combine(filepath, loggerNameEnum.ToString()); if (!Directory.Exists(filepath)) Directory.CreateDirectory(filepath); filepath = Path.Combine(filepath, filename); LoggingInformation.cacheLogger.Add(logName, logName); if (loggerNameEnum != NCacheLog.LoggerNames.ClientLogs) { LoggingInformation.staticCacheLogger.Add(loggerNameEnum.ToString(), logName); } SetLevel(logName, NCacheLog.Level.OFF.ToString()); AddAppender(logName, CreateBufferAppender(logName, filepath)); } catch (Exception) { throw; } } } /// <summary> /// Stop the cache logging functionality. /// </summary> public static void Close(string cacheName) { lock (lockObj) { if (cacheName != null) if (cacheName.Length != 0) { string temploggerName = LoggingInformation.GetLoggerName(cacheName); //called at remove cache if (temploggerName != null) { SetLevel(temploggerName, "OFF"); if (temploggerName != null) { log4net.ILog log = log4net.LogManager.GetLogger(temploggerName); log4net.Core.IAppenderAttachable closingAppenders = (log4net.Core.IAppenderAttachable)log.Logger; AppenderCollection collection = closingAppenders.Appenders; for (int i = 0; i < collection.Count; i++) { if (collection[i] is BufferingForwardingAppender) { //This FLUSH and close the current appenders along with all of its children appenders ((BufferingForwardingAppender)collection[i]).Close(); } } RemoveAllAppender(temploggerName); LoggingInformation.cacheLogger.Remove(cacheName); } } } } } /// <summary> /// Creates Buffer Appender, Responsible for storing all logging events in memory buffer /// and writing them down when by passing the logging events on to the file appender it holds /// when its buffer becomes full /// Can also be made a lossy logger which writes only writes down to a file when a specific crieteria/condition is met /// </summary> /// <param name="cacheName">CacheName used to name the Buffer Appender</param> /// <param name="fileName">File name to log into</param> /// <returns>Returns the created Appender</returns> private static log4net.Appender.IAppender CreateBufferAppender(string cacheName, string fileName) { log4net.Appender.BufferingForwardingAppender appender = new BufferingForwardingAppender(); appender.Name = "BufferingForwardingAppender" + cacheName; //Pick from config int bufferSize = NCacheLog.bufferDefaultSize; NCacheLog.ReadConfig(out bufferSize); if (bufferSize == NCacheLog.bufferDefaultSize) NCacheLog.ReadClientConfig(out bufferSize); if (bufferSize < 1) bufferSize = NCacheLog.bufferDefaultSize; appender.BufferSize = bufferSize; //Threshold is maintained by the logger rather than the appenders appender.Threshold = log4net.Core.Level.All; //Adds the appender to which it will pass on all the logging levels upon filling up the buffer appender.AddAppender(CreateRollingFileAppender(cacheName, fileName)); //necessary to apply the appender property changes appender.ActivateOptions(); return appender; } /// <summary> /// Create File appender, This appender is responsible to write stream of data when invoked, in /// our case, this appender is handeled my the Bufferappender /// </summary> /// <param name="cacheName">Name of the file appender</param> /// <param name="fileName">Filename to which is to write logs</param> /// <returns>returns the created appender</returns> private static log4net.Appender.IAppender CreateRollingFileAppender(string cacheName, string fileName) { log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender(); appender.Name = "RollingFileAppender" + cacheName; appender.File = fileName; //doesnt matter since all files are created with a new name appender.AppendToFile = false; appender.RollingStyle = RollingFileAppender.RollingMode.Size; appender.MaximumFileSize = "5MB"; appender.MaxSizeRollBackups = -1; //Threshold is maintained by the logger rather than the appenders appender.Threshold = log4net.Core.Level.All; log4net.Layout.PatternLayout layout = new log4net.Layout.PatternLayout(); layout.ConversionPattern = "%-27date{ISO8601}" + "\t%-45.42appdomain" + "\t%-35logger" + "\t%-42thread" + "\t%-9level" + "\t%message" + "%newline"; layout.Header = "TIMESTAMP \tAPPDOMAIN \tLOGGERNAME \tTHREADNAME \tLEVEL \tMESSAGE\r\n"; layout.Footer = "END \n"; layout.ActivateOptions(); appender.Layout = layout; appender.ActivateOptions(); return appender; } /// <summary> /// Add a desired appender to the logger /// </summary> /// <param name="loggerName">Name of the logger to which the appender is to be added</param> /// <param name="appender">Appender to add to the logger</param> private static void AddAppender(string loggerName, log4net.Appender.IAppender appender) { log4net.ILog log = log4net.LogManager.GetLogger(loggerName); log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)log.Logger; l.AddAppender(appender); } private static void RemoveAllAppender(string loggerName) { log4net.ILog log = log4net.LogManager.GetLogger(loggerName); log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)log.Logger; l.RemoveAllAppenders(); } /// <summary> /// Set desire level for a specific logger /// </summary> /// <param name="loggerName">Name of the logger</param> /// <param name="levelName">Name of the desire level</param> private static void SetLevel(string loggerName, string levelName) { log4net.Core.Level lvl; switch (levelName.ToLower()) { case "all": lvl = log4net.Core.Level.All; break; case "error": lvl = log4net.Core.Level.Error; break; case "fatal": lvl = log4net.Core.Level.Fatal; break; case "info": lvl = log4net.Core.Level.Info; break; case "debug": lvl = log4net.Core.Level.Debug; break; case "warn": lvl = log4net.Core.Level.Warn; break; case "off": lvl = log4net.Core.Level.Off; break; default: lvl = log4net.Core.Level.All; break; } //If the logger doesnot exist it will create one else fetches one log4net.ILog log = log4net.LogManager.GetLogger(loggerName); //adds the logger as a seperate hierchy, not dependant on any other logger log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)log.Logger; //Applies the logger threshold level l.Level = l.Hierarchy.LevelMap[levelName]; IAppender[] appenderCol = log.Logger.Repository.GetAppenders(); for (int i = 0; i < appenderCol.Length; i++) { IAppender appender = appenderCol[i]; if (appender != null) { if (appender is BufferingForwardingAppender) { ((BufferingForwardingAppender)appender).Threshold = lvl; } if (appender is RollingFileAppender) { ((RollingFileAppender)appender).Threshold = lvl; } } } } private static void EnableFilter(string loggerName, string stringToMatch) { log4net.ILog log = log4net.LogManager.GetLogger(loggerName); log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)log.Logger; } /// <summary> /// To find an appender /// </summary> /// <param name="appenderName">name of the appender to find</param> /// <returns> if not found null will be returned</returns> public static log4net.Appender.IAppender FindAppender(string appenderName) { foreach (log4net.Appender.IAppender appender in log4net.LogManager.GetRepository().GetAppenders()) { if (appender.Name == appenderName) { return appender; } } return null; } ~Log4net() { IEnumerator cacheNameEnum = LoggingInformation.cacheLogger.GetEnumerator(); while (cacheNameEnum.MoveNext()) { Close((string)cacheNameEnum.Current); } cacheNameEnum = LoggingInformation.staticCacheLogger.GetEnumerator(); while (cacheNameEnum.MoveNext()) { Close((string)cacheNameEnum.Current); } } } }
// 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 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.EventHub { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for EventHubsOperations. /// </summary> public static partial class EventHubsOperationsExtensions { /// <summary> /// Gets all the Event Hubs in a Namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> public static IPage<Eventhub> ListByNamespace(this IEventHubsOperations operations, string resourceGroupName, string namespaceName) { return operations.ListByNamespaceAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult(); } /// <summary> /// Gets all the Event Hubs in a Namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Eventhub>> ListByNamespaceAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByNamespaceWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a new Event Hub as a nested resource within a Namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='parameters'> /// Parameters supplied to create an Event Hub resource. /// </param> public static Eventhub CreateOrUpdate(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, Eventhub parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, namespaceName, eventHubName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a new Event Hub as a nested resource within a Namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='parameters'> /// Parameters supplied to create an Event Hub resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Eventhub> CreateOrUpdateAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, Eventhub parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an Event Hub from the specified Namespace and resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> public static void Delete(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName) { operations.DeleteAsync(resourceGroupName, namespaceName, eventHubName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an Event Hub from the specified Namespace and resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets an Event Hubs description for the specified Event Hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> public static Eventhub Get(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName) { return operations.GetAsync(resourceGroupName, namespaceName, eventHubName).GetAwaiter().GetResult(); } /// <summary> /// Gets an Event Hubs description for the specified Event Hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Eventhub> GetAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the authorization rules for an Event Hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> public static IPage<AuthorizationRule> ListAuthorizationRules(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName) { return operations.ListAuthorizationRulesAsync(resourceGroupName, namespaceName, eventHubName).GetAwaiter().GetResult(); } /// <summary> /// Gets the authorization rules for an Event Hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<AuthorizationRule>> ListAuthorizationRulesAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates an AuthorizationRule for the specified Event Hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// The shared access AuthorizationRule. /// </param> public static AuthorizationRule CreateOrUpdateAuthorizationRule(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, AuthorizationRule parameters) { return operations.CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates an AuthorizationRule for the specified Event Hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// The shared access AuthorizationRule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AuthorizationRule> CreateOrUpdateAuthorizationRuleAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, AuthorizationRule parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets an AuthorizationRule for an Event Hub by rule name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> public static AuthorizationRule GetAuthorizationRule(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName) { return operations.GetAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Gets an AuthorizationRule for an Event Hub by rule name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AuthorizationRule> GetAuthorizationRuleAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an Event Hub AuthorizationRule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> public static void DeleteAuthorizationRule(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName) { operations.DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an Event Hub AuthorizationRule. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAuthorizationRuleAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the ACS and SAS connection strings for the Event Hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> public static AccessKeys ListKeys(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName) { return operations.ListKeysAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Gets the ACS and SAS connection strings for the Event Hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessKeys> ListKeysAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the ACS and SAS connection strings for the Event Hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the AuthorizationRule Keys /// (PrimaryKey/SecondaryKey). /// </param> public static AccessKeys RegenerateKeys(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, RegenerateAccessKeyParameters parameters) { return operations.RegenerateKeysAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Regenerates the ACS and SAS connection strings for the Event Hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='eventHubName'> /// The Event Hub name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the AuthorizationRule Keys /// (PrimaryKey/SecondaryKey). /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessKeys> RegenerateKeysAsync(this IEventHubsOperations operations, string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the Event Hubs in a Namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Eventhub> ListByNamespaceNext(this IEventHubsOperations operations, string nextPageLink) { return operations.ListByNamespaceNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the Event Hubs in a Namespace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Eventhub>> ListByNamespaceNextAsync(this IEventHubsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByNamespaceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the authorization rules for an Event Hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<AuthorizationRule> ListAuthorizationRulesNext(this IEventHubsOperations operations, string nextPageLink) { return operations.ListAuthorizationRulesNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the authorization rules for an Event Hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<AuthorizationRule>> ListAuthorizationRulesNextAsync(this IEventHubsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System.Linq; using NUnit.Framework; [TestFixture] public class ScoreMasterTest { [Test] public void ST00Vowl23 () { int[] pins = { 2, 3 }; Assert.AreEqual( 5, ScoreMaster.ScoreCumulative( pins.ToList() )[ 0 ] ); } [Test] public void ST01Bowl43 () { int[] pins = { 4, 3 }; Assert.AreEqual( 7, ScoreMaster.ScoreCumulative( pins.ToList() )[ 0 ] ); } [Test] public void ST02Strike73 () { int[] pins = { 10, 7, 3 }; Assert.AreEqual( 20, ScoreMaster.ScoreCumulative( pins.ToList() )[ 0 ] ); } [Test] public void ST03Spare7 () { int[] pins = { 6, 4, 7 }; Assert.AreEqual( 17, ScoreMaster.ScoreCumulative( pins.ToList() )[ 0 ] ); } [Test] public void ST04Turkey () { int[] pins = { 10, 10, 10 }; Assert.AreEqual( 30, ScoreMaster.ScoreCumulative( pins.ToList() )[ 0 ] ); } [Test] // bowls: X,X,7,3,2 scores: 27, 47, 59, public void ST05BowlXX732 () { int[] pins = { 10, 10, 7, 3, 2 }; Assert.AreEqual( 27, ScoreMaster.ScoreCumulative( pins.ToList() )[ 0 ] ); } [Test] public void ST06BowlXX732 () { int[] pins = { 10, 10, 7, 3, 2 }; Assert.AreEqual( 47, ScoreMaster.ScoreCumulative( pins.ToList() )[ 1 ] ); } [Test] public void ST07BowlXX732 () { int[] pins = { 10, 10, 7, 3, 2 }; Assert.AreEqual( 59, ScoreMaster.ScoreCumulative( pins.ToList() )[ 2 ] ); } [Test] // bowls: 3,0,X,9,1,2,1 frame scores: 3, 23, 35, 38 public void ST08Bowl30X9121 () { int[] pins = { 3, 0, 10, 9, 1, 2, 1 }; Assert.AreEqual( 23, ScoreMaster.ScoreCumulative( pins.ToList() )[ 1 ] ); } [Test] public void ST09Bowl30X9121 () { int[] pins = { 3, 0, 10, 9, 1, 2, 1 }; Assert.AreEqual( 35, ScoreMaster.ScoreCumulative( pins.ToList() )[ 2 ] ); } [Test] public void ST10Bowl30X9121 () { int[] pins = { 3, 0, 10, 9, 1, 2, 1 }; Assert.AreEqual( 38, ScoreMaster.ScoreCumulative( pins.ToList() )[ 3 ] ); } [Test] // 300 public void ST11PerfectGameScore () { int[] pins = { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 }; Assert.AreEqual( 300, ScoreMaster.ScoreCumulative( pins.ToList() )[ 9 ] ); } // Test Format Scores [Test] public void FS00Empty () { int[] pins = { }; string scores = ""; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS01Bowl1 () { int[] pins = { 1 }; string scores = "1"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS02Bowl12 () { int[] pins = { 1,2 }; string scores = "12"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS03BowlGutter () { int[] pins = { 0 }; string scores = "-"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS04Strike () { int[] pins = { 10 }; string scores = " X"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS05Spare () { int[] pins = { 1, 9 }; string scores = "1/"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS06Strike5 () { int[] pins = { 10, 5 }; string scores = " X5"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS07Spare5 () { int[] pins = { 1, 9, 5 }; string scores = "1/5"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS08StrikeStrike () { int[] pins = { 10, 10 }; string scores = " X X"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS09StrikeStrikeStrike () { int[] pins = { 10, 10, 10 }; string scores = " X X X"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS10StrikeSpare () { int[] pins = { 10, 5, 5 }; string scores = " X5/"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS11SpareStrike () { int[] pins = { 5, 5, 10 }; string scores = "5/ X"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS12StrikeGutter () { int[] pins = { 10, 0 }; string scores = " X-"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS13StrikeGutterSpare () { int[] pins = { 10, 0, 10 }; string scores = " X-/"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS14LastFrameStrike () { int[] pins = { 1,0, 1,0, 1,0, 1,0, 1,0, 1,0, 1,0, 1,0, 1,0, 10 }; string scores = "1-1-1-1-1-1-1-1-1-X"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS15LastFrameStrikeStrike () { int[] pins = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 10, 10 }; string scores = "1-1-1-1-1-1-1-1-1-XX"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS16LastFrameTurkey () { int[] pins = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 10, 10, 10 }; string scores = "1-1-1-1-1-1-1-1-1-XXX"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS17LastFrame () { int[] pins = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1 }; string scores = "1-1-1-1-1-1-1-1-1-11"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS19LastFrameSpare () { int[] pins = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 9 }; string scores = "1-1-1-1-1-1-1-1-1-1/"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS20LastFrameSpareStrike () { int[] pins = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 9, 10 }; string scores = "1-1-1-1-1-1-1-1-1-1/X"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS21LastFrameSpareGutter () { int[] pins = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 9, 0 }; string scores = "1-1-1-1-1-1-1-1-1-1/-"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS22LastFrameSpare5 () { int[] pins = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 9, 5 }; string scores = "1-1-1-1-1-1-1-1-1-1/5"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS23LastFrameStrike19 () { int[] pins = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 10, 1, 9 }; string scores = "1-1-1-1-1-1-1-1-1-X19"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS24Bowl8281 () { int[] rolls = { 8, 2, 8, 1 }; string rollsString = "8/81"; Assert.AreEqual( rollsString, ScoreMaster.FormatRolls( rolls.ToList() ) ); } [Test] // 300 public void FS25PerfectGameScore () { int[] rolls = { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 }; string rollsString = " X X X X X X X X XXXX"; Assert.AreEqual( rollsString, ScoreMaster.FormatRolls( rolls.ToList() ) ); } [Test] public void FS26LastFrameStrikeStrike71 () { int[] pins = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 9, 1, 10, 10, 7, 1 }; string scores = "1-1-1-1-1-1-1-9/ XX71"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS27LastFrameStrikeGutterGutter () { int[] pins = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 10, 0, 0 }; string scores = "1-1-1-1-1-1-1-1-1-X--"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS28LastFrameStrikeStrikeGutter () { int[] pins = { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 10, 10, 0 }; string scores = "1-1-1-1-1-1-1-1-1-XX-"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS29GutterStrike () { int[] pins = { 0, 10 }; string scores = "-/"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS30GutterStrikeStrike () { int[] pins = { 0, 10, 10 }; string scores = "-/ X"; Assert.AreEqual( scores, ScoreMaster.FormatRolls( pins.ToList() ) ); } [Test] public void FS31RollInTheEnd464 () { int[] rolls = { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 4, 6, 4 }; string testString = "1212121212121212124/4"; Assert.AreEqual( testString, ScoreMaster.FormatRolls( rolls.ToList() ) ); } }
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using UnityEngine; [Serializable, DebuggerDisplay("Count = {Count}")] public class SerializableDictionary<TKey, TValue> : IDictionary<TKey, TValue> { [SerializeField, HideInInspector] int[] _Buckets; [SerializeField, HideInInspector] int[] _HashCodes; [SerializeField, HideInInspector] int[] _Next; [SerializeField, HideInInspector] int _Count; [SerializeField, HideInInspector] int _Version; [SerializeField, HideInInspector] int _FreeList; [SerializeField, HideInInspector] int _FreeCount; [SerializeField, HideInInspector] TKey[] _Keys; [SerializeField, HideInInspector] TValue[] _Values; readonly IEqualityComparer<TKey> _Comparer; // Mainly for debugging purposes - to get the key-value pairs display public Dictionary<TKey, TValue> AsDictionary { get { return new Dictionary<TKey, TValue>(this); } } public int Count { get { return _Count - _FreeCount; } } public TValue this[TKey key, TValue defaultValue] { get { int index = FindIndex(key); if (index >= 0) return _Values[index]; return defaultValue; } } public TValue this[TKey key] { get { int index = FindIndex(key); if (index >= 0) return _Values[index]; throw new KeyNotFoundException(key.ToString()); } set { Insert(key, value, false); } } public SerializableDictionary() : this(0, null) { } public SerializableDictionary(int capacity) : this(capacity, null) { } public SerializableDictionary(IEqualityComparer<TKey> comparer) : this(0, comparer) { } public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer) { if (capacity < 0) throw new ArgumentOutOfRangeException("capacity"); Initialize(capacity); _Comparer = (comparer ?? EqualityComparer<TKey>.Default); } public SerializableDictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } public SerializableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : this((dictionary != null) ? dictionary.Count : 0, comparer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); foreach (KeyValuePair<TKey, TValue> current in dictionary) Add(current.Key, current.Value); } public bool ContainsValue(TValue value) { if (value == null) { for (int i = 0; i < _Count; i++) { if (_HashCodes[i] >= 0 && _Values[i] == null) return true; } } else { var defaultComparer = EqualityComparer<TValue>.Default; for (int i = 0; i < _Count; i++) { if (_HashCodes[i] >= 0 && defaultComparer.Equals(_Values[i], value)) return true; } } return false; } public bool ContainsKey(TKey key) { return FindIndex(key) >= 0; } public void Clear() { if (_Count <= 0) return; for (int i = 0; i < _Buckets.Length; i++) _Buckets[i] = -1; Array.Clear(_Keys, 0, _Count); Array.Clear(_Values, 0, _Count); Array.Clear(_HashCodes, 0, _Count); Array.Clear(_Next, 0, _Count); _FreeList = -1; _Count = 0; _FreeCount = 0; _Version++; } public void Add(TKey key, TValue value) { Insert(key, value, true); } private void Resize(int newSize, bool forceNewHashCodes) { int[] bucketsCopy = new int[newSize]; for (int i = 0; i < bucketsCopy.Length; i++) bucketsCopy[i] = -1; var keysCopy = new TKey[newSize]; var valuesCopy = new TValue[newSize]; var hashCodesCopy = new int[newSize]; var nextCopy = new int[newSize]; Array.Copy(_Values, 0, valuesCopy, 0, _Count); Array.Copy(_Keys, 0, keysCopy, 0, _Count); Array.Copy(_HashCodes, 0, hashCodesCopy, 0, _Count); Array.Copy(_Next, 0, nextCopy, 0, _Count); if (forceNewHashCodes) { for (int i = 0; i < _Count; i++) { if (hashCodesCopy[i] != -1) hashCodesCopy[i] = (_Comparer.GetHashCode(keysCopy[i]) & 2147483647); } } for (int i = 0; i < _Count; i++) { int index = hashCodesCopy[i] % newSize; nextCopy[i] = bucketsCopy[index]; bucketsCopy[index] = i; } _Buckets = bucketsCopy; _Keys = keysCopy; _Values = valuesCopy; _HashCodes = hashCodesCopy; _Next = nextCopy; } private void Resize() { Resize(PrimeHelper.ExpandPrime(_Count), false); } public bool Remove(TKey key) { if (key == null) throw new ArgumentNullException("key"); int hash = _Comparer.GetHashCode(key) & 2147483647; int index = hash % _Buckets.Length; int num = -1; for (int i = _Buckets[index]; i >= 0; i = _Next[i]) { if (_HashCodes[i] == hash && _Comparer.Equals(_Keys[i], key)) { if (num < 0) _Buckets[index] = _Next[i]; else _Next[num] = _Next[i]; _HashCodes[i] = -1; _Next[i] = _FreeList; _Keys[i] = default(TKey); _Values[i] = default(TValue); _FreeList = i; _FreeCount++; _Version++; return true; } num = i; } return false; } private void Insert(TKey key, TValue value, bool add) { if (key == null) throw new ArgumentNullException("key"); if (_Buckets == null) Initialize(0); int hash = _Comparer.GetHashCode(key) & 2147483647; int index = hash % _Buckets.Length; int num1 = 0; for (int i = _Buckets[index]; i >= 0; i = _Next[i]) { if (_HashCodes[i] == hash && _Comparer.Equals(_Keys[i], key)) { if (add) throw new ArgumentException("Key already exists: " + key); _Values[i] = value; _Version++; return; } num1++; } int num2; if (_FreeCount > 0) { num2 = _FreeList; _FreeList = _Next[num2]; _FreeCount--; } else { if (_Count == _Keys.Length) { Resize(); index = hash % _Buckets.Length; } num2 = _Count; _Count++; } _HashCodes[num2] = hash; _Next[num2] = _Buckets[index]; _Keys[num2] = key; _Values[num2] = value; _Buckets[index] = num2; _Version++; //if (num3 > 100 && HashHelpers.IsWellKnownEqualityComparer(comparer)) //{ // comparer = (IEqualityComparer<TKey>)HashHelpers.GetRandomizedEqualityComparer(comparer); // Resize(entries.Length, true); //} } private void Initialize(int capacity) { int prime = PrimeHelper.GetPrime(capacity); _Buckets = new int[prime]; for (int i = 0; i < _Buckets.Length; i++) _Buckets[i] = -1; _Keys = new TKey[prime]; _Values = new TValue[prime]; _HashCodes = new int[prime]; _Next = new int[prime]; _FreeList = -1; } private int FindIndex(TKey key) { if (key == null) throw new ArgumentNullException("key"); if (_Buckets != null) { int hash = _Comparer.GetHashCode(key) & 2147483647; for (int i = _Buckets[hash % _Buckets.Length]; i >= 0; i = _Next[i]) { if (_HashCodes[i] == hash && _Comparer.Equals(_Keys[i], key)) return i; } } return -1; } public bool TryGetValue(TKey key, out TValue value) { int index = FindIndex(key); if (index >= 0) { value = _Values[index]; return true; } value = default(TValue); return false; } private static class PrimeHelper { public static readonly int[] Primes = new int[] { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; public static bool IsPrime(int candidate) { if ((candidate & 1) != 0) { int num = (int)Math.Sqrt((double)candidate); for (int i = 3; i <= num; i += 2) { if (candidate % i == 0) { return false; } } return true; } return candidate == 2; } public static int GetPrime(int min) { if (min < 0) throw new ArgumentException("min < 0"); for (int i = 0; i < PrimeHelper.Primes.Length; i++) { int prime = PrimeHelper.Primes[i]; if (prime >= min) return prime; } for (int i = min | 1; i < 2147483647; i += 2) { if (PrimeHelper.IsPrime(i) && (i - 1) % 101 != 0) return i; } return min; } public static int ExpandPrime(int oldSize) { int num = 2 * oldSize; if (num > 2146435069 && 2146435069 > oldSize) { return 2146435069; } return PrimeHelper.GetPrime(num); } } public ICollection<TKey> Keys { get { return _Keys.Take(Count).ToArray(); } } public ICollection<TValue> Values { get { return _Values.Take(Count).ToArray(); } } public void Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } public bool Contains(KeyValuePair<TKey, TValue> item) { int index = FindIndex(item.Key); return index >= 0 && EqualityComparer<TValue>.Default.Equals(_Values[index], item.Value); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { if (array == null) throw new ArgumentNullException("array"); if (index < 0 || index > array.Length) throw new ArgumentOutOfRangeException(string.Format("index = {0} array.Length = {1}", index, array.Length)); if (array.Length - index < Count) throw new ArgumentException(string.Format("The number of elements in the dictionary ({0}) is greater than the available space from index to the end of the destination array {1}.", Count, array.Length)); for (int i = 0; i < _Count; i++) { if (_HashCodes[i] >= 0) array[index++] = new KeyValuePair<TKey, TValue>(_Keys[i], _Values[i]); } } public bool IsReadOnly { get { return false; } } public bool Remove(KeyValuePair<TKey, TValue> item) { return Remove(item.Key); } public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>> { private readonly SerializableDictionary<TKey, TValue> _Dictionary; private int _Version; private int _Index; private KeyValuePair<TKey, TValue> _Current; public KeyValuePair<TKey, TValue> Current { get { return _Current; } } internal Enumerator(SerializableDictionary<TKey, TValue> dictionary) { _Dictionary = dictionary; _Version = dictionary._Version; _Current = default(KeyValuePair<TKey, TValue>); _Index = 0; } public bool MoveNext() { if (_Version != _Dictionary._Version) throw new InvalidOperationException(string.Format("Enumerator version {0} != Dictionary version {1}", _Version, _Dictionary._Version)); while (_Index < _Dictionary._Count) { if (_Dictionary._HashCodes[_Index] >= 0) { _Current = new KeyValuePair<TKey, TValue>(_Dictionary._Keys[_Index], _Dictionary._Values[_Index]); _Index++; return true; } _Index++; } _Index = _Dictionary._Count + 1; _Current = default(KeyValuePair<TKey, TValue>); return false; } void IEnumerator.Reset() { if (_Version != _Dictionary._Version) throw new InvalidOperationException(string.Format("Enumerator version {0} != Dictionary version {1}", _Version, _Dictionary._Version)); _Index = 0; _Current = default(KeyValuePair<TKey, TValue>); } object IEnumerator.Current { get { return Current; } } public void Dispose() { } } }
using System; using System.IO; using System.Net; using DarkMultiPlayerCommon; using System.Reflection; using System.Collections.Generic; namespace DarkMultiPlayerServer { public class Settings { private const string SETTINGS_FILE_NAME = "DMPServerSettings.txt"; private static string settingsFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SETTINGS_FILE_NAME); //Port private static SettingsStore _settingsStore; public static SettingsStore settingsStore { get { //Lazy loading if (_settingsStore == null) { _settingsStore = new SettingsStore(); Load(); } return _settingsStore; } } public static void Reset() { _settingsStore = null; } private static void Load() { DarkLog.Debug("Loading settings"); FieldInfo[] settingFields = typeof(SettingsStore).GetFields(); if (!File.Exists(settingsFile)) { try { if (System.Net.Sockets.Socket.OSSupportsIPv6) { //Default to listening on IPv4 and IPv6 if possible. settingsStore.address = "::"; } } catch { //May throw on Windows XP } Save(); } using (FileStream fs = new FileStream(settingsFile, FileMode.Open)) { using (StreamReader sr = new StreamReader(fs)) { string currentLine; string trimmedLine; string currentKey; string currentValue; while (true) { currentLine = sr.ReadLine(); if (currentLine == null) { break; } trimmedLine = currentLine.Trim(); if (!String.IsNullOrEmpty(trimmedLine)) { if (trimmedLine.Contains(",") && !trimmedLine.StartsWith("#")) { currentKey = trimmedLine.Substring(0, trimmedLine.IndexOf(",")); currentValue = trimmedLine.Substring(trimmedLine.IndexOf(",") + 1); foreach (FieldInfo settingField in settingFields) { if (settingField.Name.ToLower() == currentKey) { if (settingField.FieldType == typeof(string)) { settingField.SetValue(settingsStore, currentValue); } if (settingField.FieldType == typeof(int)) { int intValue = Int32.Parse(currentValue); settingField.SetValue(settingsStore, (int)intValue); } if (settingField.FieldType == typeof(double)) { double doubleValue = Double.Parse(currentValue); settingField.SetValue(settingsStore, (double)doubleValue); } if (settingField.FieldType == typeof(bool)) { if (currentValue == "1") { settingField.SetValue(settingsStore, true); } else { settingField.SetValue(settingsStore, false); } } if (settingField.FieldType.IsEnum) { int intValue = Int32.Parse(currentValue); Array enumValues = settingField.FieldType.GetEnumValues(); if (intValue <= enumValues.Length) { settingField.SetValue(settingsStore, enumValues.GetValue(intValue)); } } //DarkLog.Debug(settingField.Name + ": " + currentValue); } } } } } } } Save(); } private static void Save() { DarkLog.Debug("Saving settings"); FieldInfo[] settingFields = typeof(SettingsStore).GetFields(); Dictionary<string,string> settingDescriptions = GetSettingsDescriptions(); if (File.Exists(settingsFile + ".tmp")) { File.Delete(settingsFile + ".tmp"); } using (FileStream fs = new FileStream(settingsFile + ".tmp", FileMode.CreateNew)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine("#Setting file format: (key),(value)"); sw.WriteLine("#This file will be re-written every time the server is started. Only known keys will be saved."); sw.WriteLine(""); foreach (FieldInfo settingField in settingFields) { if (settingDescriptions.ContainsKey(settingField.Name)) { sw.WriteLine("#" + settingField.Name.ToLower() + " - " + settingDescriptions[settingField.Name]); } if (settingField.FieldType == typeof(string) || settingField.FieldType == typeof(int) || settingField.FieldType == typeof(double)) { sw.WriteLine(settingField.Name.ToLower() + "," + settingField.GetValue(settingsStore)); } if (settingField.FieldType == typeof(bool)) { if ((bool)settingField.GetValue(settingsStore)) { sw.WriteLine(settingField.Name.ToLower() + ",1"); } else { sw.WriteLine(settingField.Name.ToLower() + ",0"); } } if (settingField.FieldType.IsEnum) { sw.WriteLine("#Valid values are:"); foreach (int enumValue in settingField.FieldType.GetEnumValues()) { sw.WriteLine("#" + enumValue + " - " + settingField.FieldType.GetEnumValues().GetValue(enumValue).ToString()); } sw.WriteLine(settingField.Name.ToLower() + "," + (int)settingField.GetValue(settingsStore)); } sw.WriteLine(""); } } } if (File.Exists(settingsFile)) { File.Delete(settingsFile); } File.Move(settingsFile + ".tmp", settingsFile); } private static Dictionary<string,string> GetSettingsDescriptions() { Dictionary<string, string> descriptionList = new Dictionary<string, string>(); descriptionList.Add("address", "The address the server listens on.\n#WARNING: You do not need to change this unless you are running 2 servers on the same port.\n#Changing this setting from 0.0.0.0 will only give you trouble if you aren't running multiple servers.\n#Change this setting to :: to listen on IPv4 and IPv6."); descriptionList.Add("port", "The port the server listens on."); descriptionList.Add("warpMode", "Specify the warp type."); descriptionList.Add("gameMode", "Specify the game type."); descriptionList.Add("gameDifficulty", "Specify the gameplay difficulty of the server."); descriptionList.Add("whitelisted", "Enable white-listing."); descriptionList.Add("modControl", "Enable mod control.\n#WARNING: Only consider turning off mod control for private servers.\n#The game will constantly complain about missing parts if there are missing mods."); descriptionList.Add("keepTickingWhileOffline", "Specify if the the server universe 'ticks' while nobody is connected or the server is shut down."); descriptionList.Add("sendPlayerToLatestSubspace", "If true, sends the player to the latest subspace upon connecting. If false, sends the player to the previous subspace they were in.\n#NOTE: This may cause time-paradoxes, and will not work across server restarts."); descriptionList.Add("useUTCTimeInLog", "Use UTC instead of system time in the log."); descriptionList.Add("logLevel", "Minimum log level."); descriptionList.Add("screenshotsPerPlayer", "Specify maximum number of screenshots to save per player. -1 = None, 0 = Unlimited"); descriptionList.Add("screenshotHeight", "Specify vertical resolution of screenshots."); descriptionList.Add("cheats", "Enable use of cheats in-game."); descriptionList.Add("httpPort", "HTTP port for server status. 0 = Disabled"); descriptionList.Add("serverName", "Name of the server."); descriptionList.Add("maxPlayers", "Maximum amount of players that can join the server."); descriptionList.Add("screenshotDirectory", "Specify a custom screenshot directory.\n#This directory must exist in order to be used. Leave blank to store it in Universe."); descriptionList.Add("autoNuke", "Specify in minutes how often /nukeksc automatically runs. 0 = Disabled"); descriptionList.Add("autoDekessler", "Specify in minutes how often /dekessler automatically runs. 0 = Disabled"); descriptionList.Add("numberOfAsteroids", "How many untracked asteroids to spawn into the universe. 0 = Disabled"); descriptionList.Add("consoleIdentifier", "Specify the name that will appear when you send a message using the server's console."); descriptionList.Add("serverMotd", "Specify the server's MOTD (message of the day)."); descriptionList.Add("expireScreenshots", "Specify the amount of days a screenshot should be considered as expired and deleted. 0 = Disabled"); descriptionList.Add("compressionEnabled", "Specify whether to enable compression. Decreases bandwidth usage but increases CPU usage. 0 = Disabled"); descriptionList.Add("expireLogs", "Specify the amount of days a log file should be considered as expired and deleted. 0 = Disabled"); return descriptionList; } } public class SettingsStore { public string address = "0.0.0.0"; public int port = 6702; public WarpMode warpMode = WarpMode.SUBSPACE; public GameMode gameMode = GameMode.SANDBOX; public GameDifficulty gameDifficulty = GameDifficulty.NORMAL; public bool whitelisted = false; public ModControlMode modControl = ModControlMode.ENABLED_STOP_INVALID_PART_SYNC; public bool keepTickingWhileOffline = true; public bool sendPlayerToLatestSubspace = true; public bool useUTCTimeInLog = false; public DarkLog.LogLevels logLevel = DarkLog.LogLevels.DEBUG; public int screenshotsPerPlayer = 20; public int screenshotHeight = 720; public bool cheats = true; public int httpPort = 0; public string serverName = "DMP Server"; public int maxPlayers = 20; public string screenshotDirectory = ""; public int autoNuke = 0; public int autoDekessler = 30; public int numberOfAsteroids = 30; public string consoleIdentifier = "Server"; public string serverMotd = "Welcome, %name%!"; public double expireScreenshots = 0; public bool compressionEnabled = true; public double expireLogs = 0; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; using Vexe.Editor.Types; using Vexe.Editor.Windows; using Vexe.Runtime.Extensions; using Vexe.Runtime.Helpers; using Vexe.Runtime.Types; using UnityObject = UnityEngine.Object; namespace Vexe.Editor.Drawers { public abstract class SequenceDrawer<TSequence, TElement> : ObjectDrawer<TSequence> where TSequence : IList<TElement> { private static readonly GUIStyle _bodyStyle = new GUIStyle(GUIStyles.HelpBox); private static readonly GUIStyle _headerStyle = new GUIStyle(GUIStyles.ToolbarButton); private static readonly GUIStyle _footerStyle = new GUIStyle(GUIStyles.ToolbarButton); private readonly Type _elementType; private readonly List<EditorMember> _elements; private SequenceOptions _options; private bool _shouldDrawAddingArea; private int _newSize; private int _advancedKey; private int _lastUpdatedCount = -1; private Attribute[] _perItemAttributes; private TextFilter _filter; private string _originalDisplay; public bool UpdateCount = true; private bool isAdvancedChecked { get { return prefs[_advancedKey]; } set { prefs[_advancedKey] = value; } } protected abstract TSequence GetNew(); public SequenceDrawer() { _elementType = typeof(TElement); _elements = new List<EditorMember>(); } public override void OnGUI() { this.gui.Space(2f); if (memberValue == null) memberValue = GetNew(); member.CollectionCount = memberValue.Count; var showAdvanced = _options.Advanced && !_options.Readonly; if (UpdateCount && _lastUpdatedCount != memberValue.Count) { _lastUpdatedCount = memberValue.Count; displayText = Regex.Replace(_originalDisplay, @"\$count", _lastUpdatedCount.ToString()); } using (gui.Vertical(_bodyStyle)) { this.gui.BeginCheck(); using (gui.Horizontal(_headerStyle)) { gui.Space(10f); DrawHeader(showAdvanced); gui.Space(-4f); } if (foldout) { if (memberValue.IsEmpty()) { gui.Space(4f); using (gui.Indent()) gui.HelpBox("Sequence is empty"); } else { DrawElements(showAdvanced); } DrawFooter(); } this.gui.HasChanged(); } } protected override void Initialize() { _headerStyle.fixedHeight = 15f; _headerStyle.margin.top = -1; _footerStyle.stretchWidth = true; var readOnlyAttr = attributes.GetAttribute<ReadOnlyAttribute>(); var displayAttr = attributes.GetAttribute<DisplayAttribute>(); var displayOption = Seq.None; if (displayAttr != null) displayOption = displayAttr.SeqOpt; if (readOnlyAttr != null) displayOption |= Seq.Readonly; _options = new SequenceOptions(displayOption); if (_options.Readonly) displayText += " (Readonly)"; _advancedKey = RuntimeHelper.CombineHashCodes(id, "advanced"); _shouldDrawAddingArea = !_options.Readonly && _elementType.IsA<UnityObject>(); var perItem = attributes.GetAttribute<PerItemAttribute>(); if (perItem != null) { if (perItem.ExplicitAttributes == null) _perItemAttributes = attributes.Where(x => !(x is PerItemAttribute)).ToArray(); else _perItemAttributes = attributes.Where(x => perItem.ExplicitAttributes.Contains(x.GetType().Name.Replace("Attribute", ""))).ToArray(); } if (_options.Filter) _filter = new TextFilter(null, id, true, prefs, null); _originalDisplay = displayText; if (memberValue == null) memberValue = GetNew(); member.CollectionCount = memberValue.Count; } private void DrawHeader(bool showAdvanced) { foldout = gui.Foldout(displayText, foldout, Layout.Auto); if (_options.Filter) _filter.Field(gui, 70f); gui.FlexibleSpace(); if (showAdvanced) isAdvancedChecked = gui.CheckButton(isAdvancedChecked, "advanced mode"); if (_options.Readonly) return; using (gui.State(memberValue.Count > 0)) { if (gui.ClearButton("list")) { RecordUndo("Clear"); Clear(); } if (gui.RemoveButton("last element")) { RecordUndo("Remove Last"); RemoveLast(); } } if (gui.AddButton("element", MiniButtonStyle.Right)) { RecordUndo("Add"); AddValue(); } } private void DrawElements(bool showAdvanced) { // body using (gui.Vertical(_options.GuiBox ? GUI.skin.box : GUIStyle.none)) { // advanced area if (isAdvancedChecked) { gui.Space(-2f); using (gui.Indent((GUI.skin.box))) { gui.Space(4f); using (gui.Horizontal()) { _newSize = gui.IntField("New size", _newSize); if (gui.MiniButton("c", "Commit", MiniButtonStyle.ModRight)) { if (_newSize != memberValue.Count) { RecordUndo("Adjust Size"); memberValue.AdjustSize(_newSize, RemoveAt, AddValue); } } } using (gui.Horizontal()) { gui.Label("Commands"); if (gui.MiniButton("Shuffle", "Shuffle list (randomize the order of the list's elements", (Layout) null)) { RecordUndo("Shuffle"); Shuffle(); } if (gui.MoveDownButton()) { RecordUndo("Shift Down"); memberValue.Shift(true); } if (gui.MoveUpButton(_elementType.IsValueType ? MiniButtonStyle.Right : MiniButtonStyle.Mid)) { RecordUndo("Shift Up"); memberValue.Shift(false); } if (!_elementType.IsValueType && gui.MiniButton("N", "Filter null values", MiniButtonStyle.Right)) { for (int i = memberValue.Count - 1; i > -1; i--) { if (memberValue[i] == null) { RecordUndo("Remove At"); RemoveAt(i); } } } } } } gui.Space(4f); using (gui.Indent(_options.GuiBox ? GUI.skin.box : GUIStyle.none)) { #if PROFILE Profiler.BeginSample("Sequence Elements"); #endif for (int i = 0; i < memberValue.Count; i++) { var elementValue = memberValue[i]; if (_filter != null && elementValue != null) { string elemStr = elementValue.ToString(); if (!_filter.IsMatch(elemStr)) continue; } using (gui.Horizontal()) { if (_options.LineNumbers) gui.NumericLabel(i); else gui.MiniLabel("="); var previous = elementValue; var changed = false; var element = GetElement(i); using (gui.If(!_options.Readonly && _elementType.IsNumeric(), gui.LabelWidth(15f))) { changed = gui.MemberField(element, @ignoreComposition: _perItemAttributes == null); } if (changed) { if (_options.Readonly) { memberValue[i] = previous; } else if (_options.UniqueItems) { int occurances = 0; for (int k = 0; k < memberValue.Count; k++) { if (memberValue[i].GenericEquals(memberValue[k])) { occurances++; if (occurances > 1) { memberValue[i] = previous; break; } } } } } var midStyle = !_options.Readonly && ( _options.PerItemRemove || _options.PerItemDuplicate); if (isAdvancedChecked) { var c = elementValue as Component; var go = c == null ? elementValue as GameObject : c.gameObject; if (go != null) gui.InspectButton(go); if (showAdvanced) { if (gui.MoveDownButton()) { RecordUndo("Move Down"); MoveElementDown(i); } if (gui.MoveUpButton(midStyle ? MiniButtonStyle.Mid : MiniButtonStyle.Right)) { RecordUndo("Move Up"); MoveElementUp(i); } } } if (!_options.Readonly && _options.PerItemRemove && gui.RemoveButton("element", MiniButtonStyle.ModRight)) { RecordUndo("Remove At"); RemoveAt(i); } // Only valid for Classes implementing ICloneable if (typeof(ICloneable).IsAssignableFrom(_elementType) && elementValue != null) { if (!_options.Readonly && _options.PerItemDuplicate && gui.AddButton("element", MiniButtonStyle.ModRight)) { ICloneable _elementToClone = (ICloneable) elementValue; TElement cloned = (TElement) _elementToClone.Clone(); RecordUndo("Add"); AddValue(cloned); } } } if (i < memberValue.Count - 1) { this.gui.Space(6f); } } #if PROFILE Profiler.EndSample(); #endif } } } private void DrawFooter() { if (!_shouldDrawAddingArea) return; Action<UnityObject> addOnDrop = obj => { var go = obj as GameObject; object value; if (go == null) value = obj; else value = _elementType == typeof(GameObject) ? (UnityObject) go : go.GetComponent(_elementType); RecordUndo("Add"); AddValue((TElement) value); }; using (gui.Indent()) { gui.Space(4f); gui.DragDropArea<UnityObject>( @label: "+Drag-Drop+", @labelSize: 14, @style: _footerStyle, @canSetVisualModeToCopy: dragObjects => dragObjects.All(obj => { var go = obj as GameObject; var isGo = go != null; if (_elementType == typeof(GameObject)) return isGo; return isGo ? go.GetComponent(_elementType) != null : obj.GetType().IsA(_elementType); }), @cursor: MouseCursor.Link, @onDrop: addOnDrop, @onMouseUp: () => SelectionWindow.Show(new Tab<UnityObject>( @getValues: () => UnityObject.FindObjectsOfType(_elementType), @getCurrent: () => null, @setTarget: item => { RecordUndo("Add"); AddValue((TElement) (object) item); }, @getValueName: value => value.name, @title: _elementType.Name + "s")), @preSpace: 0f, @postSpace: 6f, @height: 15f ); } gui.Space(4f); } private EditorMember GetElement(int index) { if (index >= _elements.Count) { var element = EditorMember.WrapIListElement( @attributes: _perItemAttributes, @elementName: string.Empty, @elementType: _elementType, @elementId: RuntimeHelper.CombineHashCodes(id, index) ); element.InitializeIList(memberValue, index, rawTarget, unityTarget); _elements.Add(element); return element; } var e = _elements[index]; e.InitializeIList(memberValue, index, rawTarget, unityTarget); return e; } #region List ops protected abstract void Clear(); protected abstract void RemoveAt(int atIndex); protected abstract void Insert(int index, TElement value); private void Shuffle() { memberValue.Shuffle(); } private void MoveElementDown(int i) { memberValue.MoveElementDown(i); } private void MoveElementUp(int i) { memberValue.MoveElementUp(i); } private void RemoveLast() { RemoveAt(memberValue.Count - 1); } private void AddValue(TElement value) { Insert(memberValue.Count, value); } private void AddValue() { AddValue((TElement) _elementType.GetDefaultValueEmptyIfString()); } #endregion List ops private struct SequenceOptions { public readonly bool Readonly; public readonly bool Advanced; public readonly bool LineNumbers; public readonly bool PerItemRemove; public readonly bool PerItemDuplicate; public readonly bool GuiBox; public readonly bool UniqueItems; public readonly bool Filter; public SequenceOptions(Seq options) { Readonly = options.HasFlag(Seq.Readonly); Advanced = options.HasFlag(Seq.Advanced); LineNumbers = options.HasFlag(Seq.LineNumbers); PerItemRemove = options.HasFlag(Seq.PerItemRemove); PerItemDuplicate = options.HasFlag(Seq.PerItemDuplicate); GuiBox = options.HasFlag(Seq.GuiBox); UniqueItems = options.HasFlag(Seq.UniqueItems); Filter = options.HasFlag(Seq.Filter); } } } public class ArrayDrawer<T> : SequenceDrawer<T[], T> { protected override T[] GetNew() { return new T[0]; } protected override void RemoveAt(int atIndex) { memberValue = memberValue.ToList().RemoveAtAndGet(atIndex).ToArray(); } protected override void Clear() { memberValue = memberValue.ToList().ClearAndGet().ToArray(); } protected override void Insert(int index, T value) { memberValue = memberValue.ToList().InsertAndGet(index, value).ToArray(); foldout = true; } } public class ListDrawer<T> : SequenceDrawer<List<T>, T> { protected override List<T> GetNew() { return new List<T>(); } protected override void RemoveAt(int index) { memberValue.RemoveAt(index); } protected override void Clear() { memberValue.Clear(); } protected override void Insert(int index, T value) { memberValue.Insert(index, value); foldout = true; } } }
using System; using System.Collections.Generic; using Moq; using Shouldly; using Spk.Common.Helpers.Collection; using Xunit; namespace Spk.Common.Tests.Helpers.Collections { public class CollectionSynchronizationTests { [Fact] public void Execute_ShouldAddNewItemsUsingNewItemsMapper_WhenNewItemsMapperIsSet() { var sourceItem1 = new SomeRandomClass { String = "item #1" }; var sourceItem2 = new SomeRandomClass { String = "item #2" }; var source = new List<SomeRandomClass> { sourceItem1, sourceItem2 }; var target = new List<SomeRandomClass>(); var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>(source, target); sync.MapNewItemsUsing(src => new SomeRandomClass { String = $"this is a new {src.String}" }); sync.Execute(); target.Count.ShouldBe(2); target.ShouldNotContain(sourceItem1); target.ShouldNotContain(sourceItem2); target.ShouldContain(item => item.String == "this is a new item #1"); target.ShouldContain(item => item.String == "this is a new item #2"); } [Fact] public void Execute_ShouldAddNotMatchedItemsFromSource_AndRemoveNotMatchedItemsFromTarget_MatchingUsingEquals_WhenMatchFunctionNotProvided() { var shouldBeAdded1 = new SomeRandomClassEqualsCaseInsensitiveString { String = "one" }; var source = new List<SomeRandomClass> { new SomeRandomClass {String = "two"}, new SomeRandomClassEqualsCaseInsensitiveString {String = "THREE"}, shouldBeAdded1 }; var shouldBeMatched2 = new SomeRandomClassEqualsCaseInsensitiveString { String = "TWO" }; var shouldBeMatched3 = new SomeRandomClass { String = "three" }; var shouldBeRemoved = new SomeRandomClassEqualsCaseInsensitiveString { String = "not matched :(" }; var target = new List<SomeRandomClass> { shouldBeMatched2, shouldBeMatched3, shouldBeRemoved }; var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>(source, target); sync.Execute(); target.Count.ShouldBe(3); target.ShouldContain(shouldBeAdded1); target.ShouldContain(shouldBeMatched2); target.ShouldContain(shouldBeMatched3); target.ShouldNotContain(shouldBeRemoved); } [Fact] public void Execute_ShouldAddNotMatchedItemsFromSource_AndRemoveNotMatchedItemsFromTarget_UsingProvidedMatchFunction() { var expected1 = new SomeRandomClass { String = "4" }; var expected2 = new SomeRandomClass { String = "2 match!" }; var expected3 = new SomeRandomClass { String = "3 match!" }; var notExpected = new SomeRandomClass { String = "not matched :(" }; var source = new List<SomeRandomClass> { new SomeRandomClass {String = "2"}, new SomeRandomClass {String = "3"}, expected1 }; var target = new List<SomeRandomClass> { expected2, expected3, notExpected }; bool MatchFunction(SomeRandomClass src, SomeRandomClass trg) { return trg.String == $"{src.String} match!"; } var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>(source, target); sync.MatchUsing(MatchFunction); sync.Execute(); target.Count.ShouldBe(3); target.ShouldContain(expected1); target.ShouldContain(expected2); target.ShouldContain(expected3); target.ShouldNotContain(notExpected); } [Fact] public void Execute_ShouldAddObjectsInTarget_WhenNewItemsMapperNotSet_AndTargetIsAssignableFromSource() { var expected1 = new ChildClass(); var expected2 = new ChildClass(); var source = new List<ChildClass> { expected1, expected2 }; var target = new List<BaseClass>(); var sync = new CollectionSynchronization<ChildClass, BaseClass>(source, target); sync.Execute(); target.Count.ShouldBe(2); target.ShouldContain(expected1); target.ShouldContain(expected2); } [Fact] public void Execute_ShouldThrow_WhenNewItemsMapperNotSet_AndTargetIsNotAssignableFromSource() { var expected1 = new ChildClass(); var expected2 = new ChildClass(); var source = new List<ChildClass> { expected1, expected2 }; var target = new List<SomeRandomClass>(); var sync = new CollectionSynchronization<ChildClass, SomeRandomClass>(source, target); Assert.Throws<InvalidOperationException>(() => sync.Execute()); } [Fact] public void Execute_ShouldInvokeAllOnInsertFunctionRegistered() { var sync = new CollectionSynchronization<int, int>( new List<int> { 1, 3 }, new List<int> { 2, 4, 6 } ); var tracker1 = new Mock<EventHandlerTracker<int, int>>(); var tracker2 = new Mock<EventHandlerTracker<int, int>>(); var tracker3 = new Mock<EventHandlerTracker<int, int>>(); sync.OnInsert(tracker1.Object.OnInsertAction, tracker3.Object.OnInsertAction); sync.OnInsert(tracker2.Object.OnInsertAction); sync.Execute(); tracker1.Verify(t => t.OnInsertAction(It.IsAny<int>(), It.IsAny<int>()), Times.Exactly(2)); tracker2.Verify(t => t.OnInsertAction(It.IsAny<int>(), It.IsAny<int>()), Times.Exactly(2)); tracker3.Verify(t => t.OnInsertAction(It.IsAny<int>(), It.IsAny<int>()), Times.Exactly(2)); } [Fact] public void Execute_ShouldInvokeOnInsertFunctionWithCorrectArgument() { var sourceItem1 = new SomeRandomClass(); var sourceItem2 = new SomeRandomClass(); var targetCollection = new List<SomeRandomClass>(); var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass> { sourceItem1, sourceItem2 }, targetCollection ); var tracker = new Mock<EventHandlerTracker<SomeRandomClass, SomeRandomClass>>(); sync.OnInsert(tracker.Object.OnInsertAction); sync.Execute(); tracker.Verify(t => t.OnInsertAction( It.Is<SomeRandomClass>(src => ReferenceEquals(src, sourceItem1)), It.Is<SomeRandomClass>(trg => targetCollection.Contains(trg))), Times.Once); tracker.Verify(t => t.OnInsertAction( It.Is<SomeRandomClass>(src => ReferenceEquals(src, sourceItem2)), It.Is<SomeRandomClass>(trg => targetCollection.Contains(trg))), Times.Once); } [Fact] public void Execute_ShouldInvokeAllOnUpdateFunctionRegistered() { var sync = new CollectionSynchronization<int, int>( new List<int> { 4, 6 }, new List<int> { 2, 4, 6 } ); var tracker1 = new Mock<EventHandlerTracker<int, int>>(); var tracker2 = new Mock<EventHandlerTracker<int, int>>(); var tracker3 = new Mock<EventHandlerTracker<int, int>>(); sync.OnUpdate(tracker1.Object.OnUpdateAction, tracker3.Object.OnUpdateAction); sync.OnUpdate(tracker2.Object.OnUpdateAction); sync.Execute(); tracker1.Verify(t => t.OnUpdateAction(It.IsAny<int>(), It.IsAny<int>()), Times.Exactly(2)); tracker2.Verify(t => t.OnUpdateAction(It.IsAny<int>(), It.IsAny<int>()), Times.Exactly(2)); tracker3.Verify(t => t.OnUpdateAction(It.IsAny<int>(), It.IsAny<int>()), Times.Exactly(2)); } [Fact] public void Execute_ShouldInvokeOnUpdateFunctionWithCorrectArgument() { var sourceItem1 = new SomeRandomClass { String = "one" }; var targetItem1 = new SomeRandomClass { String = "one" }; var sourceItem2 = new SomeRandomClass { String = "two" }; var targetItem2 = new SomeRandomClass { String = "two" }; var targetCollection = new List<SomeRandomClass> { targetItem1, targetItem2 }; var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass> { sourceItem1, sourceItem2 }, targetCollection ); var tracker = new Mock<EventHandlerTracker<SomeRandomClass, SomeRandomClass>>(); sync.MatchUsing((src, trg) => src.String == trg.String); sync.OnUpdate(tracker.Object.OnUpdateAction); sync.Execute(); tracker.Verify(t => t.OnUpdateAction( It.Is<SomeRandomClass>(src => ReferenceEquals(src, sourceItem1)), It.Is<SomeRandomClass>(trg => targetCollection.Contains(trg) && ReferenceEquals(trg, targetItem1))), Times.Once); tracker.Verify(t => t.OnUpdateAction( It.Is<SomeRandomClass>(src => ReferenceEquals(src, sourceItem2)), It.Is<SomeRandomClass>(trg => targetCollection.Contains(trg) && ReferenceEquals(trg, targetItem2))), Times.Once); } [Fact] public void Execute_ShouldInvokeAllOnRemoveFunctionRegistered() { var sync = new CollectionSynchronization<int, int>( new List<int> { 4, 6 }, new List<int> { 2, 4, 6, 9 } ); var tracker1 = new Mock<EventHandlerTracker<int, int>>(); var tracker2 = new Mock<EventHandlerTracker<int, int>>(); var tracker3 = new Mock<EventHandlerTracker<int, int>>(); sync.OnRemove(tracker1.Object.OnRemoveAction, tracker3.Object.OnRemoveAction); sync.OnRemove(tracker2.Object.OnRemoveAction); sync.Execute(); tracker1.Verify(t => t.OnRemoveAction(It.IsAny<int>()), Times.Exactly(2)); tracker2.Verify(t => t.OnRemoveAction(It.IsAny<int>()), Times.Exactly(2)); tracker3.Verify(t => t.OnRemoveAction(It.IsAny<int>()), Times.Exactly(2)); } [Fact] public void Execute_ShouldInvokeOnRemoveFunctionWithCorrectArgument() { var targetItem1 = new SomeRandomClass(); var targetItem2 = new SomeRandomClass(); var targetCollection = new List<SomeRandomClass> { targetItem1, targetItem2 }; var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), targetCollection ); var tracker = new Mock<EventHandlerTracker<SomeRandomClass, SomeRandomClass>>(); sync.OnRemove(tracker.Object.OnRemoveAction); sync.Execute(); tracker.Verify(t => t.OnRemoveAction( It.Is<SomeRandomClass>(trg => ReferenceEquals(trg, targetItem1))), Times.Once); tracker.Verify(t => t.OnRemoveAction( It.Is<SomeRandomClass>(trg => ReferenceEquals(trg, targetItem2))), Times.Once); } [Fact] public void MapNewItemsUsing_ShouldReturnInstance() { var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), new List<SomeRandomClass>() ); sync.MapNewItemsUsing(src => src).ShouldBeSameAs(sync); } [Fact] public void MapNewItemsUsing_ShouldThrow_WhenArgumentNull() { var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), new List<SomeRandomClass>() ); Assert.Throws<ArgumentNullException>(() => { sync.MapNewItemsUsing(null); }); } [Fact] public void MatchUsing_ShouldReturnInstance() { var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), new List<SomeRandomClass>() ); sync.MatchUsing((src, trg) => src == trg).ShouldBeSameAs(sync); } [Fact] public void MatchUsing_ShouldThrow_WhenArgumentNull() { var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), new List<SomeRandomClass>() ); Assert.Throws<ArgumentNullException>(() => { sync.MatchUsing(null); }); } [Fact] public void OnInsert_ShouldReturnInstance() { var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), new List<SomeRandomClass>() ); sync.OnInsert((src, trg) => { }).ShouldBeSameAs(sync); } [Fact] public void OnInsert_ShouldThrow_WhenArgumentNull() { var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), new List<SomeRandomClass>() ); Assert.Throws<ArgumentNullException>(() => { sync.OnInsert(null); }); } [Fact] public void OnRemove_ShouldReturnInstance() { var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), new List<SomeRandomClass>() ); sync.OnRemove(trg => { }).ShouldBeSameAs(sync); } [Fact] public void OnRemove_ShouldThrow_WhenArgumentNull() { var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), new List<SomeRandomClass>() ); Assert.Throws<ArgumentNullException>(() => { sync.OnRemove(null); }); } [Fact] public void OnUpdate_ShouldReturnInstance() { var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), new List<SomeRandomClass>() ); sync.OnUpdate((src, trg) => { }).ShouldBeSameAs(sync); } [Fact] public void OnUpdate_ShouldThrow_WhenArgumentNull() { var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), new List<SomeRandomClass>() ); Assert.Throws<ArgumentNullException>(() => { sync.OnUpdate(null); }); } [Fact] public void UpdateItemsUsing_ShouldReturnInstance() { var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), new List<SomeRandomClass>() ); sync.UpdateItemsUsing((src, trg) => { }).ShouldBeSameAs(sync); } [Fact] public void UpdateItemsUsing_ShouldThrow_WhenArgumentNull() { var sync = new CollectionSynchronization<SomeRandomClass, SomeRandomClass>( new List<SomeRandomClass>(), new List<SomeRandomClass>() ); Assert.Throws<ArgumentNullException>(() => { sync.UpdateItemsUsing(null); }); } } #region Helper classes public class EventHandlerTracker<TSource, TTarget> { public virtual void OnInsertAction(TSource source, TTarget target) { } public virtual void OnUpdateAction(TSource source, TTarget target) { } public virtual void OnRemoveAction(TTarget target) { } } public class SomeRandomClass { public string String { get; set; } } public class SomeRandomClassEqualsCaseInsensitiveString : SomeRandomClass { public override bool Equals(object obj) { if (obj is SomeRandomClass casted) { var result = Equals(casted); return result; } else { var result = ReferenceEquals(this, obj); return result; } } private bool Equals(SomeRandomClass other) { var result = string.Equals(String, other.String, StringComparison.CurrentCultureIgnoreCase); return result; } public override int GetHashCode() { return String != null ? String.GetHashCode() : 0; } } public class BaseClass { } public class ChildClass : BaseClass { } #endregion }
using System; using System.Text; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using CommonTests.Framework; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using System.Threading; using System.Net; namespace AWSSDK_DotNet.IntegrationTests.Tests.IAM { [TestFixture] public class PolicyTests : TestBase<AmazonIdentityManagementServiceClient> { public static string TEST_ALLOW_POLICY = @"{""Statement"":[{""Effect"":""Allow"",""Action"":""*"",""Resource"":""*""}]}", TEST_VERSIONED_POLICY = @"{""Version"": ""2012-10-17"",""Statement"":[{""Effect"":""Allow"",""Action"":""*"",""Resource"":""*""}]}", TEST_DENY_POLICY = @"{""Statement"":[{""Effect"":""Deny"",""Action"":""*"",""Resource"":""*""}]}"; [OneTimeTearDown] public void Cleanup() { BaseClean(); } [SetUp] public void TestSetup() { IAMUtil.DeleteUsersAndGroupsInTestNameSpace(Client); } [Test] [Category("IAM")] public void TestPutGetUserPolicy() { string username = IAMUtil.CreateTestUser(Client); string policyName = "test-policy-" + DateTime.Now.Ticks; try { Client.PutUserPolicyAsync( new PutUserPolicyRequest() { UserName = username, PolicyName = policyName, PolicyDocument = TEST_ALLOW_POLICY }).Wait(); GetUserPolicyResponse response = Client.GetUserPolicyAsync(new GetUserPolicyRequest() { UserName = username, PolicyName = policyName }).Result; Assert.AreEqual(username, response.UserName); Assert.AreEqual(policyName, response.PolicyName); Assert.AreEqual(TEST_ALLOW_POLICY, WebUtility.UrlDecode(response.PolicyDocument)); } finally { IAMUtil.DeleteTestUsers(Client, username); } } [Test] [Category("IAM")] public void TestPutGetGroupPolicy() { string groupname = "sdk-testgroup-" + DateTime.Now.Ticks; string policyName = "strong-password"; try { Client.CreateGroupAsync(new CreateGroupRequest() { GroupName = groupname, Path = IAMUtil.TEST_PATH }).Wait(); Client.PutGroupPolicyAsync( new PutGroupPolicyRequest() { GroupName = groupname, PolicyName = policyName, PolicyDocument = TEST_ALLOW_POLICY }).Wait(); GetGroupPolicyResponse response = Client.GetGroupPolicyAsync(new GetGroupPolicyRequest() { GroupName = groupname, PolicyName = policyName }).Result; Assert.AreEqual(groupname, response.GroupName); Assert.AreEqual(policyName, response.PolicyName); Assert.AreEqual(TEST_ALLOW_POLICY, WebUtility.UrlDecode(response.PolicyDocument)); } finally { Client.DeleteGroupPolicyAsync(new DeleteGroupPolicyRequest() { GroupName = groupname, PolicyName = policyName }).Wait(); } } [Test] [Category("IAM")] //[ExpectedException(typeof(NoSuchEntityException))] public void TestGetNonExistantPolicy() { string username = IAMUtil.CreateTestUser(Client); string policyName = "test-policy-" + DateTime.Now.Ticks; try { GetUserPolicyResponse response = Client.GetUserPolicyAsync(new GetUserPolicyRequest() { UserName = username, PolicyName = policyName }).Result; } catch (AggregateException ae) { AssertExtensions.VerifyException<NoSuchEntityException>(ae); } finally { IAMUtil.DeleteTestUsers(Client); } } [Test] [Category("IAM")] public void TestListUserPolicies() { string username = IAMUtil.CreateTestUser(Client); string[] policyNames = new string[3]; int nPolicies = 3; try { for (int i = 0; i < nPolicies; i++) { policyNames[i] = "test-policy-" + DateTime.Now.Ticks + i; Client.PutUserPolicyAsync(new PutUserPolicyRequest() { UserName = username, PolicyName = policyNames[i], PolicyDocument = TEST_ALLOW_POLICY }).Wait(); } ListUserPoliciesResponse response = Client.ListUserPoliciesAsync(new ListUserPoliciesRequest() { UserName = username }).Result; Assert.AreEqual(nPolicies, response.PolicyNames.Count()); int matches = 0; foreach (string name in response.PolicyNames) { for (int i = 0; i < nPolicies; i++) { if (name.Equals(policyNames[i])) matches |= (1 << i); } } Assert.AreEqual((1 << nPolicies) - 1, matches); } finally { IAMUtil.DeleteTestUsers(Client, username); } } [Test] [Category("IAM")] public void TestListGroupPolicies() { string grpname = "sdk-testgroup-" + DateTime.Now.Ticks; string[] policyNames = new string[3]; int nPolicies = 3; try { Client.CreateGroupAsync(new CreateGroupRequest() { GroupName = grpname, Path = IAMUtil.TEST_PATH }).Wait(); for (int i = 0; i < nPolicies; i++) { policyNames[i] = "test-policy-" + DateTime.Now.Ticks + i; Client.PutGroupPolicyAsync(new PutGroupPolicyRequest() { GroupName = grpname, PolicyName = policyNames[i], PolicyDocument = TEST_ALLOW_POLICY }).Wait(); } ListGroupPoliciesResponse response = Client.ListGroupPoliciesAsync(new ListGroupPoliciesRequest() { GroupName = grpname }).Result; Assert.AreEqual(nPolicies, response.PolicyNames.Count()); int matches = 0; foreach (string name in response.PolicyNames) { for (int i = 0; i < nPolicies; i++) { if (name.Equals(policyNames[i])) matches |= (1 << i); } } Assert.AreEqual((1 << nPolicies) - 1, matches); } finally { for (int i = 0; i < nPolicies; i++) { Client.DeleteGroupPolicyAsync(new DeleteGroupPolicyRequest() { GroupName = grpname, PolicyName = policyNames[i] }).Wait(); } Client.DeleteGroupAsync(new DeleteGroupRequest() { GroupName = grpname }).Wait(); } } [Test] [Category("IAM")] public void TestListUserPoliciesPaging() { string username = IAMUtil.CreateTestUser(Client); int nPolicies = 4; string[] policyNames = new string[nPolicies]; try { for (int i = 0; i < nPolicies; i++) { policyNames[i] = "test-policy-" + DateTime.Now.Ticks + i; Client.PutUserPolicyAsync(new PutUserPolicyRequest() { UserName = username, PolicyName = policyNames[i], PolicyDocument = TEST_ALLOW_POLICY }).Wait(); } ListUserPoliciesResponse response = Client.ListUserPoliciesAsync(new ListUserPoliciesRequest() { UserName = username, MaxItems = 2 }).Result; Assert.AreEqual(2, response.PolicyNames.Count()); Assert.AreEqual(true, response.IsTruncated); string marker = response.Marker; int matches = 0; foreach (string name in response.PolicyNames) { for (int i = 0; i < nPolicies; i++) { if (name.Equals(policyNames[i])) matches |= (1 << i); } } response = Client.ListUserPoliciesAsync(new ListUserPoliciesRequest() { UserName = username, Marker = marker }).Result; Assert.AreEqual(nPolicies - 2, response.PolicyNames.Count()); Assert.AreEqual(false, response.IsTruncated); foreach (string name in response.PolicyNames) { for (int i = 0; i < nPolicies; i++) { if (name.Equals(policyNames[i])) matches |= (1 << i); } } Assert.AreEqual((1 << nPolicies) - 1, matches); } finally { IAMUtil.DeleteTestUsers(Client, username); } } [Test] [Category("IAM")] public void TestListGroupPoliciesPaging() { string grpname = "sdk-testgroup-" + DateTime.Now.Ticks; int nPolicies = 3; string[] policyNames = new string[nPolicies]; try { Client.CreateGroupAsync(new CreateGroupRequest() { GroupName = grpname, Path = IAMUtil.TEST_PATH }).Wait(); for (int i = 0; i < nPolicies; i++) { policyNames[i] = "test-policy-" + DateTime.Now.Ticks + i; Client.PutGroupPolicyAsync(new PutGroupPolicyRequest() { GroupName = grpname, PolicyName = policyNames[i], PolicyDocument = TEST_ALLOW_POLICY }).Wait(); } ListGroupPoliciesResponse response = Client.ListGroupPoliciesAsync(new ListGroupPoliciesRequest() { GroupName = grpname, MaxItems = 2 }).Result; Assert.AreEqual(2, response.PolicyNames.Count()); Assert.AreEqual(true, response.IsTruncated); string marker = response.Marker; int matches = 0; foreach (string name in response.PolicyNames) { for (int i = 0; i < nPolicies; i++) { if (name.Equals(policyNames[i])) matches |= (1 << i); } } response = Client.ListGroupPoliciesAsync(new ListGroupPoliciesRequest() { GroupName = grpname, Marker = marker }).Result; Assert.AreEqual(nPolicies - 2, response.PolicyNames.Count()); Assert.AreEqual(false, response.IsTruncated); foreach (string name in response.PolicyNames) { for (int i = 0; i < nPolicies; i++) { if (name.Equals(policyNames[i])) matches |= (1 << i); } } Assert.AreEqual((1 << nPolicies) - 1, matches); } finally { for (int i = 0; i < nPolicies; i++) { Client.DeleteGroupPolicyAsync(new DeleteGroupPolicyRequest() { GroupName = grpname, PolicyName = policyNames[i] }).Wait(); } Client.DeleteGroupAsync(new DeleteGroupRequest() { GroupName = grpname }).Wait(); } } [Test] [Category("IAM")] public void TestDeleteUserPolicy() { string username = IAMUtil.CreateTestUser(Client); string pName = "sdk-policy-" + DateTime.Now.Ticks; try { Client.PutUserPolicyAsync(new PutUserPolicyRequest() { UserName = username, PolicyName = pName, PolicyDocument = TEST_ALLOW_POLICY }).Wait(); ListUserPoliciesResponse response = Client.ListUserPoliciesAsync(new ListUserPoliciesRequest() { UserName = username }).Result; Assert.AreEqual(1, response.PolicyNames.Count()); Client.DeleteUserPolicyAsync(new DeleteUserPolicyRequest() { UserName = username, PolicyName = pName }).Wait(); response = Client.ListUserPoliciesAsync(new ListUserPoliciesRequest() { UserName = username }).Result; Assert.AreEqual(0, response.PolicyNames.Count()); } finally { IAMUtil.DeleteTestUsers(Client, username); } } [Test] [Category("IAM")] public void TestDeleteGroupPolicy() { string groupname = "sdk-testgroup-" + DateTime.Now.Ticks; string pName = "test-policy-" + DateTime.Now.Ticks; try { Client.CreateGroupAsync(new CreateGroupRequest() { GroupName = groupname, Path = IAMUtil.TEST_PATH }).Wait(); Client.PutGroupPolicyAsync(new PutGroupPolicyRequest() { GroupName = groupname, PolicyName = pName, PolicyDocument = TEST_ALLOW_POLICY }).Wait(); ListGroupPoliciesResponse response = Client.ListGroupPoliciesAsync(new ListGroupPoliciesRequest() { GroupName = groupname }).Result; Assert.AreEqual(1, response.PolicyNames.Count()); Client.DeleteGroupPolicyAsync(new DeleteGroupPolicyRequest() { GroupName = groupname, PolicyName = pName }).Wait(); response = Client.ListGroupPoliciesAsync(new ListGroupPoliciesRequest() { GroupName = groupname }).Result; Assert.AreEqual(0, response.PolicyNames.Count()); } finally { Client.DeleteGroupAsync(new DeleteGroupRequest() { GroupName = groupname }).Wait(); } } [Test] [Category("IAM")] //[ExpectedException(typeof(NoSuchEntityException))] public void TestDeleteNonExistentGroupPolicyException() { string groupname = "sdk-testgroup-" + DateTime.Now.Ticks; try { Client.CreateGroupAsync(new CreateGroupRequest() { GroupName = groupname, Path = IAMUtil.TEST_PATH }).Wait(); Client.DeleteGroupPolicyAsync(new DeleteGroupPolicyRequest() { GroupName = groupname, PolicyName = "test-policy" + DateTime.Now.Ticks }).Wait(); } catch (AggregateException ae) { AssertExtensions.VerifyException<NoSuchEntityException>(ae); } finally { Client.DeleteGroupAsync(new DeleteGroupRequest() { GroupName = groupname }).Wait(); } } [Test] [Category("IAM")] //[ExpectedException(typeof(NoSuchEntityException))] public void TestGetNonExistentGroupPolicyException() { string groupname = "sdk-testgroup-" + DateTime.Now.Ticks; try { Client.CreateGroupAsync(new CreateGroupRequest() { GroupName = groupname, Path = IAMUtil.TEST_PATH }).Wait(); Client.GetGroupPolicyAsync(new GetGroupPolicyRequest() { GroupName = groupname, PolicyName = "test-policy-" + DateTime.Now.Ticks }).Wait(); } catch (AggregateException ae) { AssertExtensions.VerifyException<NoSuchEntityException>(ae); } finally { Client.DeleteGroupAsync(new DeleteGroupRequest() { GroupName = groupname }).Wait(); } } [Test] [Category("IAM")] //[ExpectedException(typeof(NoSuchEntityException))] public void TestDeleteNonExistentUserPolicyException() { string username = IAMUtil.CreateTestUser(Client); try { Client.DeleteUserPolicyAsync(new DeleteUserPolicyRequest() { UserName = username, PolicyName = "test-policy-" + DateTime.Now.Ticks }).Wait(); } catch (AggregateException ae) { AssertExtensions.VerifyException<NoSuchEntityException>(ae); } finally { IAMUtil.DeleteTestUsers(Client, username); } } [Test] [Category("IAM")] //[ExpectedException(typeof(NoSuchEntityException))] public void TestGetNonExistentUserPolicyException() { string username = IAMUtil.CreateTestUser(Client); try { Client.GetUserPolicyAsync(new GetUserPolicyRequest() { UserName = username, PolicyName = "test-policy-" + DateTime.Now.Ticks }).Wait(); } catch (AggregateException ae) { AssertExtensions.VerifyException<NoSuchEntityException>(ae); } finally { IAMUtil.DeleteTestUsers(Client, username); } } [Test] [Category("IAM")] //[ExpectedException(typeof(MalformedPolicyDocumentException))] public void TestPutUserPolicyMalformedPolicyDocumentException() { string username = IAMUtil.CreateTestUser(Client); string policyName = "test-policy-" + DateTime.Now.Ticks; try { Client.PutUserPolicyAsync(new PutUserPolicyRequest() { UserName = username, PolicyName = policyName, PolicyDocument = "[" }).Wait(); } catch (AggregateException ae) { AssertExtensions.VerifyException<MalformedPolicyDocumentException>(ae); } finally { IAMUtil.DeleteTestUsers(Client, username); } } [Test] [Category("IAM")] public void TestCreateManagedPolicy() { string policyName = "test-policy-" + DateTime.Now.Ticks; string arn = null; Client.CreatePolicyAsync(new CreatePolicyRequest { PolicyName = policyName, PolicyDocument = TEST_VERSIONED_POLICY }).Wait(); try { arn = UtilityMethods.WaitUntilSuccess(() => FindPolicy(policyName)); } finally { if (arn != null) Client.DeletePolicyAsync(new DeletePolicyRequest { PolicyArn = arn }).Wait(); } } private string FindPolicy(string policyName) { string arn = null; var policies = ListAllPolicies().ToList(); var found = false; foreach (var policy in policies) { if (policy.PolicyName.Equals(policyName)) { found = true; arn = policy.Arn; } } Assert.IsTrue(found); Assert.IsNotNull(arn); return arn; } private IEnumerable<ManagedPolicy> ListAllPolicies() { var request = new ListPoliciesRequest(); ListPoliciesResponse response; do { response = Client.ListPoliciesAsync(request).Result; foreach (var p in response.Policies) yield return p; request.Marker = response.Marker; } while (response.IsTruncated); } [Test] [Category("IAM")] public void TestAttachManagedPolicy() { string username = IAMUtil.CreateTestUser(Client); string policyName = "sdk-policy-" + DateTime.Now.Ticks; var policyArn = Client.CreatePolicyAsync(new CreatePolicyRequest { PolicyName = policyName, PolicyDocument = TEST_VERSIONED_POLICY }).Result.Policy.Arn; try { Client.AttachUserPolicyAsync(new AttachUserPolicyRequest { UserName = username, PolicyArn = policyArn }).Wait(); Client.DetachUserPolicyAsync(new DetachUserPolicyRequest { UserName = username, PolicyArn = policyArn }).Wait(); } finally { IAMUtil.DeleteTestUsers(Client, username); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using Newtonsoft.Json.Linq; using Umbraco.Core; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; namespace Umbraco.Web.PropertyEditors { [PropertyEditor(Constants.PropertyEditors.UploadFieldAlias, "File upload", "fileupload", Icon = "icon-download-alt", Group = "media")] public class FileUploadPropertyEditor : PropertyEditor, IApplicationEventHandler { private static MediaFileSystem MediaFileSystem { // v8 will get rid of singletons get { return FileSystemProviderManager.Current.MediaFileSystem; } } /// <summary> /// Creates the corresponding property value editor. /// </summary> /// <returns>The corresponding property value editor.</returns> protected override PropertyValueEditor CreateValueEditor() { var baseEditor = base.CreateValueEditor(); baseEditor.Validators.Add(new UploadFileTypeValidator()); return new FileUploadPropertyValueEditor(baseEditor, MediaFileSystem); } /// <summary> /// Gets a value indicating whether a property is an upload field. /// </summary> /// <param name="property">The property.</param> /// <param name="ensureValue">A value indicating whether to check that the property has a non-empty value.</param> /// <returns>A value indicating whether a property is an upload field, and (optionaly) has a non-empty value.</returns> private static bool IsUploadField(Property property, bool ensureValue) { if (property.PropertyType.PropertyEditorAlias != Constants.PropertyEditors.UploadFieldAlias) return false; if (ensureValue == false) return true; return property.Value is string && string.IsNullOrWhiteSpace((string) property.Value) == false; } /// <summary> /// Gets the files that need to be deleted when entities are deleted. /// </summary> /// <param name="properties">The properties that were deleted.</param> static IEnumerable<string> GetFilesToDelete(IEnumerable<Property> properties) { return properties .Where(x => IsUploadField(x, true)) .Select(x => MediaFileSystem.GetRelativePath((string) x.Value)) .ToList(); } /// <summary> /// After a content has been copied, also copy uploaded files. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="args">The event arguments.</param> static void ContentServiceCopied(IContentService sender, Core.Events.CopyEventArgs<IContent> args) { // get the upload field properties with a value var properties = args.Original.Properties.Where(x => IsUploadField(x, true)); // copy files var isUpdated = false; foreach (var property in properties) { var sourcePath = MediaFileSystem.GetRelativePath((string) property.Value); var copyPath = MediaFileSystem.CopyFile(args.Copy, property.PropertyType, sourcePath); args.Copy.SetValue(property.Alias, MediaFileSystem.GetUrl(copyPath)); isUpdated = true; } // if updated, re-save the copy with the updated value if (isUpdated) sender.Save(args.Copy); } /// <summary> /// After a media has been created, auto-fill the properties. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="args">The event arguments.</param> static void MediaServiceCreated(IMediaService sender, Core.Events.NewEventArgs<IMedia> args) { AutoFillProperties(args.Entity); } /// <summary> /// After a media has been saved, auto-fill the properties. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="args">The event arguments.</param> static void MediaServiceSaving(IMediaService sender, Core.Events.SaveEventArgs<IMedia> args) { foreach (var entity in args.SavedEntities) AutoFillProperties(entity); } /// <summary> /// After a content item has been saved, auto-fill the properties. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="args">The event arguments.</param> static void ContentServiceSaving(IContentService sender, Core.Events.SaveEventArgs<IContent> args) { foreach (var entity in args.SavedEntities) AutoFillProperties(entity); } /// <summary> /// Auto-fill properties (or clear). /// </summary> /// <param name="content">The content.</param> static void AutoFillProperties(IContentBase content) { var properties = content.Properties.Where(x => IsUploadField(x, false)); foreach (var property in properties) { var autoFillConfig = MediaFileSystem.UploadAutoFillProperties.GetConfig(property.Alias); if (autoFillConfig == null) continue; var svalue = property.Value as string; if (string.IsNullOrWhiteSpace(svalue)) MediaFileSystem.UploadAutoFillProperties.Reset(content, autoFillConfig); else MediaFileSystem.UploadAutoFillProperties.Populate(content, autoFillConfig, MediaFileSystem.GetRelativePath(svalue)); } } #region Application event handler, used to bind to events on startup // The FileUploadPropertyEditor properties own files and as such must manage these files, // so we are binding to events in order to make sure that // - files are deleted when the owning content/media is // - files are copied when the owning content is // - populate the auto-fill properties when the owning content/media is saved // // NOTE: // although some code fragments seem to want to support uploading multiple files, // this is NOT a feature of the FileUploadPropertyEditor and is NOT supported // // auto-fill properties are recalculated EVERYTIME the content/media is saved, // even if the property has NOT been modified (it could be the same filename but // a different file) - this is accepted (auto-fill props should die) // // TODO in v8: // for some weird backward compatibility reasons, // - media copy is not supported // - auto-fill properties are not supported for content items // - auto-fill runs on MediaService.Created which makes no sense (no properties yet) public void OnApplicationInitialized(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { // nothing } public void OnApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { // nothing } public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { // only if the app is configured // see ApplicationEventHandler.ShouldExecute if (applicationContext.IsConfigured == false || applicationContext.DatabaseContext.IsDatabaseConfigured == false) return; MediaService.Created += MediaServiceCreated; // see above - makes no sense MediaService.Saving += MediaServiceSaving; //MediaService.Copied += MediaServiceCopied; // see above - missing ContentService.Copied += ContentServiceCopied; //ContentService.Saving += ContentServiceSaving; // see above - missing MediaService.Deleted += (sender, args) => args.MediaFilesToDelete.AddRange( GetFilesToDelete(args.DeletedEntities.SelectMany(x => x.Properties))); MediaService.EmptiedRecycleBin += (sender, args) => args.Files.AddRange( GetFilesToDelete(args.AllPropertyData.SelectMany(x => x.Value))); ContentService.Deleted += (sender, args) => args.MediaFilesToDelete.AddRange( GetFilesToDelete(args.DeletedEntities.SelectMany(x => x.Properties))); ContentService.EmptiedRecycleBin += (sender, args) => args.Files.AddRange( GetFilesToDelete(args.AllPropertyData.SelectMany(x => x.Value))); MemberService.Deleted += (sender, args) => args.MediaFilesToDelete.AddRange( GetFilesToDelete(args.DeletedEntities.SelectMany(x => x.Properties))); } #endregion } }
using System; using System.Globalization; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using EnvDTE; using Microsoft.VisualStudio.ExtensionsExplorer.UI; using Microsoft.VisualStudio.PlatformUI; using NuGet.Dialog.PackageManagerUI; using NuGet.Dialog.Providers; using NuGet.VisualStudio; using System.Diagnostics.CodeAnalysis; namespace NuGet.Dialog { [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public partial class PackageManagerWindow : DialogWindow { internal static PackageManagerWindow CurrentInstance; private const string DialogUserAgentClient = "NuGet Add Package Dialog"; private readonly Lazy<string> _dialogUserAgent = new Lazy<string>(() => HttpUtility.CreateUserAgentString(DialogUserAgentClient)); private const string F1Keyword = "vs.ExtensionManager"; private readonly IHttpClientEvents _httpClientEvents; private bool _hasOpenedOnlineProvider; private ComboBox _prereleaseComboBox; private readonly SmartOutputConsoleProvider _smartOutputConsoleProvider; private readonly IProviderSettings _providerSettings; private readonly IProductUpdateService _productUpdateService; private readonly IOptionsPageActivator _optionsPageActivator; private readonly Project _activeProject; public PackageManagerWindow(Project project) : this(project, ServiceLocator.GetInstance<DTE>(), ServiceLocator.GetInstance<IVsPackageManagerFactory>(), ServiceLocator.GetInstance<IPackageRepositoryFactory>(), ServiceLocator.GetInstance<IPackageSourceProvider>(), ServiceLocator.GetInstance<IRecentPackageRepository>(), ServiceLocator.GetInstance<IHttpClientEvents>(), ServiceLocator.GetInstance<IProductUpdateService>(), ServiceLocator.GetInstance<IPackageRestoreManager>(), ServiceLocator.GetInstance<ISolutionManager>(), ServiceLocator.GetInstance<IOptionsPageActivator>()) { } private PackageManagerWindow(Project project, DTE dte, IVsPackageManagerFactory packageManagerFactory, IPackageRepositoryFactory repositoryFactory, IPackageSourceProvider packageSourceProvider, IRecentPackageRepository recentPackagesRepository, IHttpClientEvents httpClientEvents, IProductUpdateService productUpdateService, IPackageRestoreManager packageRestoreManager, ISolutionManager solutionManager, IOptionsPageActivator optionPageActivator) : base(F1Keyword) { InitializeComponent(); #if !VS10 // set unique search guid for VS11 explorer.SearchCategory = new Guid("{85566D5F-E585-411F-B299-5BF006E9F11E}"); #endif _httpClientEvents = httpClientEvents; if (_httpClientEvents != null) { _httpClientEvents.SendingRequest += OnSendingRequest; } _productUpdateService = productUpdateService; _optionsPageActivator = optionPageActivator; _activeProject = project; // replace the ConsoleOutputProvider with SmartOutputConsoleProvider so that we can clear // the console the first time an entry is written to it var providerServices = new ProviderServices(); _smartOutputConsoleProvider = new SmartOutputConsoleProvider(providerServices.OutputConsoleProvider); providerServices.OutputConsoleProvider = _smartOutputConsoleProvider; _providerSettings = providerServices.ProviderSettings; AddUpdateBar(productUpdateService); AddRestoreBar(packageRestoreManager); InsertDisclaimerElement(); AdjustSortComboBoxWidth(); PreparePrereleaseComboBox(); SetupProviders( project, dte, packageManagerFactory, repositoryFactory, packageSourceProvider, providerServices, recentPackagesRepository, httpClientEvents, solutionManager, packageRestoreManager); } private void AddUpdateBar(IProductUpdateService productUpdateService) { var updateBar = new ProductUpdateBar(productUpdateService); updateBar.UpdateStarting += ExecutedClose; LayoutRoot.Children.Add(updateBar); updateBar.SizeChanged += OnHeaderBarSizeChanged; } private void AddRestoreBar(IPackageRestoreManager packageRestoreManager) { var restoreBar = new PackageRestoreBar(packageRestoreManager); LayoutRoot.Children.Add(restoreBar); restoreBar.SizeChanged += OnHeaderBarSizeChanged; } private void OnHeaderBarSizeChanged(object sender, SizeChangedEventArgs e) { // when the update bar appears, we adjust the window position // so that it doesn't push the main content area down if (e.HeightChanged) { double heightDifference = e.NewSize.Height - e.PreviousSize.Height; if (heightDifference > 0) { Top = Math.Max(0, Top - heightDifference); } } } [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] private void SetupProviders(Project activeProject, DTE dte, IVsPackageManagerFactory packageManagerFactory, IPackageRepositoryFactory packageRepositoryFactory, IPackageSourceProvider packageSourceProvider, ProviderServices providerServices, IPackageRepository recentPackagesRepository, IHttpClientEvents httpClientEvents, ISolutionManager solutionManager, IPackageRestoreManager packageRestoreManager) { // This package manager is not used for installing from a remote source, and therefore does not need a fallback repository for resolving dependencies IVsPackageManager packageManager = packageManagerFactory.CreatePackageManager(ServiceLocator.GetInstance<IPackageRepository>(), useFallbackForDependencies: false); IPackageRepository localRepository; // we need different sets of providers depending on whether the dialog is open for solution or a project OnlineProvider onlineProvider; InstalledProvider installedProvider; UpdatesProvider updatesProvider; OnlineProvider recentProvider; if (activeProject == null) { Title = String.Format( CultureInfo.CurrentUICulture, NuGet.Dialog.Resources.Dialog_Title, dte.Solution.GetName() + ".sln"); localRepository = packageManager.LocalRepository; onlineProvider = new SolutionOnlineProvider( localRepository, Resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, httpClientEvents, solutionManager); installedProvider = new SolutionInstalledProvider( packageManager, localRepository, Resources, providerServices, httpClientEvents, solutionManager, packageRestoreManager); updatesProvider = new SolutionUpdatesProvider( localRepository, Resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, httpClientEvents, solutionManager); recentProvider = new SolutionRecentProvider( localRepository, Resources, packageRepositoryFactory, packageManagerFactory, recentPackagesRepository, packageSourceProvider, providerServices, httpClientEvents, solutionManager); } else { IProjectManager projectManager = packageManager.GetProjectManager(activeProject); localRepository = projectManager.LocalRepository; Title = String.Format( CultureInfo.CurrentUICulture, NuGet.Dialog.Resources.Dialog_Title, activeProject.GetDisplayName()); onlineProvider = new OnlineProvider( activeProject, localRepository, Resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, httpClientEvents, solutionManager); installedProvider = new InstalledProvider( packageManager, activeProject, localRepository, Resources, providerServices, httpClientEvents, solutionManager, packageRestoreManager); updatesProvider = new UpdatesProvider( activeProject, localRepository, Resources, packageRepositoryFactory, packageSourceProvider, packageManagerFactory, providerServices, httpClientEvents, solutionManager); recentProvider = new RecentProvider( activeProject, localRepository, Resources, packageRepositoryFactory, packageManagerFactory, recentPackagesRepository, packageSourceProvider, providerServices, httpClientEvents, solutionManager); } explorer.Providers.Add(installedProvider); explorer.Providers.Add(onlineProvider); explorer.Providers.Add(updatesProvider); explorer.Providers.Add(recentProvider); installedProvider.IncludePrerelease = onlineProvider.IncludePrerelease = updatesProvider.IncludePrerelease = recentProvider.IncludePrerelease = _providerSettings.IncludePrereleasePackages; // retrieve the selected provider from the settings int selectedProvider = Math.Min(3, _providerSettings.SelectedProvider); explorer.SelectedProvider = explorer.Providers[selectedProvider]; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't care about exception handling here.")] private void CanExecuteCommandOnPackage(object sender, CanExecuteRoutedEventArgs e) { if (OperationCoordinator.IsBusy) { e.CanExecute = false; return; } VSExtensionsExplorerCtl control = e.Source as VSExtensionsExplorerCtl; if (control == null) { e.CanExecute = false; return; } PackageItem selectedItem = control.SelectedExtension as PackageItem; if (selectedItem == null) { e.CanExecute = false; return; } try { e.CanExecute = selectedItem.IsEnabled; } catch (Exception) { e.CanExecute = false; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't care about exception handling here.")] private void ExecutedPackageCommand(object sender, ExecutedRoutedEventArgs e) { if (OperationCoordinator.IsBusy) { return; } VSExtensionsExplorerCtl control = e.Source as VSExtensionsExplorerCtl; if (control == null) { return; } PackageItem selectedItem = control.SelectedExtension as PackageItem; if (selectedItem == null) { return; } PackagesProviderBase provider = control.SelectedProvider as PackagesProviderBase; if (provider != null) { try { provider.Execute(selectedItem); } catch (Exception exception) { MessageHelper.ShowErrorMessage(exception, NuGet.Dialog.Resources.Dialog_MessageBoxTitle); ExceptionHelper.WriteToActivityLog(exception); } } } private void ExecutedClose(object sender, EventArgs e) { Close(); } private void ExecutedShowOptionsPage(object sender, ExecutedRoutedEventArgs e) { Close(); _optionsPageActivator.ActivatePage( OptionsPage.PackageSources, () => OnActivated(_activeProject)); } /// <summary> /// Called when coming back from the Options dialog /// </summary> private static void OnActivated(Project project) { var window = new PackageManagerWindow(project); try { window.ShowModal(); } catch (TargetInvocationException exception) { MessageHelper.ShowErrorMessage(exception, NuGet.Dialog.Resources.Dialog_MessageBoxTitle); ExceptionHelper.WriteToActivityLog(exception); } } private void ExecuteOpenLicenseLink(object sender, ExecutedRoutedEventArgs e) { Hyperlink hyperlink = e.OriginalSource as Hyperlink; if (hyperlink != null && hyperlink.NavigateUri != null) { UriHelper.OpenExternalLink(hyperlink.NavigateUri); e.Handled = true; } } private void ExecuteSetFocusOnSearchBox(object sender, ExecutedRoutedEventArgs e) { explorer.SetFocusOnSearchBox(); } private void OnCategorySelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { PackagesTreeNodeBase selectedNode = explorer.SelectedExtensionTreeNode as PackagesTreeNodeBase; if (selectedNode != null) { // notify the selected node that it is opened. selectedNode.OnOpened(); } } private void OnDialogWindowClosing(object sender, System.ComponentModel.CancelEventArgs e) { // don't allow the dialog to be closed if an operation is pending if (OperationCoordinator.IsBusy) { e.Cancel = true; } } private void OnDialogWindowClosed(object sender, EventArgs e) { foreach (PackagesProviderBase provider in explorer.Providers) { // give each provider a chance to clean up itself provider.Dispose(); } explorer.Providers.Clear(); // flush output messages to the Output console at once when the dialog is closed. _smartOutputConsoleProvider.Flush(); CurrentInstance = null; } /// <summary> /// HACK HACK: Insert the disclaimer element into the correct place inside the Explorer control. /// We don't want to bring in the whole control template of the extension explorer control. /// </summary> private void InsertDisclaimerElement() { Grid grid = LogicalTreeHelper.FindLogicalNode(explorer, "resGrid") as Grid; if (grid != null) { // m_Providers is the name of the expander provider control (the one on the leftmost column) UIElement providerExpander = FindChildElementByNameOrType(grid, "m_Providers", typeof(ProviderExpander)); if (providerExpander != null) { // remove disclaimer text and provider expander from their current parents grid.Children.Remove(providerExpander); LayoutRoot.Children.Remove(DisclaimerText); // create the inner grid which will host disclaimer text and the provider extender Grid innerGrid = new Grid(); innerGrid.RowDefinitions.Add(new RowDefinition()); innerGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0, GridUnitType.Auto) }); innerGrid.Children.Add(providerExpander); Grid.SetRow(DisclaimerText, 1); innerGrid.Children.Add(DisclaimerText); // add the inner grid to the first column of the original grid grid.Children.Add(innerGrid); } } } private void AdjustSortComboBoxWidth() { ComboBox sortCombo = FindComboBox("cmd_SortOrder"); if (sortCombo != null) { // The default style fixes the Sort combo control's width to 160, which is bad for localization. // We fix it by setting Min width as 160, and let the control resize to content. sortCombo.ClearValue(FrameworkElement.WidthProperty); sortCombo.MinWidth = 160; } } private void PreparePrereleaseComboBox() { // This ComboBox is actually used to display framework versions in various VS dialogs. // We "repurpose" it here to show Prerelease option instead. ComboBox fxCombo = FindComboBox("cmb_Fx"); if (fxCombo != null) { fxCombo.Items.Clear(); fxCombo.Items.Add(NuGet.Dialog.Resources.Filter_StablePackages); fxCombo.Items.Add(NuGet.Dialog.Resources.Filter_IncludePrerelease); fxCombo.SelectedIndex = _providerSettings.IncludePrereleasePackages ? 1 : 0; fxCombo.SelectionChanged += OnFxComboBoxSelectionChanged; _prereleaseComboBox = fxCombo; } } private void OnFxComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e) { var combo = (ComboBox)sender; if (combo.SelectedIndex == -1) { return; } bool includePrerelease = combo.SelectedIndex == 1; // persist the option to VS settings store _providerSettings.IncludePrereleasePackages = includePrerelease; // set the flags on all providers foreach (PackagesProviderBase provider in explorer.Providers) { provider.IncludePrerelease = includePrerelease; } var selectedTreeNode = explorer.SelectedExtensionTreeNode as PackagesTreeNodeBase; if (selectedTreeNode != null) { selectedTreeNode.Refresh(resetQueryBeforeRefresh: true); } } private ComboBox FindComboBox(string name) { Grid grid = LogicalTreeHelper.FindLogicalNode(explorer, "resGrid") as Grid; if (grid != null) { return FindChildElementByNameOrType(grid, name, typeof(SortCombo)) as ComboBox; } return null; } private static UIElement FindChildElementByNameOrType(Grid parent, string childName, Type childType) { UIElement element = parent.FindName(childName) as UIElement; if (element != null) { return element; } else { foreach (UIElement child in parent.Children) { if (childType.IsInstanceOfType(child)) { return child; } } return null; } } private void OnProviderSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { var selectedProvider = explorer.SelectedProvider as PackagesProviderBase; if (selectedProvider != null) { explorer.NoItemsMessage = selectedProvider.NoItemsMessage; _prereleaseComboBox.Visibility = selectedProvider.ShowPrereleaseComboBox ? Visibility.Visible : Visibility.Collapsed; // save the selected provider to user settings _providerSettings.SelectedProvider = explorer.Providers.IndexOf(selectedProvider); // if this is the first time online provider is opened, call to check for update if (selectedProvider == explorer.Providers[1] && !_hasOpenedOnlineProvider) { _hasOpenedOnlineProvider = true; _productUpdateService.CheckForAvailableUpdateAsync(); } } else { _prereleaseComboBox.Visibility = Visibility.Collapsed; } } private void OnSendingRequest(object sender, WebRequestEventArgs e) { HttpUtility.SetUserAgent(e.Request, _dialogUserAgent.Value); } private void CanExecuteClose(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = !OperationCoordinator.IsBusy; e.Handled = true; } private void OnDialogWindowLoaded(object sender, RoutedEventArgs e) { // HACK: Keep track of the currently open instance of this class. CurrentInstance = this; } } }
namespace SQLServerSearcher.Presenters { using System; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Text.RegularExpressions; using DAL; using DAL.Contracts; using Model; using Model.EventArgs; using Views; using Index = Model.Index; public class FrmSqlServerSearcherPresenter { private readonly IFrmSqlServerSearcher _view; private readonly IServer _server; private readonly IDatabases _databases; private readonly ITables _tables; private readonly IViews _views; private readonly IIndexes _indexes; private readonly IStoredProcedures _storedProcedures; private readonly IFunctions _functions; public FrmSqlServerSearcherPresenter(IFrmSqlServerSearcher view, IServer server, IDatabases databases, ITables tables, IViews views, IIndexes indexes, IStoredProcedures storedProcedures, IFunctions functions) { _view = view; _server = server; _databases = databases; _tables = tables; _views = views; _indexes = indexes; _storedProcedures = storedProcedures; _functions = functions; Initialize(); } public FrmSqlServerSearcherPresenter(IFrmSqlServerSearcher view) : this( view, new Server(view.AppState), new Databases(view.AppState), new Tables(view.AppState), new Views(view.AppState), new Indexes(view.AppState), new StoredProcedures(view.AppState), new Functions(view.AppState) ) { } private void Initialize() { _view.BtnFindClick += DoBtnFindClick; _view.BtnConnectClick += DoBtnConnectClick; _view.EnableDisableBtnConnect += DoEnableDisableBtnConnect; _view.TreeviewNodeClick += DoTreeviewNodeClick; _view.CopyQueryToClipboardToolStripMenuItemClick += DoCopyQueryToClipboardToolStripMenuItemClick; _view.CopyNameToClipboardToolStripMenuItemClick += DoCopyNameToClipboardToolStripMenuItemClick; _view.CopyInformationToClipboardToolStripMenuItemClick += DoCopyInformationToClipboardToolStripMenuItemClick; _view.CopyServerInformationClick += DoCopyServerInformationClick; _view.CopyListToClipboardToolStripMenuItemClick += DoCopyListToClipboardToolStripMenuItemClick; _view.DatabaseSelectedIndexChanged += DoDatabaseSelectedIndexChanged; } private void DoBtnConnectClick(object sender, ConnectEventArgs args) { if (_view.ShowLoginDialog(args.Server)) { _view.InsertServerIntoCombobox(args.Server); try { _view.AppState.CurrentConnection.Open(); var databases = _databases.GetDatabases(); _view.ClearDatabasesCombobox(); foreach (var database in databases.OrderBy(p => p.Name)) { _view.InsertDatabaseIntoCombobox(database.Name); } var serverInfo = _server.GetServerInfo(); _view.ShowServerInfo(serverInfo); _view.SetLblServerName(); } catch (SqlException sqlEx) { _view.ShowErrorDialog(string.Format("Connection to server failed: {0}", sqlEx.Message)); } catch (Exception ex) { _view.ShowErrorDialog(string.Format("Connection to server failed: {0}", ex)); } } } private void DoDatabaseSelectedIndexChanged(object sender, DatabaseChangedEventArgs args) { _view.ClearDatabaseInformation(); var databaseMetaInfo = _databases.FindDatabaseMetaInfo(args.Database); _view.ShowDatabaseInfo(databaseMetaInfo); _view.SetLblDatabase(); } private void DoBtnFindClick(object sender, FindEventArgs args) { _view.ClearResults(); _view.ClearObjectInformation(); var startTime = DateTime.Now; int rowCount = 0; rowCount += DoFindTables(args); rowCount += DoFindViews(args); rowCount += DoFindIndexes(args); rowCount += DoFindStoredProcedures(args); rowCount += DoFindFunctions(args); _view.InsertSearchQueryIntoCombobox(args.FindWhat); var executionTime = DateTime.Now - startTime; _view.SetExecutionTime(executionTime); _view.SetLblRowCount(rowCount); if (rowCount == 0) { _view.ShowNoResultsFound(); } } private int DoFindTables(FindEventArgs args) { int rowCount = 0; if (args.LookInTables) { var tables = _tables.FindTables(args.Database, args.FindWhat); if (args.MatchCase) { tables = tables.Where(p => string.Compare(p.Name, args.FindWhat, StringComparison.Ordinal) == 0).ToList(); } tables = tables.OrderBy(p => p.SchemaName).ThenBy(p => p.Name).ThenBy(p => p.ColumnName).ToList(); _view.InsertTableIntoTreeview(tables); rowCount = tables.Count; rowCount += DoFindTableExtendedProperties(args); } return rowCount; } private int DoFindTableExtendedProperties(FindEventArgs args) { int rowCount = 0; if (args.LookInExtendedProperties) { var tableExtendedProperties = _tables.FindTableExtendedProperties(args.Database, args.FindWhat); if (args.MatchCase) { tableExtendedProperties = tableExtendedProperties.Where(p => string.Compare(p.Name, args.FindWhat, StringComparison.Ordinal) == 0).ToList(); } tableExtendedProperties = tableExtendedProperties.OrderBy(p => p.SchemaName).ThenBy(p => p.TableName).ThenBy(p => p.ColumnName).ThenBy(p => p.Name).ToList(); _view.InsertTableExtendedPropertiesIntoTreeview(tableExtendedProperties); rowCount = tableExtendedProperties.Count; } return rowCount; } private int DoFindViews(FindEventArgs args) { int rowCount = 0; if (args.LookInViews) { var views = _views.FindViews(args.Database, args.FindWhat); if (args.MatchCase) { views = views.Where(p => string.Compare(p.Name, args.FindWhat, StringComparison.Ordinal) == 0).ToList(); } views = views.OrderBy(p => p.SchemaName).ThenBy(p => p.Name).ThenBy(p => p.ColumnName).ToList(); _view.InsertViewIntoTreeview(views); rowCount = views.Count; rowCount += DoFindViewExtendedProperties(args); } return rowCount; } private int DoFindViewExtendedProperties(FindEventArgs args) { int rowCount = 0; if (args.LookInExtendedProperties) { var viewExtendedProperties = _views.FindViewExtendedProperties(args.Database, args.FindWhat); if (args.MatchCase) { viewExtendedProperties = viewExtendedProperties.Where(p => string.Compare(p.Name, args.FindWhat, StringComparison.Ordinal) == 0).ToList(); } viewExtendedProperties = viewExtendedProperties.OrderBy(p => p.SchemaName).ThenBy(p => p.TableName).ThenBy(p => p.ColumnName).ThenBy(p => p.Name).ToList(); _view.InsertViewExtendedPropertiesIntoTreeview(viewExtendedProperties); rowCount = viewExtendedProperties.Count; } return rowCount; } private int DoFindIndexes(FindEventArgs args) { int rowCount = 0; if (args.LookInIndexes) { var indexes = _indexes.FindIndexes(args.Database, args.FindWhat); if (args.MatchCase) { indexes = indexes.Where(p => string.Compare(p.Name, args.FindWhat, StringComparison.Ordinal) == 0).ToList(); } indexes = indexes.OrderBy(p => p.TableName).ThenBy(p => p.Name).ThenBy(p => p.ColumnName).ToList(); _view.InsertIndexIntoTreeview(indexes); rowCount = indexes.Count; } return rowCount; } private int DoFindStoredProcedures(FindEventArgs args) { int rowCount = 0; if (args.LookInStoredProcedures) { var procedures = _storedProcedures.FindProcedures(args.Database, args.FindWhat); if (args.MatchCase) { procedures = procedures.Where(p => string.Compare(p.Name, args.FindWhat, StringComparison.Ordinal) == 0 || p.Definition.IndexOf(args.FindWhat, StringComparison.Ordinal) >= 0).ToList(); } procedures = procedures.OrderBy(p => p.SchemaName).ThenBy(p => p.Name).ThenBy(p => p.ParameterName).ToList(); _view.InsertProcedureIntoTreeview(procedures); rowCount = procedures.Count; rowCount += DoFindStoredProcedureExtendedProperties(args); } return rowCount; } private int DoFindStoredProcedureExtendedProperties(FindEventArgs args) { int rowCount = 0; if (args.LookInExtendedProperties) { var procedureExtendedProperties = _storedProcedures.FindProcedureExtendedProperties(args.Database, args.FindWhat); if (args.MatchCase) { procedureExtendedProperties = procedureExtendedProperties.Where(p => string.Compare(p.Name, args.FindWhat, StringComparison.Ordinal) == 0).ToList(); } procedureExtendedProperties = procedureExtendedProperties.OrderBy(p => p.SchemaName).ThenBy(p => p.ProcedureName).ThenBy(p => p.ParameterName).ThenBy(p => p.Name).ToList(); _view.InsertProcedureExtendedPropertiesIntoTreeview(procedureExtendedProperties); rowCount = procedureExtendedProperties.Count; } return rowCount; } private int DoFindFunctions(FindEventArgs args) { int rowCount = 0; if (args.LookInFunctions) { var functions = _functions.FindFunctions(args.Database, args.FindWhat); if (args.MatchCase) { functions = functions.Where(p => string.Compare(p.Name, args.FindWhat, StringComparison.Ordinal) == 0 || p.Definition.IndexOf(args.FindWhat, StringComparison.Ordinal) >= 0).ToList(); } functions = functions.OrderBy(p => p.SchemaName).ThenBy(p => p.Name).ThenBy(p => p.ParameterName).ToList(); _view.InsertFunctionIntoTreeview(functions); rowCount = functions.Count; rowCount += DoFindFunctionExtendedProperties(args); } return rowCount; } private int DoFindFunctionExtendedProperties(FindEventArgs args) { int rowCount = 0; if (args.LookInExtendedProperties) { var functionExtendedProperties = _functions.FindFunctionExtendedProperties(args.Database, args.FindWhat); if (args.MatchCase) { functionExtendedProperties = functionExtendedProperties.Where(p => string.Compare(p.Name, args.FindWhat, StringComparison.Ordinal) == 0).ToList(); } functionExtendedProperties = functionExtendedProperties.OrderBy(p => p.SchemaName).ThenBy(p => p.ProcedureName).ThenBy(p => p.ParameterName).ThenBy(p => p.Name).ToList(); _view.InsertFunctionExtendedPropertiesIntoTreeview(functionExtendedProperties); rowCount = functionExtendedProperties.Count; } return rowCount; } private void DoEnableDisableBtnConnect(object sender, EventArgs e) { _view.BtnConnectEnabled = !String.IsNullOrEmpty(_view.CmbServerText); } private void DoTreeviewNodeClick(object sender, TreeviewNodeClickEventArgs args) { switch (args.ParentNodeName) { case "ViewsNode": ViewNodeClicked(args); break; case "TablesNode": TableNodeClicked(args); break; case "IndexesNode": IndexNodeClicked(args); break; case "StoredProceduresNode": StoredProcedureNodeClicked(args); break; case "FunctionsNode": FunctionsNodeClicked(args); break; default: return; } } private void TableNodeClicked(TreeviewNodeClickEventArgs args) { var table = args.NodeTag as Table; if (table != null) { table.RowCount = _tables.FindTableRowCount(args.Database, table.SchemaName + ".[" + table.Name + "]"); _view.ShowTableInfo(table); } else { var tableExtendedInfo = args.NodeTag as TableExtendedProperty; if (tableExtendedInfo != null) { _view.ShowTableExtendedPropertyInfo(tableExtendedInfo); } } } private void ViewNodeClicked(TreeviewNodeClickEventArgs args) { var view = args.NodeTag as View; if (view != null) { _view.ShowViewInfo(view); } else { var viewExtendedInfo = args.NodeTag as ViewExtendedProperty; if (viewExtendedInfo != null) { _view.ShowViewExtendedPropertyInfo(viewExtendedInfo); } } } private void IndexNodeClicked(TreeviewNodeClickEventArgs args) { var index = (Index)args.NodeTag; _view.ShowIndexInfo(index); } private void StoredProcedureNodeClicked(TreeviewNodeClickEventArgs args) { var procedure = args.NodeTag as Procedure; if (procedure != null) { _view.ShowProcedureInfo(procedure); } else { var procedureExtendedInfo = args.NodeTag as ProcedureExtendedProperty; if (procedureExtendedInfo != null) { _view.ShowProcedureExtendedPropertyInfo(procedureExtendedInfo); } } } private void FunctionsNodeClicked(TreeviewNodeClickEventArgs args) { var function = args.NodeTag as Function; if (function != null) { _view.ShowFunctionInfo(function); } else { var functionExtendedInfo = args.NodeTag as FunctionExtendedProperty; if (functionExtendedInfo != null) { _view.ShowFunctionExtendedPropertyInfo(functionExtendedInfo); } } } private void DoCopyQueryToClipboardToolStripMenuItemClick(object sender, FindEventArgs e) { var sb = new StringBuilder(); if (e.LookInTables) { AppendSqlSection(_tables.GetFindTablesSql(e.Database, e.FindWhat), sb); } if (e.LookInViews) { AppendSqlSection(_views.GetFindViewsSql(e.Database, e.FindWhat), sb); } if (e.LookInIndexes) { AppendSqlSection(_indexes.GetFindIndexesSql(e.Database, e.FindWhat), sb); } if (e.LookInStoredProcedures) { AppendSqlSection(_storedProcedures.GetFindStoredProceduresSql(e.Database, e.FindWhat), sb); } if (e.LookInFunctions) { AppendSqlSection(_functions.GetFindFunctionsSql(e.Database, e.FindWhat), sb); } string sql = sb.ToString(); sql = Regex.Replace(sql, @"[ \t]+", " "); _view.CopyStringToSlipBoard(sql); } private void AppendSqlSection(string sql, StringBuilder sb) { if (!string.IsNullOrEmpty(sql)) { sb.AppendLine(sql); sb.AppendLine("GO"); sb.AppendLine(); } } private void DoCopyNameToClipboardToolStripMenuItemClick(object sender, CopyNameEventArgs e) { _view.CopyStringToSlipBoard(e.Name); } private void DoCopyInformationToClipboardToolStripMenuItemClick(object sender, CopyInformationEventArgs e) { string information = ""; foreach (var arr in e.DatabaseObject.ToArrayList()) { information += arr[0] + " " + arr[1] + Environment.NewLine; } _view.CopyStringToSlipBoard(information); } private void DoCopyServerInformationClick(object sender, EventArgs e) { var serverInfo = _server.GetServerInfo(); string serverInformation = ""; foreach (var arr in serverInfo.ToArrayList()) { serverInformation += arr[0] + " " + arr[1] + Environment.NewLine; } _view.CopyStringToSlipBoard(serverInformation); } private void DoCopyListToClipboardToolStripMenuItemClick(object sender, CopyListToClipboardEventArgs e) { _view.CopyStringToSlipBoard(string.Join(Environment.NewLine, e.NameList)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.Rule { using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Net; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using ODataValidator.Rule.Helper; using ODataValidator.RuleEngine; using ODataValidator.RuleEngine.Common; /// <summary> /// Class of extension rule /// </summary> [Export(typeof(ExtensionRule))] public class MetadataCore4564 : ExtensionRule { /// <summary> /// Gets Category property /// </summary> public override string Category { get { return "core"; } } /// <summary> /// Gets rule name /// </summary> public override string Name { get { return "Metadata.Core.4564"; } } /// <summary> /// Gets rule description /// </summary> public override string Description { get { return "Edm.Stream, or a type definition whose underlying type is Edm.Stream, cannot be used in collections or for non-binding parameters to functions or actions."; } } /// <summary> /// Gets rule specification in OData document /// </summary> public override string SpecificationSection { get { return "4.4"; } } /// <summary> /// Gets location of help information of the rule /// </summary> public override string HelpLink { get { return null; } } /// <summary> /// Gets the error message for validation failure /// </summary> public override string ErrorMessage { get { return this.Description; } } /// <summary> /// Gets the requirement level. /// </summary> public override RequirementLevel RequirementLevel { get { return RequirementLevel.Must; } } /// <summary> /// Gets the version. /// </summary> public override ODataVersion? Version { get { return ODataVersion.V4; } } /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.Metadata; } } /// <summary> /// Gets the flag whether the rule requires metadata document /// </summary> public override bool? RequireMetadata { get { return true; } } /// <summary> /// Gets the offline context to which the rule applies /// </summary> public override bool? IsOfflineContext { get { return false; } } /// <summary> /// Gets the payload format to which the rule applies. /// </summary> public override PayloadFormat? PayloadFormat { get { return RuleEngine.PayloadFormat.Xml; } } /// <summary> /// Verify Metadata.Core.4564 /// </summary> /// <param name="context">Service context</param> /// <param name="info">out parameter to return violation information when rule fail</param> /// <returns>true if rule passes; false otherwise</returns> public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool? passed = null; info = null; XElement metaXml = XElement.Parse(context.MetadataDocument); string xpath = string.Format(@"//*[local-name()='Schema']"); XElement element = metaXml.XPathSelectElement(xpath, ODataNamespaceManager.Instance); AliasNamespacePair aliasNameSpace = MetadataHelper.GetAliasAndNamespace(element); // Load MetadataDocument into XMLDOM XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(context.MetadataDocument); List<string> typeDefinitionNames = MetadataHelper.GetNamesOfTypeDefinitionByUnderlyingType(context.MetadataDocument, "Edm.Stream"); List<string> qualifiedTypes = new List<string>(); foreach (string underlyingType in typeDefinitionNames) { if (!string.IsNullOrEmpty(aliasNameSpace.Alias)) { qualifiedTypes.Add(aliasNameSpace.Alias + "." + underlyingType); } if (!string.IsNullOrEmpty(aliasNameSpace.Namespace)) { qualifiedTypes.Add(aliasNameSpace.Namespace + "." + underlyingType); } } qualifiedTypes.Add("Edm.Stream"); foreach (string type in qualifiedTypes) { // Find all collection that uses Edm.Stream as core type or underlying type. xpath = string.Format("//*[@Type = 'Collection({0})']", type); XmlNodeList propertyNodeList = xmlDoc.SelectNodes(xpath); if (propertyNodeList.Count == 0) { passed = true; } else { passed = false; info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload); break; } // Find non-binding parameter that uses Edm.Stream as type or underlying type. xpath = string.Format("//*[local-name()='Parameter' and @Type='{0}']", type); propertyNodeList = xmlDoc.SelectNodes(xpath); if (propertyNodeList.Count == 0) { passed = true; } else { passed = false; info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload); break; } } return passed; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.SubCommands { using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DocAsCode; using Microsoft.DocAsCode.Build.Engine; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Exceptions; using Microsoft.DocAsCode.Plugins; using Newtonsoft.Json; internal sealed class BuildCommand : ISubCommand { private readonly string _version; private readonly TemplateManager _templateManager; public string Name { get; } = nameof(BuildCommand); public BuildJsonConfig Config { get; } public bool AllowReplay => true; public BuildCommand(BuildJsonConfig config) { Config = config; var assembly = typeof(Program).Assembly; _version = EnvironmentContext.Version; SetDefaultConfigValue(Config); _templateManager = new TemplateManager(assembly, Constants.EmbeddedTemplateFolderName, Config.Templates, Config.Themes, Config.BaseDirectory); } public BuildCommand(BuildCommandOptions options) : this(ParseOptions(options)) { } public void Exec(SubCommandRunningContext context) { EnvironmentContext.SetBaseDirectory(Path.GetFullPath(string.IsNullOrEmpty(Config.BaseDirectory) ? Directory.GetCurrentDirectory() : Config.BaseDirectory)); // TODO: remove BaseDirectory from Config, it may cause potential issue when abused var baseDirectory = EnvironmentContext.BaseDirectory; var intermediateOutputFolder = Path.Combine(baseDirectory, "obj"); var outputFolder = Path.GetFullPath(Path.Combine(string.IsNullOrEmpty(Config.OutputFolder) ? baseDirectory : Config.OutputFolder, Config.Destination ?? string.Empty)); BuildDocument(baseDirectory, outputFolder); _templateManager.ProcessTheme(outputFolder, true); // TODO: SEARCH DATA if (Config?.Serve ?? false) { ServeCommand.Serve(outputFolder, Config.Host, Config.Port); } EnvironmentContext.Clean(); } #region BuildCommand ctor related private void SetDefaultConfigValue(BuildJsonConfig config) { if (Config.Templates == null || Config.Templates.Count == 0) { Config.Templates = new ListWithStringFallback { DocAsCode.Constants.DefaultTemplateName }; } if (config.GlobalMetadata == null) { config.GlobalMetadata = new Dictionary<string, object> { ["_docfxVersion"] = _version }; } else if (!config.GlobalMetadata.ContainsKey("_docfxVersion")) { config.GlobalMetadata["_docfxVersion"] = _version; } } /// <summary> /// TODO: refactor /// </summary> /// <param name="options"></param> /// <returns></returns> private static BuildJsonConfig ParseOptions(BuildCommandOptions options) { var configFile = GetConfigFilePath(options); BuildJsonConfig config; if (configFile == null) { if (options.Content == null && options.Resource == null) { throw new OptionParserException("Either provide config file or specify content files to start building documentation."); } config = new BuildJsonConfig(); MergeOptionsToConfig(options, config); return config; } config = CommandUtility.GetConfig<BuildConfig>(configFile).Item; if (config == null) throw new DocumentException($"Unable to find build subcommand config in file '{configFile}'."); config.BaseDirectory = Path.GetDirectoryName(configFile); MergeOptionsToConfig(options, config); return config; } internal static string GetConfigFilePath(BuildCommandOptions options) { var configFile = options.ConfigFile; if (string.IsNullOrEmpty(configFile)) { if (!File.Exists(Constants.ConfigFileName)) { return null; } else { Logger.Log(LogLevel.Verbose, $"Config file {Constants.ConfigFileName} is found."); return Constants.ConfigFileName; } } return configFile; } internal static void MergeOptionsToConfig(BuildCommandOptions options, BuildJsonConfig config) { // base directory for content from command line is current directory // e.g. C:\folder1>docfx build folder2\docfx.json --content "*.cs" // for `--content "*.cs*`, base directory should be `C:\folder1` string optionsBaseDirectory = Directory.GetCurrentDirectory(); config.OutputFolder = options.OutputFolder; // Override config file with options from command line if (options.Templates != null && options.Templates.Count > 0) { config.Templates = new ListWithStringFallback(options.Templates); } if (options.PostProcessors != null && options.PostProcessors.Count > 0) { config.PostProcessors = new ListWithStringFallback(options.PostProcessors); } if (options.Themes != null && options.Themes.Count > 0) { config.Themes = new ListWithStringFallback(options.Themes); } if (options.Content != null) { if (config.Content == null) { config.Content = new FileMapping(new FileMappingItem()); } config.Content.Add( new FileMappingItem { Files = new FileItems(options.Content), SourceFolder = optionsBaseDirectory, }); } if (options.Resource != null) { if (config.Resource == null) { config.Resource = new FileMapping(new FileMappingItem()); } config.Resource.Add( new FileMappingItem { Files = new FileItems(options.Resource), SourceFolder = optionsBaseDirectory, }); } if (options.Overwrite != null) { if (config.Overwrite == null) { config.Overwrite = new FileMapping(new FileMappingItem()); } config.Overwrite.Add( new FileMappingItem { Files = new FileItems(options.Overwrite), SourceFolder = optionsBaseDirectory, }); } if (options.ExternalReference != null) { if (config.ExternalReference == null) { config.ExternalReference = new FileMapping(new FileMappingItem()); } config.ExternalReference.Add( new FileMappingItem { Files = new FileItems(options.ExternalReference), SourceFolder = optionsBaseDirectory, }); } if (options.XRefMaps != null) { config.XRefMaps = new ListWithStringFallback( (config.XRefMaps ?? new ListWithStringFallback()) .Concat(options.XRefMaps) .Where(x => !string.IsNullOrWhiteSpace(x)) .Distinct()); } //to-do: get changelist from options if (options.Serve) { config.Serve = options.Serve; } if (options.Host != null) { config.Host = options.Host; } if (options.Port.HasValue) { config.Port = options.Port.Value.ToString(); } config.Force |= options.ForceRebuild; config.EnableDebugMode |= options.EnableDebugMode; // When force to rebuild, should force to post process as well config.ForcePostProcess = config.ForcePostProcess | options.ForcePostProcess | config.Force; config.ExportRawModel |= options.ExportRawModel; config.ExportViewModel |= options.ExportViewModel; if (!string.IsNullOrEmpty(options.OutputFolderForDebugFiles)) { config.OutputFolderForDebugFiles = Path.GetFullPath(options.OutputFolderForDebugFiles); } if (!string.IsNullOrEmpty(options.RawModelOutputFolder)) { config.RawModelOutputFolder = Path.GetFullPath(options.RawModelOutputFolder); } if (!string.IsNullOrEmpty(options.ViewModelOutputFolder)) { config.ViewModelOutputFolder = Path.GetFullPath(options.ViewModelOutputFolder); } config.DryRun |= options.DryRun; if (options.MaxParallelism != null) { config.MaxParallelism = options.MaxParallelism; } if (options.MarkdownEngineName != null) { config.MarkdownEngineName = options.MarkdownEngineName; } if (options.MarkdownEngineProperties != null) { config.MarkdownEngineProperties = JsonConvert.DeserializeObject<Dictionary<string, object>>( options.MarkdownEngineProperties, new JsonSerializerSettings { Converters = { new JObjectDictionaryToObjectDictionaryConverter() } }); } if (options.NoLangKeyword != null) { config.NoLangKeyword = options.NoLangKeyword.Value; } if (options.IntermediateFolder != null) { config.IntermediateFolder = options.IntermediateFolder; } config.IntermediateFolder = config.IntermediateFolder ?? Path.Combine(config.BaseDirectory ?? optionsBaseDirectory, "obj", ".cache", "build"); if (options.ChangesFile != null) { config.ChangesFile = options.ChangesFile; } if (options.GlobalMetadataFilePaths != null && options.GlobalMetadataFilePaths.Any()) { config.GlobalMetadataFilePaths.AddRange(options.GlobalMetadataFilePaths); } config.GlobalMetadataFilePaths = new ListWithStringFallback(config.GlobalMetadataFilePaths.Select( path => PathUtility.IsRelativePath(path) ? Path.Combine(config.BaseDirectory, path) : path).Reverse()); if (options.FileMetadataFilePaths != null && options.FileMetadataFilePaths.Any()) { config.FileMetadataFilePaths.AddRange(options.FileMetadataFilePaths); } config.LruSize = options.LruSize ?? config.LruSize; config.KeepFileLink |= options.KeepFileLink; config.CleanupCacheHistory |= options.CleanupCacheHistory; config.FileMetadataFilePaths = new ListWithStringFallback(config.FileMetadataFilePaths.Select( path => PathUtility.IsRelativePath(path) ? Path.Combine(config.BaseDirectory, path) : path).Reverse()); config.FileMetadata = GetFileMetadataFromOption(config.FileMetadata, options.FileMetadataFilePath, config.FileMetadataFilePaths); config.GlobalMetadata = GetGlobalMetadataFromOption(config.GlobalMetadata, options.GlobalMetadataFilePath, config.GlobalMetadataFilePaths, options.GlobalMetadata); } internal static Dictionary<string, FileMetadataPairs> GetFileMetadataFromOption(Dictionary<string, FileMetadataPairs> fileMetadataFromConfig, string fileMetadataFilePath, ListWithStringFallback fileMetadataFilePaths) { var fileMetadata = new Dictionary<string, FileMetadataPairs>(); if (fileMetadataFilePaths != null) { foreach (var filePath in fileMetadataFilePaths) { fileMetadata = MergeMetadataFromFile("fileMetadata", fileMetadata, filePath, path => JsonUtility.Deserialize<Dictionary<string, FileMetadataPairs>>(path), MergeFileMetadataPairs); } } if (fileMetadataFilePath != null) { fileMetadata = MergeMetadataFromFile("fileMetadata", fileMetadata, fileMetadataFilePath, path => JsonUtility.Deserialize<BuildJsonConfig>(path)?.FileMetadata, MergeFileMetadataPairs); } return OptionMerger.MergeDictionary( new DictionaryMergeContext<FileMetadataPairs>("fileMetadata from docfx config file", fileMetadataFromConfig), new DictionaryMergeContext<FileMetadataPairs>("fileMetadata from fileMetadata config file", fileMetadata), MergeFileMetadataPairs); } internal static Dictionary<string, object> GetGlobalMetadataFromOption(Dictionary<string, object> globalMetadataFromConfig, string globalMetadataFilePath, ListWithStringFallback globalMetadataFilePaths, string globalMetadataContent) { Dictionary<string, object> globalMetadata = null; if (globalMetadataContent != null) { using (var sr = new StringReader(globalMetadataContent)) { try { globalMetadata = JsonUtility.Deserialize<Dictionary<string, object>>(sr, GetToObjectSerializer()); } catch (JsonException e) { Logger.LogWarning($"Metadata from \"--globalMetadata {globalMetadataContent}\" is not a valid JSON format global metadata, ignored: {e.Message}"); } } } if (globalMetadataFilePaths != null) { foreach (var filePath in globalMetadataFilePaths) { globalMetadata = MergeMetadataFromFile("globalMetadata", globalMetadata, filePath, path => JsonUtility.Deserialize<Dictionary<string, object>>(path), MergeGlobalMetadataItem); } } if (globalMetadataFilePath != null) { globalMetadata = MergeMetadataFromFile("globalMetadata", globalMetadata, globalMetadataFilePath, path => JsonUtility.Deserialize<BuildJsonConfig>(path)?.GlobalMetadata, MergeGlobalMetadataItem); } return OptionMerger.MergeDictionary( new DictionaryMergeContext<object>("globalMetadata from docfx config file", globalMetadataFromConfig), new DictionaryMergeContext<object>("globalMetadata merged with command option and globalMetadata config file", globalMetadata), MergeGlobalMetadataItem); } private static Dictionary<string, T> MergeMetadataFromFile<T>( string metadataType, Dictionary<string, T> originalMetadata, string metadataFilePath, Func<string, Dictionary<string, T>> metadataFileLoader, OptionMerger.Merger<T> merger) { Dictionary<string, T> metadata = null; try { if (metadataFilePath != null) { metadata = metadataFileLoader(metadataFilePath); } if (metadata == null) { Logger.LogWarning($"File from \"{metadataType} config file {metadataFilePath}\" does not contain \"{metadataType}\" definition."); } } catch (FileNotFoundException) { Logger.LogWarning($"Invalid option \"{metadataType} config file {metadataFilePath}\": file does not exist, ignored."); } catch (JsonException e) { Logger.LogWarning($"File from \"{metadataType} config file {metadataFilePath}\" is not in valid JSON format, ignored: {e.Message}"); } if (metadata != null) { return OptionMerger.MergeDictionary( new DictionaryMergeContext<T>($"globalMetadata config file {metadataFilePath}", metadata), new DictionaryMergeContext<T>("previous global metadata", originalMetadata), merger); } return originalMetadata; } private static object MergeGlobalMetadataItem(string key, MergeContext<object> item, MergeContext<object> overrideItem) { Logger.LogWarning($"Both {item.Name} and {overrideItem.Name} contain definition for \"{key}\", the one from \"{overrideItem.Name}\" overrides the one from \"{item.Name}\"."); return overrideItem.Item; } private static FileMetadataPairs MergeFileMetadataPairs(string key, MergeContext<FileMetadataPairs> pairs, MergeContext<FileMetadataPairs> overridePairs) { var mergedItems = pairs.Item.Items.Concat(overridePairs.Item.Items).ToList(); return new FileMetadataPairs(mergedItems); } private static JsonSerializer GetToObjectSerializer() { var jsonSerializer = new JsonSerializer(); jsonSerializer.NullValueHandling = NullValueHandling.Ignore; jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Serialize; jsonSerializer.Converters.Add(new JObjectDictionaryToObjectDictionaryConverter()); return jsonSerializer; } private sealed class BuildConfig { [JsonProperty("build")] public BuildJsonConfig Item { get; set; } } #endregion #region Build document private void BuildDocument(string baseDirectory, string outputDirectory) { var pluginBaseFolder = AppDomain.CurrentDomain.BaseDirectory; var pluginFolderName = "plugins_" + Path.GetRandomFileName(); var pluginFilePath = Path.Combine(pluginBaseFolder, pluginFolderName); var defaultPluginFolderPath = Path.Combine(pluginBaseFolder, "plugins"); if (Directory.Exists(pluginFilePath)) { throw new PluginDirectoryAlreadyExistsException(pluginFilePath); } bool created = false; try { created = _templateManager.TryExportTemplateFiles(pluginFilePath, @"^(?:plugins|md\.styles)/.*"); if (created) { BuildDocumentWithPlugin(Config, _templateManager, baseDirectory, outputDirectory, pluginBaseFolder, Path.Combine(pluginFilePath, "plugins"), pluginFilePath); } else { if (Directory.Exists(defaultPluginFolderPath)) { BuildDocumentWithPlugin(Config, _templateManager, baseDirectory, outputDirectory, pluginBaseFolder, defaultPluginFolderPath, null); } else { DocumentBuilderWrapper.BuildDocument(Config, _templateManager, baseDirectory, outputDirectory, null, null); } } } finally { if (created) { Logger.LogInfo($"Cleaning up temporary plugin folder \"{pluginFilePath}\""); } try { if (Directory.Exists(pluginFilePath)) { Directory.Delete(pluginFilePath, true); } } catch (Exception e) { Logger.LogWarning($"Error occurs when cleaning up temporary plugin folder \"{pluginFilePath}\", please clean it up manually: {e.Message}"); } } } private static void BuildDocumentWithPlugin(BuildJsonConfig config, TemplateManager manager, string baseDirectory, string outputDirectory, string applicationBaseDirectory, string pluginDirectory, string templateDirectory) { AppDomain builderDomain = null; try { var pluginConfig = Path.Combine(pluginDirectory, "docfx.plugins.config"); Logger.LogInfo($"Plug-in directory: {pluginDirectory}, configuration file: {pluginConfig}"); AppDomainSetup setup = new AppDomainSetup { ApplicationBase = applicationBaseDirectory, PrivateBinPath = string.Join(";", applicationBaseDirectory, pluginDirectory), ConfigurationFile = pluginConfig }; builderDomain = AppDomain.CreateDomain("document builder domain", null, setup); builderDomain.UnhandledException += (s, e) => { }; var wrapper = new DocumentBuilderWrapper(config, manager, baseDirectory, outputDirectory, pluginDirectory, new CrossAppDomainListener(), templateDirectory); builderDomain.DoCallBack(wrapper.BuildDocument); } finally { if (builderDomain != null) { AppDomain.Unload(builderDomain); } } } #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.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class PostIncrementAssignTests : IncDecAssignTests { [Theory] [PerCompilationType(nameof(Int16sAndIncrements))] [PerCompilationType(nameof(NullableInt16sAndIncrements))] [PerCompilationType(nameof(UInt16sAndIncrements))] [PerCompilationType(nameof(NullableUInt16sAndIncrements))] [PerCompilationType(nameof(Int32sAndIncrements))] [PerCompilationType(nameof(NullableInt32sAndIncrements))] [PerCompilationType(nameof(UInt32sAndIncrements))] [PerCompilationType(nameof(NullableUInt32sAndIncrements))] [PerCompilationType(nameof(Int64sAndIncrements))] [PerCompilationType(nameof(NullableInt64sAndIncrements))] [PerCompilationType(nameof(UInt64sAndIncrements))] [PerCompilationType(nameof(NullableUInt64sAndIncrements))] [PerCompilationType(nameof(DecimalsAndIncrements))] [PerCompilationType(nameof(NullableDecimalsAndIncrements))] [PerCompilationType(nameof(SinglesAndIncrements))] [PerCompilationType(nameof(NullableSinglesAndIncrements))] [PerCompilationType(nameof(DoublesAndIncrements))] [PerCompilationType(nameof(NullableDoublesAndIncrements))] public void ReturnsCorrectValues(Type type, object value, object _, bool useInterpreter) { ParameterExpression variable = Expression.Variable(type); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant(value, type)), Expression.PostIncrementAssign(variable) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value, type), block)).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(Int16sAndIncrements))] [PerCompilationType(nameof(NullableInt16sAndIncrements))] [PerCompilationType(nameof(UInt16sAndIncrements))] [PerCompilationType(nameof(NullableUInt16sAndIncrements))] [PerCompilationType(nameof(Int32sAndIncrements))] [PerCompilationType(nameof(NullableInt32sAndIncrements))] [PerCompilationType(nameof(UInt32sAndIncrements))] [PerCompilationType(nameof(NullableUInt32sAndIncrements))] [PerCompilationType(nameof(Int64sAndIncrements))] [PerCompilationType(nameof(NullableInt64sAndIncrements))] [PerCompilationType(nameof(UInt64sAndIncrements))] [PerCompilationType(nameof(NullableUInt64sAndIncrements))] [PerCompilationType(nameof(DecimalsAndIncrements))] [PerCompilationType(nameof(NullableDecimalsAndIncrements))] [PerCompilationType(nameof(SinglesAndIncrements))] [PerCompilationType(nameof(NullableSinglesAndIncrements))] [PerCompilationType(nameof(DoublesAndIncrements))] [PerCompilationType(nameof(NullableDoublesAndIncrements))] public void AssignsCorrectValues(Type type, object value, object result, bool useInterpreter) { ParameterExpression variable = Expression.Variable(type); LabelTarget target = Expression.Label(type); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant(value, type)), Expression.PostIncrementAssign(variable), Expression.Return(target, variable), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void SingleNanToNan(bool useInterpreter) { TestPropertyClass<float> instance = new TestPropertyClass<float>(); instance.TestInstance = float.NaN; Assert.True(float.IsNaN( Expression.Lambda<Func<float>>( Expression.PostIncrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<float>), "TestInstance" ) ) ).Compile(useInterpreter)() )); Assert.True(float.IsNaN(instance.TestInstance)); } [Theory] [ClassData(typeof(CompilationTypes))] public void DoubleNanToNan(bool useInterpreter) { TestPropertyClass<double> instance = new TestPropertyClass<double>(); instance.TestInstance = double.NaN; Assert.True(double.IsNaN( Expression.Lambda<Func<double>>( Expression.PostIncrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<double>), "TestInstance" ) ) ).Compile(useInterpreter)() )); Assert.True(double.IsNaN(instance.TestInstance)); } [Theory] [PerCompilationType(nameof(IncrementOverflowingValues))] public void OverflowingValuesThrow(object value, bool useInterpreter) { ParameterExpression variable = Expression.Variable(value.GetType()); Action overflow = Expression.Lambda<Action>( Expression.Block( typeof(void), new[] { variable }, Expression.Assign(variable, Expression.Constant(value)), Expression.PostIncrementAssign(variable) ) ).Compile(useInterpreter); Assert.Throws<OverflowException>(overflow); } [Theory] [MemberData(nameof(UnincrementableAndUndecrementableTypes))] public void InvalidOperandType(Type type) { ParameterExpression variable = Expression.Variable(type); Assert.Throws<InvalidOperationException>(() => Expression.PostIncrementAssign(variable)); } [Theory] [ClassData(typeof(CompilationTypes))] public void MethodCorrectResult(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(string)); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant("hello")), Expression.PostIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")) ); Assert.Equal("hello", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void MethodCorrectAssign(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(string)); LabelTarget target = Expression.Label(typeof(string)); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant("hello")), Expression.PostIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")), Expression.Return(target, variable), Expression.Label(target, Expression.Default(typeof(string))) ); Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)()); } [Fact] public void IncorrectMethodType() { Expression variable = Expression.Variable(typeof(int)); MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"); Assert.Throws<InvalidOperationException>(() => Expression.PostIncrementAssign(variable, method)); } [Fact] public void IncorrectMethodParameterCount() { Expression variable = Expression.Variable(typeof(string)); MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals"); Assert.Throws<ArgumentException>("method", () => Expression.PostIncrementAssign(variable, method)); } [Fact] public void IncorrectMethodReturnType() { Expression variable = Expression.Variable(typeof(int)); MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString"); Assert.Throws<ArgumentException>(null, () => Expression.PostIncrementAssign(variable, method)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StaticMemberAccessCorrect(bool useInterpreter) { TestPropertyClass<long>.TestStatic = 2L; Assert.Equal( 2L, Expression.Lambda<Func<long>>( Expression.PostIncrementAssign( Expression.Property(null, typeof(TestPropertyClass<long>), "TestStatic") ) ).Compile(useInterpreter)() ); Assert.Equal(3L, TestPropertyClass<long>.TestStatic); } [Theory] [ClassData(typeof(CompilationTypes))] public void InstanceMemberAccessCorrect(bool useInterpreter) { TestPropertyClass<int> instance = new TestPropertyClass<int>(); instance.TestInstance = 2; Assert.Equal( 2, Expression.Lambda<Func<int>>( Expression.PostIncrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<int>), "TestInstance" ) ) ).Compile(useInterpreter)() ); Assert.Equal(3, instance.TestInstance); } [Theory] [ClassData(typeof(CompilationTypes))] public void ArrayAccessCorrect(bool useInterpreter) { int[] array = new int[1]; array[0] = 2; Assert.Equal( 2, Expression.Lambda<Func<int>>( Expression.PostIncrementAssign( Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0)) ) ).Compile(useInterpreter)() ); Assert.Equal(3, array[0]); } [Fact] public void CanReduce() { ParameterExpression variable = Expression.Variable(typeof(int)); UnaryExpression op = Expression.PostIncrementAssign(variable); Assert.True(op.CanReduce); Assert.NotSame(op, op.ReduceAndCheck()); } [Fact] public void NullOperand() { Assert.Throws<ArgumentNullException>("expression", () => Expression.PostIncrementAssign(null)); } [Fact] public void UnwritableOperand() { Assert.Throws<ArgumentException>("expression", () => Expression.PostIncrementAssign(Expression.Constant(1))); } [Fact] public void UnreadableOperand() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("expression", () => Expression.PostIncrementAssign(value)); } [Fact] public void UpdateSameOperandSameNode() { UnaryExpression op = Expression.PostIncrementAssign(Expression.Variable(typeof(int))); Assert.Same(op, op.Update(op.Operand)); Assert.Same(op, NoOpVisitor.Instance.Visit(op)); } [Fact] public void UpdateDiffOperandDiffNode() { UnaryExpression op = Expression.PostIncrementAssign(Expression.Variable(typeof(int))); Assert.NotSame(op, op.Update(Expression.Variable(typeof(int)))); } [Fact] public void ToStringTest() { UnaryExpression e = Expression.PostIncrementAssign(Expression.Parameter(typeof(int), "x")); Assert.Equal("x++", e.ToString()); } } }
using System.Collections.Generic; using LD39.Map; using UnityEngine; using UnityEngine.AI; namespace LD39 { [AddComponentMenu("LD39/Managers/MapManager")] public class MapManager : Singleton<MapManager> { public const float NAV_STEP = 0.1f; public const float NAV_HEIGHT = 1f; public const float NAV_RADIUS = 0.5f; public const float NAV_SLOPE = 25f; public float chunkSize = 20f; public int chunksX = 10; public int chunksY = 10; public int seed = 456159; public int mainPathLength = 10; public Transform mapRoot; public Transform rotatedRoot; public MapChunkPrefab startingRoom; public MapChunkPrefab endingRoom; public MapChunkPrefab[] roomPrefabs; public MapGrid Grid { get; private set; } private List<Vector2i> mainPath; public void Awake() { if (DifficultyManager.I == null) { new GameObject().AddComponent<DifficultyManager>(); DifficultyManager.I.currentDifficulty = 3; } mainPathLength = DifficultyManager.I.currentDifficulty; EntityManager.I.player.OnRoomChange += OnPlayerChangedRoom; //seed = (int) System.DateTime.Now.ToUniversalTime().Subtract(new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc)).TotalMilliseconds; seed = Random.Range(System.Int32.MinValue, System.Int32.MaxValue); } public void Start() { if (mapRoot == null) { mapRoot = new GameObject("Map").transform; } if (rotatedRoot == null) { rotatedRoot = new GameObject("RotatedRoot").transform; rotatedRoot.gameObject.SetActive(false); } Random.InitState(seed); startingRoom.Init(); endingRoom.Init(); foreach (MapChunkPrefab pref in roomPrefabs) { pref.Init(); } FillPrefabs(); GenerateMap(); //GenerateNavMesh(); } public void Update() { } public void OnPlayerChangedRoom(MapChunk nRoom) { if (!nRoom.gameObject.activeInHierarchy) { nRoom.gameObject.SetActive(true); foreach (MobSpawner spawner in nRoom.transform.GetComponentsInChildren<MobSpawner>()) { spawner.SpawnMob(1f); } } } public void GenerateNavMesh() { NavMeshBuildSettings navSettings = new NavMeshBuildSettings(); navSettings.agentClimb = NAV_STEP; navSettings.agentHeight = NAV_HEIGHT; navSettings.agentRadius = NAV_RADIUS; navSettings.agentSlope = NAV_SLOPE; NavMeshBuildSource src = new NavMeshBuildSource(); src.sourceObject = mapRoot; src.shape = NavMeshBuildSourceShape.Mesh; List<NavMeshBuildSource> srcs = new List<NavMeshBuildSource>(); NavMeshBuilder.BuildNavMeshData(navSettings, srcs, new Bounds(), Vector3.zero, Quaternion.identity); } public void FillPrefabs() { List<MapChunkPrefab> filled = new List<MapChunkPrefab>(); foreach (MapChunkPrefab pref in roomPrefabs) { filled.Add(pref); filled.AddRange(pref.GenerateRotatedVersions()); } roomPrefabs = filled.ToArray(); Debug.Log("New Room Prefab Length = " + roomPrefabs.Length); } public void GenerateMap() { Grid = new MapGrid(chunksX, chunksY, chunkSize); GenerateMainPath(mainPathLength); GenerateOptionnalPaths(); } private void GenerateMainPath(int mainPathLength) { mainPath = new List<Vector2i>(); MapChunk curChunk = MapChunk.CreateMapChunk(startingRoom); Grid.SetChunk(new Vector2i(0, 0), curChunk); mainPath.Add(curChunk.FakePos); Side nextSide = null; bool stuck = false; for (int i = 0; i < mainPathLength; i++) { List<Side> possibleSides = curChunk.GetAllOpenUnusedSides(); nextSide = possibleSides[Random.Range(0, possibleSides.Count)]; possibleSides.Remove(nextSide); Orientation requiredOri = nextSide.Orient.GetOposite(); MapChunkPrefab prefab = null; while (Grid.GetAdjacentSidesLeadingToTile(nextSide.GetAdjacentPos(), requiredOri).Length != 0) { if (possibleSides.Count == 0) { stuck = true; break; } nextSide = possibleSides[Random.Range(0, possibleSides.Count)]; possibleSides.Remove(nextSide); requiredOri = nextSide.Orient.GetOposite(); } List<MapChunkPrefab> possiblePrefabs = GetAllRoomPrefabs(requiredOri, nextSide.Type, Grid.GetAdjacentSidesOccupied(nextSide.GetAdjacentPos(), requiredOri)); prefab = possiblePrefabs[Random.Range(0, possiblePrefabs.Count)]; possiblePrefabs.Remove(prefab); while (prefab.OpenCount < 2) { if (possiblePrefabs.Count == 0) { stuck = true; break; } prefab = possiblePrefabs[Random.Range(0, possiblePrefabs.Count)]; possiblePrefabs.Remove(prefab); } if (stuck) { break; } curChunk = MapChunk.CreateMapChunk(prefab); Grid.SetChunk(nextSide.GetAdjacentPos(), curChunk); mainPath.Add(curChunk.FakePos); } nextSide = curChunk.GetRandomOpenUnusedSide(); curChunk = MapChunk.CreateMapChunk(endingRoom); Grid.SetChunk(nextSide.GetAdjacentPos(), curChunk); mainPath.Add(curChunk.FakePos); } private void GenerateOptionnalPaths() { foreach (Vector2i mainPos in mainPath) { MapChunk mainChunk = Grid[mainPos.x, mainPos.z]; List<Side> openUnusedSides = mainChunk.GetAllOpenUnusedSides(); if (openUnusedSides.Count == 0) { continue; } foreach (Side unusedSide in openUnusedSides) { List<Orientation> adjOpen = null; if (unusedSide.adjacentChunk != null) { adjOpen = unusedSide.adjacentChunk.GetAllOpenSidesOrientations(); } else { adjOpen = new List<Orientation>(); } adjOpen.Add(unusedSide.Orient.GetOposite()); Grid.SetChunk(unusedSide.GetAdjacentPos(), MapChunk.CreateMapChunk(GetPrefabMatchingExactly(adjOpen))); } } } public MapChunkPrefab GetPrefabMatchingExactly(List<Orientation> openSides) { List<Orientation> closedSides = new List<Orientation>(); closedSides.Add(Orientation.TOP); closedSides.Add(Orientation.RIGHT); closedSides.Add(Orientation.BOTTOM); closedSides.Add(Orientation.LEFT); foreach (Orientation side in openSides) { closedSides.Remove(side); } foreach (MapChunkPrefab prefab in roomPrefabs) { bool matches = true; foreach (Orientation requiredOpen in openSides) { if (!prefab.isSideOpen(requiredOpen)) { matches = false; break; } } foreach (Orientation requiredClosed in closedSides) { if (prefab.isSideOpen(requiredClosed)) { matches = false; break; } } if (!matches) { continue; } else { return prefab; } } return null; } public MapChunkPrefab GetRandomRoomPrefab() { return roomPrefabs[Random.Range(0, roomPrefabs.Length)]; } public MapChunkPrefab GetRandomRoomPrefab(Orientation requiredOri, SideType requiredType) { MapChunkPrefab[] validChunkPrefabs = new MapChunkPrefab[roomPrefabs.Length]; int count = 0; foreach (MapChunkPrefab chunkPrefab in roomPrefabs) { if (chunkPrefab.GetSideType(requiredOri) == requiredType) { validChunkPrefabs[count++] = chunkPrefab; } } return validChunkPrefabs[Random.Range(0, count)]; } public MapChunkPrefab GetRandomRoomPrefab(Orientation requiredOri, SideType requiredType, Orientation[] blockedSides) { MapChunkPrefab[] validChunkPrefabs = new MapChunkPrefab[roomPrefabs.Length]; int count = 0; foreach (MapChunkPrefab chunkPrefab in roomPrefabs) { if (chunkPrefab.GetSideType(requiredOri) == requiredType) { bool leadsToBlocked = false; foreach (Orientation blocked in blockedSides) { if (chunkPrefab.GetSideType(blocked) != SideType.CLOSED) { leadsToBlocked = true; break; } } if (!leadsToBlocked) { validChunkPrefabs[count++] = chunkPrefab; } } } return validChunkPrefabs[Random.Range(0, count)]; } public List<MapChunkPrefab> GetAllRoomPrefabs(Orientation requiredOri, SideType requiredType, Orientation[] blockedSides) { List<MapChunkPrefab> validChunkPrefabs = new List<MapChunkPrefab>(); foreach (MapChunkPrefab chunkPrefab in roomPrefabs) { if (chunkPrefab.GetSideType(requiredOri) == requiredType) { bool leadsToBlocked = false; foreach (Orientation blocked in blockedSides) { if (chunkPrefab.GetSideType(blocked) != SideType.CLOSED) { leadsToBlocked = true; break; } } if (!leadsToBlocked) { validChunkPrefabs.Add(chunkPrefab); } } } return validChunkPrefabs; } } }
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 SailingTripMap.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 2021 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 gcov = Google.Cloud.OrgPolicy.V2; using sys = System; namespace Google.Cloud.OrgPolicy.V2 { /// <summary>Resource name for the <c>Constraint</c> resource.</summary> public sealed partial class ConstraintName : gax::IResourceName, sys::IEquatable<ConstraintName> { /// <summary>The possible contents of <see cref="ConstraintName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/constraints/{constraint}</c>.</summary> ProjectConstraint = 1, /// <summary>A resource name with pattern <c>folders/{folder}/constraints/{constraint}</c>.</summary> FolderConstraint = 2, /// <summary> /// A resource name with pattern <c>organizations/{organization}/constraints/{constraint}</c>. /// </summary> OrganizationConstraint = 3, } private static gax::PathTemplate s_projectConstraint = new gax::PathTemplate("projects/{project}/constraints/{constraint}"); private static gax::PathTemplate s_folderConstraint = new gax::PathTemplate("folders/{folder}/constraints/{constraint}"); private static gax::PathTemplate s_organizationConstraint = new gax::PathTemplate("organizations/{organization}/constraints/{constraint}"); /// <summary>Creates a <see cref="ConstraintName"/> 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="ConstraintName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ConstraintName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ConstraintName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ConstraintName"/> with the pattern <c>projects/{project}/constraints/{constraint}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ConstraintName"/> constructed from the provided ids.</returns> public static ConstraintName FromProjectConstraint(string projectId, string constraintId) => new ConstraintName(ResourceNameType.ProjectConstraint, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), constraintId: gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId))); /// <summary> /// Creates a <see cref="ConstraintName"/> with the pattern <c>folders/{folder}/constraints/{constraint}</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ConstraintName"/> constructed from the provided ids.</returns> public static ConstraintName FromFolderConstraint(string folderId, string constraintId) => new ConstraintName(ResourceNameType.FolderConstraint, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), constraintId: gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId))); /// <summary> /// Creates a <see cref="ConstraintName"/> with the pattern /// <c>organizations/{organization}/constraints/{constraint}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ConstraintName"/> constructed from the provided ids.</returns> public static ConstraintName FromOrganizationConstraint(string organizationId, string constraintId) => new ConstraintName(ResourceNameType.OrganizationConstraint, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), constraintId: gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConstraintName"/> with pattern /// <c>projects/{project}/constraints/{constraint}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ConstraintName"/> with pattern /// <c>projects/{project}/constraints/{constraint}</c>. /// </returns> public static string Format(string projectId, string constraintId) => FormatProjectConstraint(projectId, constraintId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConstraintName"/> with pattern /// <c>projects/{project}/constraints/{constraint}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ConstraintName"/> with pattern /// <c>projects/{project}/constraints/{constraint}</c>. /// </returns> public static string FormatProjectConstraint(string projectId, string constraintId) => s_projectConstraint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConstraintName"/> with pattern /// <c>folders/{folder}/constraints/{constraint}</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ConstraintName"/> with pattern /// <c>folders/{folder}/constraints/{constraint}</c>. /// </returns> public static string FormatFolderConstraint(string folderId, string constraintId) => s_folderConstraint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConstraintName"/> with pattern /// <c>organizations/{organization}/constraints/{constraint}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ConstraintName"/> with pattern /// <c>organizations/{organization}/constraints/{constraint}</c>. /// </returns> public static string FormatOrganizationConstraint(string organizationId, string constraintId) => s_organizationConstraint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId))); /// <summary>Parses the given resource name string into a new <see cref="ConstraintName"/> 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}/constraints/{constraint}</c></description></item> /// <item><description><c>folders/{folder}/constraints/{constraint}</c></description></item> /// <item><description><c>organizations/{organization}/constraints/{constraint}</c></description></item> /// </list> /// </remarks> /// <param name="constraintName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ConstraintName"/> if successful.</returns> public static ConstraintName Parse(string constraintName) => Parse(constraintName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ConstraintName"/> 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}/constraints/{constraint}</c></description></item> /// <item><description><c>folders/{folder}/constraints/{constraint}</c></description></item> /// <item><description><c>organizations/{organization}/constraints/{constraint}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="constraintName">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="ConstraintName"/> if successful.</returns> public static ConstraintName Parse(string constraintName, bool allowUnparsed) => TryParse(constraintName, allowUnparsed, out ConstraintName 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="ConstraintName"/> 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}/constraints/{constraint}</c></description></item> /// <item><description><c>folders/{folder}/constraints/{constraint}</c></description></item> /// <item><description><c>organizations/{organization}/constraints/{constraint}</c></description></item> /// </list> /// </remarks> /// <param name="constraintName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ConstraintName"/>, 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 constraintName, out ConstraintName result) => TryParse(constraintName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ConstraintName"/> 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}/constraints/{constraint}</c></description></item> /// <item><description><c>folders/{folder}/constraints/{constraint}</c></description></item> /// <item><description><c>organizations/{organization}/constraints/{constraint}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="constraintName">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="ConstraintName"/>, 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 constraintName, bool allowUnparsed, out ConstraintName result) { gax::GaxPreconditions.CheckNotNull(constraintName, nameof(constraintName)); gax::TemplatedResourceName resourceName; if (s_projectConstraint.TryParseName(constraintName, out resourceName)) { result = FromProjectConstraint(resourceName[0], resourceName[1]); return true; } if (s_folderConstraint.TryParseName(constraintName, out resourceName)) { result = FromFolderConstraint(resourceName[0], resourceName[1]); return true; } if (s_organizationConstraint.TryParseName(constraintName, out resourceName)) { result = FromOrganizationConstraint(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(constraintName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ConstraintName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string constraintId = null, string folderId = null, string organizationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ConstraintId = constraintId; FolderId = folderId; OrganizationId = organizationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="ConstraintName"/> class from the component parts of pattern /// <c>projects/{project}/constraints/{constraint}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="constraintId">The <c>Constraint</c> ID. Must not be <c>null</c> or empty.</param> public ConstraintName(string projectId, string constraintId) : this(ResourceNameType.ProjectConstraint, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), constraintId: gax::GaxPreconditions.CheckNotNullOrEmpty(constraintId, nameof(constraintId))) { } /// <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>Constraint</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string ConstraintId { get; } /// <summary> /// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string FolderId { get; } /// <summary> /// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string OrganizationId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </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.ProjectConstraint: return s_projectConstraint.Expand(ProjectId, ConstraintId); case ResourceNameType.FolderConstraint: return s_folderConstraint.Expand(FolderId, ConstraintId); case ResourceNameType.OrganizationConstraint: return s_organizationConstraint.Expand(OrganizationId, ConstraintId); 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 ConstraintName); /// <inheritdoc/> public bool Equals(ConstraintName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ConstraintName a, ConstraintName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ConstraintName a, ConstraintName b) => !(a == b); } public partial class Constraint { /// <summary> /// <see cref="gcov::ConstraintName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcov::ConstraintName ConstraintName { get => string.IsNullOrEmpty(Name) ? null : gcov::ConstraintName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// 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: Class to represent all synchronization objects in the runtime (that allow multiple wait) ** ** =============================================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using Internal.Runtime.Augments; using Microsoft.Win32.SafeHandles; namespace System.Threading { public abstract partial class WaitHandle : MarshalByRefObject, IDisposable { internal const int WaitObject0 = (int)Interop.Constants.WaitObject0; public const int WaitTimeout = (int)Interop.Constants.WaitTimeout; internal const int WaitAbandoned = (int)Interop.Constants.WaitAbandoned0; internal const int WaitFailed = unchecked((int)Interop.Constants.WaitFailed); internal const int MaxWaitHandles = 64; protected static readonly IntPtr InvalidHandle = Interop.InvalidHandleValue; internal SafeWaitHandle _waitHandle; internal enum OpenExistingResult { Success, NameNotFound, PathNotFound, NameInvalid } protected WaitHandle() { } [Obsolete("Use the SafeWaitHandle property instead.")] public virtual IntPtr Handle { get { return _waitHandle == null ? InvalidHandle : _waitHandle.DangerousGetHandle(); } set { if (value == InvalidHandle) { // This line leaks a handle. However, it's currently // not perfectly clear what the right behavior is here // anyways. This preserves Everett behavior. We should // ideally do these things: // *) Expose a settable SafeHandle property on WaitHandle. // *) Expose a settable OwnsHandle property on SafeHandle. if (_waitHandle != null) { _waitHandle.SetHandleAsInvalid(); _waitHandle = null; } } else { _waitHandle = new SafeWaitHandle(value, true); } } } public SafeWaitHandle SafeWaitHandle { get { if (_waitHandle == null) { _waitHandle = new SafeWaitHandle(InvalidHandle, false); } return _waitHandle; } set { _waitHandle = value; } } internal static int ToTimeoutMilliseconds(TimeSpan timeout) { var timeoutMilliseconds = (long)timeout.TotalMilliseconds; if (timeoutMilliseconds < -1 || timeoutMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return (int)timeoutMilliseconds; } public virtual bool WaitOne(int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } Contract.EndContractBlock(); return WaitOneCore(millisecondsTimeout); } private bool WaitOneCore(int millisecondsTimeout) { Debug.Assert(millisecondsTimeout >= -1); // The field value is modifiable via the public <see cref="WaitHandle.SafeWaitHandle"/> property, save it locally // to ensure that one instance is used in all places in this method SafeWaitHandle waitHandle = _waitHandle; if (waitHandle == null) { // Throw ObjectDisposedException for backward compatibility even though it is not be representative of the issue throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); } waitHandle.DangerousAddRef(); try { return WaitOneCore(waitHandle.DangerousGetHandle(), millisecondsTimeout); } finally { waitHandle.DangerousRelease(); } } public virtual bool WaitOne(TimeSpan timeout) => WaitOneCore(ToTimeoutMilliseconds(timeout)); public virtual bool WaitOne() => WaitOneCore(Timeout.Infinite); public virtual bool WaitOne(int millisecondsTimeout, bool exitContext) => WaitOne(millisecondsTimeout); public virtual bool WaitOne(TimeSpan timeout, bool exitContext) => WaitOne(timeout); /// <summary> /// Obtains all of the corresponding safe wait handles and adds a ref to each. Since the <see cref="SafeWaitHandle"/> /// property is publically modifiable, this makes sure that we add and release refs one the same set of safe wait /// handles to keep them alive during a multi-wait operation. /// </summary> private static SafeWaitHandle[] ObtainSafeWaitHandles( RuntimeThread currentThread, WaitHandle[] waitHandles, out SafeWaitHandle[] rentedSafeWaitHandles) { Debug.Assert(currentThread == RuntimeThread.CurrentThread); Debug.Assert(waitHandles != null); Debug.Assert(waitHandles.Length > 0); Debug.Assert(waitHandles.Length <= MaxWaitHandles); rentedSafeWaitHandles = currentThread.RentWaitedSafeWaitHandleArray(waitHandles.Length); SafeWaitHandle[] safeWaitHandles = rentedSafeWaitHandles ?? new SafeWaitHandle[waitHandles.Length]; bool success = false; try { for (int i = 0; i < waitHandles.Length; ++i) { WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) { throw new ArgumentNullException("waitHandles[" + i + ']', SR.ArgumentNull_ArrayElement); } SafeWaitHandle safeWaitHandle = waitHandle._waitHandle; if (safeWaitHandle == null) { // Throw ObjectDisposedException for backward compatibility even though it is not be representative of the issue throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); } safeWaitHandle.DangerousAddRef(); safeWaitHandles[i] = safeWaitHandle; } success = true; } finally { if (!success) { for (int i = 0; i < waitHandles.Length; ++i) { SafeWaitHandle safeWaitHandle = safeWaitHandles[i]; if (safeWaitHandle == null) { break; } safeWaitHandle.DangerousRelease(); safeWaitHandles[i] = null; } if (rentedSafeWaitHandles != null) { currentThread.ReturnWaitedSafeWaitHandleArray(rentedSafeWaitHandles); } } } return safeWaitHandles; } public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout) { if (waitHandles == null) { throw new ArgumentNullException(nameof(waitHandles), SR.ArgumentNull_Waithandles); } if (waitHandles.Length == 0) { // // Some history: in CLR 1.0 and 1.1, we threw ArgumentException in this case, which was correct. // Somehow, in 2.0, this became ArgumentNullException. This was not fixed until Silverlight 2, // which went back to ArgumentException. // // Now we're in a bit of a bind. Backward-compatibility requires us to keep throwing ArgumentException // in CoreCLR, and ArgumentNullException in the desktop CLR. This is ugly, but so is breaking // user code. // throw new ArgumentNullException(nameof(waitHandles), SR.Argument_EmptyWaithandleArray); } if (waitHandles.Length > MaxWaitHandles) { throw new NotSupportedException(SR.NotSupported_MaxWaitHandles); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } Contract.EndContractBlock(); RuntimeThread currentThread = RuntimeThread.CurrentThread; SafeWaitHandle[] rentedSafeWaitHandles; SafeWaitHandle[] safeWaitHandles = ObtainSafeWaitHandles(currentThread, waitHandles, out rentedSafeWaitHandles); try { return WaitAllCore(currentThread, safeWaitHandles, waitHandles, millisecondsTimeout); } finally { for (int i = 0; i < waitHandles.Length; ++i) { safeWaitHandles[i].DangerousRelease(); safeWaitHandles[i] = null; } if (rentedSafeWaitHandles != null) { currentThread.ReturnWaitedSafeWaitHandleArray(rentedSafeWaitHandles); } } } public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout) => WaitAll(waitHandles, ToTimeoutMilliseconds(timeout)); public static bool WaitAll(WaitHandle[] waitHandles) => WaitAll(waitHandles, Timeout.Infinite); public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) => WaitAll(waitHandles, millisecondsTimeout); public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) => WaitAll(waitHandles, timeout); /*======================================================================== ** Waits for notification from any of the objects. ** timeout indicates how long to wait before the method returns. ** This method will return either when either one of the object have been ** signalled or timeout milliseonds have elapsed. ========================================================================*/ public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout) { if (waitHandles == null) { throw new ArgumentNullException(nameof(waitHandles), SR.ArgumentNull_Waithandles); } if (waitHandles.Length == 0) { throw new ArgumentException(SR.Argument_EmptyWaithandleArray); } if (MaxWaitHandles < waitHandles.Length) { throw new NotSupportedException(SR.NotSupported_MaxWaitHandles); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } Contract.EndContractBlock(); RuntimeThread currentThread = RuntimeThread.CurrentThread; SafeWaitHandle[] rentedSafeWaitHandles; SafeWaitHandle[] safeWaitHandles = ObtainSafeWaitHandles(currentThread, waitHandles, out rentedSafeWaitHandles); try { return WaitAnyCore(currentThread, safeWaitHandles, waitHandles, millisecondsTimeout); } finally { for (int i = 0; i < waitHandles.Length; ++i) { safeWaitHandles[i].DangerousRelease(); safeWaitHandles[i] = null; } if (rentedSafeWaitHandles != null) { currentThread.ReturnWaitedSafeWaitHandleArray(rentedSafeWaitHandles); } } } public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout) => WaitAny(waitHandles, ToTimeoutMilliseconds(timeout)); public static int WaitAny(WaitHandle[] waitHandles) => WaitAny(waitHandles, Timeout.Infinite); public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) => WaitAny(waitHandles, millisecondsTimeout); public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) => WaitAny(waitHandles, timeout); /*================================================= == == SignalAndWait == ==================================================*/ private static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout) { if (null == toSignal) { throw new ArgumentNullException(nameof(toSignal)); } if (null == toWaitOn) { throw new ArgumentNullException(nameof(toWaitOn)); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } // The field value is modifiable via the public <see cref="WaitHandle.SafeWaitHandle"/> property, save it locally // to ensure that one instance is used in all places in this method SafeWaitHandle safeWaitHandleToSignal = toSignal._waitHandle; SafeWaitHandle safeWaitHandleToWaitOn = toWaitOn._waitHandle; if (safeWaitHandleToSignal == null || safeWaitHandleToWaitOn == null) { // Throw ObjectDisposedException for backward compatibility even though it is not be representative of the issue throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); } Contract.EndContractBlock(); safeWaitHandleToSignal.DangerousAddRef(); try { safeWaitHandleToWaitOn.DangerousAddRef(); try { return SignalAndWaitCore( safeWaitHandleToSignal.DangerousGetHandle(), safeWaitHandleToWaitOn.DangerousGetHandle(), millisecondsTimeout); } finally { safeWaitHandleToWaitOn.DangerousRelease(); } } finally { safeWaitHandleToSignal.DangerousRelease(); } } public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn) => SignalAndWait(toSignal, toWaitOn, Timeout.Infinite); public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, TimeSpan timeout, bool exitContext) => SignalAndWait(toSignal, toWaitOn, ToTimeoutMilliseconds(timeout)); [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")] public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext) => SignalAndWait(toSignal, toWaitOn, millisecondsTimeout); public virtual void Close() => Dispose(); protected virtual void Dispose(bool explicitDisposing) { if (_waitHandle != null) { _waitHandle.Close(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } internal static void ThrowInvalidHandleException() { var ex = new InvalidOperationException(SR.InvalidOperation_InvalidHandle); ex.SetErrorCode(__HResults.ERROR_INVALID_HANDLE); throw ex; } } }
// 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. #if DJANGO_HTML_EDITOR using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using DebuggerTests; using Microsoft.PythonTools.Debugger; using Microsoft.PythonTools.Infrastructure; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; namespace DjangoTests { [TestClass] public class DjangoDebuggerTests : BaseDebuggerTests { private static DbState _dbstate; enum DbState { Unknown, OarApp } private void AssertDjangoVersion(Version min = null, Version max = null) { Version.AssertInstalled(); using (var output = ProcessOutput.RunHiddenAndCapture( Version.InterpreterPath, new[] { "-c", "import django; print(django.get_version())" })) { output.Wait(); Assert.AreEqual(0, output.ExitCode); var version = System.Version.Parse(output.StandardOutputLines.FirstOrDefault()); if (min != null && version < min) { Assert.Inconclusive("Django before {0} not supported", min); } if (max != null && version >= max) { Assert.Inconclusive("Django {0} and later not supported", max); } } } /// <summary> /// Ensures the app is initialized with the appropriate set of data. If we're /// already initialized that way we don't re-initialize. /// </summary> private void Init(DbState requiredState) { if (_dbstate != requiredState) { Version.AssertInstalled(); switch (requiredState) { case DbState.OarApp: using (var output = ProcessOutput.Run(Version.InterpreterPath, new [] {"manage.py", "migrate", "--noinput"}, DebuggerTestPath, null, false, null)) { output.Wait(); Console.WriteLine(" ** stdout **"); Console.WriteLine(string.Join(Environment.NewLine, output.StandardOutputLines)); Console.WriteLine(" ** stderr **"); Console.WriteLine(string.Join(Environment.NewLine, output.StandardErrorLines)); Assert.AreEqual(0, output.ExitCode); } using (var output = ProcessOutput.Run(Version.InterpreterPath, new [] {"manage.py", "loaddata", "data.json"}, DebuggerTestPath, null, false, null)) { output.Wait(); Console.WriteLine(" ** stdout **"); Console.WriteLine(string.Join(Environment.NewLine, output.StandardOutputLines)); Console.WriteLine(" ** stderr **"); Console.WriteLine(string.Join(Environment.NewLine, output.StandardErrorLines)); Assert.AreEqual(0, output.ExitCode); } break; } _dbstate = requiredState; } } private void OutputDataReceived(object sender, DataReceivedEventArgs e) { if (e != null) { Console.WriteLine("Output: {0}", e.Data); } } [TestMethod, Priority(3)] [TestCategory("10s"), TestCategory("60s")] public async Task TemplateStepping() { Init(DbState.OarApp); await StepTestAsync( Path.Combine(Environment.CurrentDirectory, DebuggerTestPath, "manage.py"), Path.Combine(Environment.CurrentDirectory, DebuggerTestPath, "Templates\\polls\\loop.html"), "runserver --noreload", new[] { 1 }, // break on line 1, new Action<PythonProcess>[] { x => { } }, new WebPageRequester("http://127.0.0.1:8000/loop/").DoRequest, PythonDebugOptions.DjangoDebugging, false, new ExpectedStep(StepKind.Resume, 2), // first line in manage.py new ExpectedStep(StepKind.Over, 1), // step over for new ExpectedStep(StepKind.Over, 2), // step over {{ color }} new ExpectedStep(StepKind.Over, 3), // step over {{ color }} new ExpectedStep(StepKind.Over, 2), // step over {{ color }} new ExpectedStep(StepKind.Over, 3), // step over {{ color }} new ExpectedStep(StepKind.Over, 2), // step over {{ color }} new ExpectedStep(StepKind.Resume, 3) // step over {{ color }} ); // https://pytools.codeplex.com/workitem/1316 await StepTestAsync( Path.Combine(Environment.CurrentDirectory, DebuggerTestPath, "manage.py"), Path.Combine(Environment.CurrentDirectory, DebuggerTestPath, "Templates\\polls\\loop2.html"), "runserver --noreload", new[] { 3 }, // break on line 3, new Action<PythonProcess>[] { x => { } }, new WebPageRequester("http://127.0.0.1:8000/loop2/").DoRequest, PythonDebugOptions.DjangoDebugging, false, new ExpectedStep(StepKind.Resume, 2), // first line in manage.py new ExpectedStep(StepKind.Over, 3), // step over for new ExpectedStep(StepKind.Over, 4), // step over {{ color }} new ExpectedStep(StepKind.Over, 4), // step over {{ color }} new ExpectedStep(StepKind.Resume, 4) // step over {{ endfor }} ); await StepTestAsync( Path.Combine(Environment.CurrentDirectory, DebuggerTestPath, "manage.py"), Path.Combine(Environment.CurrentDirectory, DebuggerTestPath, "Templates\\polls\\loop_nobom.html"), "runserver --noreload", new[] { 1 }, // break on line 1, new Action<PythonProcess>[] { x => { } }, new WebPageRequester("http://127.0.0.1:8000/loop_nobom/").DoRequest, PythonDebugOptions.DjangoDebugging, false, new ExpectedStep(StepKind.Resume, 2), // first line in manage.py new ExpectedStep(StepKind.Over, 1), // step over for new ExpectedStep(StepKind.Over, 2), // step over {{ color }} new ExpectedStep(StepKind.Over, 3), // step over {{ color }} new ExpectedStep(StepKind.Over, 2), // step over {{ color }} new ExpectedStep(StepKind.Over, 3), // step over {{ color }} new ExpectedStep(StepKind.Over, 2), // step over {{ color }} new ExpectedStep(StepKind.Resume, 3) // step over {{ color }} ); } [TestMethod, Priority(3)] [TestCategory("10s")] public async Task BreakInTemplate() { Init(DbState.OarApp); string cwd = Path.Combine(Environment.CurrentDirectory, DebuggerTestPath); await new BreakpointTest(this, "manage.py") { BreakFileName = Path.Combine(cwd, "Templates", "polls", "index.html"), Breakpoints = { new DjangoBreakpoint(1), new DjangoBreakpoint(3), new DjangoBreakpoint(4) }, ExpectedHits = { 0, 1, 2 }, Arguments = "runserver --noreload", ExpectHitOnMainThread = false, WaitForExit = false, DebugOptions = PythonDebugOptions.DjangoDebugging, OnProcessLoaded = proc => new WebPageRequester().DoRequest() }.RunAsync(); } [TestMethod, Priority(3)] public async Task TemplateLocals() { Init(DbState.OarApp); await DjangoLocalsTestAsync("polls\\index.html", 3, new[] { "latest_poll_list" }); await DjangoLocalsTestAsync("polls\\index.html", 4, new[] { "forloop", "latest_poll_list", "poll" }); } private async Task DjangoLocalsTestAsync(string filename, int breakLine, string[] expectedLocals) { string cwd = Path.Combine(Environment.CurrentDirectory, DebuggerTestPath); var test = new LocalsTest(this, "manage.py", breakLine) { BreakFileName = Path.Combine(cwd, "Templates", filename), Arguments = "runserver --noreload", ProcessLoaded = new WebPageRequester().DoRequest, DebugOptions = PythonDebugOptions.DjangoDebugging, WaitForExit = false }; test.Locals.AddRange(expectedLocals); await test.RunAsync(); } class WebPageRequester { private readonly string _url; public WebPageRequester(string url = "http://127.0.0.1:8000/Oar/") { _url = url; } public void DoRequest() { ThreadPool.QueueUserWorkItem(DoRequestWorker, null); } public void DoRequestWorker(object data) { Console.WriteLine("Waiting for port to open..."); var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Blocking = true; for (int i = 0; i < 200; i++) { try { socket.Connect(IPAddress.Loopback, 8000); break; } catch { System.Threading.Thread.Sleep(1000); } } socket.Close(); Console.WriteLine("Requesting {0}", _url); HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(_url); try { var response = myReq.GetResponse(); using (var stream = response.GetResponseStream()) { Console.WriteLine("Response: {0}", new StreamReader(stream).ReadToEnd()); } } catch (WebException) { // the process can be killed and the connection with it } } } internal override string DebuggerTestPath { get { return TestData.GetPath(@"TestData\DjangoProject\"); } } private PythonVersion _version; internal override PythonVersion Version { get { if (_version == null) { _version = PythonPaths.Versions.Reverse().FirstOrDefault(v => v != null && Directory.Exists(Path.Combine(v.PrefixPath, "Lib")) && Directory.EnumerateDirectories(Path.Combine(v.PrefixPath, "Lib", "site-packages")).Any(d => Path.GetFileName(d).StartsWith("django") ) ); } return _version; } } } } #endif
using System; using UnityEngine; namespace Sanicball { public class CameraFade : MonoBehaviour { public GUIStyle m_BackgroundStyle = new GUIStyle(); // Style for background tiling public Texture2D m_FadeTexture; // 1x1 pixel texture used for fading public Color m_CurrentScreenOverlayColor = new Color(0, 0, 0, 0); // default starting color: black and fully transparrent public Color m_TargetScreenOverlayColor = new Color(0, 0, 0, 0); // default target color: black and fully transparrent public Color m_DeltaColor = new Color(0, 0, 0, 0); // the delta-color is basically the "speed / second" at which the current color should change public int m_FadeGUIDepth = -1000; public float m_FadeDelay = 0; // make sure this texture is drawn on top of everything public Action m_OnFadeFinish = null; private static CameraFade mInstance = null; private static CameraFade instance { get { if (mInstance == null) { mInstance = GameObject.FindObjectOfType(typeof(CameraFade)) as CameraFade; if (mInstance == null) { mInstance = new GameObject("CameraFade").AddComponent<CameraFade>(); } } return mInstance; } } /// <summary> /// Starts the fade from color newScreenOverlayColor. If isFadeIn, start fully opaque, else start transparent. /// </summary> /// <param name='newScreenOverlayColor'> /// Target screen overlay Color. /// </param> /// <param name='fadeDuration'> /// Fade duration. /// </param> public static void StartAlphaFade(Color newScreenOverlayColor, bool isFadeIn, float fadeDuration) { if (fadeDuration <= 0.0f) { SetScreenOverlayColor(newScreenOverlayColor); } else { if (isFadeIn) { instance.m_TargetScreenOverlayColor = new Color(newScreenOverlayColor.r, newScreenOverlayColor.g, newScreenOverlayColor.b, 0); SetScreenOverlayColor(newScreenOverlayColor); } else { instance.m_TargetScreenOverlayColor = newScreenOverlayColor; SetScreenOverlayColor(new Color(newScreenOverlayColor.r, newScreenOverlayColor.g, newScreenOverlayColor.b, 0)); } instance.m_DeltaColor = (instance.m_TargetScreenOverlayColor - instance.m_CurrentScreenOverlayColor) / fadeDuration; } } /// <summary> /// Starts the fade from color newScreenOverlayColor. If isFadeIn, start fully opaque, else start transparent, after a delay. /// </summary> /// <param name='newScreenOverlayColor'> /// New screen overlay color. /// </param> /// <param name='fadeDuration'> /// Fade duration. /// </param> /// <param name='fadeDelay'> /// Fade delay. /// </param> public static void StartAlphaFade(Color newScreenOverlayColor, bool isFadeIn, float fadeDuration, float fadeDelay) { if (fadeDuration <= 0.0f) { SetScreenOverlayColor(newScreenOverlayColor); } else { instance.m_FadeDelay = Time.time + fadeDelay; if (isFadeIn) { instance.m_TargetScreenOverlayColor = new Color(newScreenOverlayColor.r, newScreenOverlayColor.g, newScreenOverlayColor.b, 0); SetScreenOverlayColor(newScreenOverlayColor); } else { instance.m_TargetScreenOverlayColor = newScreenOverlayColor; SetScreenOverlayColor(new Color(newScreenOverlayColor.r, newScreenOverlayColor.g, newScreenOverlayColor.b, 0)); } instance.m_DeltaColor = (instance.m_TargetScreenOverlayColor - instance.m_CurrentScreenOverlayColor) / fadeDuration; } } /// <summary> /// Starts the fade from color newScreenOverlayColor. If isFadeIn, start fully opaque, else start transparent, after a delay, with Action OnFadeFinish. /// </summary> /// <param name='newScreenOverlayColor'> /// New screen overlay color. /// </param> /// <param name='fadeDuration'> /// Fade duration. /// </param> /// <param name='fadeDelay'> /// Fade delay. /// </param> /// <param name='OnFadeFinish'> /// On fade finish, doWork(). /// </param> public static void StartAlphaFade(Color newScreenOverlayColor, bool isFadeIn, float fadeDuration, float fadeDelay, Action OnFadeFinish) { if (fadeDuration <= 0.0f) { SetScreenOverlayColor(newScreenOverlayColor); } else { instance.m_OnFadeFinish = OnFadeFinish; instance.m_FadeDelay = Time.time + fadeDelay; if (isFadeIn) { instance.m_TargetScreenOverlayColor = new Color(newScreenOverlayColor.r, newScreenOverlayColor.g, newScreenOverlayColor.b, 0); SetScreenOverlayColor(newScreenOverlayColor); } else { instance.m_TargetScreenOverlayColor = newScreenOverlayColor; SetScreenOverlayColor(new Color(newScreenOverlayColor.r, newScreenOverlayColor.g, newScreenOverlayColor.b, 0)); } instance.m_DeltaColor = (instance.m_TargetScreenOverlayColor - instance.m_CurrentScreenOverlayColor) / fadeDuration; } } // Initialize the texture, background-style and initial color: public void init() { instance.m_FadeTexture = new Texture2D(1, 1); instance.m_BackgroundStyle.normal.background = instance.m_FadeTexture; } /// <summary> /// Sets the color of the screen overlay instantly. Useful to start a fade. /// </summary> /// <param name='newScreenOverlayColor'> /// New screen overlay color. /// </param> private static void SetScreenOverlayColor(Color newScreenOverlayColor) { instance.m_CurrentScreenOverlayColor = newScreenOverlayColor; instance.m_FadeTexture.SetPixel(0, 0, instance.m_CurrentScreenOverlayColor); instance.m_FadeTexture.Apply(); } private void Awake() { if (mInstance == null) { mInstance = this as CameraFade; instance.init(); } } // Draw the texture and perform the fade: private void OnGUI() { // If delay is over... if (Time.time > instance.m_FadeDelay) { // If the current color of the screen is not equal to the desired color: keep fading! if (instance.m_CurrentScreenOverlayColor != instance.m_TargetScreenOverlayColor) { // If the difference between the current alpha and the desired alpha is smaller than delta-alpha * deltaTime, then we're pretty much done fading: if (Mathf.Abs(instance.m_CurrentScreenOverlayColor.a - instance.m_TargetScreenOverlayColor.a) < Mathf.Abs(instance.m_DeltaColor.a) * Time.deltaTime) { instance.m_CurrentScreenOverlayColor = instance.m_TargetScreenOverlayColor; SetScreenOverlayColor(instance.m_CurrentScreenOverlayColor); instance.m_DeltaColor = new Color(0, 0, 0, 0); if (instance.m_OnFadeFinish != null) instance.m_OnFadeFinish(); Die(); } else { // Fade! SetScreenOverlayColor(instance.m_CurrentScreenOverlayColor + instance.m_DeltaColor * Time.deltaTime); } } } // Only draw the texture when the alpha value is greater than 0: if (m_CurrentScreenOverlayColor.a > 0) { GUI.depth = instance.m_FadeGUIDepth; GUI.Label(new Rect(-10, -10, Screen.width + 10, Screen.height + 10), instance.m_FadeTexture, instance.m_BackgroundStyle); } } private void Die() { mInstance = null; Destroy(gameObject); } private void OnApplicationQuit() { mInstance = null; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using BenchmarkDotNet.Running; using Benchmarks.MapReduce; using Benchmarks.Ping; using Benchmarks.Transactions; using Benchmarks.GrainStorage; namespace Benchmarks { class Program { private static readonly Dictionary<string, Action<string[]>> _benchmarks = new Dictionary<string, Action<string[]>> { ["MapReduce"] = _ => { RunBenchmark( "Running MapReduce benchmark", () => { var mapReduceBenchmark = new MapReduceBenchmark(); mapReduceBenchmark.BenchmarkSetup(); return mapReduceBenchmark; }, benchmark => benchmark.Bench().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Memory"] = _ => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 20000, 5000); benchmark.MemorySetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Memory.Throttled"] = _ => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 200000, 15000); benchmark.MemoryThrottledSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Azure"] = _ => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 20000, 5000); benchmark.AzureSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Azure.Throttled"] = _ => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 200000, 15000); benchmark.AzureThrottledSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["Transactions.Azure.Overloaded"] = _ => { RunBenchmark( "Running Transactions benchmark", () => { var benchmark = new TransactionBenchmark(2, 200000, 15000); benchmark.AzureSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["SequentialPing"] = _ => { BenchmarkRunner.Run<PingBenchmark>(); }, ["ConcurrentPing"] = _ => { { Console.WriteLine("## Client to Silo ##"); var test = new PingBenchmark(numSilos: 1, startClient: true); test.PingConcurrent().GetAwaiter().GetResult(); test.Shutdown().GetAwaiter().GetResult(); } GC.Collect(); { Console.WriteLine("## Client to 2 Silos ##"); var test = new PingBenchmark(numSilos: 2, startClient: true); test.PingConcurrent().GetAwaiter().GetResult(); test.Shutdown().GetAwaiter().GetResult(); } GC.Collect(); { Console.WriteLine("## Hosted Client ##"); var test = new PingBenchmark(numSilos: 1, startClient: false); test.PingConcurrentHostedClient().GetAwaiter().GetResult(); test.Shutdown().GetAwaiter().GetResult(); } GC.Collect(); { // All calls are cross-silo because the calling silo doesn't have any grain classes. Console.WriteLine("## Silo to Silo ##"); var test = new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true); test.PingConcurrentHostedClient(blocksPerWorker: 10).GetAwaiter().GetResult(); test.Shutdown().GetAwaiter().GetResult(); } }, ["ConcurrentPing_OneSilo"] = _ => { new PingBenchmark(numSilos: 1, startClient: true).PingConcurrent().GetAwaiter().GetResult(); }, ["ConcurrentPing_TwoSilos"] = _ => { new PingBenchmark(numSilos: 2, startClient: true).PingConcurrent().GetAwaiter().GetResult(); }, ["ConcurrentPing_HostedClient"] = _ => { new PingBenchmark(numSilos: 1, startClient: false).PingConcurrentHostedClient().GetAwaiter().GetResult(); }, ["ConcurrentPing_HostedClient_Forever"] = _ => { var benchmark = new PingBenchmark(numSilos: 1, startClient: false); Console.WriteLine("Press any key to begin."); Console.ReadKey(); Console.WriteLine("Press any key to end."); Console.WriteLine("## Hosted Client ##"); while (!Console.KeyAvailable) { benchmark.PingConcurrentHostedClient().GetAwaiter().GetResult(); } Console.WriteLine("Interrupted by user"); }, ["ConcurrentPing_SiloToSilo"] = _ => { new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true).PingConcurrentHostedClient(blocksPerWorker: 10).GetAwaiter().GetResult(); }, ["ConcurrentPing_SiloToSilo_Forever"] = _ => { Console.WriteLine("Press any key to begin."); Console.ReadKey(); Console.WriteLine("Press any key to end."); Console.WriteLine("## Silo to Silo ##"); while (!Console.KeyAvailable) { var test = new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true); Console.WriteLine("Starting"); test.PingConcurrentHostedClient(blocksPerWorker: 10).GetAwaiter().GetResult(); Console.WriteLine("Stopping"); test.Shutdown().GetAwaiter().GetResult(); } Console.WriteLine("Interrupted by user"); }, ["ConcurrentPing_SiloToSilo_Long"] = _ => { new PingBenchmark(numSilos: 2, startClient: false, grainsOnSecondariesOnly: true).PingConcurrentHostedClient(blocksPerWorker: 1000).GetAwaiter().GetResult(); }, ["ConcurrentPing_OneSilo_Forever"] = _ => { new PingBenchmark(numSilos: 1, startClient: true).PingConcurrentForever().GetAwaiter().GetResult(); }, ["PingOnce"] = _ => { new PingBenchmark().Ping().GetAwaiter().GetResult(); }, ["PingForever"] = _ => { new PingBenchmark().PingForever().GetAwaiter().GetResult(); }, ["PingPongForever"] = _ => { new PingBenchmark().PingPongForever().GetAwaiter().GetResult(); }, ["GrainStorage.Memory"] = _ => { RunBenchmark( "Running grain storage benchmark against memory", () => { var benchmark = new GrainStorageBenchmark(10, 10000, TimeSpan.FromSeconds( 30 )); benchmark.MemorySetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["GrainStorage.AzureTable"] = _ => { RunBenchmark( "Running grain storage benchmark against Azure Table", () => { var benchmark = new GrainStorageBenchmark(100, 10000, TimeSpan.FromSeconds( 30 )); benchmark.AzureTableSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["GrainStorage.AzureBlob"] = _ => { RunBenchmark( "Running grain storage benchmark against Azure Blob", () => { var benchmark = new GrainStorageBenchmark(10, 10000, TimeSpan.FromSeconds( 30 )); benchmark.AzureBlobSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["GrainStorage.AdoNet"] = _ => { RunBenchmark( "Running grain storage benchmark against AdoNet", () => { var benchmark = new GrainStorageBenchmark(100, 10000, TimeSpan.FromSeconds( 30 )); benchmark.AdoNetSetup(); return benchmark; }, benchmark => benchmark.RunAsync().GetAwaiter().GetResult(), benchmark => benchmark.Teardown()); }, ["suite"] = args => { _ = BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); } }; // requires benchmark name or 'All' word as first parameter public static void Main(string[] args) { var slicedArgs = args.Skip(1).ToArray(); if (args.Length > 0 && args[0].Equals("all", StringComparison.InvariantCultureIgnoreCase)) { Console.WriteLine("Running full benchmarks suite"); _benchmarks.Select(pair => pair.Value).ToList().ForEach(action => action(slicedArgs)); return; } if (args.Length == 0 || !_benchmarks.ContainsKey(args[0])) { Console.WriteLine("Please, select benchmark, list of available:"); _benchmarks .Select(pair => pair.Key) .ToList() .ForEach(Console.WriteLine); Console.WriteLine("All"); return; } _benchmarks[args[0]](slicedArgs); } private static void RunBenchmark<T>(string name, Func<T> init, Action<T> benchmarkAction, Action<T> tearDown) { Console.WriteLine(name); var bench = init(); var stopWatch = Stopwatch.StartNew(); benchmarkAction(bench); Console.WriteLine($"Elapsed milliseconds: {stopWatch.ElapsedMilliseconds}"); Console.WriteLine("Press any key to continue ..."); tearDown(bench); Console.ReadLine(); } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; using Prajna.Tools; using Prajna.Core; using Prajna.Service.ServiceEndpoint; using VMHub.Data; using VMHub.ServiceEndpoint; using Prajna.Service.CSharp; namespace SampleRecogServerCSharp { [Serializable] public class SampleRecogInstanceCSharpParam : VHubBackendStartParam { public string SaveImageDirectory { get; set; } public static SampleRecogInstanceCSharp ConstructSampleRecogInstanceCSharp() { return new SampleRecogInstanceCSharp(); } } public class SampleRecogInstanceCSharp : VHubBackEndInstance<SampleRecogInstanceCSharpParam> { public static SampleRecogInstanceCSharp Current { get; set; } public string SaveImageDirectory { get; set; } internal SampleRecogInstanceCSharp() : /// Fill in your recognizing engine name here base("Your Engine Name") { /// CSharp does support closure, so we have to pass the recognizing instance somewhere, /// We use a static variable for this example. But be aware that this method of variable passing will hold a reference to SampleRecogInstanceCSharp SampleRecogInstanceCSharp.Current = this; Func<SampleRecogInstanceCSharpParam, bool> del = InitializeRecognizer; this.OnStartBackEnd.Add(del); } public static bool InitializeRecognizer(SampleRecogInstanceCSharpParam pa) { var bInitialized = true; var x = SampleRecogInstanceCSharp.Current; x.SaveImageDirectory = pa.SaveImageDirectory; if (!Object.ReferenceEquals( x, null )) { /// <remarks> /// To implement your own image recognizer, please obtain a connection Guid by contacting jinl@microsoft.com /// </remarks> x.RegisterAppInfo(new Guid("843EF294-C635-42DA-9AD8-E79E82F9A357"), "0.0.0.1"); Func<Guid, int, RecogRequest, RecogReply> del = QueryFunc; /// <remarks> /// Register your query function here. /// </remarks> x.RegisterClassifierCS("#dog", "dog.jpg", 100, del); } else { bInitialized = false; } return bInitialized; } public static RecogReply QueryFunc( Guid id,int timeBudgetInMS,RecogRequest req ) { var resultString = "Unknown"; return VHubRecogResultHelper.FixedClassificationResult(resultString, resultString); } } class Program { static void Main(string[] args) { var usage = @" Usage: Launch an intance of SampleRecogServerFSharp. The application is intended to run on any machine. It will home in to an image recognition hub gateway for service\n\ Command line arguments: \n\ -start Launch a Prajna Recognition service in cluster\n\ -stop Stop existing Prajna Recognition service in cluster\n\ -exe Execute in exe mode \n\ -cluster CLUSTER_NAME Name of the cluster for service launch \n\ -port PORT Port used for service \n\ -node NODE_Name Launch the recognizer on the node of the cluster only (note that the cluster parameter still need to be provided \n\ -rootdir Root_Directory this directories holds DLLs, data model files that need to be remoted for execution\n\ -gateway SERVERURI ServerUri\n\ -only SERVERURI Only register with this server, disregard default. \n\ -saveimage DIRECTORY Directory where recognized image is saved \n\ "; var parse = new ArgumentParser(args); var prajnaClusterFile = parse.ParseString("-cluster", ""); var usePort = parse.ParseInt( "-port", VHubSetting.RegisterServicePort ); var nodeName = parse.ParseString( "-node", "" ); var curfname = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; var curdir = Directory.GetParent( curfname ).FullName; var upperdir = Directory.GetParent( curdir ).FullName; var upper2dir = Directory.GetParent( upperdir ).FullName; var defaultRootdir = upper2dir; var rootdir = parse.ParseString( "-rootdir", defaultRootdir); var dlldir = parse.ParseString( "-dlldir", defaultRootdir ); var bStart = parse.ParseBoolean("-start", false); var bStop = parse.ParseBoolean( "-stop", false); var bExe = parse.ParseBoolean( "-exe", true); var saveImageDirectory = parse.ParseString( "-saveimage", @"."); var gatewayServers = parse.ParseStrings( "-gateway", new string[]{}); var onlyServers = parse.ParseStrings( "-only", new string[]{}); var serviceName = "SampleRecognitionServiceCS"; /// <remark> /// The code below is from PrajnaRecogServer for register multiple classifier (one for each domain) /// You should modify the code to retrieve your own classifiers /// </remark> var bAllParsed = parse.AllParsed( usage ); if (bAllParsed) { Cluster.StartCluster(prajnaClusterFile ); if (!(StringTools.IsNullOrEmpty( nodeName )) ) { var cluster = Cluster.GetCurrent().GetSingleNodeCluster( nodeName ); if (Object.ReferenceEquals(cluster,null)) { throw new Exception( "Can't find node in cluster" ); } else Cluster.SetCurrent( cluster ); } } if ( bExe ) { JobDependencies.DefaultTypeOfJobMask = JobTaskKind.ApplicationMask; } var curJob = JobDependencies.setCurrentJob( "SampleRecogServerCSharp" ); if (bStart) { // add other file dependencies // allow mapping local to different location in remote in case user specifies different model files var exeName = System.Reflection.Assembly.GetExecutingAssembly().Location; var exePath = Path.GetDirectoryName( exeName ); /// If you need to change the current directory at remote, uncomment and set the following variable the following // curJob.EnvVars.Add(DeploymentSettings.EnvStringSetJobDirectory, "." ) /// All data files are placed under rootdir locally, and will be placed at root (relative directory at remote ). var dirAtRemote = curJob.AddDataDirectoryWithPrefix( null, rootdir, "root", "*", SearchOption.AllDirectories ); /// Add all var dlls = curJob.AddDataDirectory( dlldir, "*", SearchOption.AllDirectories ); var managedDlls = curJob.AddDataDirectoryWithPrefix( null, exePath, "dependencies", "*", SearchOption.AllDirectories ); var startParam = new SampleRecogInstanceCSharpParam { SaveImageDirectory = saveImageDirectory } ; /// Add traffic manager gateway, see http://azure.microsoft.com/en-us/services/traffic-manager/, /// Gateway that is added as traffic manager will be repeatedly resovled via DNS resolve foreach ( var gatewayServer in gatewayServers ) { if (!(StringTools.IsNullOrEmpty( gatewayServer)) ) startParam.AddOneTrafficManager( gatewayServer, usePort ); }; /// Add simple gateway, no repeated DNS service. foreach ( var onlyServer in onlyServers ) { if (!(StringTools.IsNullOrEmpty( onlyServer)) ) startParam.AddOneServer( onlyServer, usePort ); } var curCluster = Cluster.GetCurrent(); if (Object.ReferenceEquals(curCluster, null)) { // If no cluster parameter, start a local instance. RemoteInstance.StartLocal(serviceName, startParam, SampleRecogInstanceCSharpParam.ConstructSampleRecogInstanceCSharp ); while (RemoteInstance.IsRunningLocal(serviceName)) { if (Console.KeyAvailable) { var cki = Console.ReadKey(true); if (cki.Key == ConsoleKey.Enter) { RemoteInstance.StopLocal(serviceName); } else { System.Threading.Thread.Sleep(10); } } } } else // If there is cluster parameter, start remote recognition cluster. RemoteInstance.Start(serviceName, startParam, SampleRecogInstanceCSharpParam.ConstructSampleRecogInstanceCSharp); } else if (bStop) { RemoteInstance.Stop(serviceName); } } } }
using Orleans; using Orleans.Runtime; using Orleans.Runtime.TestHooks; using Orleans.TestingHost; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime.Configuration; using Tester; using TestExtensions; using UnitTests; using UnitTests.GrainInterfaces; using Xunit; using Xunit.Abstractions; namespace AWSUtils.Tests.StorageTests { public abstract class Base_PersistenceGrainTests_AWSStore : OrleansTestingBase { private readonly ITestOutputHelper output; protected TestCluster HostedCluster { get; private set; } private readonly double timingFactor; private const int LoopIterations_Grain = 1000; private const int BatchSize = 100; private const int MaxReadTime = 200; private const int MaxWriteTime = 2000; private readonly BaseTestClusterFixture fixture; public Base_PersistenceGrainTests_AWSStore(ITestOutputHelper output, BaseTestClusterFixture fixture) { if (!AWSTestConstants.IsDynamoDbAvailable) throw new SkipException("Unable to connect to DynamoDB simulator"); this.output = output; this.fixture = fixture; HostedCluster = fixture.HostedCluster; timingFactor = TestUtils.CalibrateTimings(); } protected async Task Grain_AWSStore_Delete() { Guid id = Guid.NewGuid(); IAWSStorageTestGrain grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id); await grain.DoWrite(1); await grain.DoDelete(); int val = await grain.GetValue(); // Should this throw instead? Assert.Equal(0, val); // "Value after Delete" await grain.DoWrite(2); val = await grain.GetValue(); Assert.Equal(2, val); // "Value after Delete + New Write" } protected async Task Grain_AWSStore_Read() { Guid id = Guid.NewGuid(); IAWSStorageTestGrain grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id); int val = await grain.GetValue(); Assert.Equal(0, val); // "Initial value" } protected async Task Grain_GuidKey_AWSStore_Read_Write() { Guid id = Guid.NewGuid(); IAWSStorageTestGrain grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id); int val = await grain.GetValue(); Assert.Equal(0, val); // "Initial value" await grain.DoWrite(1); val = await grain.GetValue(); Assert.Equal(1, val); // "Value after Write-1" await grain.DoWrite(2); val = await grain.GetValue(); Assert.Equal(2, val); // "Value after Write-2" val = await grain.DoRead(); Assert.Equal(2, val); // "Value after Re-Read" } protected async Task Grain_LongKey_AWSStore_Read_Write() { long id = random.Next(); IAWSStorageTestGrain_LongKey grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain_LongKey>(id); int val = await grain.GetValue(); Assert.Equal(0, val); // "Initial value" await grain.DoWrite(1); val = await grain.GetValue(); Assert.Equal(1, val); // "Value after Write-1" await grain.DoWrite(2); val = await grain.GetValue(); Assert.Equal(2, val); // "Value after Write-2" val = await grain.DoRead(); Assert.Equal(2, val); // "Value after Re-Read" } protected async Task Grain_LongKeyExtended_AWSStore_Read_Write() { long id = random.Next(); string extKey = random.Next().ToString(CultureInfo.InvariantCulture); IAWSStorageTestGrain_LongExtendedKey grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain_LongExtendedKey>(id, extKey, null); int val = await grain.GetValue(); Assert.Equal(0, val); // "Initial value" await grain.DoWrite(1); val = await grain.GetValue(); Assert.Equal(1, val); // "Value after Write-1" await grain.DoWrite(2); val = await grain.GetValue(); Assert.Equal(2, val); // "Value after Write-2" val = await grain.DoRead(); Assert.Equal(2, val); // "Value after DoRead" val = await grain.GetValue(); Assert.Equal(2, val); // "Value after Re-Read" string extKeyValue = await grain.GetExtendedKeyValue(); Assert.Equal(extKey, extKeyValue); // "Extended Key" } protected async Task Grain_GuidKeyExtended_AWSStore_Read_Write() { var id = Guid.NewGuid(); string extKey = random.Next().ToString(CultureInfo.InvariantCulture); IAWSStorageTestGrain_GuidExtendedKey grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain_GuidExtendedKey>(id, extKey, null); int val = await grain.GetValue(); Assert.Equal(0, val); // "Initial value" await grain.DoWrite(1); val = await grain.GetValue(); Assert.Equal(1, val); // "Value after Write-1" await grain.DoWrite(2); val = await grain.GetValue(); Assert.Equal(2, val); // "Value after Write-2" val = await grain.DoRead(); Assert.Equal(2, val); // "Value after DoRead" val = await grain.GetValue(); Assert.Equal(2, val); // "Value after Re-Read" string extKeyValue = await grain.GetExtendedKeyValue(); Assert.Equal(extKey, extKeyValue); // "Extended Key" } protected async Task Grain_Generic_AWSStore_Read_Write() { long id = random.Next(); IAWSStorageGenericGrain<int> grain = this.fixture.GrainFactory.GetGrain<IAWSStorageGenericGrain<int>>(id); int val = await grain.GetValue(); Assert.Equal(0, val); // "Initial value" await grain.DoWrite(1); val = await grain.GetValue(); Assert.Equal(1, val); // "Value after Write-1" await grain.DoWrite(2); val = await grain.GetValue(); Assert.Equal(2, val); // "Value after Write-2" val = await grain.DoRead(); Assert.Equal(2, val); // "Value after Re-Read" } protected async Task Grain_Generic_AWSStore_DiffTypes() { long id1 = random.Next(); long id2 = id1; long id3 = id1; IAWSStorageGenericGrain<int> grain1 = this.fixture.GrainFactory.GetGrain<IAWSStorageGenericGrain<int>>(id1); IAWSStorageGenericGrain<string> grain2 = this.fixture.GrainFactory.GetGrain<IAWSStorageGenericGrain<string>>(id2); IAWSStorageGenericGrain<double> grain3 = this.fixture.GrainFactory.GetGrain<IAWSStorageGenericGrain<double>>(id3); int val1 = await grain1.GetValue(); Assert.Equal(0, val1); // "Initial value - 1" string val2 = await grain2.GetValue(); Assert.Null(val2); // "Initial value - 2" double val3 = await grain3.GetValue(); Assert.Equal(0.0, val3); // "Initial value - 3" int expected1 = 1; await grain1.DoWrite(expected1); val1 = await grain1.GetValue(); Assert.Equal(expected1, val1); // "Value after Write#1 - 1" string expected2 = "Three"; await grain2.DoWrite(expected2); val2 = await grain2.GetValue(); Assert.Equal(expected2, val2); // "Value after Write#1 - 2" double expected3 = 5.1; await grain3.DoWrite(expected3); val3 = await grain3.GetValue(); Assert.Equal(expected3, val3); // "Value after Write#1 - 3" val1 = await grain1.GetValue(); Assert.Equal(expected1, val1); // "Value before Write#2 - 1" expected1 = 2; await grain1.DoWrite(expected1); val1 = await grain1.GetValue(); Assert.Equal(expected1, val1); // "Value after Write#2 - 1" val1 = await grain1.DoRead(); Assert.Equal(expected1, val1); // "Value after Re-Read - 1" val2 = await grain2.GetValue(); Assert.Equal(expected2, val2); // "Value before Write#2 - 2" expected2 = "Four"; await grain2.DoWrite(expected2); val2 = await grain2.GetValue(); Assert.Equal(expected2, val2); // "Value after Write#2 - 2" val2 = await grain2.DoRead(); Assert.Equal(expected2, val2); // "Value after Re-Read - 2" val3 = await grain3.GetValue(); Assert.Equal(expected3, val3); // "Value before Write#2 - 3" expected3 = 6.2; await grain3.DoWrite(expected3); val3 = await grain3.GetValue(); Assert.Equal(expected3, val3); // "Value after Write#2 - 3" val3 = await grain3.DoRead(); Assert.Equal(expected3, val3); // "Value after Re-Read - 3" } protected async Task Grain_AWSStore_SiloRestart() { var initialServiceId = this.HostedCluster.Options.ServiceId; var initialDeploymentId = this.HostedCluster.Options.ClusterId; var serviceId = await this.HostedCluster.Client.GetGrain<IServiceIdGrain>(Guid.Empty).GetServiceId(); output.WriteLine("ClusterId={0} ServiceId={1}", this.HostedCluster.Options.ClusterId, serviceId); Guid id = Guid.NewGuid(); IAWSStorageTestGrain grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id); int val = await grain.GetValue(); Assert.Equal(0, val); // "Initial value" await grain.DoWrite(1); output.WriteLine("About to reset Silos"); foreach (var silo in this.HostedCluster.GetActiveSilos().ToList()) { await this.HostedCluster.RestartSiloAsync(silo); } this.HostedCluster.InitializeClient(); output.WriteLine("Silos restarted"); serviceId = await this.HostedCluster.Client.GetGrain<IServiceIdGrain>(Guid.Empty).GetServiceId(); output.WriteLine("ClusterId={0} ServiceId={1}", this.HostedCluster.Options.ClusterId, serviceId); Assert.Equal(initialServiceId, serviceId); // "ServiceId same after restart." Assert.Equal(initialDeploymentId, this.HostedCluster.Options.ClusterId); // "ClusterId same after restart." val = await grain.GetValue(); Assert.Equal(1, val); // "Value after Write-1" await grain.DoWrite(2); val = await grain.GetValue(); Assert.Equal(2, val); // "Value after Write-2" val = await grain.DoRead(); Assert.Equal(2, val); // "Value after Re-Read" } protected void Persistence_Perf_Activate() { const string testName = "Persistence_Perf_Activate"; int n = LoopIterations_Grain; TimeSpan target = TimeSpan.FromMilliseconds(MaxReadTime * n); // Timings for Activate RunPerfTest(n, testName, target, grainNoState => grainNoState.PingAsync(), grainMemory => grainMemory.DoSomething(), grainMemoryStore => grainMemoryStore.GetValue(), grainAWSStore => grainAWSStore.GetValue()); } protected void Persistence_Perf_Write() { const string testName = "Persistence_Perf_Write"; int n = LoopIterations_Grain; TimeSpan target = TimeSpan.FromMilliseconds(MaxWriteTime * n); // Timings for Write RunPerfTest(n, testName, target, grainNoState => grainNoState.EchoAsync(testName), grainMemory => grainMemory.DoWrite(n), grainMemoryStore => grainMemoryStore.DoWrite(n), grainAWSStore => grainAWSStore.DoWrite(n)); } protected void Persistence_Perf_Write_Reread() { const string testName = "Persistence_Perf_Write_Read"; int n = LoopIterations_Grain; TimeSpan target = TimeSpan.FromMilliseconds(MaxWriteTime * n); // Timings for Write RunPerfTest(n, testName + "--Write", target, grainNoState => grainNoState.EchoAsync(testName), grainMemory => grainMemory.DoWrite(n), grainMemoryStore => grainMemoryStore.DoWrite(n), grainAWSStore => grainAWSStore.DoWrite(n)); // Timings for Activate RunPerfTest(n, testName + "--ReRead", target, grainNoState => grainNoState.GetLastEchoAsync(), grainMemory => grainMemory.DoRead(), grainMemoryStore => grainMemoryStore.DoRead(), grainAWSStore => grainAWSStore.DoRead()); } protected async Task Persistence_Silo_StorageProvider_AWS(Type providerType) { List<SiloHandle> silos = this.HostedCluster.GetActiveSilos().ToList(); foreach (var silo in silos) { string provider = providerType.FullName; ICollection<string> providers = await this.HostedCluster.Client.GetTestHooks(silo).GetStorageProviderNames(); Assert.True(providers.Contains(provider), $"No storage provider found: {provider}"); } } // ---------- Utility functions ---------- protected void RunPerfTest(int n, string testName, TimeSpan target, Func<IEchoTaskGrain, Task> actionNoState, Func<IPersistenceTestGrain, Task> actionMemory, Func<IMemoryStorageTestGrain, Task> actionMemoryStore, Func<IAWSStorageTestGrain, Task> actionAWSTable) { IEchoTaskGrain[] noStateGrains = new IEchoTaskGrain[n]; IPersistenceTestGrain[] memoryGrains = new IPersistenceTestGrain[n]; IAWSStorageTestGrain[] awsStoreGrains = new IAWSStorageTestGrain[n]; IMemoryStorageTestGrain[] memoryStoreGrains = new IMemoryStorageTestGrain[n]; for (int i = 0; i < n; i++) { Guid id = Guid.NewGuid(); noStateGrains[i] = this.fixture.GrainFactory.GetGrain<IEchoTaskGrain>(id); memoryGrains[i] = this.fixture.GrainFactory.GetGrain<IPersistenceTestGrain>(id); awsStoreGrains[i] = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id); memoryStoreGrains[i] = this.fixture.GrainFactory.GetGrain<IMemoryStorageTestGrain>(id); } TimeSpan baseline, elapsed; elapsed = baseline = TestUtils.TimeRun(n, TimeSpan.Zero, testName + " (No state)", () => RunIterations(testName, n, i => actionNoState(noStateGrains[i]))); elapsed = TestUtils.TimeRun(n, baseline, testName + " (Local Memory Store)", () => RunIterations(testName, n, i => actionMemory(memoryGrains[i]))); elapsed = TestUtils.TimeRun(n, baseline, testName + " (Dev Store Grain Store)", () => RunIterations(testName, n, i => actionMemoryStore(memoryStoreGrains[i]))); elapsed = TestUtils.TimeRun(n, baseline, testName + " (AWS Table Store)", () => RunIterations(testName, n, i => actionAWSTable(awsStoreGrains[i]))); if (elapsed > target.Multiply(timingFactor)) { string msg = string.Format("{0}: Elapsed time {1} exceeds target time {2}", testName, elapsed, target); if (elapsed > target.Multiply(2.0 * timingFactor)) { Assert.True(false, msg); } else { throw new SkipException(msg); } } } private void RunIterations(string testName, int n, Func<int, Task> action) { List<Task> promises = new List<Task>(); Stopwatch sw = Stopwatch.StartNew(); // Fire off requests in batches for (int i = 0; i < n; i++) { var promise = action(i); promises.Add(promise); if ((i % BatchSize) == 0 && i > 0) { Task.WaitAll(promises.ToArray()); promises.Clear(); //output.WriteLine("{0} has done {1} iterations in {2} at {3} RPS", // testName, i, sw.Elapsed, i / sw.Elapsed.TotalSeconds); } } Task.WaitAll(promises.ToArray()); sw.Stop(); output.WriteLine("{0} completed. Did {1} iterations in {2} at {3} RPS", testName, n, sw.Elapsed, n / sw.Elapsed.TotalSeconds); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ReplicationNetworkMappingsOperations. /// </summary> public static partial class ReplicationNetworkMappingsOperationsExtensions { /// <summary> /// Gets all the network mappings under a vault. /// </summary> /// <remarks> /// Lists all ASR network mappings in the vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<NetworkMapping> List(this IReplicationNetworkMappingsOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all the network mappings under a vault. /// </summary> /// <remarks> /// Lists all ASR network mappings in the vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkMapping>> ListAsync(this IReplicationNetworkMappingsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the network mappings under a network. /// </summary> /// <remarks> /// Lists all ASR network mappings for the specified network. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> public static IPage<NetworkMapping> ListByReplicationNetworks(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName) { return operations.ListByReplicationNetworksAsync(fabricName, networkName).GetAwaiter().GetResult(); } /// <summary> /// Gets all the network mappings under a network. /// </summary> /// <remarks> /// Lists all ASR network mappings for the specified network. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkMapping>> ListByReplicationNetworksAsync(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByReplicationNetworksWithHttpMessagesAsync(fabricName, networkName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets network mapping by name. /// </summary> /// <remarks> /// Gets the details of an ASR network mapping /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// Network mapping name. /// </param> public static NetworkMapping Get(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName) { return operations.GetAsync(fabricName, networkName, networkMappingName).GetAwaiter().GetResult(); } /// <summary> /// Gets network mapping by name. /// </summary> /// <remarks> /// Gets the details of an ASR network mapping /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// Network mapping name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkMapping> GetAsync(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(fabricName, networkName, networkMappingName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates network mapping. /// </summary> /// <remarks> /// The operation to create an ASR network mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// Network mapping name. /// </param> /// <param name='input'> /// Create network mapping input. /// </param> public static NetworkMapping Create(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName, CreateNetworkMappingInput input) { return operations.CreateAsync(fabricName, networkName, networkMappingName, input).GetAwaiter().GetResult(); } /// <summary> /// Creates network mapping. /// </summary> /// <remarks> /// The operation to create an ASR network mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// Network mapping name. /// </param> /// <param name='input'> /// Create network mapping input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkMapping> CreateAsync(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName, CreateNetworkMappingInput input, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(fabricName, networkName, networkMappingName, input, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete network mapping. /// </summary> /// <remarks> /// The operation to delete a network mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// ARM Resource Name for network mapping. /// </param> public static void Delete(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName) { operations.DeleteAsync(fabricName, networkName, networkMappingName).GetAwaiter().GetResult(); } /// <summary> /// Delete network mapping. /// </summary> /// <remarks> /// The operation to delete a network mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// ARM Resource Name for network mapping. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(fabricName, networkName, networkMappingName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Updates network mapping. /// </summary> /// <remarks> /// The operation to update an ASR network mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// Network mapping name. /// </param> /// <param name='input'> /// Update network mapping input. /// </param> public static NetworkMapping Update(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName, UpdateNetworkMappingInput input) { return operations.UpdateAsync(fabricName, networkName, networkMappingName, input).GetAwaiter().GetResult(); } /// <summary> /// Updates network mapping. /// </summary> /// <remarks> /// The operation to update an ASR network mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// Network mapping name. /// </param> /// <param name='input'> /// Update network mapping input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkMapping> UpdateAsync(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName, UpdateNetworkMappingInput input, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(fabricName, networkName, networkMappingName, input, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates network mapping. /// </summary> /// <remarks> /// The operation to create an ASR network mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// Network mapping name. /// </param> /// <param name='input'> /// Create network mapping input. /// </param> public static NetworkMapping BeginCreate(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName, CreateNetworkMappingInput input) { return operations.BeginCreateAsync(fabricName, networkName, networkMappingName, input).GetAwaiter().GetResult(); } /// <summary> /// Creates network mapping. /// </summary> /// <remarks> /// The operation to create an ASR network mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// Network mapping name. /// </param> /// <param name='input'> /// Create network mapping input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkMapping> BeginCreateAsync(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName, CreateNetworkMappingInput input, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(fabricName, networkName, networkMappingName, input, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete network mapping. /// </summary> /// <remarks> /// The operation to delete a network mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// ARM Resource Name for network mapping. /// </param> public static void BeginDelete(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName) { operations.BeginDeleteAsync(fabricName, networkName, networkMappingName).GetAwaiter().GetResult(); } /// <summary> /// Delete network mapping. /// </summary> /// <remarks> /// The operation to delete a network mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// ARM Resource Name for network mapping. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(fabricName, networkName, networkMappingName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Updates network mapping. /// </summary> /// <remarks> /// The operation to update an ASR network mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// Network mapping name. /// </param> /// <param name='input'> /// Update network mapping input. /// </param> public static NetworkMapping BeginUpdate(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName, UpdateNetworkMappingInput input) { return operations.BeginUpdateAsync(fabricName, networkName, networkMappingName, input).GetAwaiter().GetResult(); } /// <summary> /// Updates network mapping. /// </summary> /// <remarks> /// The operation to update an ASR network mapping. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Primary fabric name. /// </param> /// <param name='networkName'> /// Primary network name. /// </param> /// <param name='networkMappingName'> /// Network mapping name. /// </param> /// <param name='input'> /// Update network mapping input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkMapping> BeginUpdateAsync(this IReplicationNetworkMappingsOperations operations, string fabricName, string networkName, string networkMappingName, UpdateNetworkMappingInput input, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(fabricName, networkName, networkMappingName, input, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the network mappings under a vault. /// </summary> /// <remarks> /// Lists all ASR network mappings in the vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NetworkMapping> ListNext(this IReplicationNetworkMappingsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the network mappings under a vault. /// </summary> /// <remarks> /// Lists all ASR network mappings in the vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkMapping>> ListNextAsync(this IReplicationNetworkMappingsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the network mappings under a network. /// </summary> /// <remarks> /// Lists all ASR network mappings for the specified network. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NetworkMapping> ListByReplicationNetworksNext(this IReplicationNetworkMappingsOperations operations, string nextPageLink) { return operations.ListByReplicationNetworksNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the network mappings under a network. /// </summary> /// <remarks> /// Lists all ASR network mappings for the specified network. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkMapping>> ListByReplicationNetworksNextAsync(this IReplicationNetworkMappingsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByReplicationNetworksNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace WebApplication2 { /// <summary> /// Summary description for frmAddProcedure. /// </summary> public partial class frmUpdProfileSEProcs : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn=new SqlConnection(strDB); private string Id; private int GetIndexOfProjects (string s) { return (lstProjects.Items.IndexOf (lstProjects.Items.FindByValue(s))); } /*private int GetIndexOfRoles (string s) { return (lstRoles.Items.IndexOf (lstRoles.Items.FindByValue(s))); } private int GetIndexOfDeadlines (string s) { return (lstTypesOfDeadlines.Items.IndexOf (lstTypesOfDeadlines.Items.FindByValue(s))); } private int GetIndexOfImpact (string s) { return (lstTypesOfImpact.Items.IndexOf (lstTypesOfImpact.Items.FindByValue(s))); } private int GetIndexOfImpactMagnitude (string s) { return (lstTypesOfImpactMagnitude.Items.IndexOf (lstTypesOfImpactMagnitude.Items.FindByValue(s))); }*/ private int GetIndexOfProcs (string s) { return (lstProcs.Items.IndexOf (lstProcs.Items.FindByValue(s))); } private int GetIndexOfService (string s) { return (lstService.Items.IndexOf (lstService.Items.FindByValue(s))); } /*private int GetIndexOfLocs (string s) { return (lstLocs.Items.IndexOf (lstLocs.Items.FindByValue(s))); }*/ protected void Page_Load(object sender, System.EventArgs e) { if (Session["btnAction"].ToString() == "Update") { Id=Session["Id"].ToString(); } /*if (cbxTTs.Checked) { lstProjects.Visible=true; Label2.Visible=true; } else { lstProjects.Visible=false; Label2.Visible=false; }*/ if (!IsPostBack) { lblProfilesName.Text = "Business Profile for: " + Session["ProfilesName"].ToString(); lblServiceName.Text = "Service Delivered: " + Session["ServiceName"].ToString(); lblDeliverableName.Text = "Deliverable: " + Session["EventsName"].ToString(); btnAction.Text= Session["btnAction"].ToString() + " Process"; if (Session["btnAction"].ToString() == "Add") { lblAction.Text = "You may now select from procedures" + "related to other services, i.e. in addition to the service indicated above."; } else { lblAction.Text="You may now update the name and description for this process"; lblName.Text = "Process Name"; } //loadLocs(); loadProjects(); /*loadRoles(); loadTypesOfDeadlines(); loadTypesOfImpact(); loadTypesOfImpactMagnitude();*/ loadServices(); if (Session["btnAction"].ToString() == "Update") { loadData(); } else { loadProcs(); } cbxTTs.AutoPostBack=true; cbxCosts.AutoPostBack=true; } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion private void loadData() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveProfileSEProcsUpd"; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Id; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Upd"); txtName.Text=ds.Tables["Upd"].Rows[0][1].ToString(); /*lstTypesOfDeadlines.SelectedIndex=GetIndexOfDeadlines (ds.Tables["Upd"].Rows[0][1].ToString()); txtAcceptableSlip.Text=ds.Tables["Upd"].Rows[0][2].ToString(); lstTypesOfImpact.SelectedIndex=GetIndexOfImpact (ds.Tables["Upd"].Rows[0][3].ToString()); lstTypesOfImpactMagnitude.SelectedIndex=GetIndexOfImpactMagnitude (ds.Tables["Upd"].Rows[0][4].ToString()); txtDollarCostSlip.Text=ds.Tables["Upd"].Rows[0][5].ToString();*/ //lstLocs.SelectedIndex=GetIndexOfLocs (ds.Tables["Upd"].Rows[0][2].ToString()); lstProjects.SelectedIndex=GetIndexOfProjects (ds.Tables["Upd"].Rows[0][3].ToString()); lstService.SelectedIndex=GetIndexOfService (ds.Tables["Upd"].Rows[0][6].ToString()); //lstRoles.SelectedIndex=GetIndexOfRoles (ds.Tables["Upd"].Rows[0][8].ToString()); if (ds.Tables["Upd"].Rows[0][4].ToString() == "1") cbxTTs.Checked=true; if (ds.Tables["Upd"].Rows[0][5].ToString() == "1") cbxCosts.Checked=true; if ((cbxCosts.Checked)|| (cbxTTs.Checked) ) { lstProjects.Visible=true; lblProject.Visible=true; } loadProcs1(); lstProcs.SelectedIndex=GetIndexOfProcs (ds.Tables["Upd"].Rows[0][0].ToString()); //lblContents1.Text=rblTimetable.SelectedItem.Value.ToString() + " - " + rblTimetable.SelectedItem.Value; } private void loadProcs() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveProcs"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); cmd.Parameters.Add ("@ServiceTypesId",SqlDbType.Int); //cmd.Parameters["@ServiceTypesId"].Value=lstService.SelectedItem.Value; cmd.Parameters["@ServiceTypesId"].Value=Session["ServicesId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Procs"); lstProcs.DataSource = ds; lstProcs.DataMember= "Procs"; lstProcs.DataTextField = "Name"; lstProcs.DataValueField = "Id"; lstProcs.DataBind(); } private void loadServices() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveServiceTypes"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"ServiceTypes"); lstService.DataSource = ds; lstService.DataMember= "ServiceTypes"; lstService.DataTextField = "Name"; lstService.DataValueField = "Id"; lstService.DataBind(); if (Session["btnAction"].ToString() != "Update") { lstService.SelectedIndex=GetIndexOfService (Session["ServicesId"].ToString()); } } private void loadProjects() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveProjectTypes"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"ProjectTypes"); lstProjects.DataSource = ds; lstProjects.DataMember= "ProjectTypes"; lstProjects.DataTextField = "Name"; lstProjects.DataValueField = "Id"; lstProjects.DataBind(); } /*private void loadRoles() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveRoles"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Roles"); lstRoles.DataSource = ds; lstRoles.DataMember= "Roles"; lstRoles.DataTextField = "Name"; lstRoles.DataValueField = "Id"; lstRoles.DataBind(); }*/ /*private void loadLocs() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveLocTypes"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"LocTypes"); lstLocs.DataSource = ds; lstLocs.DataMember= "LocTypes"; lstLocs.DataTextField = "Name"; lstLocs.DataValueField = "Id"; lstLocs.DataBind(); }*/ /*private void loadTypesOfImpactMagnitude() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveTypesOfImpactMagnitude"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"TypesOfImpactMagnitude"); lstTypesOfImpactMagnitude.DataSource = ds; lstTypesOfImpactMagnitude.DataMember= "TypesOfImpactMagnitude"; lstTypesOfImpactMagnitude.DataTextField = "Name"; lstTypesOfImpactMagnitude.DataValueField = "Id"; lstTypesOfImpactMagnitude.DataBind(); } private void loadTypesOfImpact() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveTypesOfImpact"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"TypesOfImpact"); lstTypesOfImpact.DataSource = ds; lstTypesOfImpact.DataMember= "TypesOfImpact"; lstTypesOfImpact.DataTextField = "Name"; lstTypesOfImpact.DataValueField = "Id"; lstTypesOfImpact.DataBind(); } private void loadTypesOfDeadlines() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveTypesOfDeadlines"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"TypesOfDeadlines"); lstTypesOfDeadlines.DataSource = ds; lstTypesOfDeadlines.DataMember= "TypesOfDeadlines"; lstTypesOfDeadlines.DataTextField = "Name"; lstTypesOfDeadlines.DataValueField = "Id"; lstTypesOfDeadlines.DataBind(); }*/ protected void btnAction_Click(object sender, System.EventArgs e) { if (Session["btnAction"].ToString() == "Update") { SqlCommand cmd = new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_UpdateProfileSEProcs"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value= Int32.Parse(Id); cmd.Parameters.Add ("@ProcsId",SqlDbType.Int); cmd.Parameters["@ProcsId"].Value= lstProcs.SelectedItem.Value; /*cmd.Parameters.Add ("@LocsId",SqlDbType.Int); cmd.Parameters["@LocsId"].Value= lstLocs.SelectedItem.Value;*/ cmd.Parameters.Add ("@Name",SqlDbType.VarChar); cmd.Parameters["@Name"].Value= txtName.Text; /*cmd.Parameters.Add ("@TypesOfDeadlinesId",SqlDbType.Int); cmd.Parameters["@TypesOfDeadlinesId"].Value= lstTypesOfDeadlines.SelectedItem.Value; cmd.Parameters.Add ("@AcceptableSlip",SqlDbType.NVarChar); cmd.Parameters["@AcceptableSlip"].Value= txtAcceptableSlip.Text; cmd.Parameters.Add ("@TypesOfImpactId",SqlDbType.Int); cmd.Parameters["@TypesOfImpactId"].Value= lstTypesOfImpact.SelectedItem.Value; cmd.Parameters.Add ("@TypesOfImpactMagnitudeId",SqlDbType.Int); cmd.Parameters["@TypesOfImpactMagnitudeId"].Value= lstTypesOfImpactMagnitude.SelectedItem.Value; cmd.Parameters.Add ("@DollarCostSlip",SqlDbType.Int); cmd.Parameters.Add ("@RolesId",SqlDbType.Int); cmd.Parameters["@RolesId"].Value= lstRoles.SelectedItem.Value;*/ cmd.Parameters.Add ("@ProjectTypesId",SqlDbType.Int); cmd.Parameters["@ProjectTypesId"].Value= lstProjects.SelectedItem.Value; cmd.Parameters.Add ("@Timetables",SqlDbType.Int); if (cbxTTs.Checked) { cmd.Parameters["@Timetables"].Value= 1; } else { cmd.Parameters["@Timetables"].Value= 0; } cmd.Parameters.Add ("@Costs",SqlDbType.Int); if (cbxCosts.Checked) { cmd.Parameters["@Costs"].Value= 1; } else { cmd.Parameters["@Costs"].Value= 0; } /*if (txtDollarCostSlip.Text == "") { cmd.Parameters["@DollarCostSlip"].Value= 0; } else { cmd.Parameters["@DollarCostSlip"].Value= Int32.Parse(txtDollarCostSlip.Text); }*/ cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Done(); } else { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_AddProfileSEProcs"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@ProfileSEventsId",SqlDbType.Int); cmd.Parameters["@ProfileSEventsId"].Value= Session["ProfileSEventsId"].ToString(); cmd.Parameters.Add ("@ProcsId",SqlDbType.Int); cmd.Parameters["@ProcsId"].Value= lstProcs.SelectedItem.Value; /*cmd.Parameters.Add ("@LocsId",SqlDbType.Int); cmd.Parameters["@LocsId"].Value= lstLocs.SelectedItem.Value;*/ cmd.Parameters.Add ("@Name",SqlDbType.VarChar); if (txtName.Text == "") { cmd.Parameters["@Name"].Value=lstProcs.SelectedItem.Text; } else { cmd.Parameters["@Name"].Value= txtName.Text; } /*cmd.Parameters.Add ("@TypesOfDeadlinesId",SqlDbType.Int); cmd.Parameters["@TypesOfDeadlinesId"].Value= lstTypesOfDeadlines.SelectedItem.Value; cmd.Parameters.Add ("@AcceptableSlip",SqlDbType.NVarChar); cmd.Parameters["@AcceptableSlip"].Value= txtAcceptableSlip.Text; cmd.Parameters.Add ("@TypesOfImpactId",SqlDbType.Int); cmd.Parameters["@TypesOfImpactId"].Value= lstTypesOfImpact.SelectedItem.Value; cmd.Parameters.Add ("@TypesOfImpactMagnitudeId",SqlDbType.Int); cmd.Parameters["@TypesOfImpactMagnitudeId"].Value= lstTypesOfImpactMagnitude.SelectedItem.Value; cmd.Parameters.Add ("@RolesId",SqlDbType.Int); cmd.Parameters["@RolesId"].Value= lstRoles.SelectedItem.Value;*/ cmd.Parameters.Add ("@ProjectTypesId",SqlDbType.Int); cmd.Parameters["@ProjectTypesId"].Value= lstProjects.SelectedItem.Value; cmd.Parameters.Add ("@Timetables",SqlDbType.Int); if (cbxTTs.Checked) { cmd.Parameters["@Timetables"].Value= 1; } else { cmd.Parameters["@Timetables"].Value= 0; } cmd.Parameters.Add ("@Costs",SqlDbType.Int); if (cbxCosts.Checked) { cmd.Parameters["@Costs"].Value= 1; } else { cmd.Parameters["@Costs"].Value= 0; } /*cmd.Parameters.Add ("@DollarCostSlip",SqlDbType.Int); if (txtDollarCostSlip.Text == "") { cmd.Parameters["@DollarCostSlip"].Value= 0; } else { cmd.Parameters["@DollarCostSlip"].Value= Int32.Parse(txtDollarCostSlip.Text); }*/ cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Done(); } } private void Done() { Response.Redirect (strURL + Session["CUPSEP"].ToString() + ".aspx?"); } protected void btnCancel_Click(object sender, System.EventArgs e) { Done(); } protected void cbxTTs_CheckedChanged(object sender, System.EventArgs e) { cbxChanged(); } private void cbxChanged() { if ((cbxCosts.Checked)|| (cbxTTs.Checked) ) { lstProjects.Visible=true; lblProject.Visible=true; } else { lstProjects.Visible=false; lblProject.Visible=false; } } protected void cbxCosts_CheckedChanged(object sender, System.EventArgs e) { cbxChanged(); } protected void lstService_SelectedIndexChanged(object sender, System.EventArgs e) { loadProcs1(); lblAction.Text="Process List Changed to reflect service selected."; } private void loadProcs1() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveProcs"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); cmd.Parameters.Add ("@ServiceTypesId",SqlDbType.Int); cmd.Parameters["@ServiceTypesId"].Value=lstService.SelectedItem.Value; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Procs"); lstProcs.DataSource = ds; lstProcs.DataMember= "Procs"; lstProcs.DataTextField = "Name"; lstProcs.DataValueField = "Id"; lstProcs.DataBind(); } } }
// 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.Specialized.Tests { public static class StringCollectionTests { private const string ElementNotPresent = "element-not-present"; /// <summary> /// Data used for testing with Insert. /// </summary> /// Format is: /// 1. initial Collection /// 2. internal data /// 3. data to insert (ElementNotPresent or null) /// 4. location to insert (0, count / 2, count) /// <returns>Row of data</returns> public static IEnumerable<object[]> Insert_Data() { foreach (object[] data in StringCollection_Data().Concat(StringCollection_Duplicates_Data())) { string[] d = (string[])(data[1]); foreach (string element in new[] { ElementNotPresent, null }) { foreach (int location in new[] { 0, d.Length / 2, d.Length }.Distinct()) { StringCollection initial = new StringCollection(); initial.AddRange(d); yield return new object[] { initial, d, element, location }; } } } }/// <summary> /// Data used for testing with RemoveAt. /// </summary> /// Format is: /// 1. initial Collection /// 2. internal data /// 3. location to remove (0, count / 2, count) /// <returns>Row of data</returns> public static IEnumerable<object[]> RemoveAt_Data() { foreach (object[] data in StringCollection_Data().Concat(StringCollection_Duplicates_Data())) { string[] d = (string[])(data[1]); if (d.Length > 0) { foreach (int location in new[] { 0, d.Length / 2, d.Length - 1 }.Distinct()) { StringCollection initial = new StringCollection(); initial.AddRange(d); yield return new object[] { initial, d, location }; } } } } /// <summary> /// Data used for testing with a set of collections. /// </summary> /// Format is: /// 1. Collection /// 2. internal data /// <returns>Row of data</returns> public static IEnumerable<object[]> StringCollection_Data() { yield return ConstructRow(new string[] { /* empty */ }); yield return ConstructRow(new string[] { null }); yield return ConstructRow(new string[] { "single" }); yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x.ToString()).ToArray()); for (int index = 0; index < 100; index += 25) { yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x == index ? null : x.ToString()).ToArray()); } } /// <summary> /// Data used for testing with a set of collections, where the data has duplicates. /// </summary> /// Format is: /// 1. Collection /// 2. internal data /// <returns>Row of data</returns> public static IEnumerable<object[]> StringCollection_Duplicates_Data() { yield return ConstructRow(Enumerable.Range(0, 100).Select(x => (string)null).ToArray()); yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x % 10 == 0 ? null : (x % 10).ToString()).ToArray()); yield return ConstructRow(Enumerable.Range(0, 100).Select(x => (x % 10).ToString()).ToArray()); } private static object[] ConstructRow(string[] data) { if (data.Contains(ElementNotPresent)) throw new ArgumentException("Do not include \"" + ElementNotPresent + "\" in data."); StringCollection col = new StringCollection(); col.AddRange(data); return new object[] { col, data }; } [Fact] public static void Constructor_DefaultTest() { StringCollection sc = new StringCollection(); Assert.Equal(0, sc.Count); Assert.False(sc.Contains(null)); Assert.False(sc.Contains("")); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void AddTest(StringCollection collection, string[] data) { StringCollection added = new StringCollection(); for (int i = 0; i < data.Length; i++) { Assert.Equal(i, added.Count); Assert.Throws<ArgumentOutOfRangeException>(() => added[i]); added.Add(data[i]); Assert.Equal(data[i], added[i]); Assert.Equal(i + 1, added.Count); } Assert.Equal(collection, added); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Add_ExplicitInterface_Test(StringCollection collection, string[] data) { IList added = new StringCollection(); for (int i = 0; i < data.Length; i++) { Assert.Equal(i, added.Count); Assert.Throws<ArgumentOutOfRangeException>(() => added[i]); added.Add(data[i]); Assert.Equal(data[i], added[i]); Assert.Equal(i + 1, added.Count); } Assert.Equal(collection, added); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void AddRangeTest(StringCollection collection, string[] data) { StringCollection added = new StringCollection(); added.AddRange(data); Assert.Equal(collection, added); added.AddRange(new string[] { /*empty*/}); Assert.Equal(collection, added); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void AddRange_NullTest(StringCollection collection, string[] data) { AssertExtensions.Throws<ArgumentNullException>("value", () => collection.AddRange(null)); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void ClearTest(StringCollection collection, string[] data) { Assert.Equal(data.Length, collection.Count); collection.Clear(); Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void CopyToTest(StringCollection collection, string[] data) { string[] full = new string[data.Length]; collection.CopyTo(full, 0); Assert.Equal(data, full); string[] large = new string[data.Length * 2]; collection.CopyTo(large, data.Length / 4); for (int i = 0; i < large.Length; i++) { if (i < data.Length / 4 || i >= data.Length + data.Length / 4) { Assert.Null(large[i]); } else { Assert.Equal(data[i - data.Length / 4], large[i]); } } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void CopyTo_ExplicitInterface_Test(ICollection collection, string[] data) { string[] full = new string[data.Length]; collection.CopyTo(full, 0); Assert.Equal(data, full); string[] large = new string[data.Length * 2]; collection.CopyTo(large, data.Length / 4); for (int i = 0; i < large.Length; i++) { if (i < data.Length / 4 || i >= data.Length + data.Length / 4) { Assert.Null(large[i]); } else { Assert.Equal(data[i - data.Length / 4], large[i]); } } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void CopyTo_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(data, -1)); if (data.Length > 0) { Assert.Throws<ArgumentException>(() => collection.CopyTo(new string[0], data.Length - 1)); Assert.Throws<ArgumentException>(() => collection.CopyTo(new string[data.Length - 1], 0)); } // As explicit interface implementation Assert.Throws<ArgumentNullException>(() => ((ICollection)collection).CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ((ICollection)collection).CopyTo(data, -1)); if (data.Length > 0) { Assert.Throws<ArgumentException>(() => ((ICollection)collection).CopyTo(new string[0], data.Length - 1)); Assert.Throws<ArgumentException>(() => ((ICollection)collection).CopyTo(new string[data.Length - 1], 0)); } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void CountTest(StringCollection collection, string[] data) { Assert.Equal(data.Length, collection.Count); collection.Clear(); Assert.Equal(0, collection.Count); collection.Add("one"); Assert.Equal(1, collection.Count); collection.AddRange(data); Assert.Equal(1 + data.Length, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void ContainsTest(StringCollection collection, string[] data) { Assert.All(data, element => Assert.True(collection.Contains(element))); Assert.All(data, element => Assert.True(((IList)collection).Contains(element))); Assert.False(collection.Contains(ElementNotPresent)); Assert.False(((IList)collection).Contains(ElementNotPresent)); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetEnumeratorTest(StringCollection collection, string[] data) { bool repeat = true; StringEnumerator enumerator = collection.GetEnumerator(); Assert.NotNull(enumerator); while (repeat) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); foreach (string element in data) { Assert.True(enumerator.MoveNext()); Assert.Equal(element, enumerator.Current); Assert.Equal(element, enumerator.Current); } Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator.Reset(); enumerator.Reset(); repeat = false; } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetEnumerator_ModifiedCollectionTest(StringCollection collection, string[] data) { StringEnumerator enumerator = collection.GetEnumerator(); Assert.NotNull(enumerator); if (data.Length > 0) { Assert.True(enumerator.MoveNext()); string current = enumerator.Current; Assert.Equal(data[0], current); collection.RemoveAt(0); if (data.Length > 1 && data[0] != data[1]) { Assert.NotEqual(current, collection[0]); } Assert.Equal(current, enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); } else { collection.Add("newValue"); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetSetTest(StringCollection collection, string[] data) { for (int i = 0; i < data.Length; i++) { Assert.Equal(data[i], collection[i]); } for (int i = 0; i < data.Length / 2; i++) { string temp = collection[i]; collection[i] = collection[data.Length - i - 1]; collection[data.Length - i - 1] = temp; } for (int i = 0; i < data.Length; i++) { Assert.Equal(data[data.Length - i - 1], collection[i]); } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetSet_ExplicitInterface_Test(IList collection, string[] data) { for (int i = 0; i < data.Length; i++) { Assert.Equal(data[i], collection[i]); } for (int i = 0; i < data.Length / 2; i++) { object temp = collection[i]; if (temp != null) { Assert.IsType<string>(temp); } collection[i] = collection[data.Length - i - 1]; collection[data.Length - i - 1] = temp; } for (int i = 0; i < data.Length; i++) { Assert.Equal(data[data.Length - i - 1], collection[i]); } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetSet_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = null); Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length] = null); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length]); // As explicitly implementing the interface Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1] = null); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length] = null); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length]); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void IndexOfTest(StringCollection collection, string[] data) { Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), collection.IndexOf(element))); Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), ((IList)collection).IndexOf(element))); Assert.Equal(-1, collection.IndexOf(ElementNotPresent)); Assert.Equal(-1, ((IList)collection).IndexOf(ElementNotPresent)); } [Theory] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void IndexOf_DuplicateTest(StringCollection collection, string[] data) { // Only the index of the first element will be returned. data = data.Distinct().ToArray(); Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), collection.IndexOf(element))); Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), ((IList)collection).IndexOf(element))); Assert.Equal(-1, collection.IndexOf(ElementNotPresent)); Assert.Equal(-1, ((IList)collection).IndexOf(ElementNotPresent)); } [Theory] [MemberData(nameof(Insert_Data))] public static void InsertTest(StringCollection collection, string[] data, string element, int location) { collection.Insert(location, element); Assert.Equal(data.Length + 1, collection.Count); if (element == ElementNotPresent) { Assert.Equal(location, collection.IndexOf(ElementNotPresent)); } for (int i = 0; i < data.Length + 1; i++) { if (i < location) { Assert.Equal(data[i], collection[i]); } else if (i == location) { Assert.Equal(element, collection[i]); } else { Assert.Equal(data[i - 1], collection[i]); } } } [Theory] [MemberData(nameof(Insert_Data))] public static void Insert_ExplicitInterface_Test(IList collection, string[] data, string element, int location) { collection.Insert(location, element); Assert.Equal(data.Length + 1, collection.Count); if (element == ElementNotPresent) { Assert.Equal(location, collection.IndexOf(ElementNotPresent)); } for (int i = 0; i < data.Length + 1; i++) { if (i < location) { Assert.Equal(data[i], collection[i]); } else if (i == location) { Assert.Equal(element, collection[i]); } else { Assert.Equal(data[i - 1], collection[i]); } } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Insert_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, ElementNotPresent)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(data.Length + 1, ElementNotPresent)); // And as explicit interface implementation Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection).Insert(-1, ElementNotPresent)); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection).Insert(data.Length + 1, ElementNotPresent)); } [Fact] public static void IsFixedSizeTest() { Assert.False(((IList)new StringCollection()).IsFixedSize); } [Fact] public static void IsReadOnlyTest() { Assert.False(new StringCollection().IsReadOnly); Assert.False(((IList)new StringCollection()).IsReadOnly); } [Fact] public static void IsSynchronizedTest() { Assert.False(new StringCollection().IsSynchronized); Assert.False(((IList)new StringCollection()).IsSynchronized); } [Theory] [MemberData(nameof(StringCollection_Data))] public static void RemoveTest(StringCollection collection, string[] data) { Assert.All(data, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); collection.Remove(element); Assert.False(collection.Contains(element)); Assert.False(((IList)collection).Contains(element)); }); Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] public static void Remove_IListTest(StringCollection collection, string[] data) { Assert.All(data, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); Assert.False(collection.Contains(element)); Assert.False(((IList)collection).Contains(element)); }); Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Remove_NotPresentTest(StringCollection collection, string[] data) { collection.Remove(ElementNotPresent); Assert.Equal(data.Length, collection.Count); ((IList)collection).Remove(ElementNotPresent); Assert.Equal(data.Length, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Remove_DuplicateTest(StringCollection collection, string[] data) { // Only the first element will be removed. string[] first = data.Distinct().ToArray(); Assert.All(first, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); collection.Remove(element); Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); }); Assert.Equal(data.Length - first.Length, collection.Count); for (int i = first.Length; i < data.Length; i++) { string element = data[i]; Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); collection.Remove(element); bool stillPresent = i < data.Length - first.Length; Assert.Equal(stillPresent, collection.Contains(element)); Assert.Equal(stillPresent, ((IList)collection).Contains(element)); } Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(RemoveAt_Data))] public static void RemoveAtTest(StringCollection collection, string[] data, int location) { collection.RemoveAt(location); Assert.Equal(data.Length - 1, collection.Count); for (int i = 0; i < data.Length - 1; i++) { if (i < location) { Assert.Equal(data[i], collection[i]); } else if (i >= location) { Assert.Equal(data[i + 1], collection[i]); } } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void RemoveAt_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(data.Length)); } [Theory] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Remove_Duplicate_IListTest(StringCollection collection, string[] data) { // Only the first element will be removed. string[] first = data.Distinct().ToArray(); Assert.All(first, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); }); Assert.Equal(data.Length - first.Length, collection.Count); for (int i = first.Length; i < data.Length; i++) { string element = data[i]; Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); bool stillPresent = i < data.Length - first.Length; Assert.Equal(stillPresent, collection.Contains(element)); Assert.Equal(stillPresent, ((IList)collection).Contains(element)); } Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void SyncRootTest(StringCollection collection, string[] data) { object syncRoot = collection.SyncRoot; Assert.NotNull(syncRoot); Assert.IsType<object>(syncRoot); Assert.Same(syncRoot, collection.SyncRoot); Assert.NotSame(syncRoot, new StringCollection().SyncRoot); StringCollection other = new StringCollection(); other.AddRange(data); Assert.NotSame(syncRoot, other.SyncRoot); } } }
using UnityEngine; using System.Collections; public class GameController : MonoBehaviour { public int initialHealth = 100; public int maxBoost = 100; public GUIText scoreDescrLabel; public GUIText scoreLabel; public GUIText healthLabel; public GUIText healthDescrLabel; public GUIText boostLabel; public GUIText boostDescrLabel; public GUIText finalScoreLabel; public GUIText newHighScoreLabel; public GUIText highScoreLabel; public GameObject titleLabels; public GameObject gameoverLabels; public Camera minimapCamera; public AudioClip beginGameClip; public AudioClip gameoverClip; public bool isTitleShowing = true; public GameObject playerBody; /********* SHIPS *********/ public int maxNumberOfShips = 100; private int numberOfShips = 0; private int health; private int boost; private int score; private int highScore; private Vector3 originalMinimapPosition; private bool isDead = false; void Awake() { // We want the fastest possible framerate Application.targetFrameRate = -1; } // Use this for initialization void Start () { health = initialHealth; boost = maxBoost; score = 0; highScore = PlayerPrefs.GetInt("HighScore"); SetGameplayLabelsVisible(false); SetTitleLabelsVisible(true); SetGameoverLabelsVisible(false); // SetMusicPlaying(false); // Stop ships from generating GetComponent <ShipGenerator>().enabled = false; } void Update () { // If the player touches the screen, or presses the Start button (enter/return) if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) || Input.GetButtonDown("Start")){ if (isTitleShowing){ isTitleShowing = false; //Update the labels on screen SetTitleLabelsVisible(false); SetGameplayLabelsVisible(true); GetComponent <ShipGenerator>().enabled = true; if (beginGameClip != null){ AudioSource.PlayClipAtPoint(beginGameClip, Vector3.zero); } // SetMusicPlaying(true); } else if (isPlayerDead()){ Application.LoadLevel("DefaultScene"); } } if (isPlayerDead() && !AreGameOverLabelsVisible()){ SetGameplayLabelsVisible(false); SetGameoverLabelsVisible(true); // SetMusicPlaying(false); finalScoreLabel.text = "Your Score: " + score; // Set the highscore if (score > highScore) { highScore = score; PlayerPrefs.SetInt("HighScore", highScore); newHighScoreLabel.text = "New High Score!"; } else { newHighScoreLabel.text = ""; } } else if (!isPlayerDead()){ Vector2 temp = transform.position; transform.position = new Vector2(playerBody.transform.position.x, temp.y); } } public bool isPlayerDead() { return isDead; } // ***************** SHIPS ***************** // public bool CanGenerateShip(){ return (numberOfShips < maxNumberOfShips); } public void ShipCreated(){ numberOfShips++; } public void ShipDestroyed(){ numberOfShips--; } public int getNumberOfTotalShips(){ return numberOfShips; } // ***************** PLAYER ***************** // public void RemoveHealth(int healthToRemove){ health -= healthToRemove; if (health <= 0){ health = 0; isDead = true; if (gameoverClip){ AudioSource.PlayClipAtPoint(gameoverClip, Camera.main.transform.position); } } UpdateHealth(); } public void AddToBoost (int boostToAdd) { boost += boostToAdd; UpdateBoost(); } public void RemoveFromBoost(int boostToRemove) { boost -= boostToRemove; if (boost < 0){ boost = 0; } UpdateBoost(); } public void AddScore(int scoreToAdd){ score += scoreToAdd; UpdateScore(); } public int GetScore() { return score; } public int GetHealth() { return health; } public int GetBoost() { return boost; } void UpdateScore () { scoreLabel.text = "" + score; } void UpdateHealth () { healthLabel.text = health + "%"; } void UpdateBoost () { boostLabel.text = boost + "%"; } void SetGameplayLabelsVisible(bool areVisible){ scoreLabel.enabled = areVisible; scoreDescrLabel.enabled = areVisible; healthLabel.enabled = areVisible; healthDescrLabel.enabled = areVisible; boostLabel.enabled = areVisible; boostDescrLabel.enabled = areVisible; SetMinimapVisible(areVisible); } void SetTitleLabelsVisible (bool areVisible){ if (areVisible){ titleLabels.transform.position = new Vector3(0.05f, 0.1f); // If we've got a high score, display it if (highScore != 0){ highScoreLabel.text = "High Score: " + highScore; } else { highScoreLabel.text = ""; } } else { titleLabels.transform.position = new Vector3(-1.0f, -1.0f); } } void SetGameoverLabelsVisible (bool areVisible){ if (areVisible){ gameoverLabels.transform.position = new Vector3(0.05f, 0.1f); } else { gameoverLabels.transform.position = new Vector3(-1.0f, -1.0f); } } bool AreGameOverLabelsVisible () { if (gameoverLabels.transform.position == new Vector3(0.05f, 0.1f)){ return true; } else { return false; } } void SetMinimapVisible (bool areVisible) { minimapCamera.enabled = areVisible; } void SetMusicPlaying(bool shouldPlay){ // if (shouldPlay){ // audio.Play(); // } // else { // audio.Stop(); // } } public bool isRunningInEditor() { if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.WindowsEditor){ return true; } return false; } public static GameController sharedGameController(){ GameObject gameControllerObject = GameObject.FindWithTag ("GameController"); GameController gameController = gameControllerObject.GetComponent <GameController>(); return gameController; } }
using System; using System.IO; using ServiceStack.Service; using ServiceStack.ServiceClient.Web; using ServiceStack.ServiceHost; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints.Support.Mocks; using ServiceStack.WebHost.Endpoints.Tests.Mocks; namespace ServiceStack.WebHost.Endpoints.Tests.Support { public class DirectServiceClient : IServiceClient, IRestClient { ServiceManager ServiceManager { get; set; } readonly HttpRequestMock httpReq = new HttpRequestMock(); readonly HttpResponseMock httpRes = new HttpResponseMock(); public DirectServiceClient(ServiceManager serviceManager) { this.ServiceManager = serviceManager; } public void SendOneWay(object request) { ServiceManager.Execute(request); } public void SendOneWay(string relativeOrAbsoluteUrl, object request) { ServiceManager.Execute(request); } private bool ApplyRequestFilters<TResponse>(object request) { if (EndpointHost.ApplyRequestFilters(httpReq, httpRes, request)) { ThrowIfError<TResponse>(httpRes); return true; } return false; } private void ThrowIfError<TResponse>(HttpResponseMock httpRes) { if (httpRes.StatusCode >= 400) { var webEx = new WebServiceException("WebServiceException, StatusCode: " + httpRes.StatusCode) { StatusCode = httpRes.StatusCode, StatusDescription = httpRes.StatusDescription, }; try { var deserializer = EndpointHost.AppHost.ContentTypeFilters.GetStreamDeserializer(httpReq.ResponseContentType); webEx.ResponseDto = deserializer(typeof(TResponse), httpRes.OutputStream); } catch (Exception ex) { Console.WriteLine(ex); } throw webEx; } } private bool ApplyResponseFilters<TResponse>(object response) { if (EndpointHost.ApplyResponseFilters(httpReq, httpRes, response)) { ThrowIfError<TResponse>(httpRes); return true; } return false; } public TResponse Send<TResponse>(object request) { httpReq.HttpMethod = HttpMethod.Post; if (ApplyRequestFilters<TResponse>(request)) return default(TResponse); var response = ServiceManager.ServiceController.Execute(request, new HttpRequestContext(httpReq, httpRes, request, EndpointAttributes.HttpPost)); if (ApplyResponseFilters<TResponse>(response)) return (TResponse)response; return (TResponse)response; } public TResponse Get<TResponse>(string relativeOrAbsoluteUrl) { httpReq.HttpMethod = HttpMethod.Get; var requestTypeName = typeof(TResponse).Namespace + "." + relativeOrAbsoluteUrl; var requestType = typeof (TResponse).Assembly.GetType(requestTypeName); if (requestType == null) throw new ArgumentException("Type not found: " + requestTypeName); var request = requestType.CreateInstance(); if (ApplyRequestFilters<TResponse>(request)) return default(TResponse); var response = ServiceManager.ServiceController.Execute(request, new HttpRequestContext(httpReq, httpRes, request, EndpointAttributes.HttpGet)); if (ApplyResponseFilters<TResponse>(response)) return (TResponse)response; return (TResponse)response; } public TResponse Delete<TResponse>(string relativeOrAbsoluteUrl) { throw new NotImplementedException(); } public TResponse Post<TResponse>(string relativeOrAbsoluteUrl, object request) { throw new NotImplementedException(); } public TResponse Put<TResponse>(string relativeOrAbsoluteUrl, object request) { throw new NotImplementedException(); } public TResponse Patch<TResponse>(string relativeOrAbsoluteUrl, object request) { throw new NotImplementedException(); } public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, string mimeType) { throw new NotImplementedException(); } public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileInfo, string mimeType) { throw new NotImplementedException(); } public void SendAsync<TResponse>(object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { var response = default(TResponse); try { try { if (ApplyRequestFilters<TResponse>(request)) { onSuccess(default(TResponse)); return; } } catch (Exception ex) { onError(default(TResponse), ex); return; } response = this.Send<TResponse>(request); try { if (ApplyResponseFilters<TResponse>(request)) { onSuccess(response); return; } } catch (Exception ex) { onError(response, ex); return; } onSuccess(response); } catch (Exception ex) { if (onError != null) { onError(response, ex); return; } Console.WriteLine("Error: " + ex.Message); } } public void SetCredentials(string userName, string password) { throw new NotImplementedException(); } public void GetAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } public void Dispose() { } public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, object request) { throw new NotImplementedException(); } public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, object request) { throw new NotImplementedException(); } } }
// Sharp Essentials // Copyright 2017 Matthew Hamilton - matthamilton@live.com // // 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.Threading.Tasks; namespace SharpEssentials.Concurrency { /// <summary> /// Provides extension methods for the Task type. /// </summary> public static class TaskExtensions { /// <summary> /// Schedules a task to be executed after completion of this task while propagating /// its result, error, or cancellation states. /// </summary> /// <typeparam name="T1">The result type of this Task</typeparam> /// <typeparam name="T2">The result type of the second Task</typeparam> /// <param name="first">The Task to execute first</param> /// <param name="next">The Task to execute after completion of the first</param> /// <returns>A Task representing completion of both Tasks</returns> public static Task<T2> Then<T1, T2>(this Task<T1> first, Func<T1, Task<T2>> next) { if (first == null) throw new ArgumentNullException(nameof(first)); if (next == null) throw new ArgumentNullException(nameof(next)); var tcs = new TaskCompletionSource<T2>(); first.ContinueWith(delegate { if (first.IsFaulted) { tcs.TrySetException(first.Exception.InnerExceptions); } else if (first.IsCanceled) { tcs.TrySetCanceled(); } else { try { var nextTask = next(first.Result); if (nextTask == null) { tcs.TrySetCanceled(); } else nextTask.ContinueWith(delegate { tcs.TrySetFromTask(nextTask); }, TaskContinuationOptions.ExecuteSynchronously); } catch (Exception e) { tcs.TrySetException(e); } } }, TaskContinuationOptions.ExecuteSynchronously); return tcs.Task; } /// <summary> /// Schedules a task to be executed after completion of this task while propagating /// its error or cancellation states. /// </summary> /// <typeparam name="T2">The result type of the second Task</typeparam> /// <param name="first">The Task to execute first</param> /// <param name="next">The Task to execute after completion of the first</param> /// <returns>A Task representing completion of both Tasks</returns> public static Task<T2> Then<T2>(this Task first, Func<Task<T2>> next) { if (first == null) throw new ArgumentNullException(nameof(first)); if (next == null) throw new ArgumentNullException(nameof(next)); var tcs = new TaskCompletionSource<T2>(); first.ContinueWith(delegate { if (first.IsFaulted) { tcs.TrySetException(first.Exception.InnerExceptions); } else if (first.IsCanceled) { tcs.TrySetCanceled(); } else { try { var nextTask = next(); if (nextTask == null) { tcs.TrySetCanceled(); } else nextTask.ContinueWith(delegate { tcs.TrySetFromTask(nextTask); }, TaskContinuationOptions.ExecuteSynchronously); } catch (Exception e) { tcs.TrySetException(e); } } }, TaskContinuationOptions.ExecuteSynchronously); return tcs.Task; } /// <summary> /// Schedules a task to be executed after completion of this task while propagating /// its error or cancellation states. /// </summary> /// <param name="first">The Task to execute first</param> /// <param name="next">The Task to execute after completion of the first</param> /// <returns>A Task representing completion of both Tasks</returns> public static Task Then(this Task first, Func<Task> next) { if (first == null) throw new ArgumentNullException(nameof(first)); if (next == null) throw new ArgumentNullException(nameof(next)); var tcs = new TaskCompletionSource<object>(); first.ContinueWith(delegate { if (first.IsFaulted) { tcs.TrySetException(first.Exception.InnerExceptions); } else if (first.IsCanceled) { tcs.TrySetCanceled(); } else { try { var nextTask = next(); if (nextTask == null) { tcs.TrySetCanceled(); } else nextTask.ContinueWith(delegate { tcs.TrySetFromTask(nextTask); }, TaskContinuationOptions.ExecuteSynchronously); } catch (Exception e) { tcs.TrySetException(e); } } }, TaskContinuationOptions.ExecuteSynchronously); return tcs.Task; } /// <summary> /// Schedules a continuation to be executed after completion of this task while propagating /// its result, error, or cancellation states. /// </summary> /// <typeparam name="T1">The result type of this Task</typeparam> /// <typeparam name="T2">The result type of the second Task</typeparam> /// <param name="first">The Task to execute first</param> /// <param name="continuation">A function to execute after completion of the first Task</param> /// <returns>A Task representing completion of both Tasks</returns> public static Task<T2> Then<T1, T2>(this Task<T1> first, Func<T1, T2> continuation) { if (first == null) throw new ArgumentNullException(nameof(first)); if (continuation == null) throw new ArgumentNullException(nameof(continuation)); var tcs = new TaskCompletionSource<T2>(); first.ContinueWith(delegate { if (first.IsFaulted) { tcs.TrySetException(first.Exception.InnerExceptions); } else if (first.IsCanceled) { tcs.TrySetCanceled(); } else { try { var finalResult = continuation(first.Result); tcs.TrySetResult(finalResult); } catch (Exception e) { tcs.TrySetException(e); } } }, TaskContinuationOptions.ExecuteSynchronously); return tcs.Task; } /// <summary> /// Schedules a continuation to be executed after completion of this task while propagating /// its result, error, or cancellation states. /// </summary> /// <param name="first">The Task to execute first</param> /// <param name="continuation">A function to execute after completion of the first Task</param> /// <returns>A Task representing completion of both operations</returns> public static Task Then(this Task first, Action continuation) { if (first == null) throw new ArgumentNullException(nameof(first)); if (continuation == null) throw new ArgumentNullException(nameof(continuation)); var tcs = new TaskCompletionSource<object>(); first.ContinueWith(delegate { if (first.IsFaulted) { tcs.TrySetException(first.Exception.InnerExceptions); } else if (first.IsCanceled) { tcs.TrySetCanceled(); } else { try { continuation(); tcs.TrySetResult(null); } catch (Exception e) { tcs.TrySetException(e); } } }, TaskContinuationOptions.ExecuteSynchronously); return tcs.Task; } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; using Adxstudio.Xrm.Resources; using Adxstudio.Xrm.Web.UI.WebControls; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Configuration; using Microsoft.Xrm.Client.Messages; using Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Metadata; using Microsoft.Xrm.Sdk.Query; using Adxstudio.Xrm.Services.Query; using Adxstudio.Xrm.Security; using Adxstudio.Xrm.ContentAccess; namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView { /// <summary> /// Template used when rendering a Lookup field. /// </summary> public class LookupControlTemplate : CellTemplate, ICustomFieldControlTemplate { /// <summary> /// LookupControlTemplate class initialization. /// </summary> /// <param name="field"></param> /// <param name="metadata"></param> /// <param name="validationGroup"></param> /// <param name="bindings"></param> /// <remarks>Localization of lookup display text is provided by retrieving the entity metadata and determine the primary name field and if the language code is not the base language for the organization it appends _ + language code to the primary name field and populates the control with the values from the localized attribute. i.e. if the primary name field is new_name and the language code is 1036 for French, the localized attribute name would be new_name_1036. An attribute would be added to the entity in this manner for each language to be supported and the attribute must be added to the view assigned to the lookup on the form.</remarks> public LookupControlTemplate(CrmEntityFormViewField field, FormXmlCellMetadata metadata, string validationGroup, IDictionary<string, CellBinding> bindings) : base(metadata, validationGroup, bindings) { Field = field; } /// <summary> /// Form field. /// </summary> public CrmEntityFormViewField Field { get; private set; } public override string CssClass { get { return "lookup form-control"; } } private string ValidationText { get { return Metadata.ValidationText; } } private ValidatorDisplay ValidatorDisplay { get { return string.IsNullOrWhiteSpace(ValidationText) ? ValidatorDisplay.None : ValidatorDisplay.Dynamic; } } protected override void InstantiateControlIn(Control container) { var dropDown = new DropDownList { ID = ControlID, CssClass = string.Join(" ", CssClass, Metadata.CssClass), ToolTip = Metadata.ToolTip }; dropDown.Attributes.Add("onchange", "setIsDirty(this.id);"); container.Controls.Add(dropDown); var lookupEntityName = Metadata.LookupTargets[0]; if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired) { dropDown.Attributes.Add("required", string.Empty); } if (Metadata.ReadOnly || ((WebControls.CrmEntityFormView)container.BindingContainer).Mode == FormViewMode.ReadOnly) { AddSpecialBindingAndHiddenFieldsToPersistDisabledSelect(container, lookupEntityName, dropDown); } else { PopulateDropDownIfFirstLoad(dropDown, lookupEntityName); Bindings[Metadata.DataFieldName] = new CellBinding { Get = () => { Guid id; return !Guid.TryParse(dropDown.SelectedValue, out id) ? null : new EntityReference(lookupEntityName, id); }, Set = obj => { var entityReference = (EntityReference)obj; dropDown.SelectedValue = entityReference.Id.ToString(); } }; } } protected override void InstantiateValidatorsIn(Control container) { if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired) { container.Controls.Add(new RequiredFieldValidator { ID = string.Format("RequiredFieldValidator{0}", ControlID), ControlToValidate = ControlID, ValidationGroup = ValidationGroup, Display = ValidatorDisplay, ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.RequiredFieldValidationErrorMessage) ? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("required")) ? ResourceManager.GetString("Required_Field_Error").FormatWith(Metadata.Label) : Metadata.Messages["required"].FormatWith(Metadata.Label) : Metadata.RequiredFieldValidationErrorMessage)), Text = Metadata.ValidationText, }); } this.InstantiateCustomValidatorsIn(container); } private void AddSpecialBindingAndHiddenFieldsToPersistDisabledSelect(Control container, string lookupEntityName, DropDownList dropDown) { dropDown.CssClass = "{0} readonly".FormatWith(CssClass); dropDown.Attributes["disabled"] = "disabled"; dropDown.Attributes["aria-disabled"] = "true"; var hiddenValue = new HiddenField { ID = "{0}_Value".FormatWith(ControlID) }; container.Controls.Add(hiddenValue); var hiddenSelectedIndex = new HiddenField { ID = "{0}_SelectedIndex".FormatWith(ControlID) }; container.Controls.Add(hiddenSelectedIndex); RegisterClientSideDependencies(container); Bindings[Metadata.DataFieldName] = new CellBinding { Get = () => { Guid id; return !Guid.TryParse(hiddenValue.Value, out id) ? null : new EntityReference(lookupEntityName, id); }, Set = obj => { var entityReference = (EntityReference)obj; dropDown.Items.Add(new ListItem { Value = entityReference.Id.ToString(), Text = entityReference.Name ?? string.Empty }); dropDown.SelectedValue = "{0}".FormatWith(entityReference.Id); hiddenValue.Value = dropDown.SelectedValue; hiddenSelectedIndex.Value = dropDown.SelectedIndex.ToString(CultureInfo.InvariantCulture); } }; } private static EntityMetadata GetEntityMetadata(OrganizationServiceContext context, string logicalName, IDictionary<string, EntityMetadata> metadataCache) { EntityMetadata cachedMetadata; if (metadataCache.TryGetValue(logicalName, out cachedMetadata)) { return cachedMetadata; } var metadataReponse = context.Execute(new RetrieveEntityRequest { LogicalName = logicalName, EntityFilters = EntityFilters.Attributes }) as RetrieveEntityResponse; if (metadataReponse != null && metadataReponse.EntityMetadata != null) { metadataCache[logicalName] = metadataReponse.EntityMetadata; return metadataReponse.EntityMetadata; } throw new InvalidOperationException("Unable to retrieve the metadata for entity name {0}.".FormatWith(logicalName)); } private void PopulateDropDownIfFirstLoad(DropDownList dropDown, string lookupEntityName) { if (dropDown.Items.Count > 0) { return; } var empty = new ListItem(string.Empty, string.Empty); empty.Attributes["label"] = " "; dropDown.Items.Add(empty); var context = CrmConfigurationManager.CreateContext(); var service = CrmConfigurationManager.CreateService(); var metadataCache = new Dictionary<string, EntityMetadata>(); var entityMetadata = GetEntityMetadata(context, Metadata.LookupTargets[0], metadataCache); var primaryNameAttribute = entityMetadata.PrimaryNameAttribute; var primaryKeyAttribute = entityMetadata.PrimaryIdAttribute; var localizedPrimaryNameAttribute = primaryNameAttribute; // get a localized primary attribute name if (Metadata.LanguageCode > 0) { var defaultLanguageCode = RetrieveOrganizationBaseLanguageCode(context); if (Metadata.LanguageCode != defaultLanguageCode) { localizedPrimaryNameAttribute = string.Format("{0}_{1}", primaryNameAttribute, Metadata.LanguageCode); foreach (var att in entityMetadata.Attributes.Where(att => att.LogicalName.EndsWith(localizedPrimaryNameAttribute))) { primaryNameAttribute = att.LogicalName; break; } } } // By default a lookup field cell defined in the form XML does not contain view parameters unless the user has specified a view that is not the default for that entity and we must query to find the default view. Saved Query entity's QueryType code 64 indicates a lookup view. var view = Metadata.LookupViewID == Guid.Empty ? context.CreateQuery("savedquery").FirstOrDefault(s => s.GetAttributeValue<string>("returnedtypecode") == lookupEntityName && s.GetAttributeValue<bool>("isdefault") && s.GetAttributeValue<int>("querytype") == 64) : context.CreateQuery("savedquery").FirstOrDefault(s => s.GetAttributeValue<Guid>("savedqueryid") == Metadata.LookupViewID); IQueryable<Entity> lookupEntities; if (view != null) { var fetchXml = view.GetAttributeValue<string>("fetchxml"); lookupEntities = GetLookupRecords(fetchXml, context); if (lookupEntities == null) return; } else { string fetchXml = string.Format(@" <fetch mapping='logical'> <entity name='{0}'> <attribute name='{1}'/> <attrbiute name='{2}'/> </entity> </fetch> ", lookupEntityName, primaryKeyAttribute, primaryNameAttribute); lookupEntities = GetLookupRecords(fetchXml, context); if (lookupEntities == null) return; } foreach (var entity in lookupEntities) { dropDown.Items.Add(new ListItem { Value = entity.Id.ToString(), Text = entity.Attributes.ContainsKey(localizedPrimaryNameAttribute) ? entity.GetAttributeValue(localizedPrimaryNameAttribute).ToString() : entity.Attributes.ContainsKey(primaryNameAttribute) ? entity.GetAttributeValue(primaryNameAttribute).ToString() : string.Empty }); } } private IQueryable<Entity> GetLookupRecords(string fetchXml, OrganizationServiceContext context) { var fetch = Fetch.Parse(fetchXml); var crmEntityPermissionProvider = new CrmEntityPermissionProvider(); crmEntityPermissionProvider.TryApplyRecordLevelFiltersToFetch(context, CrmEntityPermissionRight.Read, fetch); crmEntityPermissionProvider.TryApplyRecordLevelFiltersToFetch(context, CrmEntityPermissionRight.Append, fetch); // Apply Content Access Level filtering var contentAccessLevelProvider = new ContentAccessLevelProvider(); contentAccessLevelProvider.TryApplyRecordLevelFiltersToFetch(CrmEntityPermissionRight.Read, fetch); // Apply Product filtering var productAccessProvider = new ProductAccessProvider(); productAccessProvider.TryApplyRecordLevelFiltersToFetch(CrmEntityPermissionRight.Read, fetch); var response = (RetrieveMultipleResponse)context.Execute(fetch.ToRetrieveMultipleRequest()); var data = response.EntityCollection; if (data == null || data.Entities == null) return null; return data.Entities.AsQueryable(); } private static int RetrieveOrganizationBaseLanguageCode(OrganizationServiceContext context) { if (context == null) { throw new ArgumentNullException("context"); } var organizationEntityQuery = new QueryExpression("organization"); organizationEntityQuery.ColumnSet.AddColumn("languagecode"); var organizationEntities = context.RetrieveMultiple(organizationEntityQuery); if (organizationEntities == null) { throw new ApplicationException("Failed to retrieve organization entity collection."); } return (int)organizationEntities[0].Attributes["languagecode"]; } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Threading.Tasks; using Newtonsoft.Json; namespace CloudStack.Net { public class UserVmResponse { /// <summary> /// the ID of the virtual machine /// </summary> public string Id { get; set; } /// <summary> /// the account associated with the virtual machine /// </summary> public string Account { get; set; } /// <summary> /// the number of cpu this virtual machine is running with /// </summary> public int? CpuNumber { get; set; } /// <summary> /// the speed of each cpu /// </summary> public int? CpuSpeed { get; set; } /// <summary> /// the amount of the vm's CPU currently used /// </summary> public string CpuUsed { get; set; } /// <summary> /// the date when this virtual machine was created /// </summary> public DateTime Created { get; set; } /// <summary> /// Vm details in key/value pairs. /// </summary> public IDictionary<string, string> Details { get; set; } /// <summary> /// the read (io) of disk on the vm /// </summary> public long DiskIORead { get; set; } /// <summary> /// the write (io) of disk on the vm /// </summary> public long DiskIOWrite { get; set; } /// <summary> /// the read (bytes) of disk on the vm /// </summary> public long DiskKbsRead { get; set; } /// <summary> /// the write (bytes) of disk on the vm /// </summary> public long DiskKbsWrite { get; set; } /// <summary> /// the ID of the disk offering of the virtual machine /// </summary> public string DiskOfferingId { get; set; } /// <summary> /// the name of the disk offering of the virtual machine /// </summary> public string DiskOfferingName { get; set; } /// <summary> /// user generated name. The name of the virtual machine is returned if no displayname exists. /// </summary> public string DisplayName { get; set; } /// <summary> /// an optional field whether to the display the vm to the end user or not. /// </summary> public bool DisplayVm { get; set; } /// <summary> /// the name of the domain in which the virtual machine exists /// </summary> public string Domain { get; set; } /// <summary> /// the ID of the domain in which the virtual machine exists /// </summary> public string DomainId { get; set; } /// <summary> /// the virtual network for the service offering /// </summary> public bool ForVirtualNetwork { get; set; } /// <summary> /// the group name of the virtual machine /// </summary> public string Group { get; set; } /// <summary> /// the group ID of the virtual machine /// </summary> public string GroupId { get; set; } /// <summary> /// Os type ID of the virtual machine /// </summary> public string GuestOsId { get; set; } /// <summary> /// true if high-availability is enabled, false otherwise /// </summary> public bool HaEnable { get; set; } /// <summary> /// the ID of the host for the virtual machine /// </summary> public string HostId { get; set; } /// <summary> /// the name of the host for the virtual machine /// </summary> public string HostName { get; set; } /// <summary> /// the hypervisor on which the template runs /// </summary> public string Hypervisor { get; set; } /// <summary> /// instance name of the user vm; this parameter is returned to the ROOT admin only /// </summary> public string InstanceName { get; set; } /// <summary> /// true if vm contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory. /// </summary> public bool IsDynamicallyScalable { get; set; } /// <summary> /// an alternate display text of the ISO attached to the virtual machine /// </summary> public string IsoDisplayText { get; set; } /// <summary> /// the ID of the ISO attached to the virtual machine /// </summary> public string IsoId { get; set; } /// <summary> /// the name of the ISO attached to the virtual machine /// </summary> public string IsoName { get; set; } /// <summary> /// ssh key-pair /// </summary> public string Keypair { get; set; } /// <summary> /// the memory allocated for the virtual machine /// </summary> public int? Memory { get; set; } /// <summary> /// the name of the virtual machine /// </summary> public string Name { get; set; } /// <summary> /// the incoming network traffic on the vm /// </summary> public long NetworkKbsRead { get; set; } /// <summary> /// the outgoing network traffic on the host /// </summary> public long NetworkKbsWrite { get; set; } /// <summary> /// OS type id of the vm /// </summary> public long OsTypeId { get; set; } /// <summary> /// the password (if exists) of the virtual machine /// </summary> public string Password { get; set; } /// <summary> /// true if the password rest feature is enabled, false otherwise /// </summary> public bool PasswordEnabled { get; set; } /// <summary> /// the project name of the vm /// </summary> public string Project { get; set; } /// <summary> /// the project id of the vm /// </summary> public string ProjectId { get; set; } /// <summary> /// public IP address id associated with vm via Static nat rule /// </summary> public string PublicIp { get; set; } /// <summary> /// public IP address id associated with vm via Static nat rule /// </summary> public string PublicIpId { get; set; } /// <summary> /// device ID of the root volume /// </summary> public long RootDeviceId { get; set; } /// <summary> /// device type of the root volume /// </summary> public string RootDeviceType { get; set; } /// <summary> /// the ID of the service offering of the virtual machine /// </summary> public string ServiceOfferingId { get; set; } /// <summary> /// the name of the service offering of the virtual machine /// </summary> public string ServiceOfferingName { get; set; } /// <summary> /// State of the Service from LB rule /// </summary> public string ServiceState { get; set; } /// <summary> /// the state of the virtual machine /// </summary> public string State { get; set; } /// <summary> /// an alternate display text of the template for the virtual machine /// </summary> public string TemplateDisplayText { get; set; } /// <summary> /// the ID of the template for the virtual machine. A -1 is returned if the virtual machine was created from an ISO file. /// </summary> public string TemplateId { get; set; } /// <summary> /// the name of the template for the virtual machine /// </summary> public string TemplateName { get; set; } /// <summary> /// the user's ID who deployed the virtual machine /// </summary> public string UserId { get; set; } /// <summary> /// the user's name who deployed the virtual machine /// </summary> public string UserName { get; set; } /// <summary> /// the vgpu type used by the virtual machine /// </summary> public string Vgpu { get; set; } /// <summary> /// the ID of the availablility zone for the virtual machine /// </summary> public string ZoneId { get; set; } /// <summary> /// the name of the availability zone for the virtual machine /// </summary> public string ZoneName { get; set; } /// <summary> /// list of affinity groups associated with the virtual machine /// </summary> public IList<AffinityGroupResponse> Affinitygroup { get; set; } /// <summary> /// the list of nics associated with vm /// </summary> public IList<NicResponse> Nic { get; set; } /// <summary> /// list of security groups associated with the virtual machine /// </summary> public IList<SecurityGroupResponse> Securitygroup { get; set; } /// <summary> /// the list of resource tags associated with vm /// </summary> public IList<ResourceTagResponse> Tags { get; set; } public override string ToString() => JsonConvert.SerializeObject(this, Formatting.Indented); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime; using System.Threading.Tasks; namespace System.ServiceModel.Channels { internal abstract class LayeredChannelFactory<TChannel> : ChannelFactoryBase<TChannel> { public LayeredChannelFactory(IDefaultCommunicationTimeouts timeouts, IChannelFactory innerChannelFactory) : base(timeouts) { InnerChannelFactory = innerChannelFactory; } protected IChannelFactory InnerChannelFactory { get; } public override T GetProperty<T>() { if (typeof(T) == typeof(IChannelFactory<TChannel>)) { return (T)(object)this; } T baseProperty = base.GetProperty<T>(); if (baseProperty != null) { return baseProperty; } return InnerChannelFactory.GetProperty<T>(); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return InnerChannelFactory.BeginOpen(timeout, callback, state); } protected override void OnEndOpen(IAsyncResult result) { InnerChannelFactory.EndOpen(result); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedCloseAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose, InnerChannelFactory); } protected override void OnEndClose(IAsyncResult result) { ChainedCloseAsyncResult.End(result); } protected internal override async Task OnCloseAsync(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); await base.OnCloseAsync(timeoutHelper.RemainingTime()); await InnerChannelFactory.CloseHelperAsync(timeoutHelper.RemainingTime()); } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.OnClose(timeoutHelper.RemainingTime()); InnerChannelFactory.Close(timeoutHelper.RemainingTime()); } protected internal override Task OnOpenAsync(TimeSpan timeout) { return InnerChannelFactory.OpenHelperAsync(timeout); } protected override void OnOpen(TimeSpan timeout) { InnerChannelFactory.Open(timeout); } protected override void OnAbort() { base.OnAbort(); InnerChannelFactory.Abort(); } } internal class LayeredInputChannel : LayeredChannel<IInputChannel>, IAsyncInputChannel { public LayeredInputChannel(ChannelManagerBase channelManager, IInputChannel innerChannel) : base(channelManager, innerChannel) { } public virtual EndpointAddress LocalAddress { get { return InnerChannel.LocalAddress; } } private Task InternalOnReceiveAsync(Message message) { if (message != null) { return OnReceiveAsync(message); } return Task.CompletedTask; } protected virtual Task OnReceiveAsync(Message message) { return Task.CompletedTask; } public Message Receive() { return ReceiveAsync().GetAwaiter().GetResult(); } public async Task<Message> ReceiveAsync(TimeSpan timeout) { Message message; if (InnerChannel is IAsyncInputChannel asyncInputChannel) { message = await asyncInputChannel.ReceiveAsync(timeout); } else { message = await Task.Factory.FromAsync(InnerChannel.BeginReceive, InnerChannel.EndReceive, timeout, null); } await InternalOnReceiveAsync(message); return message; } public async Task<Message> ReceiveAsync() { Message message; if (InnerChannel is IAsyncInputChannel asyncInputChannel) { message = await asyncInputChannel.ReceiveAsync(); } else { message = await Task.Factory.FromAsync(InnerChannel.BeginReceive, InnerChannel.EndReceive, null); } await InternalOnReceiveAsync(message); return message; } public Message Receive(TimeSpan timeout) { return ReceiveAsync(timeout).GetAwaiter().GetResult(); } public IAsyncResult BeginReceive(AsyncCallback callback, object state) { return ReceiveAsync().ToApm(callback, state); } public IAsyncResult BeginReceive(TimeSpan timeout, AsyncCallback callback, object state) { return ReceiveAsync(timeout).ToApm(callback, state); } public Message EndReceive(IAsyncResult result) { return result.ToApmEnd<Message>(); } public IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback, object state) { return TryReceiveAsync(timeout).ToApm(callback, state); } public bool EndTryReceive(IAsyncResult result, out Message message) { bool retVal; (retVal, message) = result.ToApmEnd<(bool, Message)>(); return retVal; } public async Task<(bool, Message)> TryReceiveAsync(TimeSpan timeout) { bool retVal; Message message; if (InnerChannel is IAsyncInputChannel asyncInputChannel) { (retVal, message) = await asyncInputChannel.TryReceiveAsync(timeout); } else { (retVal, message) = await TaskHelpers.FromAsync<TimeSpan, bool, Message>(InnerChannel.BeginTryReceive, InnerChannel.EndTryReceive, timeout, null); } await InternalOnReceiveAsync(message); return (retVal, message); } public bool TryReceive(TimeSpan timeout, out Message message) { bool retVal; (retVal, message) = TryReceiveAsync(timeout).GetAwaiter().GetResult(); return retVal; } public Task<bool> WaitForMessageAsync(TimeSpan timeout) { if (InnerChannel is IAsyncInputChannel asyncInputChannel) { return asyncInputChannel.WaitForMessageAsync(timeout); } else { return Task.Factory.FromAsync(InnerChannel.BeginWaitForMessage, InnerChannel.EndWaitForMessage, timeout, null); } } public bool WaitForMessage(TimeSpan timeout) { return WaitForMessageAsync(timeout).GetAwaiter().GetResult(); } public IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state) { return WaitForMessageAsync(timeout).ToApm(callback, state); } public bool EndWaitForMessage(IAsyncResult result) { return result.ToApmEnd<bool>(); } } internal class LayeredDuplexChannel : LayeredInputChannel, IAsyncDuplexChannel { private IOutputChannel _innerOutputChannel; private EndpointAddress _localAddress; private EventHandler _onInnerOutputChannelFaulted; public LayeredDuplexChannel(ChannelManagerBase channelManager, IInputChannel innerInputChannel, EndpointAddress localAddress, IOutputChannel innerOutputChannel) : base(channelManager, innerInputChannel) { _localAddress = localAddress; _innerOutputChannel = innerOutputChannel; _onInnerOutputChannelFaulted = new EventHandler(OnInnerOutputChannelFaulted); _innerOutputChannel.Faulted += _onInnerOutputChannelFaulted; } public override EndpointAddress LocalAddress { get { return _localAddress; } } public EndpointAddress RemoteAddress { get { return _innerOutputChannel.RemoteAddress; } } public Uri Via { get { return _innerOutputChannel.Via; } } protected override void OnClosing() { _innerOutputChannel.Faulted -= _onInnerOutputChannelFaulted; base.OnClosing(); } protected override void OnAbort() { _innerOutputChannel.Abort(); base.OnAbort(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) => throw ExceptionHelper.PlatformNotSupported(); protected override void OnEndClose(IAsyncResult result) => throw ExceptionHelper.PlatformNotSupported(); protected internal override async Task OnCloseAsync(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); await _innerOutputChannel.CloseHelperAsync(timeout); await base.OnCloseAsync(timeoutHelper.RemainingTime()); } protected override void OnClose(TimeSpan timeout) => throw ExceptionHelper.PlatformNotSupported(); protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) => throw ExceptionHelper.PlatformNotSupported(); protected override void OnEndOpen(IAsyncResult result) => throw ExceptionHelper.PlatformNotSupported(); protected internal override async Task OnOpenAsync(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); await base.OnOpenAsync(timeoutHelper.RemainingTime()); await _innerOutputChannel.OpenHelperAsync(timeoutHelper.RemainingTime()); } protected override void OnOpen(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.OnOpen(timeoutHelper.RemainingTime()); _innerOutputChannel.Open(timeoutHelper.RemainingTime()); } public Task SendAsync(Message message) { return SendAsync(message, DefaultSendTimeout); } public Task SendAsync(Message message, TimeSpan timeout) { if (_innerOutputChannel is IAsyncOutputChannel asyncOutputChannel) { return asyncOutputChannel.SendAsync(message, timeout); } else { return Task.Factory.FromAsync(_innerOutputChannel.BeginSend, _innerOutputChannel.EndSend, message, timeout, null); } } public void Send(Message message) { Send(message, DefaultSendTimeout); } public void Send(Message message, TimeSpan timeout) { SendAsync(message, timeout).GetAwaiter().GetResult(); } public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state) { return BeginSend(message, DefaultSendTimeout, callback, state); } public IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return SendAsync(message, timeout).ToApm(callback, state); } public void EndSend(IAsyncResult result) { result.ToApmEnd(); } private void OnInnerOutputChannelFaulted(object sender, EventArgs e) { Fault(); } } }
using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Cyotek.Windows.Forms { // Cyotek GroupBox Component // www.cyotek.com /// <summary> /// Represents a Windows control that displays a frame at the top of a group of controls with an optional caption and icon. /// </summary> [ToolboxItem(true)] [DefaultEvent("Click")] [DefaultProperty("Text")] [Designer("System.Windows.Forms.Design.GroupBoxDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [Designer("System.Windows.Forms.Design.DocumentDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(IRootDesigner))] internal class GroupBox : System.Windows.Forms.GroupBox { #region Fields private Border3DSide _borders = Border3DSide.Top; private Pen _bottomPen; private Color _headerForeColor; private Size _iconMargin; private Image _image; private Color _lineColorBottom; private Color _lineColorTop; private bool _showBorders; private Pen _topPen; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="GroupBox"/> class. /// </summary> public GroupBox() { _showBorders = true; _iconMargin = new Size(0, 6); _lineColorBottom = SystemColors.ButtonHighlight; _lineColorTop = SystemColors.ButtonShadow; _headerForeColor = SystemColors.HotTrack; this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.SupportsTransparentBackColor, true); this.CreateResources(); } #endregion #region Properties [Category("Appearance")] [DefaultValue(typeof(Border3DSide), "Top")] public Border3DSide Borders { get { return _borders; } set { _borders = value; this.Invalidate(); } } /// <summary> /// Gets a rectangle that represents the dimensions of the <see cref="T:System.Windows.Forms.GroupBox"/>. /// </summary> /// <value></value> /// <returns> /// A <see cref="T:System.Drawing.Rectangle"/> with the dimensions of the <see cref="T:System.Windows.Forms.GroupBox"/>. /// </returns> public override Rectangle DisplayRectangle { get { Size clientSize; int fontHeight; int imageSize; clientSize = this.ClientSize; fontHeight = this.Font.Height; if (_image != null) imageSize = _iconMargin.Width + _image.Width + 3; else imageSize = 0; return new Rectangle(3 + imageSize, fontHeight + 3, Math.Max(clientSize.Width - (imageSize + 6), 0), Math.Max(clientSize.Height - fontHeight - 6, 0)); } } [Category("Appearance")] [DefaultValue(typeof(Color), "HotTrack")] public Color HeaderForeColor { get { return _headerForeColor; } set { _headerForeColor = value; this.CreateResources(); this.Invalidate(); } } /// <summary> /// Gets or sets the icon margin. /// </summary> /// <value>The icon margin.</value> [Category("Appearance")] [DefaultValue(typeof(Size), "0, 6")] public Size IconMargin { get { return _iconMargin; } set { _iconMargin = value; this.Invalidate(); } } /// <summary> /// Gets or sets the image to display. /// </summary> /// <value>The image to display.</value> [Browsable(true)] [Category("Appearance")] [DefaultValue(typeof(Image), "")] public Image Image { get { return _image; } set { _image = value; this.Invalidate(); } } /// <summary> /// Gets or sets the line color bottom. /// </summary> /// <value>The line color bottom.</value> [Browsable(true)] [Category("Appearance")] [DefaultValue(typeof(Color), "ButtonHighlight")] public Color LineColorBottom { get { return _lineColorBottom; } set { _lineColorBottom = value; this.CreateResources(); this.Invalidate(); } } /// <summary> /// Gets or sets the line color top. /// </summary> /// <value>The line color top.</value> [Browsable(true)] [Category("Appearance")] [DefaultValue(typeof(Color), "ButtonShadow")] public Color LineColorTop { get { return _lineColorTop; } set { _lineColorTop = value; this.CreateResources(); this.Invalidate(); } } [DefaultValue(true)] [Category("Appearance")] public bool ShowBorders { get { return _showBorders; } set { _showBorders = value; this.Invalidate(); } } /// <summary> /// Returns or sets the text displayed in this control. /// </summary> /// <value></value> /// <returns> /// The text associated with this control. /// </returns> [Browsable(true)] [DefaultValue("")] public override string Text { get { return base.Text; } set { base.Text = value; this.Invalidate(); } } #endregion #region Methods /// <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) this.CleanUpResources(); base.Dispose(disposing); } /// <summary> /// Occurs when the control is to be painted. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs"/> that contains the event data.</param> protected override void OnPaint(PaintEventArgs e) { SizeF size; int y; TextFormatFlags flags; Rectangle textBounds; flags = TextFormatFlags.WordEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.Left | TextFormatFlags.SingleLine; size = TextRenderer.MeasureText(e.Graphics, this.Text, this.Font, this.ClientSize, flags); y = (int)(size.Height + 3) / 2; textBounds = new Rectangle(1, 1, (int)size.Width, (int)size.Height); if (this.ShowBorders) { if ((_borders & Border3DSide.All) == Border3DSide.All) { e.Graphics.DrawRectangle(_bottomPen, 1, y + 1, this.Width - 2, this.Height - (y + 2)); e.Graphics.DrawRectangle(_topPen, 0, y, this.Width - 2, this.Height - (y + 2)); } else { if ((_borders & Border3DSide.Top) == Border3DSide.Top) { e.Graphics.DrawLine(_topPen, size.Width + 3, y, this.Width - 5, y); e.Graphics.DrawLine(_bottomPen, size.Width + 3, y + 1, this.Width - 5, y + 1); } if ((_borders & Border3DSide.Left) == Border3DSide.Left) { e.Graphics.DrawLine(_topPen, 0, y, 0, this.Height - 1); e.Graphics.DrawLine(_bottomPen, 1, y, 1, this.Height - 1); } if ((_borders & Border3DSide.Right) == Border3DSide.Right) { e.Graphics.DrawLine(_bottomPen, this.Width - 1, y, this.Width - 1, this.Height - 1); e.Graphics.DrawLine(_topPen, this.Width - 2, y, this.Width - 2, this.Height - 1); } if ((_borders & Border3DSide.Bottom) == Border3DSide.Bottom) { e.Graphics.DrawLine(_topPen, 0, this.Height - 2, this.Width, this.Height - 2); e.Graphics.DrawLine(_bottomPen, 0, this.Height - 1, this.Width, this.Height - 1); } } } // header text TextRenderer.DrawText(e.Graphics, this.Text, this.Font, textBounds, this.HeaderForeColor, flags); // draw the image if (_image != null) e.Graphics.DrawImage(_image, this.Padding.Left + _iconMargin.Width, this.Padding.Top + (int)size.Height + _iconMargin.Height, _image.Width, _image.Height); //draw a designtime outline if (this.DesignMode && (_borders & Border3DSide.All) != Border3DSide.All) { using (Pen pen = new Pen(SystemColors.ButtonShadow)) { pen.DashStyle = DashStyle.Dot; e.Graphics.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1); } } } /// <summary> /// Raises the <see cref="System.Windows.Forms.Control.SystemColorsChanged"/> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param> protected override void OnSystemColorsChanged(EventArgs e) { base.OnSystemColorsChanged(e); this.CreateResources(); this.Invalidate(); } /// <summary> /// Cleans up GDI resources. /// </summary> private void CleanUpResources() { if (_topPen != null) _topPen.Dispose(); if (_bottomPen != null) _bottomPen.Dispose(); } /// <summary> /// Creates GDI resources. /// </summary> private void CreateResources() { this.CleanUpResources(); _topPen = new Pen(_lineColorTop); _bottomPen = new Pen(_lineColorBottom); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.Debugging; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Debugging; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; using IVsDebugName = Microsoft.VisualStudio.TextManager.Interop.IVsDebugName; using IVsEnumBSTR = Microsoft.VisualStudio.TextManager.Interop.IVsEnumBSTR; using IVsTextBuffer = Microsoft.VisualStudio.TextManager.Interop.IVsTextBuffer; using IVsTextLines = Microsoft.VisualStudio.TextManager.Interop.IVsTextLines; using RESOLVENAMEFLAGS = Microsoft.VisualStudio.TextManager.Interop.RESOLVENAMEFLAGS; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService { internal abstract partial class AbstractLanguageService<TPackage, TLanguageService, TProject> { internal class VsLanguageDebugInfo : IVsLanguageDebugInfo { private readonly Guid _languageId; private readonly TLanguageService _languageService; private readonly ILanguageDebugInfoService _languageDebugInfo; private readonly IBreakpointResolutionService _breakpointService; private readonly IProximityExpressionsService _proximityExpressionsService; private readonly IWaitIndicator _waitIndicator; private readonly CachedProximityExpressionsGetter _cachedProximityExpressionsGetter; public VsLanguageDebugInfo( Guid languageId, TLanguageService languageService, HostLanguageServices languageServiceProvider, IWaitIndicator waitIndicator) { Contract.ThrowIfNull(languageService); Contract.ThrowIfNull(languageServiceProvider); _languageId = languageId; _languageService = languageService; _languageDebugInfo = languageServiceProvider.GetService<ILanguageDebugInfoService>(); _breakpointService = languageServiceProvider.GetService<IBreakpointResolutionService>(); _proximityExpressionsService = languageServiceProvider.GetService<IProximityExpressionsService>(); _cachedProximityExpressionsGetter = new CachedProximityExpressionsGetter(_proximityExpressionsService); _waitIndicator = waitIndicator; } internal void OnDebugModeChanged(DebugMode debugMode) { _cachedProximityExpressionsGetter.OnDebugModeChanged(debugMode); } public int GetLanguageID(IVsTextBuffer pBuffer, int iLine, int iCol, out Guid pguidLanguageID) { pguidLanguageID = _languageId; return VSConstants.S_OK; } public int GetLocationOfName(string pszName, out string pbstrMkDoc, out VsTextSpan pspanLocation) { pbstrMkDoc = null; pspanLocation = default(VsTextSpan); return VSConstants.E_NOTIMPL; } public int GetNameOfLocation(IVsTextBuffer pBuffer, int iLine, int iCol, out string pbstrName, out int piLineOffset) { using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetNameOfLocation, CancellationToken.None)) { string name = null; int lineOffset = 0; var succeeded = false; if (_languageDebugInfo != null) { _waitIndicator.Wait( title: ServicesVSResources.Debugger, message: ServicesVSResources.Determining_breakpoint_location, allowCancel: true, action: waitContext => { var cancellationToken = waitContext.CancellationToken; var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer); if (textBuffer != null) { var point = textBuffer.CurrentSnapshot.GetPoint(iLine, iCol); var document = point.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { // NOTE(cyrusn): We have to wait here because the debuggers' // GetNameOfLocation is a blocking call. In the future, it // would be nice if they could make it async. var debugLocationInfo = _languageDebugInfo.GetLocationInfoAsync(document, point, cancellationToken).WaitAndGetResult(cancellationToken); if (!debugLocationInfo.IsDefault) { succeeded = true; name = debugLocationInfo.Name; lineOffset = debugLocationInfo.LineOffset; } } } }); if (succeeded) { pbstrName = name; piLineOffset = lineOffset; return VSConstants.S_OK; } } // Note(DustinCa): Docs say that GetNameOfLocation should return S_FALSE if a name could not be found. // Also, that's what the old native code does, so we should do it here. pbstrName = null; piLineOffset = 0; return VSConstants.S_FALSE; } } public int GetProximityExpressions(IVsTextBuffer pBuffer, int iLine, int iCol, int cLines, out IVsEnumBSTR ppEnum) { // NOTE(cyrusn): cLines is ignored. This is to match existing dev10 behavior. using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetProximityExpressions, CancellationToken.None)) { VsEnumBSTR enumBSTR = null; var succeeded = false; _waitIndicator.Wait( title: ServicesVSResources.Debugger, message: ServicesVSResources.Determining_autos, allowCancel: true, action: waitContext => { var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer); if (textBuffer != null) { var snapshot = textBuffer.CurrentSnapshot; Document document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var point = snapshot.GetPoint(iLine, iCol); var proximityExpressions = _proximityExpressionsService.GetProximityExpressionsAsync(document, point.Position, waitContext.CancellationToken).WaitAndGetResult(waitContext.CancellationToken); if (proximityExpressions != null) { enumBSTR = new VsEnumBSTR(proximityExpressions); succeeded = true; } } } }); if (succeeded) { ppEnum = enumBSTR; return VSConstants.S_OK; } ppEnum = null; return VSConstants.E_FAIL; } } public int IsMappedLocation(IVsTextBuffer pBuffer, int iLine, int iCol) { return VSConstants.E_NOTIMPL; } public int ResolveName(string pszName, uint dwFlags, out IVsEnumDebugName ppNames) { using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_ResolveName, CancellationToken.None)) { // In VS, this method frequently get's called with an empty string to test if the language service // supports this method (some language services, like F#, implement IVsLanguageDebugInfo but don't // implement this method). In that scenario, there's no sense doing work, so we'll just return // S_FALSE (as the old VB language service did). if (string.IsNullOrEmpty(pszName)) { ppNames = null; return VSConstants.S_FALSE; } VsEnumDebugName enumName = null; var succeeded = false; _waitIndicator.Wait( title: ServicesVSResources.Debugger, message: ServicesVSResources.Resolving_breakpoint_location, allowCancel: true, action: waitContext => { var cancellationToken = waitContext.CancellationToken; if (dwFlags == (uint)RESOLVENAMEFLAGS.RNF_BREAKPOINT) { var solution = _languageService.Workspace.CurrentSolution; // NOTE(cyrusn): We have to wait here because the debuggers' ResolveName // call is synchronous. In the future it would be nice to make it async. if (_breakpointService != null) { var breakpoints = _breakpointService.ResolveBreakpointsAsync(solution, pszName, cancellationToken).WaitAndGetResult(cancellationToken); var debugNames = breakpoints.Select(bp => CreateDebugName(bp, solution, cancellationToken)).WhereNotNull().ToList(); enumName = new VsEnumDebugName(debugNames); succeeded = true; } } }); if (succeeded) { ppNames = enumName; return VSConstants.S_OK; } ppNames = null; return VSConstants.E_NOTIMPL; } } private IVsDebugName CreateDebugName(BreakpointResolutionResult breakpoint, Solution solution, CancellationToken cancellationToken) { var document = breakpoint.Document; var filePath = _languageService.Workspace.GetFilePath(document.Id); var text = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var span = text.GetVsTextSpanForSpan(breakpoint.TextSpan); // If we're inside an Venus code nugget, we need to map the span to the surface buffer. // Otherwise, we'll just use the original span. VsTextSpan mappedSpan; if (!span.TryMapSpanFromSecondaryBufferToPrimaryBuffer(solution.Workspace, document.Id, out mappedSpan)) { mappedSpan = span; } return new VsDebugName(breakpoint.LocationNameOpt, filePath, mappedSpan); } public int ValidateBreakpointLocation(IVsTextBuffer pBuffer, int iLine, int iCol, VsTextSpan[] pCodeSpan) { using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_ValidateBreakpointLocation, CancellationToken.None)) { int result = VSConstants.E_NOTIMPL; _waitIndicator.Wait( title: ServicesVSResources.Debugger, message: ServicesVSResources.Validating_breakpoint_location, allowCancel: true, action: waitContext => { result = ValidateBreakpointLocationWorker(pBuffer, iLine, iCol, pCodeSpan, waitContext.CancellationToken); }); return result; } } private int ValidateBreakpointLocationWorker( IVsTextBuffer pBuffer, int iLine, int iCol, VsTextSpan[] pCodeSpan, CancellationToken cancellationToken) { if (_breakpointService == null) { return VSConstants.E_FAIL; } var textBuffer = _languageService.EditorAdaptersFactoryService.GetDataBuffer(pBuffer); if (textBuffer != null) { var snapshot = textBuffer.CurrentSnapshot; Document document = snapshot.AsText().GetDocumentWithFrozenPartialSemanticsAsync(cancellationToken).WaitAndGetResult(cancellationToken); if (document != null) { var point = snapshot.GetPoint(iLine, iCol); var length = 0; if (pCodeSpan != null && pCodeSpan.Length > 0) { // If we have a non-empty span then it means that the debugger is asking us to adjust an // existing span. In Everett we didn't do this so we had some good and some bad // behavior. For example if you had a breakpoint on: "int i;" and you changed it to "int // i = 4;", then the breakpoint wouldn't adjust. That was bad. However, if you had the // breakpoint on an open or close curly brace then it would always "stick" to that brace // which was good. // // So we want to keep the best parts of both systems. We want to appropriately "stick" // to tokens and we also want to adjust spans intelligently. // // However, it turns out the latter is hard to do when there are parse errors in the // code. Things like missing name nodes cause a lot of havoc and make it difficult to // track a closing curly brace. // // So the way we do this is that we default to not intelligently adjusting the spans // while there are parse errors. But when there are no parse errors then the span is // adjusted. var initialBreakpointSpan = snapshot.GetSpan(pCodeSpan[0]); if (initialBreakpointSpan.Length > 0 && document.SupportsSyntaxTree) { var tree = document.GetSyntaxTreeSynchronously(cancellationToken); if (tree.GetDiagnostics(cancellationToken).Any(d => d.Severity == DiagnosticSeverity.Error)) { return VSConstants.E_FAIL; } } // If a span is provided, and the requested position falls in that span, then just // move the requested position to the start of the span. // Length will be used to determine if we need further analysis, which is only required when text spans multiple lines. if (initialBreakpointSpan.Contains(point)) { point = initialBreakpointSpan.Start; length = pCodeSpan[0].iEndLine > pCodeSpan[0].iStartLine ? initialBreakpointSpan.Length : 0; } } // NOTE(cyrusn): we need to wait here because ValidateBreakpointLocation is // synchronous. In the future, it would be nice for the debugger to provide // an async entry point for this. var breakpoint = _breakpointService.ResolveBreakpointAsync(document, new CodeAnalysis.Text.TextSpan(point.Position, length), cancellationToken).WaitAndGetResult(cancellationToken); if (breakpoint == null) { // There should *not* be a breakpoint here. E_FAIL to let the debugger know // that. return VSConstants.E_FAIL; } if (breakpoint.IsLineBreakpoint) { // Let the debugger take care of this. They'll put a line breakpoint // here. This is useful for when the user does something like put a // breakpoint in inactive code. We want to allow this as they might // just have different defines during editing versus debugging. // TODO(cyrusn): Do we need to set the pCodeSpan in this case? return VSConstants.E_NOTIMPL; } // There should be a breakpoint at the location passed back. if (pCodeSpan != null && pCodeSpan.Length > 0) { pCodeSpan[0] = breakpoint.TextSpan.ToSnapshotSpan(snapshot).ToVsTextSpan(); } return VSConstants.S_OK; } } return VSConstants.E_NOTIMPL; } public int GetDataTipText(IVsTextBuffer pBuffer, VsTextSpan[] pSpan, string pbstrText) { using (Logger.LogBlock(FunctionId.Debugging_VsLanguageDebugInfo_GetDataTipText, CancellationToken.None)) { pbstrText = null; if (pSpan == null || pSpan.Length != 1) { return VSConstants.E_INVALIDARG; } int result = VSConstants.E_FAIL; _waitIndicator.Wait( title: ServicesVSResources.Debugger, message: ServicesVSResources.Getting_DataTip_text, allowCancel: true, action: waitContext => { var debugger = _languageService.Debugger; DBGMODE[] debugMode = new DBGMODE[1]; var cancellationToken = waitContext.CancellationToken; if (ErrorHandler.Succeeded(debugger.GetMode(debugMode)) && debugMode[0] != DBGMODE.DBGMODE_Design) { var editorAdapters = _languageService.EditorAdaptersFactoryService; var textSpan = pSpan[0]; var subjectBuffer = editorAdapters.GetDataBuffer(pBuffer); var textSnapshot = subjectBuffer.CurrentSnapshot; var document = textSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var spanOpt = textSnapshot.TryGetSpan(textSpan); if (spanOpt.HasValue) { var dataTipInfo = _languageDebugInfo.GetDataTipInfoAsync(document, spanOpt.Value.Start, cancellationToken).WaitAndGetResult(cancellationToken); if (!dataTipInfo.IsDefault) { var resultSpan = dataTipInfo.Span.ToSnapshotSpan(textSnapshot); string textOpt = dataTipInfo.Text; pSpan[0] = resultSpan.ToVsTextSpan(); result = debugger.GetDataTipValue((IVsTextLines)pBuffer, pSpan, textOpt, out pbstrText); } } } } }); return result; } } } } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Generator.Enums; using Generator.Enums.Encoder; using Generator.IO; namespace Generator.Encoder { enum MethodArgType { Code, Register, RepPrefixKind, Memory, UInt8, UInt16, Int32, UInt32, Int64, UInt64, PreferedInt32, ArrayIndex, ArrayLength, ByteArray, WordArray, DwordArray, QwordArray, ByteSlice, WordSlice, DwordSlice, QwordSlice, BytePtr, WordPtr, DwordPtr, QwordPtr, } sealed class MethodArg { public string Doc { get; } public MethodArgType Type { get; } public string Name { get; } public object? DefaultValue { get; } public MethodArg(string doc, MethodArgType type, string name, object? defaultValue = null) { Doc = doc; Type = type; Name = name; DefaultValue = defaultValue; } } sealed class CreateMethod { public readonly List<string> Docs; public readonly List<MethodArg> Args = new List<MethodArg>(); public CreateMethod(params string[] docs) => Docs = docs.ToList(); } abstract class InstrCreateGen { protected abstract (TargetLanguage language, string id, string filename) GetFileInfo(); protected abstract void GenCreate(FileWriter writer, CreateMethod method, InstructionGroup group); protected abstract void GenCreateBranch(FileWriter writer, CreateMethod method); protected abstract void GenCreateFarBranch(FileWriter writer, CreateMethod method); protected abstract void GenCreateXbegin(FileWriter writer, CreateMethod method); protected virtual bool CallGenCreateMemory64 => false; // The methods are deprecated protected virtual void GenCreateMemory64(FileWriter writer, CreateMethod method) { if (CallGenCreateMemory64) throw new InvalidOperationException(); } protected abstract void GenCreateString_Reg_SegRSI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code, EnumValue register); protected abstract void GenCreateString_Reg_ESRDI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code, EnumValue register); protected abstract void GenCreateString_ESRDI_Reg(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code, EnumValue register); protected abstract void GenCreateString_SegRSI_ESRDI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code); protected abstract void GenCreateString_ESRDI_SegRSI(FileWriter writer, CreateMethod method, StringMethodKind kind, string methodBaseName, EnumValue code); protected abstract void GenCreateMaskmov(FileWriter writer, CreateMethod method, string methodBaseName, EnumValue code); protected abstract void GenCreateDeclareData(FileWriter writer, CreateMethod method, DeclareDataKind kind); protected abstract void GenCreateDeclareDataArray(FileWriter writer, CreateMethod method, DeclareDataKind kind, ArrayType arrayType); protected abstract void GenCreateDeclareDataArrayLength(FileWriter writer, CreateMethod method, DeclareDataKind kind, ArrayType arrayType); protected readonly GenTypes genTypes; protected readonly EnumType codeType; readonly Dictionary<string, EnumValue> toCode; protected InstrCreateGen(GenTypes genTypes) { this.genTypes = genTypes; codeType = genTypes[TypeIds.Code]; toCode = new Dictionary<string, EnumValue>(codeType.Values.Length); foreach (var value in codeType.Values) toCode.Add(value.RawName, value); } bool TryGetCode(string name, [NotNullWhen(true)] out EnumValue? code) => toCode.TryGetValue(name, out code); public void Generate() { // The code assumes it has value 0 so the field doesn't have to be initialized if we know that it's already 0 if (genTypes[TypeIds.OpKind][nameof(OpKind.Register)].Value != 0) throw new InvalidOperationException(); var (language, id, filename) = GetFileInfo(); new FileUpdater(language, id, filename).Generate(writer => { GenerateCreateMethods(writer); GenerateCreateBranch(writer); GenerateCreateFarBranch(writer); GenerateCreateXbegin(writer); GenCreateMemory64(writer); GenCreateStringInstructions(writer); GenCreateDeclareXxx(writer); }); } void GenerateCreateMethods(FileWriter writer) { var groups = new InstructionGroups(genTypes).GetGroups(); bool writeLine = false; foreach (var info in GetCreateMethods(groups)) { if (writeLine) writer.WriteLine(); writeLine = true; GenCreate(writer, info.method, info.group); } } static IEnumerable<(CreateMethod method, InstructionGroup group)> GetCreateMethods(InstructionGroup[] groups) { foreach (var group in groups) { yield return (GetMethod(group, false), group); if (GetOpKindCount(group).immCount > 0) yield return (GetMethod(group, true), group); } } static void AddCodeArg(CreateMethod method) => method.Args.Add(new MethodArg("Code value", MethodArgType.Code, "code")); static void AddAddressSizeArg(CreateMethod method) => method.Args.Add(new MethodArg("16, 32, or 64", MethodArgType.PreferedInt32, "addressSize")); static void AddTargetArg(CreateMethod method) => method.Args.Add(new MethodArg("Target address", MethodArgType.UInt64, "target")); static void AddBitnessArg(CreateMethod method) => method.Args.Add(new MethodArg("16, 32, or 64", MethodArgType.PreferedInt32, "bitness")); void AddSegmentPrefixArg(CreateMethod method) => method.Args.Add(new MethodArg("Segment override or #(e:Register.None)#", MethodArgType.Register, "segmentPrefix", genTypes[TypeIds.Register][nameof(Register.None)])); void AddRepPrefixArg(CreateMethod method) => method.Args.Add(new MethodArg("Rep prefix or #(e:RepPrefixKind.None)#", MethodArgType.RepPrefixKind, "repPrefix", genTypes[TypeIds.RepPrefixKind][nameof(RepPrefixKind.None)])); static CreateMethod GetMethod(InstructionGroup group, bool unsigned) { var (regCount, immCount, memCount) = GetOpKindCount(group); int regId = 1, immId = 1, memId = 1; string doc = group.Operands.Length switch { 0 => "Creates an instruction with no operands", 1 => "Creates an instruction with 1 operand", _ => $"Creates an instruction with {group.Operands.Length} operands", }; var method = new CreateMethod(doc); AddCodeArg(method); int opNum = -1; foreach (var op in group.Operands) { opNum++; switch (op) { case InstructionOperand.Register: method.Args.Add(new MethodArg($"op{opNum}: Register", MethodArgType.Register, GetArgName("register", regCount, regId++))); break; case InstructionOperand.Memory: method.Args.Add(new MethodArg($"op{opNum}: Memory operand", MethodArgType.Memory, GetArgName("memory", memCount, memId++))); break; case InstructionOperand.Imm32: method.Args.Add(new MethodArg($"op{opNum}: Immediate value", unsigned ? MethodArgType.UInt32 : MethodArgType.Int32, GetArgName("immediate", immCount, immId++))); break; case InstructionOperand.Imm64: method.Args.Add(new MethodArg($"op{opNum}: Immediate value", unsigned ? MethodArgType.UInt64 : MethodArgType.Int64, GetArgName("immediate", immCount, immId++))); break; default: throw new InvalidOperationException(); } } return method; static string GetArgName(string name, int count, int id) { if (count <= 1) return name; return name + id.ToString(); } } static (int regCount, int immCount, int memCount) GetOpKindCount(InstructionGroup group) { int regCount = 0; int immCount = 0; int memCount = 0; foreach (var op in group.Operands) { switch (op) { case InstructionOperand.Register: regCount++; break; case InstructionOperand.Memory: memCount++; break; case InstructionOperand.Imm32: case InstructionOperand.Imm64: immCount++; break; default: throw new InvalidOperationException(); } } return (regCount, immCount, memCount); } void GenerateCreateBranch(FileWriter writer) { writer.WriteLine(); var method = new CreateMethod("Creates a new near/short branch instruction"); AddCodeArg(method); AddTargetArg(method); GenCreateBranch(writer, method); } void GenerateCreateFarBranch(FileWriter writer) { writer.WriteLine(); var method = new CreateMethod("Creates a new far branch instruction"); AddCodeArg(method); method.Args.Add(new MethodArg("Selector/segment value", MethodArgType.UInt16, "selector")); method.Args.Add(new MethodArg("Offset", MethodArgType.UInt32, "offset")); GenCreateFarBranch(writer, method); } void GenerateCreateXbegin(FileWriter writer) { writer.WriteLine(); var method = new CreateMethod("Creates a new #(c:XBEGIN)# instruction"); AddBitnessArg(method); AddTargetArg(method); if (TryGetCode(nameof(Code.Xbegin_rel16), out _) && TryGetCode(nameof(Code.Xbegin_rel32), out _)) GenCreateXbegin(writer, method); } void GenCreateMemory64(FileWriter writer) { if (!CallGenCreateMemory64) return; writer.WriteLine(); { var method = new CreateMethod("Creates an instruction with a 64-bit memory offset as the second operand, eg. #(c:mov al,[123456789ABCDEF0])#"); AddCodeArg(method); method.Args.Add(new MethodArg("Register (#(c:AL)#, #(c:AX)#, #(c:EAX)#, #(c:RAX)#)", MethodArgType.Register, "register")); method.Args.Add(new MethodArg("64-bit address", MethodArgType.UInt64, "address")); AddSegmentPrefixArg(method); GenCreateMemory64(writer, method); } writer.WriteLine(); { var method = new CreateMethod("Creates an instruction with a 64-bit memory offset as the first operand, eg. #(c:mov [123456789ABCDEF0],al)#"); AddCodeArg(method); method.Args.Add(new MethodArg("64-bit address", MethodArgType.UInt64, "address")); method.Args.Add(new MethodArg("Register (#(c:AL)#, #(c:AX)#, #(c:EAX)#, #(c:RAX)#)", MethodArgType.Register, "register")); AddSegmentPrefixArg(method); GenCreateMemory64(writer, method); } } void GenCreateStringInstructions(FileWriter writer) { GenCreateString_Reg_SegRSI(writer); GenCreateString_Reg_ESRDI(writer); GenCreateString_ESRDI_Reg(writer); GenCreateString_SegRSI_ESRDI(writer); GenCreateString_ESRDI_SegRSI(writer); GenCreateMaskmov(writer); } protected enum StringMethodKind { Full, Rep, Repe, Repne, } void GenCreateString_Reg_SegRSI(FileWriter writer) { Gen(writer, "outsb", nameof(Code.Outsb_DX_m8), genTypes[TypeIds.Register][nameof(Register.DX)]); Gen(writer, "outsw", nameof(Code.Outsw_DX_m16), genTypes[TypeIds.Register][nameof(Register.DX)]); Gen(writer, "outsd", nameof(Code.Outsd_DX_m32), genTypes[TypeIds.Register][nameof(Register.DX)]); Gen(writer, "lodsb", nameof(Code.Lodsb_AL_m8), genTypes[TypeIds.Register][nameof(Register.AL)]); Gen(writer, "lodsw", nameof(Code.Lodsw_AX_m16), genTypes[TypeIds.Register][nameof(Register.AX)]); Gen(writer, "lodsd", nameof(Code.Lodsd_EAX_m32), genTypes[TypeIds.Register][nameof(Register.EAX)]); Gen(writer, "lodsq", nameof(Code.Lodsq_RAX_m64), genTypes[TypeIds.Register][nameof(Register.RAX)]); void Gen(FileWriter writer, string mnemonic, string codeStr, EnumValue register) { if (!TryGetCode(codeStr, out var code)) return; var mnemonicUpper = mnemonic.ToUpperInvariant(); var baseName = mnemonicUpper[0..1] + mnemonicUpper[1..].ToLowerInvariant(); { writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:{mnemonicUpper})# instruction"); var name = baseName; AddAddressSizeArg(method); AddSegmentPrefixArg(method); AddRepPrefixArg(method); GenCreateString_Reg_SegRSI(writer, method, StringMethodKind.Full, name, code, register); } { writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:REP {mnemonicUpper})# instruction"); var name = "Rep" + baseName; AddAddressSizeArg(method); GenCreateString_Reg_SegRSI(writer, method, StringMethodKind.Rep, name, code, register); } } } void GenCreateString_Reg_ESRDI(FileWriter writer) { Gen(writer, "scasb", nameof(Code.Scasb_AL_m8), genTypes[TypeIds.Register][nameof(Register.AL)]); Gen(writer, "scasw", nameof(Code.Scasw_AX_m16), genTypes[TypeIds.Register][nameof(Register.AX)]); Gen(writer, "scasd", nameof(Code.Scasd_EAX_m32), genTypes[TypeIds.Register][nameof(Register.EAX)]); Gen(writer, "scasq", nameof(Code.Scasq_RAX_m64), genTypes[TypeIds.Register][nameof(Register.RAX)]); void Gen(FileWriter writer, string mnemonic, string codeStr, EnumValue register) { if (!TryGetCode(codeStr, out var code)) return; var mnemonicUpper = mnemonic.ToUpperInvariant(); var baseName = mnemonicUpper[0..1] + mnemonicUpper[1..].ToLowerInvariant(); { writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:{mnemonicUpper})# instruction"); var name = baseName; AddAddressSizeArg(method); AddRepPrefixArg(method); GenCreateString_Reg_ESRDI(writer, method, StringMethodKind.Full, name, code, register); } { writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:REPE {mnemonicUpper})# instruction"); var name = "Repe" + baseName; AddAddressSizeArg(method); GenCreateString_Reg_ESRDI(writer, method, StringMethodKind.Repe, name, code, register); } { writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:REPNE {mnemonicUpper})# instruction"); var name = "Repne" + baseName; AddAddressSizeArg(method); GenCreateString_Reg_ESRDI(writer, method, StringMethodKind.Repne, name, code, register); } } } void GenCreateString_ESRDI_Reg(FileWriter writer) { Gen(writer, "insb", nameof(Code.Insb_m8_DX), genTypes[TypeIds.Register][nameof(Register.DX)]); Gen(writer, "insw", nameof(Code.Insw_m16_DX), genTypes[TypeIds.Register][nameof(Register.DX)]); Gen(writer, "insd", nameof(Code.Insd_m32_DX), genTypes[TypeIds.Register][nameof(Register.DX)]); Gen(writer, "stosb", nameof(Code.Stosb_m8_AL), genTypes[TypeIds.Register][nameof(Register.AL)]); Gen(writer, "stosw", nameof(Code.Stosw_m16_AX), genTypes[TypeIds.Register][nameof(Register.AX)]); Gen(writer, "stosd", nameof(Code.Stosd_m32_EAX), genTypes[TypeIds.Register][nameof(Register.EAX)]); Gen(writer, "stosq", nameof(Code.Stosq_m64_RAX), genTypes[TypeIds.Register][nameof(Register.RAX)]); void Gen(FileWriter writer, string mnemonic, string codeStr, EnumValue register) { if (!TryGetCode(codeStr, out var code)) return; var mnemonicUpper = mnemonic.ToUpperInvariant(); var baseName = mnemonicUpper[0..1] + mnemonicUpper[1..].ToLowerInvariant(); { writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:{mnemonicUpper})# instruction"); var name = baseName; AddAddressSizeArg(method); AddRepPrefixArg(method); GenCreateString_ESRDI_Reg(writer, method, StringMethodKind.Full, name, code, register); } { writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:REP {mnemonicUpper})# instruction"); var name = "Rep" + baseName; AddAddressSizeArg(method); GenCreateString_ESRDI_Reg(writer, method, StringMethodKind.Rep, name, code, register); } } } void GenCreateString_SegRSI_ESRDI(FileWriter writer) { Gen(writer, "cmpsb", nameof(Code.Cmpsb_m8_m8)); Gen(writer, "cmpsw", nameof(Code.Cmpsw_m16_m16)); Gen(writer, "cmpsd", nameof(Code.Cmpsd_m32_m32)); Gen(writer, "cmpsq", nameof(Code.Cmpsq_m64_m64)); void Gen(FileWriter writer, string mnemonic, string codeStr) { if (!TryGetCode(codeStr, out var code)) return; var mnemonicUpper = mnemonic.ToUpperInvariant(); var baseName = mnemonicUpper[0..1] + mnemonicUpper[1..].ToLowerInvariant(); { writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:{mnemonicUpper})# instruction"); var name = baseName; AddAddressSizeArg(method); AddSegmentPrefixArg(method); AddRepPrefixArg(method); GenCreateString_SegRSI_ESRDI(writer, method, StringMethodKind.Full, name, code); } { writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:REPE {mnemonicUpper})# instruction"); var name = "Repe" + baseName; AddAddressSizeArg(method); GenCreateString_SegRSI_ESRDI(writer, method, StringMethodKind.Repe, name, code); } { writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:REPNE {mnemonicUpper})# instruction"); var name = "Repne" + baseName; AddAddressSizeArg(method); GenCreateString_SegRSI_ESRDI(writer, method, StringMethodKind.Repne, name, code); } } } void GenCreateString_ESRDI_SegRSI(FileWriter writer) { Gen(writer, "movsb", nameof(Code.Movsb_m8_m8)); Gen(writer, "movsw", nameof(Code.Movsw_m16_m16)); Gen(writer, "movsd", nameof(Code.Movsd_m32_m32)); Gen(writer, "movsq", nameof(Code.Movsq_m64_m64)); void Gen(FileWriter writer, string mnemonic, string codeStr) { if (!TryGetCode(codeStr, out var code)) return; var mnemonicUpper = mnemonic.ToUpperInvariant(); var baseName = mnemonicUpper[0..1] + mnemonicUpper[1..].ToLowerInvariant(); { writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:{mnemonicUpper})# instruction"); var name = baseName; AddAddressSizeArg(method); AddSegmentPrefixArg(method); AddRepPrefixArg(method); GenCreateString_ESRDI_SegRSI(writer, method, StringMethodKind.Full, name, code); } { writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:REP {mnemonicUpper})# instruction"); var name = "Rep" + baseName; AddAddressSizeArg(method); GenCreateString_ESRDI_SegRSI(writer, method, StringMethodKind.Rep, name, code); } } } void GenCreateMaskmov(FileWriter writer) { Gen(writer, "maskmovq", nameof(Code.Maskmovq_rDI_mm_mm)); Gen(writer, "maskmovdqu", nameof(Code.Maskmovdqu_rDI_xmm_xmm)); Gen(writer, "vmaskmovdqu", nameof(Code.VEX_Vmaskmovdqu_rDI_xmm_xmm)); void Gen(FileWriter writer, string mnemonic, string codeStr) { if (!TryGetCode(codeStr, out var code)) return; var mnemonicUpper = mnemonic.ToUpperInvariant(); var baseName = mnemonicUpper[0..1] + mnemonicUpper[1..].ToLowerInvariant(); writer.WriteLine(); var method = new CreateMethod($"Creates a #(c:{mnemonicUpper})# instruction"); var name = baseName; AddAddressSizeArg(method); method.Args.Add(new MethodArg("Register", MethodArgType.Register, "register1")); method.Args.Add(new MethodArg("Register", MethodArgType.Register, "register2")); AddSegmentPrefixArg(method); GenCreateMaskmov(writer, method, name, code); } } protected enum DeclareDataKind { Byte, Word, Dword, Qword, } protected enum ArrayType { ByteArray, WordArray, DwordArray, QwordArray, ByteSlice, WordSlice, DwordSlice, QwordSlice, BytePtr, WordPtr, DwordPtr, QwordPtr, } void GenCreateDeclareXxx(FileWriter writer) { if (TryGetCode(nameof(Code.DeclareByte), out _)) GenCreateDeclareByte(writer); if (TryGetCode(nameof(Code.DeclareWord), out _)) GenCreateDeclareWord(writer); if (TryGetCode(nameof(Code.DeclareDword), out _)) GenCreateDeclareDword(writer); if (TryGetCode(nameof(Code.DeclareQword), out _)) GenCreateDeclareQword(writer); } static class DeclareConsts { public const string dbDoc = "Creates a #(c:db)#/#(c:.byte)# asm directive"; public const string dwDoc = "Creates a #(c:dw)#/#(c:.word)# asm directive"; public const string ddDoc = "Creates a #(c:dd)#/#(c:.int)# asm directive"; public const string dqDoc = "Creates a #(c:dq)#/#(c:.quad)# asm directive"; public const string dataArgName = "data"; public const string dataArgDoc = "Data"; public const string indexArgName = "index"; public const string indexArgDoc = "Start index"; public const string lengthArgName = "length"; public const string lengthBytesDoc = "Number of bytes"; public const string lengthElemsDoc = "Number of elements"; } void GenCreateDeclareByte(FileWriter writer) { for (int args = 1; args <= 16; args++) { var method = new CreateMethod(DeclareConsts.dbDoc); for (int i = 0; i < args; i++) method.Args.Add(new MethodArg($"Byte {i}", MethodArgType.UInt8, $"b{i}")); GenCreateDeclareData(writer, method, DeclareDataKind.Byte); } { var method = new CreateMethod(DeclareConsts.dbDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.BytePtr, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthBytesDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Byte, ArrayType.BytePtr); } { var method = new CreateMethod(DeclareConsts.dbDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.ByteSlice, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Byte, ArrayType.ByteSlice); } { var method = new CreateMethod(DeclareConsts.dbDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.ByteArray, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Byte, ArrayType.ByteArray); } { var method = new CreateMethod(DeclareConsts.dbDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.ByteArray, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.indexArgDoc, MethodArgType.ArrayIndex, DeclareConsts.indexArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthBytesDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArrayLength(writer, method, DeclareDataKind.Byte, ArrayType.ByteArray); } } void GenCreateDeclareWord(FileWriter writer) { for (int args = 1; args <= 8; args++) { var method = new CreateMethod(DeclareConsts.dwDoc); for (int i = 0; i < args; i++) method.Args.Add(new MethodArg($"Word {i}", MethodArgType.UInt16, $"w{i}")); GenCreateDeclareData(writer, method, DeclareDataKind.Word); } { var method = new CreateMethod(DeclareConsts.dwDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.BytePtr, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthBytesDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Word, ArrayType.BytePtr); } { var method = new CreateMethod(DeclareConsts.dwDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.ByteSlice, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Word, ArrayType.ByteSlice); } { var method = new CreateMethod(DeclareConsts.dwDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.ByteArray, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Word, ArrayType.ByteArray); } { var method = new CreateMethod(DeclareConsts.dwDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.ByteArray, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.indexArgDoc, MethodArgType.ArrayIndex, DeclareConsts.indexArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthBytesDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArrayLength(writer, method, DeclareDataKind.Word, ArrayType.ByteArray); } { var method = new CreateMethod(DeclareConsts.dwDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.WordPtr, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthElemsDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Word, ArrayType.WordPtr); } { var method = new CreateMethod(DeclareConsts.dwDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.WordSlice, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Word, ArrayType.WordSlice); } { var method = new CreateMethod(DeclareConsts.dwDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.WordArray, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Word, ArrayType.WordArray); } { var method = new CreateMethod(DeclareConsts.dwDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.WordArray, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.indexArgDoc, MethodArgType.ArrayIndex, DeclareConsts.indexArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthElemsDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArrayLength(writer, method, DeclareDataKind.Word, ArrayType.WordArray); } } void GenCreateDeclareDword(FileWriter writer) { for (int args = 1; args <= 4; args++) { var method = new CreateMethod(DeclareConsts.ddDoc); for (int i = 0; i < args; i++) method.Args.Add(new MethodArg($"Dword {i}", MethodArgType.UInt32, $"d{i}")); GenCreateDeclareData(writer, method, DeclareDataKind.Dword); } { var method = new CreateMethod(DeclareConsts.ddDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.BytePtr, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthBytesDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Dword, ArrayType.BytePtr); } { var method = new CreateMethod(DeclareConsts.ddDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.ByteSlice, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Dword, ArrayType.ByteSlice); } { var method = new CreateMethod(DeclareConsts.ddDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.ByteArray, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Dword, ArrayType.ByteArray); } { var method = new CreateMethod(DeclareConsts.ddDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.ByteArray, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.indexArgDoc, MethodArgType.ArrayIndex, DeclareConsts.indexArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthBytesDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArrayLength(writer, method, DeclareDataKind.Dword, ArrayType.ByteArray); } { var method = new CreateMethod(DeclareConsts.ddDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.DwordPtr, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthElemsDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Dword, ArrayType.DwordPtr); } { var method = new CreateMethod(DeclareConsts.ddDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.DwordSlice, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Dword, ArrayType.DwordSlice); } { var method = new CreateMethod(DeclareConsts.ddDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.DwordArray, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Dword, ArrayType.DwordArray); } { var method = new CreateMethod(DeclareConsts.ddDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.DwordArray, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.indexArgDoc, MethodArgType.ArrayIndex, DeclareConsts.indexArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthElemsDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArrayLength(writer, method, DeclareDataKind.Dword, ArrayType.DwordArray); } } void GenCreateDeclareQword(FileWriter writer) { for (int args = 1; args <= 2; args++) { var method = new CreateMethod(DeclareConsts.dqDoc); for (int i = 0; i < args; i++) method.Args.Add(new MethodArg($"Qword {i}", MethodArgType.UInt64, $"q{i}")); GenCreateDeclareData(writer, method, DeclareDataKind.Qword); } { var method = new CreateMethod(DeclareConsts.dqDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.BytePtr, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthBytesDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Qword, ArrayType.BytePtr); } { var method = new CreateMethod(DeclareConsts.dqDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.ByteSlice, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Qword, ArrayType.ByteSlice); } { var method = new CreateMethod(DeclareConsts.dqDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.ByteArray, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Qword, ArrayType.ByteArray); } { var method = new CreateMethod(DeclareConsts.dqDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.ByteArray, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.indexArgDoc, MethodArgType.ArrayIndex, DeclareConsts.indexArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthBytesDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArrayLength(writer, method, DeclareDataKind.Qword, ArrayType.ByteArray); } { var method = new CreateMethod(DeclareConsts.dqDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.QwordPtr, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthElemsDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Qword, ArrayType.QwordPtr); } { var method = new CreateMethod(DeclareConsts.dqDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.QwordSlice, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Qword, ArrayType.QwordSlice); } { var method = new CreateMethod(DeclareConsts.dqDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.QwordArray, DeclareConsts.dataArgName)); GenCreateDeclareDataArray(writer, method, DeclareDataKind.Qword, ArrayType.QwordArray); } { var method = new CreateMethod(DeclareConsts.dqDoc); method.Args.Add(new MethodArg(DeclareConsts.dataArgDoc, MethodArgType.QwordArray, DeclareConsts.dataArgName)); method.Args.Add(new MethodArg(DeclareConsts.indexArgDoc, MethodArgType.ArrayIndex, DeclareConsts.indexArgName)); method.Args.Add(new MethodArg(DeclareConsts.lengthElemsDoc, MethodArgType.ArrayLength, DeclareConsts.lengthArgName)); GenCreateDeclareDataArrayLength(writer, method, DeclareDataKind.Qword, ArrayType.QwordArray); } } } }
// 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.Net.Sockets; using System.Net.Test.Common; using System.Runtime.ExceptionServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public class ServerAsyncAuthenticateTest : IDisposable { private readonly ITestOutputHelper _log; private readonly ITestOutputHelper _logVerbose; private readonly X509Certificate2 _serverCertificate; public ServerAsyncAuthenticateTest() { _log = TestLogging.GetInstance(); _logVerbose = VerboseTestLogging.GetInstance(); _serverCertificate = Configuration.Certificates.GetServerCertificate(); } public void Dispose() { _serverCertificate.Dispose(); } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] public async Task ServerAsyncAuthenticate_EachSupportedProtocol_Success(SslProtocols protocol) { await ServerAsyncSslHelper(protocol, protocol); } [Theory] [ClassData(typeof(SslProtocolSupport.UnsupportedSslProtocolsTestData))] public async Task ServerAsyncAuthenticate_EachServerUnsupportedProtocol_Fail(SslProtocols protocol) { await Assert.ThrowsAsync<NotSupportedException>(() => { return ServerAsyncSslHelper( SslProtocolSupport.SupportedSslProtocols, protocol, expectedToFail: true); }); } [Theory] [MemberData(nameof(ProtocolMismatchData))] public async Task ServerAsyncAuthenticate_MismatchProtocols_Fails( SslProtocols serverProtocol, SslProtocols clientProtocol, Type expectedException) { await Assert.ThrowsAsync( expectedException, () => { return ServerAsyncSslHelper( serverProtocol, clientProtocol, expectedToFail: true); }); } [Fact] public async Task ServerAsyncAuthenticate_UnsupportedAllServer_Fail() { await Assert.ThrowsAsync<NotSupportedException>(() => { return ServerAsyncSslHelper( SslProtocolSupport.SupportedSslProtocols, SslProtocolSupport.UnsupportedSslProtocols, expectedToFail: true); }); } [Theory] [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))] public async Task ServerAsyncAuthenticate_AllClientVsIndividualServerSupportedProtocols_Success( SslProtocols serverProtocol) { await ServerAsyncSslHelper(SslProtocolSupport.SupportedSslProtocols, serverProtocol); } private static IEnumerable<object[]> ProtocolMismatchData() { yield return new object[] { SslProtocols.Tls, SslProtocols.Tls11, typeof(AuthenticationException) }; yield return new object[] { SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException) }; yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls, typeof(TimeoutException) }; yield return new object[] { SslProtocols.Tls11, SslProtocols.Tls12, typeof(AuthenticationException) }; yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls, typeof(TimeoutException) }; yield return new object[] { SslProtocols.Tls12, SslProtocols.Tls11, typeof(TimeoutException) }; } #region Helpers private async Task ServerAsyncSslHelper( SslProtocols clientSslProtocols, SslProtocols serverSslProtocols, bool expectedToFail = false) { _log.WriteLine( "Server: " + serverSslProtocols + "; Client: " + clientSslProtocols + " expectedToFail: " + expectedToFail); int timeOut = expectedToFail ? TestConfiguration.FailingTestTimeoutMiliseconds : TestConfiguration.PassingTestTimeoutMilliseconds; IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0); var server = new TcpListener(endPoint); server.Start(); using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6)) { IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint; Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port); Task<TcpClient> serverAccept = server.AcceptTcpClientAsync(); // We expect that the network-level connect will always complete. await Task.WhenAll(new Task[] { clientConnect, serverAccept }).TimeoutAfter( TestConfiguration.PassingTestTimeoutMilliseconds); using (TcpClient serverConnection = await serverAccept) using (SslStream sslClientStream = new SslStream(clientConnection.GetStream())) using (SslStream sslServerStream = new SslStream( serverConnection.GetStream(), false, AllowAnyServerCertificate)) { string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false); _logVerbose.WriteLine("ServerAsyncAuthenticateTest.AuthenticateAsClientAsync start."); Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync( serverName, null, clientSslProtocols, false); _logVerbose.WriteLine("ServerAsyncAuthenticateTest.AuthenticateAsServerAsync start."); Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync( _serverCertificate, true, serverSslProtocols, false); try { await clientAuthentication.TimeoutAfter(timeOut); _logVerbose.WriteLine("ServerAsyncAuthenticateTest.clientAuthentication complete."); } catch (Exception ex) { // Ignore client-side errors: we're only interested in server-side behavior. _log.WriteLine("Client exception: " + ex); } await serverAuthentication.TimeoutAfter(timeOut); _logVerbose.WriteLine("ServerAsyncAuthenticateTest.serverAuthentication complete."); _log.WriteLine( "Server({0}) authenticated with encryption cipher: {1} {2}-bit strength", serverEndPoint, sslServerStream.CipherAlgorithm, sslServerStream.CipherStrength); Assert.True( sslServerStream.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(sslServerStream.CipherStrength > 0, "Cipher strength should be greater than 0"); } } } // The following method is invoked by the RemoteCertificateValidationDelegate. private bool AllowAnyServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { Assert.True( (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == SslPolicyErrors.RemoteCertificateNotAvailable, "Client didn't supply a cert, the server required one, yet sslPolicyErrors is " + sslPolicyErrors); return true; // allow everything } #endregion Helpers } }
// 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> /// IpPoolsOperations operations. /// </summary> internal partial class IpPoolsOperations : IServiceOperations<FabricAdminClient>, IIpPoolsOperations { /// <summary> /// Initializes a new instance of the IpPoolsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal IpPoolsOperations(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 ip pool. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='ipPool'> /// Ip pool 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<IpPool>> GetWithHttpMessagesAsync(string location, string ipPool, 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 (ipPool == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ipPool"); } 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("ipPool", ipPool); 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}/ipPools/{ipPool}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{ipPool}", System.Uri.EscapeDataString(ipPool)); 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<IpPool>(); _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<IpPool>(_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> /// Create an ip pool. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='ipPool'> /// Ip pool name. /// </param> /// <param name='pool'> /// Ip pool object to send. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<OperationStatus>> CreateWithHttpMessagesAsync(string location, string ipPool, IpPool pool, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<OperationStatus> _response = await BeginCreateWithHttpMessagesAsync(location, ipPool, pool, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get a list of all ip pools at a certain 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<IpPool>>> ListWithHttpMessagesAsync(string location, ODataQuery<IpPool> odataQuery = default(ODataQuery<IpPool>), 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}/ipPools").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<IpPool>>(); _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<IpPool>>(_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> /// Create an ip pool. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='ipPool'> /// Ip pool name. /// </param> /// <param name='pool'> /// Ip pool object to send. /// </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<OperationStatus>> BeginCreateWithHttpMessagesAsync(string location, string ipPool, IpPool pool, 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 (ipPool == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ipPool"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (pool == null) { throw new ValidationException(ValidationRules.CannotBeNull, "pool"); } // 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("ipPool", ipPool); tracingParameters.Add("pool", pool); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", 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}/ipPools/{ipPool}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{ipPool}", System.Uri.EscapeDataString(ipPool)); 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("PUT"); _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; if(pool != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(pool, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // 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 && (int)_statusCode != 202) { 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<OperationStatus>(); _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<OperationStatus>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<OperationStatus>(_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 ip pools at a certain 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<IpPool>>> 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<IpPool>>(); _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<IpPool>>(_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; } } }
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 Battleships.WebServices.Areas.HelpPage.ModelDescriptions; using Battleships.WebServices.Areas.HelpPage.Models; namespace Battleships.WebServices.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); } } } }
//----------------------------------------------------------------------- // <copyright file="LayoutManager.cs" company="Google"> // // Copyright 2019 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. // // </copyright> //----------------------------------------------------------------------- using System; using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine; namespace SIS { public interface ILayoutManagerDelegate { void LayoutManagerLoadedNewLayout(LayoutManager manager, Layout newLayout); void LayoutManagerHotspotListChanged(LayoutManager manager, Layout layout); void LayoutManagerLoadedAudioClipsChanged(LayoutManager manager, int hotspotCount); void StartCoroutineOn(IEnumerator e); } public class LayoutManager : ILayoutDelegate, IAudioClipLoadingDelegate { public ILayoutManagerDelegate layoutManagerDelegate = null; public Layout layout; // Current scene layout in memory public AudioClipLoadingManager onDemandLoadingManager = new AudioClipLoadingManager(); public Dictionary<string, SoundFile> soundDictionary; public Dictionary<string, SoundFile> getSoundDictionary() { return soundDictionary; } public int getNumLoadedInSoundDictionary() { return loadedAudioClipCount; } public int loadingAudioClipCount { get { return soundDictionary.Values.Aggregate(0, (acc, x) => { // Don't count the loading of the default sound file... return acc + (!x.isDefaultSoundFile && x.loadState == LoadState.Loading ? 1 : 0); }); } } public int loadedAudioClipCount { get { return soundDictionary.Values.Aggregate(0, (acc, x) => { // Don't count the loading of the default sound file... return acc + (!x.isDefaultSoundFile && x.loadState == LoadState.Success ? 1 : 0); }); } } // Top level save state int public int currentLayoutId { get { return PlayerPrefs.GetInt("layout", 0); } set { PlayerPrefs.SetInt("layout", value); } } // =========== // HOTSPOT METHODS public Hotspot AddNewHotspot(Vector3 localPos, Vector3 rotation, float minDist, float maxDist) { Hotspot h = new Hotspot(localPos, rotation, minDist, maxDist); layout.AddHotspot(h); layoutManagerDelegate?.LayoutManagerHotspotListChanged(this, layout); return h; } public void EraseHotspot(Hotspot hotspot) { if (layout == null) return; layout?.EraseHotspot(hotspot); layoutManagerDelegate?.LayoutManagerHotspotListChanged(this, layout); } public void EraseAllHotspots() { layout.EraseHotspots(); layoutManagerDelegate?.LayoutManagerHotspotListChanged(this, layout); } // ============ // SOUND FILE METHODS public void Bind(SoundMarker obj, Hotspot hotspot, bool startPlayback, bool reloadSoundClips) { AudioClip clip = soundDictionary.TryGetValue(hotspot.soundID, out SoundFile sf) ? sf.clip // If the sound is found, use it : SoundFile.defaultSoundFile.clip; // Fallback to default // bind these together obj.SetHotspot(hotspot, true); // with override color etc obj.LaunchNewClip(clip, playAudio: startPlayback); } public void Bind(SoundMarker obj, SoundFile sf, bool reloadSoundClips) { // bind these obj.hotspot.Set(sf.filename); obj.LaunchNewClip(sf.clip); // When a new binding occurs, we SHOULD refresh the loaded sound clips // if (reloadSoundClips) { LoadSoundClipsExclusivelyForCurrentLayout(() => { }); } if (reloadSoundClips && layout.onDemandActive) { RefreshLoadStateForSoundMarkers(MainController.soundMarkers, () => { }); } } // ================= // LAYOUT METHODS // Directory for save files public int NextLayoutId() { var lIds = AllLayouts().Select((l) => { return l.id; }); if (lIds.Count() == 0) return 0; return lIds.Max() + 1; } public int NearestLayoutId(int to) { (int, int) closest = (0, int.MaxValue); foreach (var l in AllLayouts()) { int diff = Math.Abs(l.id - to); if (diff < int.MaxValue) { closest = (l.id, diff); } } return closest.Item1; } public void DuplicateLayout(Layout layout) { Debug.Log("DuplicateLayout: " + layout.filename); // to duplicate, take all data of the current layout, but overwrite the id // to the next available var newLayout = layout; newLayout.id = NextLayoutId(); newLayout.Save(); currentLayoutId = newLayout.id; } public void DeleteLayout(Layout layout) { // Remove the layout from hdd, then select the closest layout to load DeleteLayoutsWith(id: layout.id); // Order dependent, the nearest layout is derived from disk currentLayoutId = NearestLayoutId(to: layout.id); } // ILayoutDelegate public SoundFile GetSoundFileFromSoundID(string soundID) { if (soundID != null && soundDictionary.TryGetValue(soundID, out SoundFile sf)) { return sf; } return SoundFile.defaultSoundFile; } public IEnumerable<SoundMarker> SoundMarkersUsingSoundFileID(string soundFileID, string hotspotIDToExclude = null) { return hotspotIDToExclude == null ? MainController.soundMarkers.Where(marker => marker.hotspot.soundID == soundFileID) : MainController.soundMarkers.Where(marker => marker.hotspot.id != hotspotIDToExclude && marker.hotspot.soundID == soundFileID); } // ============ // IO METHODS] private static Regex jsonRegex = new Regex("json$"); // Ends in json private static string[] jsonFiles { get { return Directory.GetFiles(Layout.saveDirectory).Where(f => jsonRegex.IsMatch(f)).ToArray(); } } private static Layout LayoutFromFile(string filename) { // IO is risky business. Let's not make assumptions try { string dataAsJson = File.ReadAllText(filename); var l = JsonUtility.FromJson<Layout>(dataAsJson); l.filename = filename; // filename is not guaranteed same, so we store it on load return l; } catch (Exception e) { Debug.Log("failed to load layout: " + e); return null; } } public static Layout LayoutWithId(int LayoutID) { var layouts = AllLayouts(); var withID = layouts.Where( l => { return l.id == LayoutID; } ); if (withID.Count() < 1) { Debug.LogError(string.Format("There is no file with the id {}.", LayoutID)); throw new Exception(string.Format("There is no file with the id {}.", LayoutID)); } if (withID.Count() > 1) { Debug.LogError(string.Format("There are multiple files with id: {}.", LayoutID)); throw new Exception(string.Format("There are multiple files with id: {}.", LayoutID)); } // Nice, exactly one return withID.First(); } public static List<Layout> AllLayouts() { List<Layout> lays = new List<Layout>(); foreach (var filename in jsonFiles) { Layout l = LayoutFromFile(filename); if (l != null) lays.Add(l); } return lays; } public void LoadCurrentLayout() { // Try to load a single layout with the current id // If anything goes wrong, make a new layout with the next valid id try { this.layout = LayoutWithId(currentLayoutId); } catch { Debug.LogError("FAILED to create layout with currentLayoutId: " + currentLayoutId); // Create a new layout instead this.currentLayoutId = NextLayoutId(); this.layout = new Layout(currentLayoutId); this.layout.Save(); } // Set appropriate references layout.layoutDelegate = this; layout.SetHotspotDelegates(); layoutManagerDelegate?.LayoutManagerLoadedNewLayout(this, this.layout); } private static void DeleteLayoutsWith(int id) { // observe every file for any with the correct id foreach (var filename in jsonFiles) { Layout l = LayoutFromFile(filename); if (l.id != id) continue; // Must have the same id now File.Delete(filename); } } // Load all Audio File's into the SoundFile dictionary public void LoadSoundMetaFiles(Action completion) { // Make sure all 'audio files on disk' have meta files SoundFile.CreateNewMetas(); // Populate the SoundFile dictionary int numLoaded = 0; Dictionary<string, SoundFile> sfDict = this.soundDictionary; foreach (var filename in SoundFile.metaFiles) { SoundFile newSoundFile = SoundFile.ReadFromMeta(filename); // If the SoundFile has already been loaded, don't reload it if (sfDict.TryGetValue(newSoundFile.filename, out SoundFile sf)) { if (sf.loadState == LoadState.Success) { ++numLoaded; } continue; } newSoundFile.loadState = LoadState.NotLoaded; sfDict[newSoundFile.filename] = newSoundFile; } layoutManagerDelegate?.LayoutManagerLoadedAudioClipsChanged(this, hotspotCount: layout != null ? layout.hotspots.Count : 0); // Debug.Log("Reloaded Metafiles... " + numLoaded + " SoundClip(s) are loaded. " // + ( SoundFile.metaFiles.Count() - numLoaded ) + " NOT loaded."); completion(); } // - - - - - - - - - - - - #region IOnDemandLoadingDelegate public void OnDemandLoadingLoadedAudioClipsChanged(AudioClipLoadingManager manager) { layoutManagerDelegate?.LayoutManagerLoadedAudioClipsChanged(this, hotspotCount: this.layout != null ? this.layout.hotspots.Count : 0); } public void StartCoroutineOn(IEnumerator e) { layoutManagerDelegate?.StartCoroutineOn(e); } #endregion public void LoadClipInSoundFile(SoundFile soundFile, System.Action<SoundFile> completion) { onDemandLoadingManager.LoadClipInSoundFile(soundFile, completion); } public void UnloadSoundMarkerAndSyncedClips(SoundMarker marker, IEnumerable<SoundMarker> syncedMarkers) { onDemandLoadingManager.UnloadSoundMarkerAndSyncedClips(marker, syncedMarkers); } public void LoadSoundMarkerAndSyncedClips(SoundMarker marker, Action<HashSet<SoundMarker>> completion) { onDemandLoadingManager.LoadSoundMarkerAndSyncedClips(marker, this.layout, completion); } public void RefreshLoadStateForSoundMarkers(List<SoundMarker> markers, Action completion) { onDemandLoadingManager.RefreshLoadStateForSoundMarkers(markers, this.layout, completion); } public void LoadAllAudioClipsIntoMemory(List<SoundMarker> markers, Action completion) { onDemandLoadingManager.LoadAllAudioClipsIntoMemory(markers, this.layout, completion); } public void ReloadSoundFiles(Action completion) { // LoadSoundFiles(completion); LoadSoundMetaFiles(completion); } public List<SoundFile> AllSoundFiles() { return soundDictionary.Values.ToList(); } public LayoutManager() { // load the latest scene from memory or create new save soundDictionary = new Dictionary<string, SoundFile>(); soundDictionary[SoundFile.DEFAULT_CLIP] = SoundFile.defaultSoundFile; onDemandLoadingManager.setDelegate(this); } } }
#region File Description //----------------------------------------------------------------------------- // PlatformerGame.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion using System; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Input.Touch; using Penumbra; namespace Platformer2D { /// <summary> /// This is the main type for your game /// </summary> public class PlatformerGame : Microsoft.Xna.Framework.Game { // Resources for drawing. private GraphicsDeviceManager graphics; private PenumbraComponent penumbra; private SpriteBatch spriteBatch; Vector2 baseScreenSize = new Vector2(800, 480); private Matrix globalTransformation; // Global content. private SpriteFont hudFont; private Texture2D winOverlay; private Texture2D loseOverlay; private Texture2D diedOverlay; // Meta-level game state. private int levelIndex = -1; private Level level; private bool wasContinuePressed; // When the time remaining is less than the warning time, it blinks on the hud private static readonly TimeSpan WarningTime = TimeSpan.FromSeconds(30); // We store our input states so that we only poll once per frame, // then we use the same input state wherever needed private GamePadState gamePadState; private KeyboardState keyboardState; private TouchCollection touchState; private AccelerometerState accelerometerState; private VirtualGamePad virtualGamePad; // The number of levels in the Levels directory of our content. We assume that // levels in our content are 0-based and that all numbers under this constant // have a level file present. This allows us to not need to check for the file // or handle exceptions, both of which can add unnecessary time to level loading. private const int numberOfLevels = 3; public PlatformerGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; #if WINDOWS_PHONE TargetElapsedTime = TimeSpan.FromTicks(333333); #endif graphics.IsFullScreen = false; graphics.PreferredBackBufferWidth = 1280; graphics.PreferredBackBufferHeight = 720; graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight; Accelerometer.Initialize(); // Create our lighting component and register it as a service so that subsystems can access it. penumbra = new PenumbraComponent(this) { AmbientColor = new Color(new Vector3(0.1f)) }; Services.AddService(penumbra); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // Load fonts hudFont = Content.Load<SpriteFont>("Fonts/Hud"); // Load overlay textures winOverlay = Content.Load<Texture2D>("Overlays/you_win"); loseOverlay = Content.Load<Texture2D>("Overlays/you_lose"); diedOverlay = Content.Load<Texture2D>("Overlays/you_died"); //Work out how much we need to scale our graphics to fill the screen float horScaling = GraphicsDevice.PresentationParameters.BackBufferWidth / baseScreenSize.X; float verScaling = GraphicsDevice.PresentationParameters.BackBufferHeight / baseScreenSize.Y; Vector3 screenScalingFactor = new Vector3(horScaling, verScaling, 1); globalTransformation = Matrix.CreateScale(screenScalingFactor); virtualGamePad = new VirtualGamePad(baseScreenSize, globalTransformation, Content.Load<Texture2D>("Sprites/VirtualControlArrow")); //Known issue that you get exceptions if you use Media PLayer while connected to your PC //See http://social.msdn.microsoft.com/Forums/en/windowsphone7series/thread/c8a243d2-d360-46b1-96bd-62b1ef268c66 //Which means its impossible to test this from VS. //So we have to catch the exception and throw it away try { MediaPlayer.IsRepeating = true; MediaPlayer.Play(Content.Load<Song>("Sounds/Music")); } catch { } // Load penumbra penumbra.Initialize(); penumbra.Transform = globalTransformation; LoadNextLevel(); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Handle polling for our input and handling high-level input HandleInput(gameTime); // update our level, passing down the GameTime along with all of our input states level.Update(gameTime, keyboardState, gamePadState, accelerometerState, Window.CurrentOrientation); if (level.Player.Velocity != Vector2.Zero) virtualGamePad.NotifyPlayerIsMoving(); base.Update(gameTime); } private void HandleInput(GameTime gameTime) { // get all of our input states keyboardState = Keyboard.GetState(); touchState = TouchPanel.GetState(); gamePadState = virtualGamePad.GetState(touchState, GamePad.GetState(PlayerIndex.One)); accelerometerState = Accelerometer.GetState(); #if !NETFX_CORE // Exit the game when back is pressed. if (gamePadState.Buttons.Back == ButtonState.Pressed) Exit(); #endif bool continuePressed = keyboardState.IsKeyDown(Keys.Space) || gamePadState.IsButtonDown(Buttons.A) || touchState.AnyTouch(); // Perform the appropriate action to advance the game and // to get the player back to playing. if (!wasContinuePressed && continuePressed) { if (!level.Player.IsAlive) { level.StartNewLife(); } else if (level.TimeRemaining == TimeSpan.Zero) { if (level.ReachedExit) LoadNextLevel(); else ReloadCurrentLevel(); } } wasContinuePressed = continuePressed; virtualGamePad.Update(gameTime); } private void LoadNextLevel() { // move to the next level levelIndex = (levelIndex + 1) % numberOfLevels; // Unloads the content for the current level before loading the next one. if (level != null) level.Dispose(); // Load the level. string levelPath = string.Format("Content/Levels/{0}.txt", levelIndex); using (Stream fileStream = TitleContainer.OpenStream(levelPath)) level = new Level(Services, fileStream, levelIndex); } private void ReloadCurrentLevel() { --levelIndex; LoadNextLevel(); } /// <summary> /// Draws the game from background to foreground. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { // Everything after this call will be affected by the lighting system. penumbra.BeginDraw(); graphics.GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null,null, globalTransformation); level.Draw(gameTime, spriteBatch); spriteBatch.End(); // Draw the actual lit scene. penumbra.Draw(gameTime); // Draw stuff that is not affected by lighting (UI, etc). spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, null, globalTransformation); DrawHud(); spriteBatch.End(); base.Draw(gameTime); } private void DrawHud() { Rectangle titleSafeArea = GraphicsDevice.Viewport.TitleSafeArea; Vector2 hudLocation = new Vector2(titleSafeArea.X, titleSafeArea.Y); //Vector2 center = new Vector2(titleSafeArea.X + titleSafeArea.Width / 2.0f, // titleSafeArea.Y + titleSafeArea.Height / 2.0f); Vector2 center = new Vector2(baseScreenSize.X / 2, baseScreenSize.Y / 2); // Draw time remaining. Uses modulo division to cause blinking when the // player is running out of time. string timeString = "TIME: " + level.TimeRemaining.Minutes.ToString("00") + ":" + level.TimeRemaining.Seconds.ToString("00"); Color timeColor; if (level.TimeRemaining > WarningTime || level.ReachedExit || (int)level.TimeRemaining.TotalSeconds % 2 == 0) { timeColor = Color.Yellow; } else { timeColor = Color.Red; } DrawShadowedString(hudFont, timeString, hudLocation, timeColor); // Draw score float timeHeight = hudFont.MeasureString(timeString).Y; DrawShadowedString(hudFont, "SCORE: " + level.Score.ToString(), hudLocation + new Vector2(0.0f, timeHeight * 1.2f), Color.Yellow); // Determine the status overlay message to show. Texture2D status = null; if (level.TimeRemaining == TimeSpan.Zero) { if (level.ReachedExit) { status = winOverlay; } else { status = loseOverlay; } } else if (!level.Player.IsAlive) { status = diedOverlay; } if (status != null) { // Draw status message. Vector2 statusSize = new Vector2(status.Width, status.Height); spriteBatch.Draw(status, center - statusSize / 2, Color.White); } if (touchState.IsConnected) virtualGamePad.Draw(spriteBatch); } private void DrawShadowedString(SpriteFont font, string value, Vector2 position, Color color) { spriteBatch.DrawString(font, value, position + new Vector2(1.0f, 1.0f), Color.Black); spriteBatch.DrawString(font, value, position, color); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Xml.Linq; using Microsoft.Extensions.ProjectModel.Utilities; using NuGet.Frameworks; namespace Microsoft.Extensions.ProjectModel.Resolution { public class FrameworkReferenceResolver { // FrameworkConstants doesn't have dnx46 yet private static readonly NuGetFramework Dnx46 = new NuGetFramework( FrameworkConstants.FrameworkIdentifiers.Dnx, new Version(4, 6)); private readonly IDictionary<NuGetFramework, FrameworkInformation> _cache = new Dictionary<NuGetFramework, FrameworkInformation>(); private static readonly IDictionary<NuGetFramework, NuGetFramework[]> _aliases = new Dictionary<NuGetFramework, NuGetFramework[]> { { FrameworkConstants.CommonFrameworks.Dnx451, new [] { FrameworkConstants.CommonFrameworks.Net451 } }, { Dnx46, new [] { FrameworkConstants.CommonFrameworks.Net46 } } }; public FrameworkReferenceResolver(string referenceAssembliesPath) { ReferenceAssembliesPath = referenceAssembliesPath; } public string ReferenceAssembliesPath { get; } public bool TryGetAssembly(string name, NuGetFramework targetFramework, out string path, out Version version) { path = null; version = null; var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation); if (information == null || !information.Exists) { return false; } lock (information.Assemblies) { AssemblyEntry entry; if (information.Assemblies.TryGetValue(name, out entry)) { if (string.IsNullOrEmpty(entry.Path)) { entry.Path = GetAssemblyPath(information.SearchPaths, name); } if (!string.IsNullOrEmpty(entry.Path) && entry.Version == null) { // This code path should only run on mono entry.Version = VersionUtility.GetAssemblyVersion(entry.Path).Version; } path = entry.Path; version = entry.Version; } } return !string.IsNullOrEmpty(path); } public bool IsInstalled(NuGetFramework targetFramework) { var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation); return information?.Exists == true; } public string GetFrameworkRedistListPath(NuGetFramework targetFramework) { var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation); if (information == null || !information.Exists) { return null; } return information.RedistListPath; } private FrameworkInformation GetFrameworkInformation(NuGetFramework targetFramework) { string referenceAssembliesPath = ReferenceAssembliesPath; if (string.IsNullOrEmpty(referenceAssembliesPath)) { return null; } NuGetFramework[] candidates; if (_aliases.TryGetValue(targetFramework, out candidates)) { foreach (var framework in candidates) { var information = GetFrameworkInformation(framework); if (information != null) { return information; } } return null; } else { return GetFrameworkInformation(targetFramework, referenceAssembliesPath); } } private static FrameworkInformation GetFrameworkInformation(NuGetFramework targetFramework, string referenceAssembliesPath) { // Check for legacy frameworks if (targetFramework.IsDesktop() && targetFramework.Version <= new Version(3, 5)) { return GetLegacyFrameworkInformation(targetFramework, referenceAssembliesPath); } var basePath = Path.Combine(referenceAssembliesPath, targetFramework.Framework, "v" + GetDisplayVersion(targetFramework)); if (!string.IsNullOrEmpty(targetFramework.Profile)) { basePath = Path.Combine(basePath, "Profile", targetFramework.Profile); } var version = new DirectoryInfo(basePath); if (!version.Exists) { return null; } return GetFrameworkInformation(version, targetFramework); } private static FrameworkInformation GetLegacyFrameworkInformation(NuGetFramework targetFramework, string referenceAssembliesPath) { var frameworkInfo = new FrameworkInformation(); // Always grab .NET 2.0 data var searchPaths = new List<string>(); var net20Dir = Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "Microsoft.NET", "Framework", "v2.0.50727"); if (!Directory.Exists(net20Dir)) { return null; } // Grab reference assemblies first, if present for this framework if (targetFramework.Version.Major == 3) { // Most specific first (i.e. 3.5) if (targetFramework.Version.Minor == 5) { var refAsms35Dir = Path.Combine(referenceAssembliesPath, "v3.5"); if (!string.IsNullOrEmpty(targetFramework.Profile)) { // The 3.5 Client Profile assemblies ARE in .NETFramework... it's weird. refAsms35Dir = Path.Combine(referenceAssembliesPath, ".NETFramework", "v3.5", "Profile", targetFramework.Profile); } if (Directory.Exists(refAsms35Dir)) { searchPaths.Add(refAsms35Dir); } } // Always search the 3.0 reference assemblies if (string.IsNullOrEmpty(targetFramework.Profile)) { // a) 3.0 didn't have profiles // b) When using a profile, we don't want to fall back to 3.0 or 2.0 var refAsms30Dir = Path.Combine(referenceAssembliesPath, "v3.0"); if (Directory.Exists(refAsms30Dir)) { searchPaths.Add(refAsms30Dir); } } } // .NET 2.0 reference assemblies go last (but only if there's no profile in the TFM) if (string.IsNullOrEmpty(targetFramework.Profile)) { searchPaths.Add(net20Dir); } frameworkInfo.Exists = true; frameworkInfo.Path = searchPaths.First(); frameworkInfo.SearchPaths = searchPaths; // Load the redist list in reverse order (most general -> most specific) for (int i = searchPaths.Count - 1; i >= 0; i--) { var dir = new DirectoryInfo(searchPaths[i]); if (dir.Exists) { PopulateFromRedistList(dir, frameworkInfo); } } if (string.IsNullOrEmpty(frameworkInfo.Name)) { frameworkInfo.Name = SynthesizeFrameworkFriendlyName(targetFramework); } return frameworkInfo; } private static string SynthesizeFrameworkFriendlyName(NuGetFramework targetFramework) { // Names are not present in the RedistList.xml file for older frameworks or on Mono // We do some custom version string rendering to match how net40 is rendered (.NET Framework 4) if (targetFramework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.Net)) { string versionString = targetFramework.Version.Minor == 0 ? targetFramework.Version.Major.ToString() : GetDisplayVersion(targetFramework).ToString(); string profileString = string.IsNullOrEmpty(targetFramework.Profile) ? string.Empty : $" {targetFramework.Profile} Profile"; return ".NET Framework " + versionString + profileString; } return targetFramework.ToString(); } private static FrameworkInformation GetFrameworkInformation(DirectoryInfo directory, NuGetFramework targetFramework) { var frameworkInfo = new FrameworkInformation(); frameworkInfo.Exists = true; frameworkInfo.Path = directory.FullName; frameworkInfo.SearchPaths = new[] { frameworkInfo.Path, Path.Combine(frameworkInfo.Path, "Facades") }; PopulateFromRedistList(directory, frameworkInfo); if (string.IsNullOrEmpty(frameworkInfo.Name)) { frameworkInfo.Name = SynthesizeFrameworkFriendlyName(targetFramework); } return frameworkInfo; } private static void PopulateFromRedistList(DirectoryInfo directory, FrameworkInformation frameworkInfo) { // The redist list contains the list of assemblies for this target framework string redistList = Path.Combine(directory.FullName, "RedistList", "FrameworkList.xml"); if (File.Exists(redistList)) { frameworkInfo.RedistListPath = redistList; using (var stream = File.OpenRead(redistList)) { var frameworkList = XDocument.Load(stream); // On mono, the RedistList.xml has an entry pointing to the TargetFrameworkDirectory // It basically uses the GAC as the reference assemblies for all .NET framework // profiles var targetFrameworkDirectory = frameworkList.Root.Attribute("TargetFrameworkDirectory")?.Value; if (!string.IsNullOrEmpty(targetFrameworkDirectory)) { // For some odd reason, the paths are actually listed as \ so normalize them here targetFrameworkDirectory = targetFrameworkDirectory.Replace('\\', Path.DirectorySeparatorChar); // The specified path is the relative path from the RedistList.xml itself var resovledPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(redistList), targetFrameworkDirectory)); // Update the path to the framework frameworkInfo.Path = resovledPath; PopulateAssemblies(frameworkInfo.Assemblies, resovledPath); PopulateAssemblies(frameworkInfo.Assemblies, Path.Combine(resovledPath, "Facades")); } else { foreach (var e in frameworkList.Root.Elements()) { var assemblyName = e.Attribute("AssemblyName").Value; var version = e.Attribute("Version")?.Value; var entry = new AssemblyEntry(); entry.Version = version != null ? Version.Parse(version) : null; frameworkInfo.Assemblies[assemblyName] = entry; } } var nameAttribute = frameworkList.Root.Attribute("Name"); frameworkInfo.Name = nameAttribute == null ? null : nameAttribute.Value; } } } private static void PopulateAssemblies(IDictionary<string, AssemblyEntry> assemblies, string path) { if (!Directory.Exists(path)) { return; } foreach (var assemblyPath in Directory.GetFiles(path, "*.dll")) { var name = Path.GetFileNameWithoutExtension(assemblyPath); var entry = new AssemblyEntry(); entry.Path = assemblyPath; assemblies[name] = entry; } } private static string GetAssemblyPath(IEnumerable<string> basePaths, string assemblyName) { foreach (var basePath in basePaths) { var assemblyPath = Path.Combine(basePath, assemblyName + ".dll"); if (File.Exists(assemblyPath)) { return assemblyPath; } } return null; } private static Version GetDisplayVersion(NuGetFramework framework) { // Fix the target framework version due to https://github.com/NuGet/Home/issues/1600, this is relevant // when looking up in the reference assembly folder return new FrameworkName(framework.DotNetFrameworkName).Version; } } }
#region License // // Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using FluentMigrator.Builders; using FluentMigrator.Builders.Create.Column; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure; using FluentMigrator.Model; using FluentMigrator.Oracle; using FluentMigrator.SqlServer; using Moq; using NUnit.Framework; using Shouldly; namespace FluentMigrator.Tests.Unit.Builders.Create { [TestFixture] public class CreateColumnExpressionBuilderTests { [Test] public void CallingOnTableSetsTableName() { var expressionMock = new Mock<CreateColumnExpression>(); var contextMock = new Mock<IMigrationContext>(); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.OnTable("Bacon"); expressionMock.VerifySet(x => x.TableName = "Bacon"); } [Test] public void CallingAsAnsiStringSetsColumnDbTypeToAnsiString() { VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString()); } [Test] public void CallingAsAnsiStringWithSizeSetsColumnDbTypeToAnsiString() { VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString(42)); } [Test] public void CallingAsAnsiStringWithSizeSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(42, b => b.AsAnsiString(42)); } [Test] public void CallingAsBinarySetsColumnDbTypeToBinary() { VerifyColumnDbType(DbType.Binary, b => b.AsBinary()); } [Test] public void CallingAsBinaryWithSizeSetsColumnDbTypeToBinary() { VerifyColumnDbType(DbType.Binary, b => b.AsBinary(42)); } [Test] public void CallingAsBinaryWithSizeSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(42, b => b.AsBinary(42)); } [Test] public void CallingAsBooleanSetsColumnDbTypeToBoolean() { VerifyColumnDbType(DbType.Boolean, b => b.AsBoolean()); } [Test] public void CallingAsByteSetsColumnDbTypeToByte() { VerifyColumnDbType(DbType.Byte, b => b.AsByte()); } [Test] public void CallingAsCurrencySetsColumnDbTypeToCurrency() { VerifyColumnDbType(DbType.Currency, b => b.AsCurrency()); } [Test] public void CallingAsDateSetsColumnDbTypeToDate() { VerifyColumnDbType(DbType.Date, b => b.AsDate()); } [Test] public void CallingAsDateTimeSetsColumnDbTypeToDateTime() { VerifyColumnDbType(DbType.DateTime, b => b.AsDateTime()); } [Test] public void CallingAsDateTime2SetsColumnDbTypeToDateTime2() { VerifyColumnDbType(DbType.DateTime2, b => b.AsDateTime2()); } [Test] public void CallingAsDateTimeOffsetSetsColumnDbTypeToDateTimeOffset() { VerifyColumnDbType(DbType.DateTimeOffset, b => b.AsDateTimeOffset()); } [Test] public void CallingAsDecimalSetsColumnDbTypeToDecimal() { VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal()); } [Test] public void CallingAsDecimalWithSizeAndPrecisionSetsColumnDbTypeToDecimal() { VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal(1, 2)); } [Test] public void CallingAsDecimalStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(1, b => b.AsDecimal(1, 2)); } [Test] public void CallingAsDecimalStringSetsColumnPrecisionToSpecifiedValue() { VerifyColumnPrecision(2, b => b.AsDecimal(1, 2)); } [Test] public void CallingAsDoubleSetsColumnDbTypeToDouble() { VerifyColumnDbType(DbType.Double, b => b.AsDouble()); } [Test] public void CallingAsGuidSetsColumnDbTypeToGuid() { VerifyColumnDbType(DbType.Guid, b => b.AsGuid()); } [Test] public void CallingAsFixedLengthStringSetsColumnDbTypeToStringFixedLength() { VerifyColumnDbType(DbType.StringFixedLength, e => e.AsFixedLengthString(255)); } [Test] public void CallingAsFixedLengthStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsFixedLengthString(255)); } [Test] public void CallingAsFixedLengthAnsiStringSetsColumnDbTypeToAnsiStringFixedLength() { VerifyColumnDbType(DbType.AnsiStringFixedLength, b => b.AsFixedLengthAnsiString(255)); } [Test] public void CallingAsFixedLengthAnsiStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255)); } [Test] public void CallingAsFloatSetsColumnDbTypeToSingle() { VerifyColumnDbType(DbType.Single, b => b.AsFloat()); } [Test] public void CallingAsInt16SetsColumnDbTypeToInt16() { VerifyColumnDbType(DbType.Int16, b => b.AsInt16()); } [Test] public void CallingAsInt32SetsColumnDbTypeToInt32() { VerifyColumnDbType(DbType.Int32, b => b.AsInt32()); } [Test] public void CallingAsInt64SetsColumnDbTypeToInt64() { VerifyColumnDbType(DbType.Int64, b => b.AsInt64()); } [Test] public void CallingAsStringSetsColumnDbTypeToString() { VerifyColumnDbType(DbType.String, b => b.AsString()); } [Test] public void CallingAsStringWithLengthSetsColumnDbTypeToString() { VerifyColumnDbType(DbType.String, b => b.AsString(255)); } [Test] public void CallingAsStringSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255)); } [Test] public void CallingAsAnsiStringWithCollation() { VerifyColumnCollation(Generators.GeneratorTestHelper.TestColumnCollationName, b => b.AsAnsiString(Generators.GeneratorTestHelper.TestColumnCollationName)); } [Test] public void CallingAsFixedLengthAnsiStringWithCollation() { VerifyColumnCollation(Generators.GeneratorTestHelper.TestColumnCollationName, b => b.AsFixedLengthAnsiString(255, Generators.GeneratorTestHelper.TestColumnCollationName)); } [Test] public void CallingAsFixedLengthStringWithCollation() { VerifyColumnCollation(Generators.GeneratorTestHelper.TestColumnCollationName, b => b.AsFixedLengthString(255, Generators.GeneratorTestHelper.TestColumnCollationName)); } [Test] public void CallingAsStringWithCollation() { VerifyColumnCollation(Generators.GeneratorTestHelper.TestColumnCollationName, b => b.AsString(Generators.GeneratorTestHelper.TestColumnCollationName)); } [Test] public void CallingAsTimeSetsColumnDbTypeToTime() { VerifyColumnDbType(DbType.Time, b => b.AsTime()); } [Test] public void CallingAsXmlSetsColumnDbTypeToXml() { VerifyColumnDbType(DbType.Xml, b => b.AsXml()); } [Test] public void CallingAsXmlWithSizeSetsColumnDbTypeToXml() { VerifyColumnDbType(DbType.Xml, b => b.AsXml(255)); } [Test] public void CallingAsXmlSetsColumnSizeToSpecifiedValue() { VerifyColumnSize(255, b => b.AsXml(255)); } [Test] public void CallingAsCustomSetsTypeToNullAndSetsCustomType() { VerifyColumnProperty(c => c.Type = null, b => b.AsCustom("Test")); VerifyColumnProperty(c => c.CustomType = "Test", b => b.AsCustom("Test")); } [Test] public void CallingWithDefaultValueSetsDefaultValue() { const int value = 42; var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var contextMock = new Mock<IMigrationContext>(); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.WithDefaultValue(value); columnMock.VerifySet(c => c.DefaultValue = value); } [Test] public void CallingWithDefaultSetsDefaultValue() { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var contextMock = new Mock<IMigrationContext>(); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.WithDefault(SystemMethods.NewGuid); columnMock.VerifySet(c => c.DefaultValue = SystemMethods.NewGuid); } [Test] public void CallingForeignKeySetsIsForeignKeyToTrue() { VerifyColumnProperty(c => c.IsForeignKey = true, b => b.ForeignKey()); } [Test] public void CallingIdentitySetsIsIdentityToTrue() { VerifyColumnProperty(c => c.IsIdentity = true, b => b.Identity()); } [Test] public void CallingSeededIdentitySetsAdditionalProperties() { var contextMock = new Mock<IMigrationContext>(); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.Identity(23, 44); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(SqlServerExtensions.IdentitySeed, 23)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(SqlServerExtensions.IdentityIncrement, 44)); } [Test] public void CallingSeededLongIdentitySetsAdditionalProperties() { var contextMock = new Mock<IMigrationContext>(); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.Identity(long.MaxValue, 44); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(SqlServerExtensions.IdentitySeed, long.MaxValue)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(SqlServerExtensions.IdentityIncrement, 44)); } [Test] public void CallingGeneratedIdentitySetsAdditionalProperties() { var contextMock = new Mock<IMigrationContext>(); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.Identity(OracleGenerationType.Always, startWith: 0, incrementBy: 1); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityGeneration, OracleGenerationType.Always)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityStartWith, 0)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityIncrementBy, 1)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityMinValue, null)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityMaxValue, null)); } [Test] public void CallingGeneratedLongIdentitySetsAdditionalProperties() { var contextMock = new Mock<IMigrationContext>(); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.Identity(OracleGenerationType.Always, startWith: 0L, incrementBy: 1); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityGeneration, OracleGenerationType.Always)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityStartWith, 0L)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityIncrementBy, 1)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityMinValue, null)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityMaxValue, null)); } [Test] public void CallingGeneratedIdentityMinMaxSetsAdditionalProperties() { var contextMock = new Mock<IMigrationContext>(); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.Identity(OracleGenerationType.Always, startWith: 0, incrementBy: 1, minValue: 0, long.MaxValue); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityGeneration, OracleGenerationType.Always)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityStartWith, 0L)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityIncrementBy, 1)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityMinValue, 0L)); columnMock.Object.AdditionalFeatures.ShouldContain( new KeyValuePair<string, object>(OracleExtensions.IdentityMaxValue, long.MaxValue)); } [Test] public void CallingIndexedCallsHelperWithNullIndexName() { VerifyColumnHelperCall(c => c.Indexed(), h => h.Indexed(null)); } [Test] public void CallingIndexedNamedCallsHelperWithName() { VerifyColumnHelperCall(c => c.Indexed("MyIndexName"), h => h.Indexed("MyIndexName")); } [Test] public void CallingPrimaryKeySetsIsPrimaryKeyToTrue() { VerifyColumnProperty(c => c.IsPrimaryKey = true, b => b.PrimaryKey()); } [Test] public void CallingReferencesAddsNewForeignKeyExpressionToContext() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupGet(x => x.TableName).Returns("Bacon"); expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.ReferencedBy("fk_foo", "FooTable", "BarColumn"); collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>( fk => fk.ForeignKey.Name == "fk_foo" && fk.ForeignKey.ForeignTable == "FooTable" && fk.ForeignKey.ForeignColumns.Contains("BarColumn") && fk.ForeignKey.ForeignColumns.Count == 1 && fk.ForeignKey.PrimaryTable == "Bacon" && fk.ForeignKey.PrimaryColumns.Contains("BaconId") && fk.ForeignKey.PrimaryColumns.Count == 1 ))); contextMock.VerifyGet(x => x.Expressions); } [Test] public void CallingReferencedByAddsNewForeignKeyExpressionToContext() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupGet(x => x.TableName).Returns("Bacon"); expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.ReferencedBy("fk_foo", "FooTable", "BarColumn"); collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>( fk => fk.ForeignKey.Name == "fk_foo" && fk.ForeignKey.ForeignTable == "FooTable" && fk.ForeignKey.ForeignColumns.Contains("BarColumn") && fk.ForeignKey.ForeignColumns.Count == 1 && fk.ForeignKey.PrimaryTable == "Bacon" && fk.ForeignKey.PrimaryColumns.Contains("BaconId") && fk.ForeignKey.PrimaryColumns.Count == 1 ))); contextMock.VerifyGet(x => x.Expressions); } [Test] public void CallingForeignKeyAddsNewForeignKeyExpressionToContext() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupGet(x => x.TableName).Returns("Bacon"); expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.ForeignKey("fk_foo", "FooTable", "BarColumn"); contextMock.VerifyGet(x => x.Expressions); collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>( fk => fk.ForeignKey.Name == "fk_foo" && fk.ForeignKey.PrimaryTable == "FooTable" && fk.ForeignKey.PrimaryColumns.Contains("BarColumn") && fk.ForeignKey.PrimaryColumns.Count == 1 && fk.ForeignKey.ForeignTable == "Bacon" && fk.ForeignKey.ForeignColumns.Contains("BaconId") && fk.ForeignKey.ForeignColumns.Count == 1 ))); } [Test] public void CallingForeignKeyWithCustomSchemaAddsNewForeignKeyExpressionToContext() { var collectionMock = new Mock<ICollection<IMigrationExpression>>(); var contextMock = new Mock<IMigrationContext>(); contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object); var columnMock = new Mock<ColumnDefinition>(); columnMock.SetupGet(x => x.Name).Returns("BaconId"); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupGet(x => x.SchemaName).Returns("FooSchema"); expressionMock.SetupGet(x => x.TableName).Returns("Bacon"); expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.ForeignKey("fk_foo", "BarSchema", "BarTable", "BarColumn"); contextMock.VerifyGet(x => x.Expressions); collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>( fk => fk.ForeignKey.Name == "fk_foo" && fk.ForeignKey.PrimaryTableSchema == "BarSchema" && fk.ForeignKey.PrimaryTable == "BarTable" && fk.ForeignKey.PrimaryColumns.Contains("BarColumn") && fk.ForeignKey.PrimaryColumns.Count == 1 && fk.ForeignKey.ForeignTableSchema == "FooSchema" && fk.ForeignKey.ForeignTable == "Bacon" && fk.ForeignKey.ForeignColumns.Contains("BaconId") && fk.ForeignKey.ForeignColumns.Count == 1 ))); } [TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)] public void CallingOnUpdateSetsOnUpdateOnForeignKeyExpression(Rule rule) { var builder = new CreateColumnExpressionBuilder(null, null) {CurrentForeignKey = new ForeignKeyDefinition()}; builder.OnUpdate(rule); Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule)); Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(Rule.None)); } [TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)] public void CallingOnDeleteSetsOnDeleteOnForeignKeyExpression(Rule rule) { var builder = new CreateColumnExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() }; builder.OnDelete(rule); Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(Rule.None)); Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule)); } [TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)] public void CallingOnDeleteOrUpdateSetsOnUpdateAndOnDeleteOnForeignKeyExpression(Rule rule) { var builder = new CreateColumnExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() }; builder.OnDeleteOrUpdate(rule); Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule)); Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule)); } [Test] public void ColumnHelperSetOnCreation() { var expressionMock = new Mock<CreateColumnExpression>(); var contextMock = new Mock<IMigrationContext>(); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); Assert.IsNotNull(builder.ColumnHelper); } [Test] public void ColumnExpressionBuilderUsesExpressionColumnSchemaAndTableName() { var expressionMock = new Mock<CreateColumnExpression>(); var contextMock = new Mock<IMigrationContext>(); expressionMock.SetupGet(n => n.SchemaName).Returns("Fred"); expressionMock.SetupGet(n => n.TableName).Returns("Flinstone"); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); var builderAsInterface = (IColumnExpressionBuilder)builder; Assert.AreEqual("Fred", builderAsInterface.SchemaName); Assert.AreEqual("Flinstone", builderAsInterface.TableName); } [Test] public void ColumnExpressionBuilderUsesExpressionColumn() { var expressionMock = new Mock<CreateColumnExpression>(); var contextMock = new Mock<IMigrationContext>(); var curColumn = new Mock<ColumnDefinition>().Object; expressionMock.SetupGet(n => n.Column).Returns(curColumn); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); var builderAsInterface = (IColumnExpressionBuilder)builder; Assert.AreSame(curColumn, builderAsInterface.Column); } [Test] public void NullableUsesHelper() { VerifyColumnHelperCall(c => c.Nullable(), h => h.SetNullable(true)); } [Test] public void NotNullableUsesHelper() { VerifyColumnHelperCall(c => c.NotNullable(), h => h.SetNullable(false)); } [Test] public void UniqueUsesHelper() { VerifyColumnHelperCall(c => c.Unique(), h => h.Unique(null)); } [Test] public void NamedUniqueUsesHelper() { VerifyColumnHelperCall(c => c.Unique("asdf"), h => h.Unique("asdf")); } [Test] public void SetExistingRowsUsesHelper() { VerifyColumnHelperCall(c => c.SetExistingRowsTo("test"), h => h.SetExistingRowsTo("test")); } private void VerifyColumnHelperCall(Action<CreateColumnExpressionBuilder> callToTest, System.Linq.Expressions.Expression<Action<ColumnExpressionBuilderHelper>> expectedHelperAction) { var expressionMock = new Mock<CreateColumnExpression>(); var contextMock = new Mock<IMigrationContext>(); var helperMock = new Mock<ColumnExpressionBuilderHelper>(); var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object); builder.ColumnHelper = helperMock.Object; callToTest(builder); helperMock.Verify(expectedHelperAction); } private void VerifyColumnProperty(Action<ColumnDefinition> columnExpression, Action<CreateColumnExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var contextMock = new Mock<IMigrationContext>(); contextMock.SetupGet(mc => mc.Expressions).Returns(new Collection<IMigrationExpression>()); callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object)); columnMock.VerifySet(columnExpression); } private void VerifyColumnDbType(DbType expected, Action<CreateColumnExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var contextMock = new Mock<IMigrationContext>(); callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object)); columnMock.VerifySet(c => c.Type = expected); } private void VerifyColumnSize(int expected, Action<CreateColumnExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var contextMock = new Mock<IMigrationContext>(); callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object)); columnMock.VerifySet(c => c.Size = expected); } private void VerifyColumnPrecision(int expected, Action<CreateColumnExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var contextMock = new Mock<IMigrationContext>(); callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object)); columnMock.VerifySet(c => c.Precision = expected); } private void VerifyColumnCollation(string expected, Action<CreateColumnExpressionBuilder> callToTest) { var columnMock = new Mock<ColumnDefinition>(); var expressionMock = new Mock<CreateColumnExpression>(); expressionMock.SetupProperty(e => e.Column); var expression = expressionMock.Object; expression.Column = columnMock.Object; var contextMock = new Mock<IMigrationContext>(); callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object)); columnMock.VerifySet(c => c.CollationName = expected); } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Debugger.V2.Snippets { using Google.Api.Gax; using Google.Api.Gax.Grpc; using apis = Google.Cloud.Debugger.V2; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; /// <summary>Generated snippets</summary> public class GeneratedController2ClientSnippets { /// <summary>Snippet for RegisterDebuggeeAsync</summary> public async Task RegisterDebuggeeAsync() { // Snippet: RegisterDebuggeeAsync(Debuggee,CallSettings) // Additional: RegisterDebuggeeAsync(Debuggee,CancellationToken) // Create client Controller2Client controller2Client = await Controller2Client.CreateAsync(); // Initialize request argument(s) Debuggee debuggee = new Debuggee(); // Make the request RegisterDebuggeeResponse response = await controller2Client.RegisterDebuggeeAsync(debuggee); // End snippet } /// <summary>Snippet for RegisterDebuggee</summary> public void RegisterDebuggee() { // Snippet: RegisterDebuggee(Debuggee,CallSettings) // Create client Controller2Client controller2Client = Controller2Client.Create(); // Initialize request argument(s) Debuggee debuggee = new Debuggee(); // Make the request RegisterDebuggeeResponse response = controller2Client.RegisterDebuggee(debuggee); // End snippet } /// <summary>Snippet for RegisterDebuggeeAsync</summary> public async Task RegisterDebuggeeAsync_RequestObject() { // Snippet: RegisterDebuggeeAsync(RegisterDebuggeeRequest,CallSettings) // Additional: RegisterDebuggeeAsync(RegisterDebuggeeRequest,CancellationToken) // Create client Controller2Client controller2Client = await Controller2Client.CreateAsync(); // Initialize request argument(s) RegisterDebuggeeRequest request = new RegisterDebuggeeRequest { Debuggee = new Debuggee(), }; // Make the request RegisterDebuggeeResponse response = await controller2Client.RegisterDebuggeeAsync(request); // End snippet } /// <summary>Snippet for RegisterDebuggee</summary> public void RegisterDebuggee_RequestObject() { // Snippet: RegisterDebuggee(RegisterDebuggeeRequest,CallSettings) // Create client Controller2Client controller2Client = Controller2Client.Create(); // Initialize request argument(s) RegisterDebuggeeRequest request = new RegisterDebuggeeRequest { Debuggee = new Debuggee(), }; // Make the request RegisterDebuggeeResponse response = controller2Client.RegisterDebuggee(request); // End snippet } /// <summary>Snippet for ListActiveBreakpointsAsync</summary> public async Task ListActiveBreakpointsAsync() { // Snippet: ListActiveBreakpointsAsync(string,CallSettings) // Additional: ListActiveBreakpointsAsync(string,CancellationToken) // Create client Controller2Client controller2Client = await Controller2Client.CreateAsync(); // Initialize request argument(s) string debuggeeId = ""; // Make the request ListActiveBreakpointsResponse response = await controller2Client.ListActiveBreakpointsAsync(debuggeeId); // End snippet } /// <summary>Snippet for ListActiveBreakpoints</summary> public void ListActiveBreakpoints() { // Snippet: ListActiveBreakpoints(string,CallSettings) // Create client Controller2Client controller2Client = Controller2Client.Create(); // Initialize request argument(s) string debuggeeId = ""; // Make the request ListActiveBreakpointsResponse response = controller2Client.ListActiveBreakpoints(debuggeeId); // End snippet } /// <summary>Snippet for ListActiveBreakpointsAsync</summary> public async Task ListActiveBreakpointsAsync_RequestObject() { // Snippet: ListActiveBreakpointsAsync(ListActiveBreakpointsRequest,CallSettings) // Additional: ListActiveBreakpointsAsync(ListActiveBreakpointsRequest,CancellationToken) // Create client Controller2Client controller2Client = await Controller2Client.CreateAsync(); // Initialize request argument(s) ListActiveBreakpointsRequest request = new ListActiveBreakpointsRequest { DebuggeeId = "", }; // Make the request ListActiveBreakpointsResponse response = await controller2Client.ListActiveBreakpointsAsync(request); // End snippet } /// <summary>Snippet for ListActiveBreakpoints</summary> public void ListActiveBreakpoints_RequestObject() { // Snippet: ListActiveBreakpoints(ListActiveBreakpointsRequest,CallSettings) // Create client Controller2Client controller2Client = Controller2Client.Create(); // Initialize request argument(s) ListActiveBreakpointsRequest request = new ListActiveBreakpointsRequest { DebuggeeId = "", }; // Make the request ListActiveBreakpointsResponse response = controller2Client.ListActiveBreakpoints(request); // End snippet } /// <summary>Snippet for UpdateActiveBreakpointAsync</summary> public async Task UpdateActiveBreakpointAsync() { // Snippet: UpdateActiveBreakpointAsync(string,Breakpoint,CallSettings) // Additional: UpdateActiveBreakpointAsync(string,Breakpoint,CancellationToken) // Create client Controller2Client controller2Client = await Controller2Client.CreateAsync(); // Initialize request argument(s) string debuggeeId = ""; Breakpoint breakpoint = new Breakpoint(); // Make the request UpdateActiveBreakpointResponse response = await controller2Client.UpdateActiveBreakpointAsync(debuggeeId, breakpoint); // End snippet } /// <summary>Snippet for UpdateActiveBreakpoint</summary> public void UpdateActiveBreakpoint() { // Snippet: UpdateActiveBreakpoint(string,Breakpoint,CallSettings) // Create client Controller2Client controller2Client = Controller2Client.Create(); // Initialize request argument(s) string debuggeeId = ""; Breakpoint breakpoint = new Breakpoint(); // Make the request UpdateActiveBreakpointResponse response = controller2Client.UpdateActiveBreakpoint(debuggeeId, breakpoint); // End snippet } /// <summary>Snippet for UpdateActiveBreakpointAsync</summary> public async Task UpdateActiveBreakpointAsync_RequestObject() { // Snippet: UpdateActiveBreakpointAsync(UpdateActiveBreakpointRequest,CallSettings) // Additional: UpdateActiveBreakpointAsync(UpdateActiveBreakpointRequest,CancellationToken) // Create client Controller2Client controller2Client = await Controller2Client.CreateAsync(); // Initialize request argument(s) UpdateActiveBreakpointRequest request = new UpdateActiveBreakpointRequest { DebuggeeId = "", Breakpoint = new Breakpoint(), }; // Make the request UpdateActiveBreakpointResponse response = await controller2Client.UpdateActiveBreakpointAsync(request); // End snippet } /// <summary>Snippet for UpdateActiveBreakpoint</summary> public void UpdateActiveBreakpoint_RequestObject() { // Snippet: UpdateActiveBreakpoint(UpdateActiveBreakpointRequest,CallSettings) // Create client Controller2Client controller2Client = Controller2Client.Create(); // Initialize request argument(s) UpdateActiveBreakpointRequest request = new UpdateActiveBreakpointRequest { DebuggeeId = "", Breakpoint = new Breakpoint(), }; // Make the request UpdateActiveBreakpointResponse response = controller2Client.UpdateActiveBreakpoint(request); // End snippet } } }
// Copyright (c) Microsoft Open Technologies, Inc. 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; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Drawing; using System.IO; using System.Runtime.InteropServices; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using VSLangProj; using IServiceProvider = System.IServiceProvider; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using ErrorHandler = Microsoft.VisualStudio.ErrorHandler; namespace Microsoft.VisualStudio.FSharp.ProjectSystem.Web { internal class VsHierarchyItem { private uint _vsitemid; private IVsHierarchy _hier; private ServiceProvider _serviceProvider; //-------------------------------------------------------------------------------------------- /// <summary> /// Constructor /// </summary> /// <param name="id">Hiearchy item id</param> /// <param name="hier">Hiearchy interface (typically the project)</param> //-------------------------------------------------------------------------------------------- internal VsHierarchyItem(uint id, IVsHierarchy hier) { Debug.Assert(hier != null, "hier cannot be null"); _vsitemid = id; _hier = hier; } internal VsHierarchyItem(IVsHierarchy hier) { Debug.Assert(hier != null, "hier cannot be null"); _vsitemid = VSConstants.VSITEMID_ROOT; _hier = hier; } public override string ToString() { return Name(); } //-------------------------------------------------------------------------------------------- /// <summary> /// Locates the item in the provided hierarchy using the provided moniker /// and return a VsHierarchyItem for it /// </summary> //-------------------------------------------------------------------------------------------- internal static VsHierarchyItem CreateFromMoniker(string moniker, IVsHierarchy hier) { VsHierarchyItem item = null; if (!string.IsNullOrEmpty(moniker) && hier != null) { IVsProject proj = hier as IVsProject; if (proj != null) { int hr; int isFound = 0; uint itemid = VSConstants.VSITEMID_NIL; VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1]; hr = proj.IsDocumentInProject(moniker, out isFound, priority, out itemid); if (ErrorHandler.Succeeded(hr) && isFound != 0 && itemid != VSConstants.VSITEMID_NIL) { item = new VsHierarchyItem(itemid, hier); } } } return item; } //-------------------------------------------------------------------------------------------- /// <summary> /// Item's id which is unique for the hieararchy /// </summary> //-------------------------------------------------------------------------------------------- internal uint VsItemID { get { return _vsitemid; } set { _vsitemid = value; } } //-------------------------------------------------------------------------------------------- /// <summary> /// Read only access to the hierarchy interface /// </summary> //-------------------------------------------------------------------------------------------- internal IVsHierarchy Hierarchy { get { return _hier; } } //-------------------------------------------------------------------------------------------- /// <summary> /// Read only access to the uihierarchy interface /// </summary> //-------------------------------------------------------------------------------------------- public IVsUIHierarchy UIHierarchy() { return _hier as IVsUIHierarchy; } //-------------------------------------------------------------------------------------------- /// <summary> /// Get the root as a VsHierarchyItem /// </summary> //-------------------------------------------------------------------------------------------- internal VsHierarchyItem Root() { return new VsHierarchyItem(VSConstants.VSITEMID_ROOT, _hier); } //-------------------------------------------------------------------------------------------- /// <summary> /// Gets the save name for the item. The save name is the string /// shown in the save and save changes dialog boxes. /// </summary> /// <returns></returns> //-------------------------------------------------------------------------------------------- internal string SaveName() { object o = GetPropHelper(__VSHPROPID.VSHPROPID_SaveName); return (o is string) ? (string)o : string.Empty; } //-------------------------------------------------------------------------------------------- /// <summary> /// Gets the string displayed in the project window for a particular item /// </summary> /// <returns>Display name for item</returns> //-------------------------------------------------------------------------------------------- internal string Caption() { object o = GetPropHelper(__VSHPROPID.VSHPROPID_Caption); return (o is string) ? (string)o : string.Empty; } //-------------------------------------------------------------------------------------------- /// <summary> /// Get the name of the item which is basically the file name /// plus extension minus the directory /// </summary> /// <returns>Name of item</returns> //-------------------------------------------------------------------------------------------- internal string Name() { object o = GetPropHelper(__VSHPROPID.VSHPROPID_Name); return (o is string) ? (string)o : string.Empty; } //-------------------------------------------------------------------------------------------- /// <summary> /// Returns the extensibility object /// </summary> /// <returns>Name of item</returns> //-------------------------------------------------------------------------------------------- internal object ExtObject() { return GetPropHelper(__VSHPROPID.VSHPROPID_ExtObject); } //-------------------------------------------------------------------------------------------- /// <summary> /// Returns the ProjectItem extensibility object /// </summary> /// <returns>Name of item</returns> //-------------------------------------------------------------------------------------------- internal ProjectItem ProjectItem() { return ExtObject() as ProjectItem; } //-------------------------------------------------------------------------------------------- /// <summary> /// Returns the ProjectItems extensibility object /// </summary> /// <returns>Name of item</returns> //-------------------------------------------------------------------------------------------- internal ProjectItems ProjectItems() { if (IsRootNode()) { Project project = ExtObject() as Project; if (project != null) { return project.ProjectItems; } } else { ProjectItem projectItem = ProjectItem(); if (projectItem != null) { return projectItem.ProjectItems; } } return null; } //-------------------------------------------------------------------------------------------- /// <summary> /// Returns the the full path of the item using extensibility. /// </summary> /// <returns>Name of item</returns> //-------------------------------------------------------------------------------------------- internal string FullPath() { string fullPath = ""; try { object obj = ExtObject(); if(obj is EnvDTE.Project) { EnvDTE.Project project = obj as EnvDTE.Project; if(project != null) fullPath = project.Properties.Item("FullPath").Value as string; } else if(obj is EnvDTE.ProjectItem) { EnvDTE.ProjectItem projItem = obj as EnvDTE.ProjectItem; if(projItem != null) fullPath = projItem.Properties.Item("FullPath").Value as string; } } catch { } return fullPath; } ///-------------------------------------------------------------------------------------------- /// <summary> /// Returns the relative path of the project item /// /// folder\file.ext /// </summary> ///-------------------------------------------------------------------------------------------- internal string ProjRelativePath() { string projRelativePath = null; string rootProjectDir = Root().ProjectDir(); rootProjectDir = WAUtilities.EnsureTrailingBackSlash(rootProjectDir); string fullPath = FullPath(); if (!string.IsNullOrEmpty(rootProjectDir) && !string.IsNullOrEmpty(fullPath)) { projRelativePath = WAUtilities.MakeRelativePath(fullPath, rootProjectDir); } return projRelativePath; } ///-------------------------------------------------------------------------------------------- /// <summary> /// Returns the relative path of the project item /// /// folder/file.ext /// </summary> ///-------------------------------------------------------------------------------------------- internal string ProjRelativeUrl() { string projRelativeUrl = null; string projRelativePath = ProjRelativePath(); if (!string.IsNullOrEmpty(projRelativePath)) { projRelativeUrl = projRelativePath.Replace(Path.DirectorySeparatorChar, '/'); } return projRelativeUrl; } //-------------------------------------------------------------------------------------------- /// <summary> /// Gets full path to project directory for this item /// </summary> /// <returns></returns> //-------------------------------------------------------------------------------------------- internal string ProjectDir() { object o = GetPropHelper(__VSHPROPID.VSHPROPID_ProjectDir); return (o is string) ? (string)o : string.Empty; } //-------------------------------------------------------------------------------------------- /// <summary> /// Get type name for this item. This is the display name used in the /// title bar to identify the type of the node or hierarchy. /// </summary> /// <returns></returns> //-------------------------------------------------------------------------------------------- internal bool IsRootNode() { return _vsitemid == VSConstants.VSITEMID_ROOT; } //-------------------------------------------------------------------------------------------- /// <summary> /// Gets the type guid for this item and compares against GUID_ItemType_PhysicalFile /// </summary> /// <returns></returns> //-------------------------------------------------------------------------------------------- internal bool IsFile() { Guid guid = GetGuidPropHelper(__VSHPROPID.VSHPROPID_TypeGuid); return guid.CompareTo(VSConstants.GUID_ItemType_PhysicalFile) == 0; } ///------------------------------------------------------------------------------------------------------------- /// <summary> /// Returns the current contents of a document /// </summary> ///------------------------------------------------------------------------------------------------------------- public string GetDocumentText() { string text = null; IVsPersistDocData docData = null; try { // Get or create the buffer IVsTextLines buffer = GetRunningDocumentTextBuffer(); if (buffer == null) { docData = CreateDocumentData(); buffer = docData as IVsTextLines; } // get the text from the buffer if (buffer != null) { IVsTextStream textStream = buffer as IVsTextStream; if (textStream != null) { int length; int hr = textStream.GetSize(out length); if (ErrorHandler.Succeeded(hr)) { if (length > 0) { IntPtr pText = Marshal.AllocCoTaskMem((length + 1) * 2); try { hr = textStream.GetStream(0, length, pText); if (ErrorHandler.Succeeded(hr)) { text = Marshal.PtrToStringUni(pText); } } finally { Marshal.FreeCoTaskMem(pText); } } else { text = string.Empty; } } } } } finally { if (docData != null) { docData.Close(); } } return text; } ///------------------------------------------------------------------------------------------------------------- /// <summary> /// Creates and loads the document data /// (You must Close() it when done) /// </summary> ///------------------------------------------------------------------------------------------------------------- public IVsPersistDocData CreateDocumentData() { if (IsFile()) { string fullPath = FullPath(); if (!string.IsNullOrEmpty(fullPath)) { IOleServiceProvider serviceProvider = (IOleServiceProvider)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(IOleServiceProvider)); IVsPersistDocData docData = WAUtilities.CreateSitedInstance<IVsPersistDocData>(serviceProvider, typeof(VsTextBufferClass).GUID); if (docData != null) { int hr = docData.LoadDocData(fullPath); if (ErrorHandler.Succeeded(hr)) { return docData; } } } } return null; } ///------------------------------------------------------------------------------------------------------------- /// <summary> /// If the document is open, it returns the IVsTextLines. /// </summary> ///------------------------------------------------------------------------------------------------------------- public IVsTextLines GetRunningDocumentTextBuffer() { IVsTextLines buffer = null; IVsPersistDocData docData = GetRunningDocumentData(); if (docData != null) { buffer = docData as IVsTextLines; if (buffer == null) { IVsTextBufferProvider provider = docData as IVsTextBufferProvider; if (provider != null) { provider.GetTextBuffer(out buffer); } } } return buffer; } ///------------------------------------------------------------------------------------------------------------- /// <summary> /// If the document is open, it returns the IVsPersistDocData for it. /// </summary> ///------------------------------------------------------------------------------------------------------------- public IVsPersistDocData GetRunningDocumentData() { IVsPersistDocData persistDocData = null; IntPtr docData = IntPtr.Zero; try { docData = GetRunningDocData(); if (docData != IntPtr.Zero) { persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData; } } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } return persistDocData; } ///------------------------------------------------------------------------------------------------------------- /// <summary> /// If the document is open, it returns the IntPtr to the doc data. /// (This is ref-counted and must be released with Marshal.Release()) /// </summary> ///------------------------------------------------------------------------------------------------------------- public IntPtr GetRunningDocData() { IntPtr docData = IntPtr.Zero; if (IsFile()) { string fullPath = FullPath(); if (!string.IsNullOrEmpty(fullPath)) { IVsRunningDocumentTable rdt = GetService<IVsRunningDocumentTable>(); if (rdt != null) { _VSRDTFLAGS flags = _VSRDTFLAGS.RDT_NoLock; uint itemid; IVsHierarchy hierarchy; uint docCookie; rdt.FindAndLockDocument ( (uint)flags, fullPath, out hierarchy, out itemid, out docData, out docCookie ); } } } return docData; } ///------------------------------------------------------------------------------------------------------------- /// <summary> /// Gets the project item Properties collection. /// </summary> ///------------------------------------------------------------------------------------------------------------- public Properties Properties() { object obj = ExtObject(); if(obj is EnvDTE.Project) return ((EnvDTE.Project)obj).Properties; else if(obj is EnvDTE.ProjectItem) return ((EnvDTE.ProjectItem)obj).Properties; return null; } ///------------------------------------------------------------------------------------------------------------- /// <summary> /// Gets the build action of the item. /// If not found returns build action none. /// </summary> ///------------------------------------------------------------------------------------------------------------- public prjBuildAction BuildAction() { Properties props = Properties(); if (props != null) { Property propBuildAction = props.Item("BuildAction"); if (propBuildAction != null) { object objValue = propBuildAction.Value; if (objValue != null) { prjBuildAction buildAction = (prjBuildAction)objValue; return buildAction; } } } return prjBuildAction.prjBuildActionNone; } ///------------------------------------------------------------------------------------------------------------- /// <summary> /// Returns true if the build action of the item is compile. /// </summary> ///------------------------------------------------------------------------------------------------------------- public bool IsBuildActionCompile() { prjBuildAction buildAction = BuildAction(); if (buildAction == prjBuildAction.prjBuildActionCompile) { return true; } return false; } //-------------------------------------------------------------------------------------------- /// <summary> /// Get the specified property from the __VSHPROPID enumeration for this item /// </summary> //-------------------------------------------------------------------------------------------- private object GetPropHelper(__VSHPROPID propid) { return GetPropHelper(_vsitemid, (int)propid); } //-------------------------------------------------------------------------------------------- /// <summary> /// Get the specified property from the __VSHPROPID2 enumeration for this item /// </summary> //-------------------------------------------------------------------------------------------- private object GetPropHelper(__VSHPROPID2 propid) { return GetPropHelper(_vsitemid, (int)propid); } //-------------------------------------------------------------------------------------------- /// <summary> /// Get the specified property for the specified item /// </summary> //-------------------------------------------------------------------------------------------- private object GetPropHelper(uint itemid, int propid) { try { object o = null; if (_hier != null) { int hr = _hier.GetProperty(itemid, propid, out o); } return o; } catch(Exception) { return null; } } //-------------------------------------------------------------------------------------------- /// <summary> /// Calls IVsHIerachy::GetGuidProperty /// </summary> //-------------------------------------------------------------------------------------------- internal Guid GetGuidPropHelper(Microsoft.VisualStudio.Shell.Interop.__VSHPROPID propid) { Guid guid; try { _hier.GetGuidProperty(_vsitemid, (int)propid, out guid); } catch(Exception) { guid = Guid.Empty; } return guid; } ///-------------------------------------------------------------------------------------------- /// <summary> /// Get hierarchy site /// </summary> ///-------------------------------------------------------------------------------------------- public IOleServiceProvider Site() { IOleServiceProvider serviceProvider = null; if (_hier != null) { _hier.GetSite(out serviceProvider); } return serviceProvider; } ///-------------------------------------------------------------------------------------------- /// <summary> /// Helper to get a shell service interface /// </summary> ///-------------------------------------------------------------------------------------------- public InterfaceType GetService<InterfaceType>() where InterfaceType : class { InterfaceType service = null; try { if (_serviceProvider == null) { IOleServiceProvider serviceProvider = Site(); if (serviceProvider != null) { _serviceProvider = new ServiceProvider(serviceProvider); } } if (_serviceProvider != null) { service = _serviceProvider.GetService(typeof(InterfaceType)) as InterfaceType; } } catch { } return service; } } }
// $Id$ #region The MIT License /* Copyright (c) 2009 denis.kiselyov@gmail.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. */ #endregion using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace OreEfficiencyCalc { public enum VesselType { Procurer = 1, Retriever = 3, Covetor = 5, Skiff = 6, Mackinaw = 7, Hulk = 8 } public enum HarvestType { ORE = 1, MERCOXIT = 2, ICE = 3, GAS = 4 } public abstract class Vessel { private double _stripBonusLow; private double _stripBonusHigh; private double _roleBonus; private double _iceCycleBonus; private double _iceCyclePenalty; private double _mercoxitBonus; private double _dronesYieldBonus; private int _harvestersCount; private Harvester _harvester; private List<Drone> _drones; private int _calibration; private int _droneBay; private double _iceCycleBonusMultiplier; public static Vessel Create(VesselType type) { Assembly a = Assembly.GetCallingAssembly(); return (Vessel)Activator.CreateInstance( a.GetType(a.GetName().Name + "." + type.ToString())); } public Vessel() { StripBonusHigh = 1; StripBonusLow = 1; RoleBonus = 1; IceCycleBonus = 1; IceCyclePenalty = 1; IceCycleBonusMultiplier = 1; MercoxitBonus = 1; _dronesYieldBonus = 1; Calibration = 400; } public Harvester Harvester { get { return _harvester; } } public int Calibration { get { return _calibration; } set { _calibration = value; } } public VesselType Type { get { return (VesselType)Enum.Parse(typeof(VesselType), this.GetType().ToString()); } } public int HarvestersCount { get { return _harvestersCount; } set { _harvestersCount = value; } } public double StripBonusLow { get { return _stripBonusLow; } set { _stripBonusLow = value; } } public double StripBonusHigh { get { return _stripBonusHigh; } set { _stripBonusHigh = value; } } public double RoleBonus { get { return _roleBonus; } set { _roleBonus = value; } } public double IceCycleBonus { get { return _iceCycleBonus; } set { _iceCycleBonus = value; } } public double IceCycleBonusMultiplier { get { return _iceCycleBonusMultiplier; } set { _iceCycleBonusMultiplier = value; } } public double MercoxitBonus { get { return _mercoxitBonus; } set { _mercoxitBonus = value; } } public double IceCyclePenalty { get { return _iceCyclePenalty; } set { _iceCyclePenalty = value; } } public int DroneBay { get { return _droneBay; } set { _droneBay = value; } } internal void mountHarvesters(Harvester harvester) { _harvester = (harvester != null) ? harvester : Harvester.NullHarvester; } internal void mountUpgrade(Upgrade upgrade) { if (upgrade != null) { this._iceCycleBonusMultiplier *= upgrade.IceHarvestCycleBonus; this._harvester.MiningAmount *= upgrade.MiningAmountBonus; } } internal void mountRig(Rig rig) { if (rig != null) { if (Calibration >= rig.CalibrationPoints) { this._dronesYieldBonus *= rig.DroneMiningAmountBonus; Calibration -= rig.CalibrationPoints; } else { throw new Exception("Insufficient calibration points"); } } } internal void addDrone(Drone drone) { if (_drones == null) { _drones = new List<Drone>(); } if (drone != null) { if (DroneBay >= drone.Volume) { _drones.Add(drone); DroneBay -= drone.Volume; } else { throw new Exception("Insufficient drone bay volume"); } } } internal void setDefaultFit(Character c) { // harvesters Harvester harv = null; switch (c.getSkillLevel(SkillTypes.MINING)) { case 1: case 2: case 3: harv = Items.i.getHarvester("28750"); break; case 4: harv = Items.i.getHarvester("17482"); break; case 5: harv = Items.i.getHarvester("17912"); break; default: break; } mountHarvesters(harv); // upgrades Upgrade upg = null; switch (c.getSkillLevel(SkillTypes.MINING_UPGRADES)) { case 1: case 2: case 3: upg = Items.i.getUpgrade("22542"); break; case 4: upg = Items.i.getUpgrade("28576"); mountUpgrade(upg); break; default: break; } if (upg != null) { mountUpgrade(upg); } // rigs int rigLvl = c.getSkillLevel(SkillTypes.DRONES_RIGGING); Rig t1rig = Items.i.getRig("25918"); Rig t2rig = Items.i.getRig("26328"); if (rigLvl > 0) { while (Calibration >= Math.Min(t1rig.CalibrationPoints, t2rig.CalibrationPoints)) { if ((Calibration >= t2rig.CalibrationPoints) && (rigLvl >= 4)) { mountRig(t2rig); } else { mountRig(t1rig); } } } // drones int minDronLvl = c.getSkillLevel(SkillTypes.MINING_DRONE_OPERATION); if (minDronLvl >= 1) { Drone t1drone = Items.i.getDrone("10246"); Drone t2drone = Items.i.getDrone("10250"); for (int i = 0; i < c.getSkillLevel(SkillTypes.DRONES); i++) { if (DroneBay >= t1drone.Volume) { addDrone(minDronLvl >= 4 ? t2drone : t1drone); } else { break; } } } } internal double getYield() { return (HarvestersCount * _harvester.MiningAmount * 60 / _harvester.Cycle) * _stripBonusHigh * _stripBonusLow; } internal double getDronesYield() { double result = 0; for (int i = 0; i < _drones.Count; i++) { result += (_drones[i].MiningAmount * 60 / _drones[i].Cycle); } return result; } } public class Procurer : Vessel { public Procurer() { StripBonusLow = 1.03; HarvestersCount = 1; DroneBay = 5; } } public class Retriever : Vessel { public Retriever() { StripBonusLow = 1.03; HarvestersCount = 2; DroneBay = 25; } } public class Covetor : Vessel { public Covetor() { StripBonusLow = 1.03; HarvestersCount = 3; DroneBay = 50; } } public class Skiff : Procurer { public Skiff() : base() { MercoxitBonus = 0.6; DroneBay = 15; } } public class Mackinaw : Retriever { public Mackinaw() : base() { IceCycleBonus = 1.05; IceCyclePenalty = 1.25; RoleBonus = 2; DroneBay = 50; } } public class Hulk : Covetor { public Hulk() : base() { StripBonusHigh = 1.03; IceCycleBonus = 1.03; DroneBay = 50; } } }
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 SecMS.Areas.HelpPage.ModelDescriptions; using SecMS.Areas.HelpPage.Models; namespace SecMS.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using Microsoft.VisualStudio.Modeling.Shell; using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace nHydrate.DslPackage.Forms { [Guid("12121DCE-997E-41D2-B2DD-B7F558B10DAF")] public class FindWindow : ToolWindow { private FindWindowControl _findControl; private nHydrate.Dsl.nHydrateModel _model = null; private DiagramDocView _diagram = null; private ModelingDocData _docView = null; private List<Guid> _loadedModels = new List<Guid>(); //creates the tool window public FindWindow(global::System.IServiceProvider serviceProvider) : base(serviceProvider) { _findControl = new FindWindowControl(); } /// <summary> /// Specifies a resource string that appears on the tool window title bar. /// </summary> public override string WindowTitle => "nHydrate Object View"; //puts a label on the tool window public override System.Windows.Forms.IWin32Window Window => this._findControl; protected override void OnDocumentWindowChanged(ModelingDocView oldView, ModelingDocView newView) { if (newView == null && oldView != null) { //The model is being unloaded var m = oldView.DocData.RootElement as nHydrate.Dsl.nHydrateModel; if (m == null) return; _loadedModels.Remove(m.Id); oldView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.nHydrateModel)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ModelChanged)); #region Entity oldView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Entity)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged)); oldView.DocData.Store.EventManagerDirectory.ElementAdded.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Entity)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler)); oldView.DocData.Store.EventManagerDirectory.ElementDeleted.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Entity)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler)); #region Field oldView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Field)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged)); oldView.DocData.Store.EventManagerDirectory.ElementAdded.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Field)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler)); oldView.DocData.Store.EventManagerDirectory.ElementDeleted.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Field)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler)); #endregion #endregion #region View oldView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.View)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged)); oldView.DocData.Store.EventManagerDirectory.ElementAdded.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.View)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler)); oldView.DocData.Store.EventManagerDirectory.ElementDeleted.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.View)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler)); #region Field oldView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.ViewField)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged)); oldView.DocData.Store.EventManagerDirectory.ElementAdded.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.ViewField)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler)); oldView.DocData.Store.EventManagerDirectory.ElementDeleted.Remove( oldView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.ViewField)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler)); #endregion #endregion return; } //When the old view is null this is the first time. Only load the first time if (newView == null) return; //Reload model if necessary _model = newView.DocData.RootElement as nHydrate.Dsl.nHydrateModel; if (_model == null) return; _diagram = ((Microsoft.VisualStudio.Modeling.Shell.SingleDiagramDocView)newView).CurrentDesigner.DocView; _docView = newView.DocData; //This model is already hooked if (!_loadedModels.Contains(_model.Id)) { _loadedModels.Add(_model.Id); newView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.nHydrateModel)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ModelChanged)); #region Entity newView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Entity)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged)); newView.DocData.Store.EventManagerDirectory.ElementAdded.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Entity)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler)); newView.DocData.Store.EventManagerDirectory.ElementDeleted.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Entity)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler)); #region Field newView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Field)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged)); newView.DocData.Store.EventManagerDirectory.ElementAdded.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Field)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler)); newView.DocData.Store.EventManagerDirectory.ElementDeleted.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.Field)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler)); #endregion #endregion #region View newView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.View)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged)); newView.DocData.Store.EventManagerDirectory.ElementAdded.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.View)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler)); newView.DocData.Store.EventManagerDirectory.ElementDeleted.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.View)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler)); #region Field newView.DocData.Store.EventManagerDirectory.ElementPropertyChanged.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.ViewField)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs>(ElementChanged)); newView.DocData.Store.EventManagerDirectory.ElementAdded.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.ViewField)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementAddedEventArgs>(ElementAddHandler)); newView.DocData.Store.EventManagerDirectory.ElementDeleted.Add( newView.DocData.Store.DomainDataDirectory.FindDomainClass(typeof(nHydrate.Dsl.ViewField)), new EventHandler<Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs>(ElementDeleteHandler)); #endregion #endregion } _findControl.SetupObjects(_model, _diagram, _docView); base.OnDocumentWindowChanged(oldView, newView); } private void ModelChanged(object sender, Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs e) { if (_model.IsLoading) return; //Name changed so rebuild if (e.DomainProperty.Name == "DiagramVisibility") { _findControl.SetupObjects(_model, _diagram, _docView); } } private void ElementChanged(object sender, Microsoft.VisualStudio.Modeling.ElementPropertyChangedEventArgs e) { if (_model.IsLoading) return; //Name changed so rebuild if (e.DomainProperty.Name == "Name") { _findControl.SetupObjects(_model, _diagram, _docView); } } private void ElementAddHandler(object sender, Microsoft.VisualStudio.Modeling.ElementAddedEventArgs e) { if (_model.IsLoading) return; _findControl.SetupObjects(_model, _diagram, _docView); } private void ElementDeleteHandler(object sender, Microsoft.VisualStudio.Modeling.ElementDeletedEventArgs e) { if (_model.IsLoading) return; _findControl.SetupObjects(_model, _diagram, _docView); } } }
namespace AutoMapper.QueryableExtensions { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Impl; using Internal; public static class Extensions { private static readonly IDictionaryFactory DictionaryFactory = PlatformAdapter.Resolve<IDictionaryFactory>(); private static readonly Internal.IDictionary<ExpressionRequest, LambdaExpression> _expressionCache = DictionaryFactory.CreateDictionary<ExpressionRequest, LambdaExpression>(); private static readonly IExpressionResultConverter[] ExpressionResultConverters = { new MemberGetterExpressionResultConverter(), new MemberResolverExpressionResultConverter(), new NullSubstitutionExpressionResultConverter() }; private static readonly IExpressionBinder[] Binders = { new NullableExpressionBinder(), new AssignableExpressionBinder(), new EnumerableExpressionBinder(), new MappedTypeExpressionBinder(), new CustomProjectionExpressionBinder(), new StringExpressionBinder() }; public static void ClearExpressionCache() { _expressionCache.Clear(); } /// <summary> /// Create an expression tree representing a mapping from the <typeparamref name="TSource"/> type to <typeparamref name="TDestination"/> type /// Includes flattening and expressions inside MapFrom member configuration /// </summary> /// <typeparam name="TSource">Source Type</typeparam> /// <typeparam name="TDestination">Destination Type</typeparam> /// <param name="mappingEngine">Mapping engine instance</param> /// <param name="parameters">Optional parameter object for parameterized mapping expressions</param> /// <param name="membersToExpand">Expand members explicitly previously marked as members to explicitly expand</param> /// <returns>Expression tree mapping source to destination type</returns> public static Expression<Func<TSource, TDestination>> CreateMapExpression<TSource, TDestination>( this IMappingEngine mappingEngine, System.Collections.Generic.IDictionary<string, object> parameters = null, params string[] membersToExpand) { return (Expression<Func<TSource, TDestination>>) mappingEngine.CreateMapExpression(typeof (TSource), typeof (TDestination), parameters, membersToExpand); } /// <summary> /// Create an expression tree representing a mapping from the source type to destination type /// Includes flattening and expressions inside MapFrom member configuration /// </summary> /// <param name="mappingEngine">Mapping engine instance</param> /// <param name="sourceType">Source Type</param> /// <param name="destinationType">Destination Type</param> /// <param name="parameters">Optional parameter object for parameterized mapping expressions</param> /// <param name="membersToExpand">Expand members explicitly previously marked as members to explicitly expand</param> /// <returns>Expression tree mapping source to destination type</returns> public static Expression CreateMapExpression(this IMappingEngine mappingEngine, Type sourceType, Type destinationType, System.Collections.Generic.IDictionary<string, object> parameters = null, params string[] membersToExpand) { //Expression.const parameters = parameters ?? new Dictionary<string, object>(); var cachedExpression = _expressionCache.GetOrAdd(new ExpressionRequest(sourceType, destinationType, membersToExpand), tp => CreateMapExpression(mappingEngine, tp, DictionaryFactory.CreateDictionary<ExpressionRequest, int>())); if (!parameters.Any()) return cachedExpression; var visitor = new ConstantExpressionReplacementVisitor(parameters); return visitor.Visit(cachedExpression); } /// <summary> /// Extention method to project from a queryable using the static <see cref="Mapper.Engine"/> property. /// Due to generic parameter inference, you need to call Project().To to execute the map /// </summary> /// <remarks>Projections are only calculated once and cached</remarks> /// <typeparam name="TSource">Source type</typeparam> /// <param name="source">Queryable source</param> /// <returns>Expression to project into</returns> public static IProjectionExpression Project<TSource>( this IQueryable<TSource> source) { return source.Project(Mapper.Engine); } /// <summary> /// Extention method to project from a queryable using the provided mapping engine /// Due to generic parameter inference, you need to call Project().To to execute the map /// </summary> /// <remarks>Projections are only calculated once and cached</remarks> /// <typeparam name="TSource">Source type</typeparam> /// <param name="source">Queryable source</param> /// <param name="mappingEngine">Mapping engine instance</param> /// <returns>Expression to project into</returns> public static IProjectionExpression Project<TSource>( this IQueryable<TSource> source, IMappingEngine mappingEngine) { return new ProjectionExpression(source, mappingEngine); } /// <summary> /// Extention method to project from a queryable using the static <see cref="Mapper.Engine"/> property. /// </summary> /// <remarks>Projections are only calculated once and cached</remarks> /// <typeparam name="TDestination">Destination type</typeparam> /// <param name="source">Queryable source</param> /// <returns>Expression to project into</returns> public static IQueryable<TDestination> ProjectTo<TDestination>( this IQueryable source) { return source.ProjectTo<TDestination>(Mapper.Engine); } /// <summary> /// Extention method to project from a queryable using the provided mapping engine /// </summary> /// <remarks>Projections are only calculated once and cached</remarks> /// <typeparam name="TDestination">Destination type</typeparam> /// <param name="source">Queryable source</param> /// <param name="mappingEngine">Mapping engine instance</param> /// <returns>Expression to project into</returns> public static IQueryable<TDestination> ProjectTo<TDestination>( this IQueryable source, IMappingEngine mappingEngine) { return new ProjectionExpression(source, mappingEngine).To<TDestination>(); } internal static LambdaExpression CreateMapExpression(IMappingEngine mappingEngine, ExpressionRequest request, Internal.IDictionary<ExpressionRequest, int> typePairCount) { // this is the input parameter of this expression with name <variableName> ParameterExpression instanceParameter = Expression.Parameter(request.SourceType, "dto"); var total = CreateMapExpression(mappingEngine, request, instanceParameter, typePairCount); return Expression.Lambda(total, instanceParameter); } internal static Expression CreateMapExpression(IMappingEngine mappingEngine, ExpressionRequest request, Expression instanceParameter, Internal.IDictionary<ExpressionRequest, int> typePairCount) { var typeMap = mappingEngine.ConfigurationProvider.ResolveTypeMap(request.SourceType, request.DestinationType); if(typeMap == null) { const string MessageFormat = "Missing map from {0} to {1}. Create using Mapper.CreateMap<{0}, {1}>."; var message = string.Format(MessageFormat, request.SourceType.Name, request.DestinationType.Name); throw new InvalidOperationException(message); } var bindings = CreateMemberBindings(mappingEngine, request, typeMap, instanceParameter, typePairCount); var parameterReplacer = new ParameterReplacementVisitor(instanceParameter); var visitor = new NewFinderVisitor(); var constructorExpression = typeMap.DestinationConstructorExpression(instanceParameter); visitor.Visit(parameterReplacer.Visit(constructorExpression)); var expression = Expression.MemberInit( visitor.NewExpression, bindings.ToArray() ); return expression; } private class NewFinderVisitor : ExpressionVisitor { public NewExpression NewExpression { get; private set; } protected override Expression VisitNew(NewExpression node) { NewExpression = node; return base.VisitNew(node); } } private static List<MemberBinding> CreateMemberBindings(IMappingEngine mappingEngine, ExpressionRequest request, TypeMap typeMap, Expression instanceParameter, Internal.IDictionary<ExpressionRequest, int> typePairCount) { var bindings = new List<MemberBinding>(); var visitCount = typePairCount.AddOrUpdate(request, 0, (tp, i) => i + 1); if (visitCount >= typeMap.MaxDepth) return bindings; foreach (var propertyMap in typeMap.GetPropertyMaps().Where(pm => pm.CanResolveValue())) { var result = ResolveExpression(propertyMap, request.SourceType, instanceParameter); if (propertyMap.ExplicitExpansion && !request.IncludedMembers.Contains(propertyMap.DestinationProperty.Name)) continue; var propertyTypeMap = mappingEngine.ConfigurationProvider.ResolveTypeMap(result.Type, propertyMap.DestinationPropertyType); var propertyRequest = new ExpressionRequest(result.Type, propertyMap.DestinationPropertyType, request.IncludedMembers); var binder = Binders.FirstOrDefault(b => b.IsMatch(propertyMap, propertyTypeMap, result)); if (binder == null) { var message = $"Unable to create a map expression from {propertyMap.SourceMember.DeclaringType.Name}.{propertyMap.SourceMember.Name} ({result.Type}) to {propertyMap.DestinationProperty.MemberInfo.DeclaringType.Name}.{propertyMap.DestinationProperty.Name} ({propertyMap.DestinationPropertyType})"; throw new AutoMapperMappingException(message); } var bindExpression = binder.Build(mappingEngine, propertyMap, propertyTypeMap, propertyRequest, result, typePairCount); bindings.Add(bindExpression); } return bindings; } private static ExpressionResolutionResult ResolveExpression(PropertyMap propertyMap, Type currentType, Expression instanceParameter) { var result = new ExpressionResolutionResult(instanceParameter, currentType); foreach (var resolver in propertyMap.GetSourceValueResolvers()) { var matchingExpressionConverter = ExpressionResultConverters.FirstOrDefault(c => c.CanGetExpressionResolutionResult(result, resolver)); if (matchingExpressionConverter == null) throw new Exception("Can't resolve this to Queryable Expression"); result = matchingExpressionConverter.GetExpressionResolutionResult(result, propertyMap, resolver); } return result; } private class ConstantExpressionReplacementVisitor : ExpressionVisitor { private readonly System.Collections.Generic.IDictionary<string, object> _paramValues; public ConstantExpressionReplacementVisitor( System.Collections.Generic.IDictionary<string, object> paramValues) { _paramValues = paramValues; } protected override Expression VisitMember(MemberExpression node) { if (!node.Member.DeclaringType.Name.Contains("<>")) return base.VisitMember(node); if (!_paramValues.ContainsKey(node.Member.Name)) return base.VisitMember(node); return Expression.Convert( Expression.Constant(_paramValues[node.Member.Name]), node.Member.GetMemberType()); } } } }
using System; using System.Collections; using System.IO; using UnityEngine; /* The MIT License (MIT) Copyright (c) 2014 Brad Nelson and Play-Em Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // AnimationToPNG is based on Twinfox and bitbutter's Render Particle to Animated Texture Scripts, // this script will render out an animation that is played when "Play" is pressed in the editor. /* Basically this is a script you can attach to any gameobject in the scene, but you have to reference a Black Camera and White Camera both of which should be set to orthographic, but this script should have it covered. There is a prefab called AnimationToPNG which should include everything needed to run the script. If you have Unity Pro, you can use Render Texture, which can accurately render the transparent background for your animations easily in full resolution of the camera. Just check the box for the variable "useRenderTexture" to use RenderTextures instead. If you are using Unity Free, then leave this unchecked and you will have a split area using half of the screen width to render the animations. You can change the "animationName" to a string of your choice for a prefix for the output file names, if it is left empty then no filename will be added. The destination folder is relative to the Project Folder root, so you can change the string to a folder name of your choice and it will be created. If it already exists, it will simply create a new folder with a number incremented as to how many of those named folders exist. Choose how many frames per second the animation will run by changing the "frameRate" variable, and how many frames of the animation you wish to capture by changing the "framesToCapture" variable. Once "Play" is pressed in the Unity Editor, it should output all the animation frames to PNGs output in the folder you have chosen, and will stop capturing after the number of frames you wish to capture is completed. */ namespace SpritesAndBones.Utility { public class AnimationToPNG : MonoBehaviour { // Animation Name to be the prefix for the output filenames public string animationName = ""; // Default folder name where you want the animations to be output public string folder = "PNG_Animations"; // Framerate at which you want to play the animation public int frameRate = 25; // How many frames you want to capture during the animation public int framesToCapture = 25; // White Camera private Camera whiteCam; // Black Camera private Camera blackCam; // Pixels to World Unit size public float pixelsToWorldUnit = 74.48275862068966f; // If you have Unity Pro you can use a RenderTexture which will render the full camera width, otherwise it will only render half private bool useRenderTexture = false; private int videoframe = 0; // how many frames we've rendered private float originaltimescaleTime; // track the original time scale so we can freeze the animation between frames private string realFolder = ""; // real folder where the output files will be private bool done = false; // is the capturing finished? private bool readyToCapture = false; // Make sure all the camera setup is complete before capturing private float cameraSize; // Size of the orthographic camera established from the current screen resolution and the pixels to world unit private Texture2D texb; // black camera texture private Texture2D texw; // white camera texture private Texture2D outputtex; // final output texture private RenderTexture blackCamRenderTexture; // black camera render texure private RenderTexture whiteCamRenderTexture; // white camera render texure public void Start() { useRenderTexture = Application.HasProLicense(); // Set the playback framerate! // (real time doesn't influence time anymore) Time.captureFramerate = frameRate; // Create a folder that doesn't exist yet. Append number if necessary. realFolder = folder; int count = 1; while (Directory.Exists(realFolder)) { realFolder = folder + count; count++; } // Create the folder Directory.CreateDirectory(realFolder); originaltimescaleTime = Time.timeScale; // Force orthographic camera to render out sprites per pixel size designated by pixels to world unit cameraSize = Screen.width / (((Screen.width / Screen.height) * 2) * pixelsToWorldUnit); GameObject bc = new GameObject("Black Camera"); bc.transform.localPosition = new Vector3(0, 0, -1); blackCam = bc.AddComponent<Camera>(); blackCam.backgroundColor = Color.black; blackCam.orthographic = true; blackCam.orthographicSize = cameraSize; blackCam.tag = "MainCamera"; GameObject wc = new GameObject("White Camera"); wc.transform.localPosition = new Vector3(0, 0, -1); whiteCam = wc.AddComponent<Camera>(); whiteCam.backgroundColor = Color.white; whiteCam.orthographic = true; whiteCam.orthographicSize = cameraSize; // If not using a Render Texture then set the cameras to split the screen to ensure we have an accurate image with alpha if (!useRenderTexture) { // Change the camera rects to have split on screen to capture the animation properly blackCam.rect = new Rect(0.0f, 0.0f, 0.5f, 1.0f); whiteCam.rect = new Rect(0.5f, 0.0f, 0.5f, 1.0f); } // Cameras are set ready to capture! readyToCapture = true; } private void Update() { // If the capturing is not done and the cameras are set, then Capture the animation if (!done && readyToCapture) { StartCoroutine(Capture()); } } private void LateUpdate() { // When we are all done capturing, clean up all the textures and RenderTextures from the scene if (done) { DestroyImmediate(texb); DestroyImmediate(texw); DestroyImmediate(outputtex); if (useRenderTexture) { //Clean Up whiteCam.targetTexture = null; RenderTexture.active = null; DestroyImmediate(whiteCamRenderTexture); blackCam.targetTexture = null; RenderTexture.active = null; DestroyImmediate(blackCamRenderTexture); } } } private IEnumerator Capture() { if (videoframe < framesToCapture) { // name is "realFolder/animationName0000.png" // string name = realFolder + "/" + animationName + Time.frameCount.ToString("0000") + ".png"; string filename = String.Format("{0}/" + animationName + "{1:D04}.png", realFolder, Time.frameCount); // Stop time Time.timeScale = 0; // Yield to next frame and then start the rendering yield return new WaitForEndOfFrame(); // If we are using a render texture to make the animation frames then set up the camera render textures if (useRenderTexture) { //Initialize and render textures blackCamRenderTexture = new RenderTexture(Screen.width, Screen.height, 24, RenderTextureFormat.ARGB32); whiteCamRenderTexture = new RenderTexture(Screen.width, Screen.height, 24, RenderTextureFormat.ARGB32); blackCam.targetTexture = blackCamRenderTexture; blackCam.Render(); RenderTexture.active = blackCamRenderTexture; texb = GetTex2D(true); //Now do it for Alpha Camera whiteCam.targetTexture = whiteCamRenderTexture; whiteCam.Render(); RenderTexture.active = whiteCamRenderTexture; texw = GetTex2D(true); } // If not using render textures then simply get the images from both cameras else { // store 'black background' image texb = GetTex2D(true); // store 'white background' image texw = GetTex2D(false); } // If we have both textures then create final output texture if (texw && texb) { int width = Screen.width; int height = Screen.height; // If we are not using a render texture then the width will only be half the screen if (!useRenderTexture) { width = width / 2; } outputtex = new Texture2D(width, height, TextureFormat.ARGB32, false); // Create Alpha from the difference between black and white camera renders for (int y = 0; y < outputtex.height; ++y) { // each row for (int x = 0; x < outputtex.width; ++x) { // each column float alpha; if (useRenderTexture) { alpha = texw.GetPixel(x, y).r - texb.GetPixel(x, y).r; } else { alpha = texb.GetPixel(x + width, y).r - texb.GetPixel(x, y).r; } alpha = 1.0f - alpha; Color color; if (alpha == 0) { color = Color.clear; } else { color = texb.GetPixel(x, y) / alpha; } color.a = alpha; outputtex.SetPixel(x, y, color); } } // Encode the resulting output texture to a byte array then write to the file byte[] pngShot = outputtex.EncodeToPNG(); #if !UNITY_WEBPLAYER File.WriteAllBytes(filename, pngShot); #endif // Reset the time scale, then move on to the next frame. Time.timeScale = originaltimescaleTime; videoframe++; } // Debug.Log("Frame " + name + " " + videoframe); } else { Debug.Log("Complete! " + videoframe + " videoframes rendered (0 indexed)"); done = true; } } // Get the texture from the screen, render all or only half of the camera private Texture2D GetTex2D(bool renderAll) { // Create a texture the size of the screen, RGB24 format int width = Screen.width; int height = Screen.height; if (!renderAll) { width = width / 2; } Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false); // Read screen contents into the texture tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); tex.Apply(); return tex; } } }
using System; using System.Text; // ReSharper disable AssignNullToNotNullAttribute namespace Thinktecture.Text.Adapters { /// <summary> /// Adapter for <see cref="Encoding"/>. /// </summary> public class EncodingAdapter : AbstractionAdapter<Encoding>, IEncoding { /// <summary>Gets an encoding for the UTF-16 format that uses the big endian byte order.</summary> /// <returns>An encoding object for the UTF-16 format that uses the big endian byte order.</returns> public static IEncoding BigEndianUnicode => new EncodingAdapter(Encoding.BigEndianUnicode); /// <summary>Gets an encoding for the UTF-16 format using the little endian byte order.</summary> /// <returns>An encoding for the UTF-16 format using the little endian byte order.</returns> public static IEncoding Unicode => new EncodingAdapter(Encoding.Unicode); /// <summary>Gets an encoding for the UTF-8 format.</summary> /// <returns>An encoding for the UTF-8 format.</returns> // ReSharper disable once InconsistentNaming public static IEncoding UTF8 => new EncodingAdapter(Encoding.UTF8); /// <summary>Converts an entire byte array from one encoding to another.</summary> /// <returns>An array of type <see cref="T:System.Byte" /> containing the results of converting <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns> /// <param name="srcEncoding">The encoding format of <paramref name="bytes" />. </param> /// <param name="dstEncoding">The target encoding format. </param> /// <param name="bytes">The bytes to convert. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception> /// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception> /// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception> public static byte[] Convert(IEncoding srcEncoding, IEncoding dstEncoding, byte[] bytes) { return Convert(srcEncoding.ToImplementation(), dstEncoding.ToImplementation(), bytes); } /// <summary>Converts an entire byte array from one encoding to another.</summary> /// <returns>An array of type <see cref="T:System.Byte" /> containing the results of converting <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns> /// <param name="srcEncoding">The encoding format of <paramref name="bytes" />. </param> /// <param name="dstEncoding">The target encoding format. </param> /// <param name="bytes">The bytes to convert. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception> /// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception> /// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception> public static byte[] Convert(IEncoding srcEncoding, Encoding dstEncoding, byte[] bytes) { return Convert(srcEncoding.ToImplementation(), dstEncoding, bytes); } /// <summary>Converts an entire byte array from one encoding to another.</summary> /// <returns>An array of type <see cref="T:System.Byte" /> containing the results of converting <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns> /// <param name="srcEncoding">The encoding format of <paramref name="bytes" />. </param> /// <param name="dstEncoding">The target encoding format. </param> /// <param name="bytes">The bytes to convert. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception> /// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception> /// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception> public static byte[] Convert(Encoding srcEncoding, IEncoding dstEncoding, byte[] bytes) { return Convert(srcEncoding, dstEncoding.ToImplementation(), bytes); } /// <summary>Converts an entire byte array from one encoding to another.</summary> /// <returns>An array of type <see cref="T:System.Byte" /> containing the results of converting <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns> /// <param name="srcEncoding">The encoding format of <paramref name="bytes" />. </param> /// <param name="dstEncoding">The target encoding format. </param> /// <param name="bytes">The bytes to convert. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception> /// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception> /// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception> public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes) { return Encoding.Convert(srcEncoding, dstEncoding, bytes); } /// <summary>Converts a range of bytes in a byte array from one encoding to another.</summary> /// <returns>An array of type <see cref="T:System.Byte" /> containing the result of converting a range of bytes in <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns> /// <param name="srcEncoding">The encoding of the source array, <paramref name="bytes" />. </param> /// <param name="dstEncoding">The encoding of the output array. </param> /// <param name="bytes">The array of bytes to convert. </param> /// <param name="index">The index of the first element of <paramref name="bytes" /> to convert. </param> /// <param name="count">The number of bytes to convert. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index" /> and <paramref name="count" /> do not specify a valid range in the byte array. </exception> /// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception> /// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception> public static byte[] Convert(IEncoding srcEncoding, IEncoding dstEncoding, byte[] bytes, int index, int count) { return Encoding.Convert(srcEncoding.ToImplementation(), dstEncoding.ToImplementation(), bytes, index, count); } /// <summary>Converts a range of bytes in a byte array from one encoding to another.</summary> /// <returns>An array of type <see cref="T:System.Byte" /> containing the result of converting a range of bytes in <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns> /// <param name="srcEncoding">The encoding of the source array, <paramref name="bytes" />. </param> /// <param name="dstEncoding">The encoding of the output array. </param> /// <param name="bytes">The array of bytes to convert. </param> /// <param name="index">The index of the first element of <paramref name="bytes" /> to convert. </param> /// <param name="count">The number of bytes to convert. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index" /> and <paramref name="count" /> do not specify a valid range in the byte array. </exception> /// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception> /// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception> public static byte[] Convert(IEncoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count) { return Encoding.Convert(srcEncoding.ToImplementation(), dstEncoding, bytes, index, count); } /// <summary>Converts a range of bytes in a byte array from one encoding to another.</summary> /// <returns>An array of type <see cref="T:System.Byte" /> containing the result of converting a range of bytes in <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns> /// <param name="srcEncoding">The encoding of the source array, <paramref name="bytes" />. </param> /// <param name="dstEncoding">The encoding of the output array. </param> /// <param name="bytes">The array of bytes to convert. </param> /// <param name="index">The index of the first element of <paramref name="bytes" /> to convert. </param> /// <param name="count">The number of bytes to convert. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index" /> and <paramref name="count" /> do not specify a valid range in the byte array. </exception> /// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception> /// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception> public static byte[] Convert(Encoding srcEncoding, IEncoding dstEncoding, byte[] bytes, int index, int count) { return Encoding.Convert(srcEncoding, dstEncoding.ToImplementation(), bytes, index, count); } /// <summary>Converts a range of bytes in a byte array from one encoding to another.</summary> /// <returns>An array of type <see cref="T:System.Byte" /> containing the result of converting a range of bytes in <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns> /// <param name="srcEncoding">The encoding of the source array, <paramref name="bytes" />. </param> /// <param name="dstEncoding">The encoding of the output array. </param> /// <param name="bytes">The array of bytes to convert. </param> /// <param name="index">The index of the first element of <paramref name="bytes" /> to convert. </param> /// <param name="count">The number of bytes to convert. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index" /> and <paramref name="count" /> do not specify a valid range in the byte array. </exception> /// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception> /// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception> public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count) { return Encoding.Convert(srcEncoding, dstEncoding, bytes, index, count); } /// <summary>Returns the encoding associated with the specified code page name.</summary> /// <returns>The encoding associated with the specified code page.</returns> /// <param name="name">The code page name of the preferred encoding. Any value returned by the <see cref="P:System.Text.Encoding.WebName" /> property is valid. Possible values are listed in the Name column of the table that appears in the <see cref="T:System.Text.Encoding" /> class topic.</param> /// <exception cref="T:System.ArgumentException"> /// <paramref name="name" /> is not a valid code page name.-or- The code page indicated by <paramref name="name" /> is not supported by the underlying platform. </exception> public static IEncoding GetEncoding(string name) { return Encoding.GetEncoding(name).ToInterface(); } /// <inheritdoc /> public string WebName => Implementation.WebName; /// <summary> /// Initializes a new instance of the <see cref="EncodingAdapter" /> class. /// </summary> /// <param name="encoding">Encoding to be used by the adapter.</param> public EncodingAdapter(Encoding encoding) : base(encoding) { } /// <inheritdoc /> public ReadOnlySpan<byte> Preamble => Implementation.Preamble; /// <inheritdoc /> public int GetByteCount(string s, int index, int count) { return Implementation.GetByteCount(s, index, count); } /// <inheritdoc /> public int GetByteCount(ReadOnlySpan<char> chars) { return Implementation.GetByteCount(chars); } /// <inheritdoc /> public int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes) { return Implementation.GetBytes(chars, bytes); } /// <inheritdoc /> public byte[] GetBytes(string s, int index, int count) { return Implementation.GetBytes(s, index, count); } /// <inheritdoc /> public int GetCharCount(ReadOnlySpan<byte> bytes) { return Implementation.GetCharCount(bytes); } /// <inheritdoc /> public int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars) { return Implementation.GetChars(bytes, chars); } /// <inheritdoc /> public string GetString(ReadOnlySpan<byte> bytes) { return Implementation.GetString(bytes); } /// <inheritdoc /> public int GetByteCount(char[] chars) { return Implementation.GetByteCount(chars); } /// <inheritdoc /> public int GetByteCount(char[] chars, int index, int count) { return Implementation.GetByteCount(chars, index, count); } /// <inheritdoc /> public int GetByteCount(string s) { return Implementation.GetByteCount(s); } /// <inheritdoc /> public byte[] GetBytes(char[] chars) { return Implementation.GetBytes(chars); } /// <inheritdoc /> public byte[] GetBytes(char[] chars, int index, int count) { return Implementation.GetBytes(chars, index, count); } /// <inheritdoc /> public int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { return Implementation.GetBytes(chars, charIndex, charCount, bytes, byteIndex); } /// <inheritdoc /> public byte[] GetBytes(string s) { return Implementation.GetBytes(s); } /// <inheritdoc /> public int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { return Implementation.GetBytes(s, charIndex, charCount, bytes, byteIndex); } /// <inheritdoc /> public int GetCharCount(byte[] bytes) { return Implementation.GetCharCount(bytes); } /// <inheritdoc /> public int GetCharCount(byte[] bytes, int index, int count) { return Implementation.GetCharCount(bytes, index, count); } /// <inheritdoc /> public char[] GetChars(byte[] bytes) { return Implementation.GetChars(bytes); } /// <inheritdoc /> public char[] GetChars(byte[] bytes, int index, int count) { return Implementation.GetChars(bytes, index, count); } /// <inheritdoc /> public int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return Implementation.GetChars(bytes, byteIndex, byteCount, chars, charIndex); } /// <inheritdoc /> public IDecoder GetDecoder() { return Implementation.GetDecoder().ToInterface(); } /// <inheritdoc /> public IEncoder GetEncoder() { return Implementation.GetEncoder().ToInterface(); } /// <inheritdoc /> public int GetMaxByteCount(int charCount) { return Implementation.GetMaxByteCount(charCount); } /// <inheritdoc /> public int GetMaxCharCount(int byteCount) { return Implementation.GetMaxCharCount(byteCount); } /// <inheritdoc /> public byte[] GetPreamble() { return Implementation.GetPreamble(); } /// <inheritdoc /> public string GetString(byte[] bytes, int index, int count) { return Implementation.GetString(bytes, index, count); } /// <inheritdoc /> public unsafe int GetByteCount(char* chars, int count) { return Implementation.GetByteCount(chars, count); } /// <inheritdoc /> public unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { return Implementation.GetBytes(chars, charCount, bytes, byteCount); } /// <inheritdoc /> public unsafe int GetCharCount(byte* bytes, int count) { return Implementation.GetCharCount(bytes, count); } /// <inheritdoc /> public unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { return Implementation.GetChars(bytes, byteCount, chars, charCount); } /// <inheritdoc /> public string GetString(byte[] bytes) { return Implementation.GetString(bytes); } /// <inheritdoc /> public unsafe string GetString(byte* bytes, int byteCount) { return Implementation.GetString(bytes, byteCount); } /// <inheritdoc /> public object Clone() { return Implementation.Clone(); } /// <inheritdoc /> public bool IsAlwaysNormalized() { return Implementation.IsAlwaysNormalized(); } /// <inheritdoc /> public bool IsAlwaysNormalized(NormalizationForm form) { return Implementation.IsAlwaysNormalized(form); } /// <inheritdoc /> public string BodyName => Implementation.BodyName; /// <inheritdoc /> public string EncodingName => Implementation.EncodingName; /// <inheritdoc /> public string HeaderName => Implementation.HeaderName; /// <inheritdoc /> public int WindowsCodePage => Implementation.WindowsCodePage; /// <inheritdoc /> public bool IsBrowserDisplay => Implementation.IsBrowserDisplay; /// <inheritdoc /> public bool IsBrowserSave => Implementation.IsBrowserSave; /// <inheritdoc /> public bool IsMailNewsDisplay => Implementation.IsMailNewsDisplay; /// <inheritdoc /> public bool IsMailNewsSave => Implementation.IsMailNewsSave; /// <inheritdoc /> public bool IsSingleByte => Implementation.IsSingleByte; /// <inheritdoc /> public EncoderFallback EncoderFallback { get => Implementation.EncoderFallback; set => Implementation.EncoderFallback = value; } /// <inheritdoc /> public DecoderFallback DecoderFallback { get => Implementation.DecoderFallback; set => Implementation.DecoderFallback = value; } /// <inheritdoc /> public bool IsReadOnly => Implementation.IsReadOnly; /// <inheritdoc /> public int CodePage => Implementation.CodePage; } }
// ----- // GNU General Public License // The Forex Professional Analyzer is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. // The Forex Professional Analyzer is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. // See the GNU Lesser General Public License for more details. // ----- using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Drawing2D; namespace fxpa { /// <summary> /// Needed to rectify problems in the GDI+ drawing mechanism. /// All coordinate dependant operations must be wrapped. /// Since GDI+ makes many problems when it works with very small (0.001 or less) or very big (100000) values, /// all conversions to actual real space are done by for it, by this class. /// This way the Graphics transformation is kept at initial state. /// </summary> public class GraphicsWrapper { Graphics _g; public Graphics Gph { get { return _g; } set { _g = value; } } public SmoothingMode SmoothingMode { get { lock (this) { return _g.SmoothingMode; } } set { lock (this) { _g.SmoothingMode = value; } } } public RectangleF VisibleClipBounds { get { lock (this) { return _g.VisibleClipBounds; } } } protected Matrix _drawingSpaceTransform = new Matrix(); /// <summary> /// Transforms from drawing to actual space. /// </summary> public Matrix DrawingSpaceTransform { get { lock (this) { return _drawingSpaceTransform.Clone(); } } } volatile bool _drawingSpaceMode = false; /// <summary> /// Should subsequent drawing be done in drawing space. /// Will auto reset on ResetTransform(); /// </summary> public bool DrawingSpaceMode { get { return _drawingSpaceMode; } set { _drawingSpaceMode = value; } } /// <summary> /// /// </summary> public GraphicsWrapper() { lock (this) { // Reverted Y axis, since Win32 drawing is top to bottom, and charting is other way round. _drawingSpaceTransform.Scale(1, -1); } } public void SynchronizeDrawingSpaceXAxis(GraphicsWrapper masterWrapper) { lock (this) { // The current transformation matrix. float[] elements = _drawingSpaceTransform.Elements; // Modify the matrix only in X direction. elements[0] = masterWrapper.DrawingSpaceTransform.Elements[0]; elements[4] = masterWrapper.DrawingSpaceTransform.Elements[4]; _drawingSpaceTransform = new Matrix(elements[0], elements[1], elements[2], elements[3], elements[4], elements[5]); } } public void SetGraphics(Graphics g) { lock (this) { _g = g; if (_g != null) { _g.ResetTransform(); } _drawingSpaceMode = false; } } public void ScaleDrawingSpaceTransform(float x, float y) { lock (this) { _drawingSpaceTransform.Scale(x, y); } } public void ScaleDrawingSpaceTransform(float x, float y, MatrixOrder order) { lock (this) { _drawingSpaceTransform.Scale(x, y, order); } } public void TranslateDrawingSpaceTransfrom(float x, float y) { lock (this) { _drawingSpaceTransform.Translate(x, y); } } public void TranslateDrawingSpaceTransfrom(float x, float y, MatrixOrder order) { lock (this) { _drawingSpaceTransform.Translate(x, y, order); } } public void ResetClip() { lock (this) { _g.ResetClip(); } } public void SetClip(Rectangle rectangle) { lock (this) { Convert(ref rectangle); _g.SetClip(rectangle); } } public void SetClip(RectangleF rectangle) { lock (this) { Convert(ref rectangle); _g.SetClip(rectangle); } } public void Convert(ref Rectangle rectangle) { lock (this) { if (_drawingSpaceMode == false) { return; } } RectangleF result = DrawingSpaceToActualSpace(rectangle); rectangle.X = (int)result.X; rectangle.Y = (int)result.Y; rectangle.Width = (int)result.Width; result.Height = (int)result.Height; } void Convert(ref RectangleF rectangle) { lock (this) { if (_drawingSpaceMode == false) { return; } } RectangleF result = DrawingSpaceToActualSpace(rectangle); rectangle.Location = result.Location; rectangle.Size = result.Size; } public void Convert(ref float x, ref float y) { lock (this) { if (_drawingSpaceMode == false) { return; } } PointF result = DrawingSpaceToActualSpace(new PointF(x, y), true); x = result.X; y = result.Y; if ((x < float.MinValue && x > float.MaxValue) || (y <= float.MinValue && y >= float.MaxValue)) { //SystemMonitor.Error("X/Y invalid value."); x = 0; y = 0; } } void Convert(ref Point point) { lock (this) { if (_drawingSpaceMode == false) { return; } } PointF newPoint = DrawingSpaceToActualSpace(point, true); point.X = (int)newPoint.X; point.Y = (int)newPoint.Y; } void Convert(ref PointF point) { lock (this) { if (_drawingSpaceMode == false) { return; } } PointF newPoint = DrawingSpaceToActualSpace(point, true); point.X = newPoint.X; point.Y = newPoint.Y; } void ReverseConvert(ref SizeF size) { lock (this) { if (_drawingSpaceMode == false) { return; } } PointF point = ActualSpaceToDrawingSpace(new PointF(size.Width, size.Height), false); size.Width = point.X; size.Height = point.Y; } public SizeF MeasureString(string text, Font font) { lock (this) { // How about compensating font size? SizeF result = _g.MeasureString(text, font); ReverseConvert(ref result); return result; } } static public void NormalizedRectangle(ref float x, ref float y, ref float width, ref float height) { if (width < 0) { x += width; width = -width; } if (height < 0) { y += height; height = -height; } } public void DrawString(string text, Font font, Brush brush, PointF point) { DrawString(text, font, brush, point.X, point.Y); } public void DrawString(string text, Font font, Brush brush, Rectangle rectangle) { Convert(ref rectangle); DrawString(text, font, brush, rectangle); } public void DrawString(string text, Font font, Brush brush, float x, float y) { //// How about compensating font size? //Convert(ref x, ref y); //GraphicsState state = _g.Save(); //_g.ScaleTransform(1, _drawingSpaceTransform.Elements[3]); //_g.DrawString(text, font, brush, new PointF(x, y * _drawingSpaceTransform.Elements[3])); //_g.Restore(state); lock (this) { // How about compensating font size? Convert(ref x, ref y); _g.DrawString(text, font, brush, x, y); } } public void DrawRectangle(Pen pen, Rectangle rectangle) { lock (this) { Convert(ref rectangle); _g.DrawRectangle(pen, rectangle); } } public void DrawRectangle(Pen pen, RectangleF rectangle) { DrawRectangle(pen, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height); } public void DrawEllipse(Pen pen, float x, float y, float width, float height) { RectangleF rectangle = new RectangleF(x, y, width, height); Convert(ref rectangle); //Convert(ref x, ref y); //_g.DrawEllipse(pen, x, y, width, height); _g.DrawEllipse(pen, rectangle.X, rectangle.Y, rectangle.Height, rectangle.Height); } public void DrawRectangle(Pen pen, float x, float y, float width, float height) { RectangleF rectangle = new RectangleF(x, y, width, height); Convert(ref rectangle); lock (this) { _g.DrawRectangle(pen, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height); } } public void DrawLine(Pen pen, float x1, float y1, float x2, float y2) { Convert(ref x1, ref y1); Convert(ref x2, ref y2); lock (this) { _g.DrawLine(pen, x1, y1, x2, y2); } } public void DrawLine(Pen pen, PointF point1, PointF point2) { Convert(ref point1); Convert(ref point2); lock (this) { _g.DrawLine(pen, point1, point2); } } public void DrawPolygon(Pen pen, PointF[] inputPoints) { PointF[] points = (PointF[])inputPoints.Clone(); lock (this) { for (int i = 0; i < points.Length; i++) { Convert(ref points[i]); } _g.DrawPolygon(pen, points); } } public void FillPolygon(Brush brush, PointF[] inputPoints) { PointF[] points = (PointF[])inputPoints.Clone(); lock (this) { for (int i = 0; i < points.Length; i++) { Convert(ref points[i]); } _g.FillPolygon(brush, points); } } public void FillRectangle(Brush brush, Rectangle rectangle) { Convert(ref rectangle); lock (this) { _g.FillRectangle(brush, rectangle); } } public void FillRectangle(Brush brush, RectangleF rectangle) { Convert(ref rectangle); lock (this) { _g.FillRectangle(brush, rectangle); } } public void FillRectangle(Brush brush, float x, float y, float width, float height) { RectangleF rectangle = new RectangleF(x, y, width, height); Convert(ref rectangle); lock (this) { _g.FillRectangle(brush, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height); } } public void DrawImage(Image image, float x, float y) { DrawImage(image, x, y, image.Width, image.Height); } public void DrawImage(Image image, PointF point) { DrawImage(image, point.X, point.Y, image.Width, image.Height); } public void DrawImage(Image image, float x, float y, float width, float height) { // Here image sizes are compensated. RectangleF rectangle = new RectangleF(x, y, width, height); Convert(ref rectangle); lock (this) { _g.DrawImage(image, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height); } } public void DrawImageUnscaledAndClipped(Image image, Rectangle rectangle) { Convert(ref rectangle); lock (this) { _g.DrawImageUnscaledAndClipped(image, rectangle); } } /// <summary> /// This operates in 1 of 2 modes: /// translation mode (translate the point including scale, and rotation) /// vector mode (rotate and scale vector) /// </summary> public PointF ActualSpaceToDrawingSpace(PointF point, bool translationMode) { lock (this) { // Must have external array, for the function to work. PointF[] array = new PointF[] { point }; Matrix matrix; matrix = _drawingSpaceTransform.Clone(); if (matrix.IsInvertible == false) {// Since some modes result in none invertible matrix, just abandon this calculation. return new PointF(); } matrix.Invert(); if (translationMode) { matrix.TransformPoints(array); } else { matrix.TransformVectors(array); } return array[0]; } } public RectangleF ActualSpaceToDrawingSpace(RectangleF rectangle) { lock (this) { PointF llCorner = ActualSpaceToDrawingSpace(rectangle.Location, true); PointF urCorner = new PointF(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height); urCorner = ActualSpaceToDrawingSpace(urCorner, true); // Normalize. if (llCorner.X > urCorner.X) { float cache = llCorner.X; llCorner.X = urCorner.X; urCorner.X = cache; } if (llCorner.Y > urCorner.Y) { float cache = llCorner.Y; llCorner.Y = urCorner.Y; urCorner.Y = cache; } return new RectangleF(llCorner.X, llCorner.Y, urCorner.X - llCorner.X, urCorner.Y - llCorner.Y); } } public RectangleF DrawingSpaceToActualSpace(RectangleF rectangle) { lock (this) { PointF llCorner = DrawingSpaceToActualSpace(rectangle.Location, true); PointF urCorner = new PointF(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height); urCorner = DrawingSpaceToActualSpace(urCorner, true); // Normalize. if (llCorner.X > urCorner.X) { float cache = llCorner.X; llCorner.X = urCorner.X; urCorner.X = cache; } if (llCorner.Y > urCorner.Y) { float cache = llCorner.Y; llCorner.Y = urCorner.Y; urCorner.Y = cache; } return new RectangleF(llCorner.X, llCorner.Y, urCorner.X - llCorner.X, urCorner.Y - llCorner.Y); } } /// <summary> /// /// </summary> public PointF DrawingSpaceToActualSpace(PointF point, bool translationMode) { lock (this) { PointF[] points = new PointF[] { point }; if (translationMode) { DrawingSpaceTransform.TransformPoints(points); } else { DrawingSpaceTransform.TransformVectors(points); } return points[0]; } } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Owin; using Newtonsoft.Json; using RElmah.Common; using RElmah.Common.Extensions; using RElmah.Extensions; namespace RElmah.Middleware { internal static class Router { public delegate Task<object> AsyncHttpRequest(IDictionary<string, object> env, IDictionary<string, string> keys, IDictionary<string, string> form); public class Route { class AsyncHttpRequestHandler { public AsyncHttpRequest Executor { get; private set; } public Func<object, int> StatusCodeGenerator { get; private set; } public AsyncHttpRequestHandler(AsyncHttpRequest executor, Func<object, int> statusCodeGenerator = null) { Executor = executor; StatusCodeGenerator = statusCodeGenerator ?? (_ => (int)HttpStatusCode.OK); } public static readonly AsyncHttpRequestHandler Null = new AsyncHttpRequestHandler( async (_, __, ___) => await Task.FromResult((object) null), _ => (int)HttpStatusCode.NotFound); } private readonly ImmutableDictionary<string, AsyncHttpRequestHandler> _handlers = ImmutableDictionary<string, AsyncHttpRequestHandler>.Empty; Route() { } Route(Route r, string verb, AsyncHttpRequest handler, Func<object, int> statusCodeGenerator) { _handlers = r._handlers.Add(verb, new AsyncHttpRequestHandler(handler, statusCodeGenerator)); } public static Route Empty { get { return new Route(); } } private Route Handle(string verb, AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null) { return new Route(this, verb, handler, statusCodeGenerator); } public Route Get(AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null) { return Handle("GET", handler, statusCodeGenerator ?? (r => r == null ? (int)HttpStatusCode.NotFound : (int)HttpStatusCode.OK)); } public Route Delete(AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null) { return Handle("DELETE", handler, statusCodeGenerator ?? (r => r == null ? (int)HttpStatusCode.NoContent : (int)HttpStatusCode.OK)); } public Route Put(AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null) { return Handle("PUT", handler, statusCodeGenerator ?? (r => r == null ? (int)HttpStatusCode.NoContent : (int)HttpStatusCode.OK)); } public Route Post(AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null) { return Handle("POST", handler, statusCodeGenerator ?? (r => r == null ? (int)HttpStatusCode.NoContent : (int)HttpStatusCode.Created)); } public async Task Invoke(IDictionary<string, object> environment, IDictionary<string, string> keys) { var completed = new TaskCompletionSource<bool>(); try { var request = new OwinRequest(environment); var handler = _handlers.GetValueOrDefault(request.Method, AsyncHttpRequestHandler.Null); keys = keys.ToDictionary(k => k.Key, v => WebUtility.UrlDecode(v.Value)); await ExecuteAsync(environment, keys, request, handler).ConfigureAwait(false); completed.TrySetResult(true); } catch (Exception ex) { completed.TrySetException(ex); throw; } } static readonly IDictionary<string, string[]> EmptyForm = new Dictionary<string, string[]>(); private static async Task ExecuteAsync( IDictionary<string, object> environment, IDictionary<string, string> keys, OwinRequest request, AsyncHttpRequestHandler handler) { var response = new OwinResponse(environment); var executor = (Func<Task<object>>)(async () => { var form = from w in request.HasForm() ? (IEnumerable<KeyValuePair<string, string[]>>)(await request.ReadFormAsync().ConfigureAwait(false)) : EmptyForm select w != null ? w[0] : null; return await handler.Executor( environment, keys, form.ToDictionary()); }); var result = await executor().ConfigureAwait(false); if (result != null) await response.WriteAsync(JsonConvert.SerializeObject(result)).ConfigureAwait(false); response.StatusCode = handler.StatusCodeGenerator != null ? handler.StatusCodeGenerator(result) : (int)HttpStatusCode.OK; } } public class RouteBuilder { private const string DefaultPrefix = "relmah"; private readonly ImmutableDictionary<string, Route> _routes = ImmutableDictionary<string, Route>.Empty; private readonly ImmutableList<string> _keys = ImmutableList<string>.Empty; public string Prefix { get; private set; } RouteBuilder(string prefix) { Prefix = String.IsNullOrWhiteSpace(prefix) ? DefaultPrefix : prefix; } RouteBuilder(RouteBuilder rb, string pattern, Route route) { Prefix = rb.Prefix; _routes = rb._routes.Add(pattern, route); _keys = rb._keys.Add(pattern); } public IDictionary<string, Route> Routes { get { return _routes; } } public IEnumerable<string> RoutesKeys { get { return _keys; } } public static RouteBuilder Empty { get { return new RouteBuilder(DefaultPrefix); } } public RouteBuilder WithPrefix(string prefix) { return new RouteBuilder(prefix); } public RouteBuilder ForRoute(string pattern, Func<Route, Route> buildRoute) { return new RouteBuilder(this, pattern, buildRoute(Route.Empty)); } } private static ImmutableList<RouteBuilder> _builders = ImmutableList<RouteBuilder>.Empty; public static void Build(Func<RouteBuilder, RouteBuilder> build) { _builders = _builders.Add(build(RouteBuilder.Empty)); } static string ToRegex(string pattern) { return Regex.Replace(pattern, @"\{(?'x'\w*)\}", @"(?'$1'[^/]+)"); } public static Task Invoke(IOwinContext context, Func<IOwinContext, Task> next) { var request = new OwinRequest(context.Environment); var segments = request.Uri.Segments; var raw = String.Join(null, segments); var matches = from builder in _builders from key in builder.RoutesKeys let matcher = new Regex(String.Format("^/{0}/{1}/?$", builder.Prefix, ToRegex(key))) let match = matcher.Match(raw) where match.Success let groups = match .Groups .Cast<Group>() .Index() let @params = (from g in groups select new KeyValuePair<string, string>( matcher.GroupNameFromNumber(g.Key), g.Value.Value)) select new { Params = @params.Skip(1).ToDictionary(k => k.Key, v => v.Value), Route = builder.Routes[key] }; var invocation = matches.FirstOrDefault(); return invocation != null ? invocation.Route.Invoke(context.Environment, invocation.Params) : next(context); } } }
/* * 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 System.IO; using System.Diagnostics; using System.Threading; using log4net; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Physics.Manager; using OpenMetaverse; using BulletDotNET; namespace OpenSim.Region.Physics.BulletDotNETPlugin { public class BulletDotNETScene : PhysicsScene { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // private string m_sceneIdentifier = string.Empty; private List<BulletDotNETCharacter> m_characters = new List<BulletDotNETCharacter>(); private Dictionary<uint, BulletDotNETCharacter> m_charactersLocalID = new Dictionary<uint, BulletDotNETCharacter>(); private List<BulletDotNETPrim> m_prims = new List<BulletDotNETPrim>(); private Dictionary<uint, BulletDotNETPrim> m_primsLocalID = new Dictionary<uint, BulletDotNETPrim>(); private List<BulletDotNETPrim> m_activePrims = new List<BulletDotNETPrim>(); private List<PhysicsActor> m_taintedActors = new List<PhysicsActor>(); private btDiscreteDynamicsWorld m_world; private btAxisSweep3 m_broadphase; private btCollisionConfiguration m_collisionConfiguration; private btConstraintSolver m_solver; private btCollisionDispatcher m_dispatcher; private PhysicsActor m_terrainShape; public btRigidBody TerrainBody; private btVector3 m_terrainPosition; private btVector3 m_gravity; public btMotionState m_terrainMotionState; public btTransform m_terrainTransform; public btVector3 VectorZero; public btQuaternion QuatIdentity; public btTransform TransZero; public float geomDefaultDensity = 10.000006836f; private float avPIDD = 65f; private float avPIDP = 21f; private float avCapRadius = 0.37f; private float avStandupTensor = 2000000f; private float avDensity = 80f; private float avHeightFudgeFactor = 0.52f; private float avMovementDivisorWalk = 1.8f; private float avMovementDivisorRun = 0.8f; // private float minimumGroundFlightOffset = 3f; public bool meshSculptedPrim = true; public float meshSculptLOD = 32; public float MeshSculptphysicalLOD = 16; public float bodyPIDD = 35f; public float bodyPIDG = 25; internal int geomCrossingFailuresBeforeOutofbounds = 4; public float bodyMotorJointMaxforceTensor = 2; public int bodyFramesAutoDisable = 20; public float WorldTimeStep = 10f/60f; public const float WorldTimeComp = 1/60f; public float gravityz = -9.8f; private float[] _origheightmap; // Used for Fly height. Kitto Flora private bool usingGImpactAlgorithm = false; // private IConfigSource m_config; private readonly btVector3 worldAabbMin = new btVector3(-10f, -10f, 0); private readonly btVector3 worldAabbMax = new btVector3((int)Constants.RegionSize + 10f, (int)Constants.RegionSize + 10f, 9000); public IMesher mesher; public IVoxelMesher voxmesher; private ContactAddedCallbackHandler m_CollisionInterface; public BulletDotNETScene(string sceneIdentifier) { // m_sceneIdentifier = sceneIdentifier; VectorZero = new btVector3(0, 0, 0); QuatIdentity = new btQuaternion(0, 0, 0, 1); TransZero = new btTransform(QuatIdentity, VectorZero); m_gravity = new btVector3(0, 0, gravityz); _origheightmap = new float[(int)Constants.RegionSize * (int)Constants.RegionSize]; } public override void Initialise(IMesher meshmerizer, IVoxelMesher voxmesh, IConfigSource config) { mesher = meshmerizer; // m_config = config; /* if (Environment.OSVersion.Platform == PlatformID.Unix) { m_log.Fatal("[BulletDotNET]: This configuration is not supported on *nix currently"); Thread.Sleep(5000); Environment.Exit(0); } */ m_broadphase = new btAxisSweep3(worldAabbMin, worldAabbMax, 16000); m_collisionConfiguration = new btDefaultCollisionConfiguration(); m_solver = new btSequentialImpulseConstraintSolver(); m_dispatcher = new btCollisionDispatcher(m_collisionConfiguration); m_world = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration); m_world.setGravity(m_gravity); EnableCollisionInterface(); voxmesher = voxmesh; } public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying) { BulletDotNETCharacter chr = new BulletDotNETCharacter(avName, this, position, size, avPIDD, avPIDP, avCapRadius, avStandupTensor, avDensity, avHeightFudgeFactor, avMovementDivisorWalk, avMovementDivisorRun); try { m_characters.Add(chr); m_charactersLocalID.Add(chr.m_localID, chr); } catch { // noop if it's already there m_log.Debug("[PHYSICS] BulletDotNet: adding duplicate avatar localID"); } AddPhysicsActorTaint(chr); return chr; } public override void RemoveAvatar(PhysicsActor actor) { BulletDotNETCharacter chr = (BulletDotNETCharacter) actor; m_charactersLocalID.Remove(chr.m_localID); m_characters.Remove(chr); m_world.removeRigidBody(chr.Body); m_world.removeCollisionObject(chr.Body); chr.Remove(); AddPhysicsActorTaint(chr); //chr = null; } public override void RemovePrim(PhysicsActor prim) { if (prim is BulletDotNETPrim) { BulletDotNETPrim p = (BulletDotNETPrim)prim; p.setPrimForRemoval(); AddPhysicsActorTaint(prim); //RemovePrimThreadLocked(p); } } private PhysicsActor AddPrim(String name, Vector3 position, Vector3 size, Quaternion rotation, IMesh mesh, PrimitiveBaseShape pbs, bool isphysical) { Vector3 pos = position; //pos.X = position.X; //pos.Y = position.Y; //pos.Z = position.Z; Vector3 siz = Vector3.Zero; siz.X = size.X; siz.Y = size.Y; siz.Z = size.Z; Quaternion rot = rotation; BulletDotNETPrim newPrim; newPrim = new BulletDotNETPrim(name, this, pos, siz, rot, mesh, pbs, isphysical); //lock (m_prims) // m_prims.Add(newPrim); return newPrim; } public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position, Vector3 size, Quaternion rotation) { return AddPrimShape(primName, pbs, position, size, rotation, false); } public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position, Vector3 size, Quaternion rotation, bool isPhysical) { PhysicsActor result; IMesh mesh = null; //switch (pbs.ProfileShape) //{ // case ProfileShape.Square: // //support simple box & hollow box now; later, more shapes // if (needsMeshing(pbs)) // { // mesh = mesher.CreateMesh(primName, pbs, size, 32f, isPhysical); // } // break; //} if (needsMeshing(pbs)) mesh = mesher.CreateMesh(primName, pbs, size, 32f, isPhysical); result = AddPrim(primName, position, size, rotation, mesh, pbs, isPhysical); return result; } public override void AddPhysicsActorTaint(PhysicsActor prim) { lock (m_taintedActors) { if (!m_taintedActors.Contains(prim)) { m_taintedActors.Add(prim); } } } internal void SetUsingGImpact() { if (!usingGImpactAlgorithm) btGImpactCollisionAlgorithm.registerAlgorithm(m_dispatcher); usingGImpactAlgorithm = true; } public override float Simulate(float timeStep) { lock (m_taintedActors) { foreach (PhysicsActor act in m_taintedActors) { if (act is BulletDotNETCharacter) ((BulletDotNETCharacter) act).ProcessTaints(timeStep); if (act is BulletDotNETPrim) ((BulletDotNETPrim)act).ProcessTaints(timeStep); } m_taintedActors.Clear(); } lock (m_characters) { foreach (BulletDotNETCharacter chr in m_characters) { chr.Move(timeStep); } } lock (m_prims) { foreach (BulletDotNETPrim prim in m_prims) { if (prim != null) prim.Move(timeStep); } } float steps = m_world.stepSimulation(timeStep, 10, WorldTimeComp); foreach (BulletDotNETCharacter chr in m_characters) { chr.UpdatePositionAndVelocity(); } foreach (BulletDotNETPrim prm in m_activePrims) { /* if (prm != null) if (prm.Body != null) */ prm.UpdatePositionAndVelocity(); } if (m_CollisionInterface != null) { List<BulletDotNETPrim> primsWithCollisions = new List<BulletDotNETPrim>(); List<BulletDotNETCharacter> charactersWithCollisions = new List<BulletDotNETCharacter>(); // get the collisions that happened this tick List<BulletDotNET.ContactAddedCallbackHandler.ContactInfo> collisions = m_CollisionInterface.GetContactList(); // passed back the localID of the prim so we can associate the prim foreach (BulletDotNET.ContactAddedCallbackHandler.ContactInfo ci in collisions) { // ContactPoint = { contactPoint, contactNormal, penetrationDepth } ContactPoint contact = new ContactPoint(new Vector3(ci.pX, ci.pY, ci.pZ), new Vector3(ci.nX, ci.nY, ci.nZ), ci.depth); ProcessContact(ci.contact, ci.contactWith, contact, ref primsWithCollisions, ref charactersWithCollisions); ProcessContact(ci.contactWith, ci.contact, contact, ref primsWithCollisions, ref charactersWithCollisions); } m_CollisionInterface.Clear(); // for those prims and characters that had collisions cause collision events foreach (BulletDotNETPrim bdnp in primsWithCollisions) { bdnp.SendCollisions(); } foreach (BulletDotNETCharacter bdnc in charactersWithCollisions) { bdnc.SendCollisions(); } } return steps; } private void ProcessContact(uint cont, uint contWith, ContactPoint contact, ref List<BulletDotNETPrim> primsWithCollisions, ref List<BulletDotNETCharacter> charactersWithCollisions) { BulletDotNETPrim bdnp; // collisions with a normal prim? if (m_primsLocalID.TryGetValue(cont, out bdnp)) { // Added collision event to the prim. This creates a pile of events // that will be sent to any subscribed listeners. bdnp.AddCollision(contWith, contact); if (!primsWithCollisions.Contains(bdnp)) { primsWithCollisions.Add(bdnp); } } else { BulletDotNETCharacter bdnc; // if not a prim, maybe it's one of the characters if (m_charactersLocalID.TryGetValue(cont, out bdnc)) { bdnc.AddCollision(contWith, contact); if (!charactersWithCollisions.Contains(bdnc)) { charactersWithCollisions.Add(bdnc); } } } } public override void GetResults() { } public override void SetTerrain(bool[] heightMap) { if (m_terrainShape != null) DeleteTerrain(); m_terrainShape = AddPrim( "__TERRAIN__", new Vector3(Constants.RegionSize / 2, Constants.RegionSize / 2, Constants.RegionSize / 2), new Vector3(Constants.RegionSize, Constants.RegionSize, Constants.RegionSize), Quaternion.Identity, voxmesher.ToMesh(heightMap), PrimitiveBaseShape.Default, false); //float AabbCenterX = Constants.RegionSize/2f; //float AabbCenterY = Constants.RegionSize/2f; //float AabbCenterZ = 0f; /* float temphfmin, temphfmax; temphfmin = hfmin; temphfmax = hfmax; if (temphfmin < 0) { temphfmax = 0 - temphfmin; temphfmin = 0 - temphfmin; } else if (temphfmin > 0) { temphfmax = temphfmax + (0 - temphfmin); //temphfmin = temphfmin + (0 - temphfmin); } AabbCenterZ = temphfmax/2f; if (m_terrainPosition == null) { m_terrainPosition = new btVector3(AabbCenterX, AabbCenterY, AabbCenterZ); } else { try { m_terrainPosition.setValue(AabbCenterX, AabbCenterY, AabbCenterZ); } catch (ObjectDisposedException) { m_terrainPosition = new btVector3(AabbCenterX, AabbCenterY, AabbCenterZ); } } */ if (m_terrainMotionState != null) { m_terrainMotionState.Dispose(); m_terrainMotionState = null; } m_terrainTransform = new btTransform(QuatIdentity, m_terrainPosition); m_terrainMotionState = new btDefaultMotionState(m_terrainTransform); } public override void SetWaterLevel(float baseheight) { } public override void DeleteTerrain() { if (TerrainBody != null) { m_world.removeRigidBody(TerrainBody); } if (m_terrainShape != null) { //m_terrainShape.Dispose(); m_terrainShape = null; } if (m_terrainMotionState != null) { m_terrainMotionState.Dispose(); m_terrainMotionState = null; } if (m_terrainTransform != null) { m_terrainTransform.Dispose(); m_terrainTransform = null; } if (m_terrainPosition != null) { m_terrainPosition.Dispose(); m_terrainPosition = null; } } public override void Dispose() { disposeAllBodies(); m_world.Dispose(); m_broadphase.Dispose(); ((btDefaultCollisionConfiguration) m_collisionConfiguration).Dispose(); ((btSequentialImpulseConstraintSolver) m_solver).Dispose(); worldAabbMax.Dispose(); worldAabbMin.Dispose(); VectorZero.Dispose(); QuatIdentity.Dispose(); m_gravity.Dispose(); VectorZero = null; QuatIdentity = null; } public override Dictionary<uint, float> GetTopColliders() { return new Dictionary<uint, float>(); } public btDiscreteDynamicsWorld getBulletWorld() { return m_world; } private void disposeAllBodies() { lock (m_prims) { m_primsLocalID.Clear(); foreach (BulletDotNETPrim prim in m_prims) { if (prim.Body != null) m_world.removeRigidBody(prim.Body); prim.Dispose(); } m_prims.Clear(); foreach (BulletDotNETCharacter chr in m_characters) { if (chr.Body != null) m_world.removeRigidBody(chr.Body); chr.Dispose(); } m_characters.Clear(); } } public override bool IsThreaded { get { return false; } } internal void addCollisionEventReporting(PhysicsActor bulletDotNETCharacter) { //TODO: FIXME: } internal void remCollisionEventReporting(PhysicsActor bulletDotNETCharacter) { //TODO: FIXME: } internal void AddRigidBody(btRigidBody Body) { m_world.addRigidBody(Body); } [Obsolete("bad!")] internal void removeFromWorld(btRigidBody body) { m_world.removeRigidBody(body); } internal void removeFromWorld(BulletDotNETPrim prm ,btRigidBody body) { lock (m_prims) { if (m_prims.Contains(prm)) { m_world.removeRigidBody(body); } remActivePrim(prm); m_primsLocalID.Remove(prm.m_localID); m_prims.Remove(prm); } } internal float GetWaterLevel() { throw new NotImplementedException(); } // Recovered for use by fly height. Kitto Flora public float GetTerrainHeightAtXY(float x, float y) { // Teravus: Kitto, this code causes recurring errors that stall physics permenantly unless // the values are checked, so checking below. // Is there any reason that we don't do this in ScenePresence? // The only physics engine that benefits from it in the physics plugin is this one if (x > (int)Constants.RegionSize || y > (int)Constants.RegionSize || x < 0.001f || y < 0.001f) return 0; return _origheightmap[(int)y * Constants.RegionSize + (int)x]; } // End recovered. Kitto Flora /// <summary> /// Routine to figure out if we need to mesh this prim with our mesher /// </summary> /// <param name="pbs"></param> /// <returns></returns> public bool needsMeshing(PrimitiveBaseShape pbs) { // most of this is redundant now as the mesher will return null if it cant mesh a prim // but we still need to check for sculptie meshing being enabled so this is the most // convenient place to do it for now... // //if (pbs.PathCurve == (byte)Primitive.PathCurve.Circle && pbs.ProfileCurve == (byte)Primitive.ProfileCurve.Circle && pbs.PathScaleY <= 0.75f) // //m_log.Debug("needsMeshing: " + " pathCurve: " + pbs.PathCurve.ToString() + " profileCurve: " + pbs.ProfileCurve.ToString() + " pathScaleY: " + Primitive.UnpackPathScale(pbs.PathScaleY).ToString()); int iPropertiesNotSupportedDefault = 0; if (pbs.SculptEntry && !meshSculptedPrim) { #if SPAM m_log.Warn("NonMesh"); #endif return false; } // if it's a standard box or sphere with no cuts, hollows, twist or top shear, return false since ODE can use an internal representation for the prim if ((pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight) || (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1 && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z)) { if (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0 && pbs.ProfileHollow == 0 && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0 && pbs.PathBegin == 0 && pbs.PathEnd == 0 && pbs.PathTaperX == 0 && pbs.PathTaperY == 0 && pbs.PathScaleX == 100 && pbs.PathScaleY == 100 && pbs.PathShearX == 0 && pbs.PathShearY == 0) { #if SPAM m_log.Warn("NonMesh"); #endif return false; } } if (pbs.ProfileHollow != 0) iPropertiesNotSupportedDefault++; if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0)) iPropertiesNotSupportedDefault++; if ((pbs.ProfileBegin != 0) || pbs.ProfileEnd != 0) iPropertiesNotSupportedDefault++; if ((pbs.PathScaleX != 100) || (pbs.PathScaleY != 100)) iPropertiesNotSupportedDefault++; if ((pbs.PathShearX != 0) || (pbs.PathShearY != 0)) iPropertiesNotSupportedDefault++; if (pbs.ProfileShape == ProfileShape.Circle && pbs.PathCurve == (byte)Extrusion.Straight) iPropertiesNotSupportedDefault++; if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1 && (pbs.Scale.X != pbs.Scale.Y || pbs.Scale.Y != pbs.Scale.Z || pbs.Scale.Z != pbs.Scale.X)) iPropertiesNotSupportedDefault++; if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1) iPropertiesNotSupportedDefault++; // test for torus if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Square) { if (pbs.PathCurve == (byte)Extrusion.Curve1) { iPropertiesNotSupportedDefault++; } } else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Circle) { if (pbs.PathCurve == (byte)Extrusion.Straight) { iPropertiesNotSupportedDefault++; } // ProfileCurve seems to combine hole shape and profile curve so we need to only compare against the lower 3 bits else if (pbs.PathCurve == (byte)Extrusion.Curve1) { iPropertiesNotSupportedDefault++; } } else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle) { if (pbs.PathCurve == (byte)Extrusion.Curve1 || pbs.PathCurve == (byte)Extrusion.Curve2) { iPropertiesNotSupportedDefault++; } } else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle) { if (pbs.PathCurve == (byte)Extrusion.Straight) { iPropertiesNotSupportedDefault++; } else if (pbs.PathCurve == (byte)Extrusion.Curve1) { iPropertiesNotSupportedDefault++; } } if (iPropertiesNotSupportedDefault == 0) { #if SPAM m_log.Warn("NonMesh"); #endif return false; } #if SPAM m_log.Debug("Mesh"); #endif return true; } internal void addActivePrim(BulletDotNETPrim pPrim) { lock (m_activePrims) { if (!m_activePrims.Contains(pPrim)) { m_activePrims.Add(pPrim); } } } public void remActivePrim(BulletDotNETPrim pDeactivatePrim) { lock (m_activePrims) { m_activePrims.Remove(pDeactivatePrim); } } internal void AddPrimToScene(BulletDotNETPrim pPrim) { lock (m_prims) { if (!m_prims.Contains(pPrim)) { try { m_prims.Add(pPrim); m_primsLocalID.Add(pPrim.m_localID, pPrim); } catch { // noop if it's already there m_log.Debug("[PHYSICS] BulletDotNet: adding duplicate prim localID"); } m_world.addRigidBody(pPrim.Body); // m_log.Debug("[PHYSICS] added prim to scene"); } } } internal void EnableCollisionInterface() { if (m_CollisionInterface == null) { m_CollisionInterface = new ContactAddedCallbackHandler(m_world); // m_world.SetCollisionAddedCallback(m_CollisionInterface); } } } }
using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; using STATSTG = System.Runtime.InteropServices.ComTypes.STATSTG; namespace Splicer.Utilities { #region Unmanaged Code declarations [Flags] internal enum STGM { Read = 0x00000000, Write = 0x00000001, ReadWrite = 0x00000002, ShareDenyNone = 0x00000040, ShareDenyRead = 0x00000030, ShareDenyWrite = 0x00000020, ShareExclusive = 0x00000010, Priority = 0x00040000, Create = 0x00001000, Convert = 0x00020000, FailIfThere = 0x00000000, Direct = 0x00000000, Transacted = 0x00010000, NoScratch = 0x00100000, NoSnapShot = 0x00200000, Simple = 0x08000000, DirectSWMR = 0x00400000, DeleteOnRelease = 0x04000000, } [Flags] internal enum STGC { Default = 0, Overwrite = 1, OnlyIfCurrent = 2, DangerouslyCommitMerelyToDiskCache = 4, Consolidate = 8 } [Guid("0000000b-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IStorage { [PreserveSig] int CreateStream( [In, MarshalAs(UnmanagedType.LPWStr)] string pwcsName, [In] STGM grfMode, [In] int reserved1, [In] int reserved2, [Out] out IStream ppstm ); [PreserveSig] int OpenStream( [In, MarshalAs(UnmanagedType.LPWStr)] string pwcsName, [In] IntPtr reserved1, [In] STGM grfMode, [In] int reserved2, [Out] out IStream ppstm ); [PreserveSig] int CreateStorage( [In, MarshalAs(UnmanagedType.LPWStr)] string pwcsName, [In] STGM grfMode, [In] int reserved1, [In] int reserved2, [Out] out IStorage ppstg ); [PreserveSig] int OpenStorage( [In, MarshalAs(UnmanagedType.LPWStr)] string pwcsName, [In] IStorage pstgPriority, [In] STGM grfMode, [In] int snbExclude, [In] int reserved, [Out] out IStorage ppstg ); [PreserveSig] int CopyTo( [In] int ciidExclude, [In] Guid[] rgiidExclude, [In] string[] snbExclude, [In] IStorage pstgDest ); [PreserveSig] int MoveElementTo( [In, MarshalAs(UnmanagedType.LPWStr)] string pwcsName, [In] IStorage pstgDest, [In, MarshalAs(UnmanagedType.LPWStr)] string pwcsNewName, [In] STGM grfFlags ); [PreserveSig] int Commit([In] STGC grfCommitFlags); [PreserveSig] int Revert(); [PreserveSig] int EnumElements( [In] int reserved1, [In] IntPtr reserved2, [In] int reserved3, [Out, MarshalAs(UnmanagedType.Interface)] out object ppenum ); [PreserveSig] int DestroyElement([In, MarshalAs(UnmanagedType.LPWStr)] string pwcsName); [PreserveSig] int RenameElement( [In, MarshalAs(UnmanagedType.LPWStr)] string pwcsOldName, [In, MarshalAs(UnmanagedType.LPWStr)] string pwcsNewName ); [PreserveSig] int SetElementTimes( [In, MarshalAs(UnmanagedType.LPWStr)] string pwcsName, [In] FILETIME pctime, [In] FILETIME patime, [In] FILETIME pmtime ); [PreserveSig] int SetClass([In, MarshalAs(UnmanagedType.LPStruct)] Guid clsid); [PreserveSig] int SetStateBits( [In] int grfStateBits, [In] int grfMask ); [PreserveSig] int Stat([Out] out STATSTG pStatStg, [In] int grfStatFlag ); } #endregion internal sealed class NativeMethods { private NativeMethods() { } [DllImport("ole32.dll")] public static extern int CreateBindCtx(int reserved, out IBindCtx ppbc); [DllImport("ole32.dll")] public static extern int MkParseDisplayName(IBindCtx pcb, [MarshalAs(UnmanagedType.LPWStr)] string szUserName, out int pchEaten, out IMoniker ppmk); [DllImport("olepro32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern int OleCreatePropertyFrame( [In] IntPtr hwndOwner, [In] int x, [In] int y, [In, MarshalAs(UnmanagedType.LPWStr)] string lpszCaption, [In] int cObjects, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.IUnknown)] object[] ppUnk, [In] int cPages, [In] IntPtr pPageClsID, [In] int lcid, [In] int dwReserved, [In] IntPtr pvReserved ); [DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern int StgCreateDocfile( [In, MarshalAs(UnmanagedType.LPWStr)] string pwcsName, [In] STGM grfMode, [In] int reserved, [Out] out IStorage ppstgOpen ); [DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern int StgIsStorageFile([In, MarshalAs(UnmanagedType.LPWStr)] string pwcsName); [DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern int StgOpenStorage( [In, MarshalAs(UnmanagedType.LPWStr)] string pwcsName, [In] IStorage pstgPriority, [In] STGM grfMode, [In] IntPtr snbExclude, [In] int reserved, [Out] out IStorage ppstgOpen ); } }
// // SqliteUtils.cs // // Author: // Scott Peterson <lunchtimemama@gmail.com> // // Copyright (C) 2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Text; using System.Collections.Generic; namespace Hyena.Data.Sqlite { public static class SqliteUtils { internal static string GetType (Type type) { if (type == typeof (string)) { return "TEXT"; } else if (type == typeof (int) || type == typeof (long) || type == typeof (bool) || type == typeof (DateTime) || type == typeof (TimeSpan) || type.IsEnum) { return "INTEGER"; } else if (type == typeof (int?) || type == typeof (long?) || type == typeof (bool?) || type == typeof (uint?)) { return "INTEGER NULL"; } else if (type == typeof (byte[])) { return "BLOB"; } else if (type == typeof (double)) { return "REAL"; } else if (type == typeof (double?)) { return "REAL NULL"; } else { throw new Exception (String.Format ( "The type {0} cannot be bound to a database column.", type.Name)); } } public static object ToDbFormat (object value) { if (value == null) return null; return ToDbFormat (value.GetType (), value); } public static object ToDbFormat (Type type, object value) { if (type == typeof (string)) { // Treat blank strings or strings with only whitespace as null return value == null || String.IsNullOrEmpty (((string)value).Trim ()) ? null : value; } else if (type == typeof (DateTime)) { return DateTime.MinValue.Equals ((DateTime)value) ? (object)null : DateTimeUtil.FromDateTime ((DateTime)value); } else if (type == typeof (TimeSpan)) { return TimeSpan.MinValue.Equals ((TimeSpan)value) ? (object)null : ((TimeSpan)value).TotalMilliseconds; } else if (type == typeof (bool)) { return ((bool)value) ? 1 : 0; } else if (enum_types.Contains (type)) { return Convert.ChangeType (value, Enum.GetUnderlyingType (type)); } else if (type.IsEnum) { enum_types.Add (type); return Convert.ChangeType (value, Enum.GetUnderlyingType (type)); } return value; } public static T FromDbFormat<T> (object value) { object o = FromDbFormat (typeof(T), value); return o == null ? default(T) : (T)o; } public static object FromDbFormat (Type type, object value) { if (Convert.IsDBNull (value)) value = null; if (type == typeof (DateTime)) { if (value == null) return DateTime.MinValue; else if (!(value is long)) value = Convert.ToInt64 (value); return DateTimeUtil.ToDateTime ((long)value); } else if (type == typeof (TimeSpan)) { if (value == null) return TimeSpan.MinValue; else if (!(value is long)) value = Convert.ToInt64 (value); return TimeSpan.FromMilliseconds ((long)value); } else if (value == null) { if (type.IsValueType) { return Activator.CreateInstance (type); } else { return null; } } else if (type == typeof (bool)) { return ((long)value == 1); } else if (type == typeof (double?)) { if (value == null) return null; double double_value = ((Single?) value).Value; return (double?) double_value; } else if (type.IsEnum) { return Enum.ToObject (type, value); } else { return Convert.ChangeType (value, type); } } internal static string BuildColumnSchema (string type, string name, string default_value, DatabaseColumnConstraints constraints) { StringBuilder builder = new StringBuilder (); builder.Append (name); builder.Append (' '); builder.Append (type); if ((constraints & DatabaseColumnConstraints.NotNull) > 0) { builder.Append (" NOT NULL"); } if ((constraints & DatabaseColumnConstraints.Unique) > 0) { builder.Append (" UNIQUE"); } if ((constraints & DatabaseColumnConstraints.PrimaryKey) > 0) { builder.Append (" PRIMARY KEY"); } if (default_value != null) { builder.Append (" DEFAULT "); builder.Append (default_value); } return builder.ToString (); } readonly static HashSet<Type> enum_types = new HashSet<Type> (); } [SqliteFunction (Name = "HYENA_BINARY_FUNCTION", FuncType = FunctionType.Scalar, Arguments = 3)] public sealed class BinaryFunction : SqliteFunction { private static Dictionary<string, Func<object, object, object>> funcs = new Dictionary<string, Func<object, object, object>> (); public static void Add (string functionId, Func<object, object, object> func) { lock (funcs) { if (funcs.ContainsKey (functionId)) { throw new ArgumentException (String.Format ("{0} is already taken", functionId), "functionId"); } funcs[functionId] = func; } } public static void Remove (string functionId) { lock (funcs) { if (!funcs.ContainsKey (functionId)) { throw new ArgumentException (String.Format ("{0} does not exist", functionId), "functionId"); } funcs.Remove (functionId); } } public override object Invoke (object[] args) { Func<object, object, object> func; if (!funcs.TryGetValue (args[0] as string, out func)) throw new ArgumentException (args[0] as string, "HYENA_BINARY_FUNCTION name (arg 0)"); return func (args[1], args[2]); } } [SqliteFunction (Name = "HYENA_COLLATION_KEY", FuncType = FunctionType.Scalar, Arguments = 1)] internal class CollationKeyFunction : SqliteFunction { public override object Invoke (object[] args) { return Hyena.StringUtil.SortKey (args[0] as string); } } [SqliteFunction (Name = "HYENA_SEARCH_KEY", FuncType = FunctionType.Scalar, Arguments = 1)] internal class SearchKeyFunction : SqliteFunction { public override object Invoke (object[] args) { return Hyena.StringUtil.SearchKey (args[0] as string); } } [SqliteFunction (Name = "HYENA_MD5", FuncType = FunctionType.Scalar, Arguments = -1)] internal class Md5Function : SqliteFunction { public override object Invoke (object[] args) { int n_args = (int)(long) args[0]; var sb = new StringBuilder (); for (int i = 1; i <= n_args; i++) { sb.Append (args[i]); } return Hyena.CryptoUtil.Md5Encode (sb.ToString (), System.Text.Encoding.UTF8); } } }
// *********************************************************************** // Copyright (c) 2006 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.ComponentModel; using NUnit.Framework.Constraints; namespace NUnit.Framework { /// <summary> /// A set of Assert methods operating on one or more collections /// </summary> // Abstract because we support syntax extension by inheriting and declaring new static members. public abstract class CollectionAssert { #region Equals and ReferenceEquals /// <summary> /// DO NOT USE! Use CollectionAssert.AreEqual(...) instead. /// The Equals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// </summary> /// <param name="a"></param> /// <param name="b"></param> [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { throw new InvalidOperationException("CollectionAssert.Equals should not be used for Assertions, use CollectionAssert.AreEqual(...) instead."); } /// <summary> /// DO NOT USE! /// The ReferenceEquals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// </summary> /// <param name="a"></param> /// <param name="b"></param> public static new void ReferenceEquals(object a, object b) { throw new InvalidOperationException("CollectionAssert.ReferenceEquals should not be used for Assertions."); } #endregion #region AllItemsAreInstancesOfType /// <summary> /// Asserts that all items contained in collection are of the type specified by expectedType. /// </summary> /// <param name="collection">IEnumerable containing objects to be considered</param> /// <param name="expectedType">System.Type that all objects in collection must be instances of</param> public static void AllItemsAreInstancesOfType (IEnumerable collection, Type expectedType) { AllItemsAreInstancesOfType(collection, expectedType, string.Empty, null); } /// <summary> /// Asserts that all items contained in collection are of the type specified by expectedType. /// </summary> /// <param name="collection">IEnumerable containing objects to be considered</param> /// <param name="expectedType">System.Type that all objects in collection must be instances of</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AllItemsAreInstancesOfType (IEnumerable collection, Type expectedType, string message, params object[] args) { Assert.That(collection, Is.All.InstanceOf(expectedType), message, args); } #endregion #region AllItemsAreNotNull /// <summary> /// Asserts that all items contained in collection are not equal to null. /// </summary> /// <param name="collection">IEnumerable containing objects to be considered</param> public static void AllItemsAreNotNull (IEnumerable collection) { AllItemsAreNotNull(collection, string.Empty, null); } /// <summary> /// Asserts that all items contained in collection are not equal to null. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AllItemsAreNotNull (IEnumerable collection, string message, params object[] args) { Assert.That(collection, Is.All.Not.Null, message, args); } #endregion #region AllItemsAreUnique /// <summary> /// Ensures that every object contained in collection exists within the collection /// once and only once. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> public static void AllItemsAreUnique (IEnumerable collection) { AllItemsAreUnique(collection, string.Empty, null); } /// <summary> /// Ensures that every object contained in collection exists within the collection /// once and only once. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AllItemsAreUnique (IEnumerable collection, string message, params object[] args) { Assert.That(collection, Is.Unique, message, args); } #endregion #region AreEqual /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> public static void AreEqual (IEnumerable expected, IEnumerable actual) { AreEqual(expected, actual, string.Empty, null); } /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> public static void AreEqual (IEnumerable expected, IEnumerable actual, IComparer comparer) { AreEqual(expected, actual, comparer, string.Empty, null); } /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreEqual (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, Is.EqualTo(expected).AsCollection, message, args); } /// <summary> /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreEqual (IEnumerable expected, IEnumerable actual, IComparer comparer, string message, params object[] args) { Assert.That(actual, Is.EqualTo(expected).Using(comparer), message, args); } #endregion #region AreEquivalent /// <summary> /// Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> public static void AreEquivalent (IEnumerable expected, IEnumerable actual) { AreEquivalent(expected, actual, string.Empty, null); } /// <summary> /// Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreEquivalent (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, Is.EquivalentTo(expected), message, args); } #endregion #region AreNotEqual /// <summary> /// Asserts that expected and actual are not exactly equal. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual) { AreNotEqual(expected, actual, string.Empty, null); } /// <summary> /// Asserts that expected and actual are not exactly equal. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual, IComparer comparer) { AreNotEqual(expected, actual, comparer, string.Empty, null); } /// <summary> /// Asserts that expected and actual are not exactly equal. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, Is.Not.EqualTo(expected).AsCollection, message, args); } /// <summary> /// Asserts that expected and actual are not exactly equal. /// If comparer is not null then it will be used to compare the objects. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="comparer">The IComparer to use in comparing objects from each IEnumerable</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreNotEqual (IEnumerable expected, IEnumerable actual, IComparer comparer, string message, params object[] args) { Assert.That(actual, Is.Not.EqualTo(expected).Using(comparer), message, args); } #endregion #region AreNotEquivalent /// <summary> /// Asserts that expected and actual are not equivalent. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> public static void AreNotEquivalent (IEnumerable expected, IEnumerable actual) { AreNotEquivalent(expected, actual, string.Empty, null); } /// <summary> /// Asserts that expected and actual are not equivalent. /// </summary> /// <param name="expected">The first IEnumerable of objects to be considered</param> /// <param name="actual">The second IEnumerable of objects to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void AreNotEquivalent (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, Is.Not.EquivalentTo(expected), message, args); } #endregion #region Contains /// <summary> /// Asserts that collection contains actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object to be found within collection</param> public static void Contains (IEnumerable collection, Object actual) { Contains(collection, actual, string.Empty, null); } /// <summary> /// Asserts that collection contains actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object to be found within collection</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void Contains (IEnumerable collection, Object actual, string message, params object[] args) { Assert.That(collection, Has.Member(actual), message, args); } #endregion #region DoesNotContain /// <summary> /// Asserts that collection does not contain actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object that cannot exist within collection</param> public static void DoesNotContain (IEnumerable collection, Object actual) { DoesNotContain(collection, actual, string.Empty, null); } /// <summary> /// Asserts that collection does not contain actual as an item. /// </summary> /// <param name="collection">IEnumerable of objects to be considered</param> /// <param name="actual">Object that cannot exist within collection</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void DoesNotContain (IEnumerable collection, Object actual, string message, params object[] args) { Assert.That(collection, Has.No.Member(actual), message, args); } #endregion #region IsNotSubsetOf /// <summary> /// Asserts that the superset does not contain the subset /// </summary> /// <param name="subset">The IEnumerable subset to be considered</param> /// <param name="superset">The IEnumerable superset to be considered</param> public static void IsNotSubsetOf (IEnumerable subset, IEnumerable superset) { IsNotSubsetOf(subset, superset, string.Empty, null); } /// <summary> /// Asserts that the superset does not contain the subset /// </summary> /// <param name="subset">The IEnumerable subset to be considered</param> /// <param name="superset">The IEnumerable superset to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsNotSubsetOf (IEnumerable subset, IEnumerable superset, string message, params object[] args) { Assert.That(subset, Is.Not.SubsetOf(superset), message, args); } #endregion #region IsSubsetOf /// <summary> /// Asserts that the superset contains the subset. /// </summary> /// <param name="subset">The IEnumerable subset to be considered</param> /// <param name="superset">The IEnumerable superset to be considered</param> public static void IsSubsetOf (IEnumerable subset, IEnumerable superset) { IsSubsetOf(subset, superset, string.Empty, null); } /// <summary> /// Asserts that the superset contains the subset. /// </summary> /// <param name="subset">The IEnumerable subset to be considered</param> /// <param name="superset">The IEnumerable superset to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsSubsetOf (IEnumerable subset, IEnumerable superset, string message, params object[] args) { Assert.That(subset, Is.SubsetOf(superset), message, args); } #endregion #region IsNotSupersetOf /// <summary> /// Asserts that the subset does not contain the superset /// </summary> /// <param name="superset">The IEnumerable superset to be considered</param> /// <param name="subset">The IEnumerable subset to be considered</param> public static void IsNotSupersetOf(IEnumerable superset, IEnumerable subset) { IsNotSupersetOf(superset, subset, string.Empty, null); } /// <summary> /// Asserts that the subset does not contain the superset /// </summary> /// <param name="superset">The IEnumerable superset to be considered</param> /// <param name="subset">The IEnumerable subset to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsNotSupersetOf(IEnumerable superset, IEnumerable subset, string message, params object[] args) { Assert.That(superset, Is.Not.SupersetOf(subset), message, args); } #endregion #region IsSupersetOf /// <summary> /// Asserts that the subset contains the superset. /// </summary> /// <param name="superset">The IEnumerable superset to be considered</param> /// <param name="subset">The IEnumerable subset to be considered</param> public static void IsSupersetOf(IEnumerable superset, IEnumerable subset) { IsSupersetOf(superset, subset, string.Empty, null); } /// <summary> /// Asserts that the subset contains the superset. /// </summary> /// <param name="superset">The IEnumerable superset to be considered</param> /// <param name="subset">The IEnumerable subset to be considered</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsSupersetOf(IEnumerable superset, IEnumerable subset, string message, params object[] args) { Assert.That(superset, Is.SupersetOf(subset), message, args); } #endregion #region IsEmpty /// <summary> /// Assert that an array, list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="message">The message to be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsEmpty(IEnumerable collection, string message, params object[] args) { Assert.That(collection, new EmptyCollectionConstraint(), message, args); } /// <summary> /// Assert that an array,list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> public static void IsEmpty(IEnumerable collection) { IsEmpty(collection, string.Empty, null); } #endregion #region IsNotEmpty /// <summary> /// Assert that an array, list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="message">The message to be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsNotEmpty(IEnumerable collection, string message, params object[] args) { Assert.That(collection, new NotConstraint(new EmptyCollectionConstraint()), message, args); } /// <summary> /// Assert that an array,list or other collection is empty /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> public static void IsNotEmpty(IEnumerable collection) { IsNotEmpty(collection, string.Empty, null); } #endregion #region IsOrdered /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="message">The message to be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsOrdered(IEnumerable collection, string message, params object[] args) { Assert.That(collection, Is.Ordered, message, args); } /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> public static void IsOrdered(IEnumerable collection) { IsOrdered(collection, string.Empty, null); } /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="comparer">A custom comparer to perform the comparisons</param> /// <param name="message">The message to be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void IsOrdered(IEnumerable collection, IComparer comparer, string message, params object[] args) { Assert.That(collection, Is.Ordered.Using(comparer), message, args); } /// <summary> /// Assert that an array, list or other collection is ordered /// </summary> /// <param name="collection">An array, list or other collection implementing IEnumerable</param> /// <param name="comparer">A custom comparer to perform the comparisons</param> public static void IsOrdered(IEnumerable collection, IComparer comparer) { IsOrdered(collection, comparer, string.Empty, null); } #endregion } }
// // StringBody.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2014 Xamarin Inc // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, 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. // using System; using System.IO; using System.Text; using Org.Apache.Http.Entity.Mime; using Org.Apache.Http.Entity.Mime.Content; using Sharpen; namespace Org.Apache.Http.Entity.Mime.Content { /// <since>4.0</since> public class StringBody : AbstractContentBody { private readonly byte[] content; private readonly Encoding charset; /// <since>4.1</since> /// <exception cref="System.ArgumentException"></exception> public static Org.Apache.Http.Entity.Mime.Content.StringBody Create(string text, string mimeType, Encoding charset) { try { return new Org.Apache.Http.Entity.Mime.Content.StringBody(text, mimeType, charset ); } catch (UnsupportedEncodingException ex) { throw new ArgumentException("Charset " + charset + " is not supported", ex); } } /// <since>4.1</since> /// <exception cref="System.ArgumentException"></exception> public static Org.Apache.Http.Entity.Mime.Content.StringBody Create(string text, Encoding charset) { return Create(text, null, charset); } /// <since>4.1</since> /// <exception cref="System.ArgumentException"></exception> public static Org.Apache.Http.Entity.Mime.Content.StringBody Create(string text) { return Create(text, null, null); } /// <summary>Create a StringBody from the specified text, mime type and character set. /// </summary> /// <remarks>Create a StringBody from the specified text, mime type and character set. /// </remarks> /// <param name="text"> /// to be used for the body, not /// <code>null</code> /// </param> /// <param name="mimeType"> /// the mime type, not /// <code>null</code> /// </param> /// <param name="charset"> /// the character set, may be /// <code>null</code> /// , in which case the US-ASCII charset is used /// </param> /// <exception cref="System.IO.UnsupportedEncodingException">System.IO.UnsupportedEncodingException /// </exception> /// <exception cref="System.ArgumentException"> /// if the /// <code>text</code> /// parameter is null /// </exception> public StringBody(string text, string mimeType, Encoding charset) : base(mimeType ) { if (text == null) { throw new ArgumentException("Text may not be null"); } if (charset == null) { charset = Sharpen.Extensions.GetEncoding("US-ASCII"); } this.content = Sharpen.Runtime.GetBytesForString(text, charset.Name()); this.charset = charset; } /// <summary>Create a StringBody from the specified text and character set.</summary> /// <remarks> /// Create a StringBody from the specified text and character set. /// The mime type is set to "text/plain". /// </remarks> /// <param name="text"> /// to be used for the body, not /// <code>null</code> /// </param> /// <param name="charset"> /// the character set, may be /// <code>null</code> /// , in which case the US-ASCII charset is used /// </param> /// <exception cref="System.IO.UnsupportedEncodingException">System.IO.UnsupportedEncodingException /// </exception> /// <exception cref="System.ArgumentException"> /// if the /// <code>text</code> /// parameter is null /// </exception> public StringBody(string text, Encoding charset) : this(text, "text/plain", charset ) { } /// <summary>Create a StringBody from the specified text.</summary> /// <remarks> /// Create a StringBody from the specified text. /// The mime type is set to "text/plain". /// The hosts default charset is used. /// </remarks> /// <param name="text"> /// to be used for the body, not /// <code>null</code> /// </param> /// <exception cref="System.IO.UnsupportedEncodingException">System.IO.UnsupportedEncodingException /// </exception> /// <exception cref="System.ArgumentException"> /// if the /// <code>text</code> /// parameter is null /// </exception> public StringBody(string text) : this(text, "text/plain", null) { } public virtual StreamReader GetReader() { return new InputStreamReader(new ByteArrayInputStream(this.content), this.charset ); } /// <exception cref="System.IO.IOException"></exception> [Obsolete] [System.ObsoleteAttribute(@"use WriteTo(System.IO.OutputStream)")] public virtual void WriteTo(OutputStream @out, int mode) { WriteTo(@out); } /// <exception cref="System.IO.IOException"></exception> public override void WriteTo(OutputStream @out) { if (@out == null) { throw new ArgumentException("Output stream may not be null"); } InputStream @in = new ByteArrayInputStream(this.content); byte[] tmp = new byte[4096]; int l; while ((l = @in.Read(tmp)) != -1) { @out.Write(tmp, 0, l); } @out.Flush(); } public override string GetTransferEncoding() { return MIME.Enc8bit; } public override string GetCharset() { return this.charset.Name(); } public override long GetContentLength() { return this.content.Length; } public override string GetFilename() { return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Collections; using System.Globalization; using System.Text; using System.Diagnostics; using Microsoft.Xml; using Microsoft.Xml.XPath; using Microsoft.Xml.Schema; namespace MS.Internal.Xml.Cache { /// <summary> /// This is the default XPath/XQuery data model cache implementation. It will be used whenever /// the user does not supply his own XPathNavigator implementation. /// </summary> internal sealed class XPathDocumentNavigator : XPathNavigator, IXmlLineInfo { private XPathNode[] _pageCurrent; private XPathNode[] _pageParent; private int _idxCurrent; private int _idxParent; private string _atomizedLocalName; //----------------------------------------------- // Constructors //----------------------------------------------- /// <summary> /// Create a new navigator positioned on the specified current node. If the current node is a namespace or a collapsed /// text node, then the parent is a virtualized parent (may be different than .Parent on the current node). /// </summary> public XPathDocumentNavigator(XPathNode[] pageCurrent, int idxCurrent, XPathNode[] pageParent, int idxParent) { Debug.Assert(pageCurrent != null && idxCurrent != 0); Debug.Assert((pageParent == null) == (idxParent == 0)); _pageCurrent = pageCurrent; _pageParent = pageParent; _idxCurrent = idxCurrent; _idxParent = idxParent; } /// <summary> /// Copy constructor. /// </summary> public XPathDocumentNavigator(XPathDocumentNavigator nav) : this(nav._pageCurrent, nav._idxCurrent, nav._pageParent, nav._idxParent) { _atomizedLocalName = nav._atomizedLocalName; } //----------------------------------------------- // XPathItem //----------------------------------------------- /// <summary> /// Get the string value of the current node, computed using data model dm:string-value rules. /// If the node has a typed value, return the string representation of the value. If the node /// is not a parent type (comment, text, pi, etc.), get its simple text value. Otherwise, /// concatenate all text node descendants of the current node. /// </summary> public override string Value { get { string value; XPathNode[] page, pageEnd; int idx, idxEnd; // Try to get the pre-computed string value of the node value = _pageCurrent[_idxCurrent].Value; if (value != null) return value; #if DEBUG switch (_pageCurrent[_idxCurrent].NodeType) { case XPathNodeType.Namespace: case XPathNodeType.Attribute: case XPathNodeType.Comment: case XPathNodeType.ProcessingInstruction: Debug.Assert(false, "ReadStringValue() should have taken care of these node types."); break; case XPathNodeType.Text: Debug.Assert(_idxParent != 0 && _pageParent[_idxParent].HasCollapsedText, "ReadStringValue() should have taken care of anything but collapsed text."); break; } #endif // If current node is collapsed text, then parent element has a simple text value if (_idxParent != 0) { Debug.Assert(_pageCurrent[_idxCurrent].NodeType == XPathNodeType.Text); return _pageParent[_idxParent].Value; } // Must be node with complex content, so concatenate the string values of all text descendants string s = string.Empty; StringBuilder bldr = null; // Get all text nodes which follow the current node in document order, but which are still descendants page = pageEnd = _pageCurrent; idx = idxEnd = _idxCurrent; if (!XPathNodeHelper.GetNonDescendant(ref pageEnd, ref idxEnd)) { pageEnd = null; idxEnd = 0; } while (XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd)) { Debug.Assert(page[idx].NodeType == XPathNodeType.Element || page[idx].IsText); if (s.Length == 0) { s = page[idx].Value; } else { if (bldr == null) { bldr = new StringBuilder(); bldr.Append(s); } bldr.Append(page[idx].Value); } } return (bldr != null) ? bldr.ToString() : s; } } //----------------------------------------------- // XPathNavigator //----------------------------------------------- /// <summary> /// Create a copy of this navigator, positioned to the same node in the tree. /// </summary> public override XPathNavigator Clone() { return new XPathDocumentNavigator(_pageCurrent, _idxCurrent, _pageParent, _idxParent); } /// <summary> /// Get the XPath node type of the current node. /// </summary> public override XPathNodeType NodeType { get { return _pageCurrent[_idxCurrent].NodeType; } } /// <summary> /// Get the local name portion of the current node's name. /// </summary> public override string LocalName { get { return _pageCurrent[_idxCurrent].LocalName; } } /// <summary> /// Get the namespace portion of the current node's name. /// </summary> public override string NamespaceURI { get { return _pageCurrent[_idxCurrent].NamespaceUri; } } /// <summary> /// Get the name of the current node. /// </summary> public override string Name { get { return _pageCurrent[_idxCurrent].Name; } } /// <summary> /// Get the prefix portion of the current node's name. /// </summary> public override string Prefix { get { return _pageCurrent[_idxCurrent].Prefix; } } /// <summary> /// Get the base URI of the current node. /// </summary> public override string BaseURI { get { XPathNode[] page; int idx; if (_idxParent != 0) { // Get BaseUri of parent for attribute, namespace, and collapsed text nodes page = _pageParent; idx = _idxParent; } else { page = _pageCurrent; idx = _idxCurrent; } do { switch (page[idx].NodeType) { case XPathNodeType.Element: case XPathNodeType.Root: case XPathNodeType.ProcessingInstruction: // BaseUri is always stored with Elements, Roots, and PIs return page[idx].BaseUri; } // Get BaseUri of parent idx = page[idx].GetParent(out page); } while (idx != 0); return string.Empty; } } /// <summary> /// Return true if this is an element which used a shortcut tag in its Xml 1.0 serialized form. /// </summary> public override bool IsEmptyElement { get { return _pageCurrent[_idxCurrent].AllowShortcutTag; } } /// <summary> /// Return the xml name table which was used to atomize all prefixes, local-names, and /// namespace uris in the document. /// </summary> public override XmlNameTable NameTable { get { return _pageCurrent[_idxCurrent].Document.NameTable; } } /// <summary> /// Position the navigator on the first attribute of the current node and return true. If no attributes /// can be found, return false. /// </summary> public override bool MoveToFirstAttribute() { XPathNode[] page = _pageCurrent; int idx = _idxCurrent; if (XPathNodeHelper.GetFirstAttribute(ref _pageCurrent, ref _idxCurrent)) { // Save element parent in order to make node-order comparison simpler _pageParent = page; _idxParent = idx; return true; } return false; } /// <summary> /// If positioned on an attribute, move to its next sibling attribute. If no attributes can be found, /// return false. /// </summary> public override bool MoveToNextAttribute() { return XPathNodeHelper.GetNextAttribute(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// True if the current node has one or more attributes. /// </summary> public override bool HasAttributes { get { return _pageCurrent[_idxCurrent].HasAttribute; } } /// <summary> /// Position the navigator on the attribute with the specified name and return true. If no matching /// attribute can be found, return false. Don't assume the name parts are atomized with respect /// to this document. /// </summary> public override bool MoveToAttribute(string localName, string namespaceURI) { XPathNode[] page = _pageCurrent; int idx = _idxCurrent; if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; if (XPathNodeHelper.GetAttribute(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI)) { // Save element parent in order to make node-order comparison simpler _pageParent = page; _idxParent = idx; return true; } return false; } /// <summary> /// Position the navigator on the namespace within the specified scope. If no matching namespace /// can be found, return false. /// </summary> public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) { XPathNode[] page; int idx; if (namespaceScope == XPathNamespaceScope.Local) { // Get local namespaces only idx = XPathNodeHelper.GetLocalNamespaces(_pageCurrent, _idxCurrent, out page); } else { // Get all in-scope namespaces idx = XPathNodeHelper.GetInScopeNamespaces(_pageCurrent, _idxCurrent, out page); } while (idx != 0) { // Don't include the xmlns:xml namespace node if scope is ExcludeXml if (namespaceScope != XPathNamespaceScope.ExcludeXml || !page[idx].IsXmlNamespaceNode) { _pageParent = _pageCurrent; _idxParent = _idxCurrent; _pageCurrent = page; _idxCurrent = idx; return true; } // Skip past xmlns:xml idx = page[idx].GetSibling(out page); } return false; } /// <summary> /// Position the navigator on the next namespace within the specified scope. If no matching namespace /// can be found, return false. /// </summary> public override bool MoveToNextNamespace(XPathNamespaceScope scope) { XPathNode[] page = _pageCurrent, pageParent; int idx = _idxCurrent, idxParent; // If current node is not a namespace node, return false if (page[idx].NodeType != XPathNodeType.Namespace) return false; while (true) { // Get next namespace sibling idx = page[idx].GetSibling(out page); // If there are no more nodes, return false if (idx == 0) return false; switch (scope) { case XPathNamespaceScope.Local: // Once parent changes, there are no longer any local namespaces idxParent = page[idx].GetParent(out pageParent); if (idxParent != _idxParent || (object)pageParent != (object)_pageParent) return false; break; case XPathNamespaceScope.ExcludeXml: // If node is xmlns:xml, then skip it if (page[idx].IsXmlNamespaceNode) continue; break; } // Found a matching next namespace node, so return it break; } _pageCurrent = page; _idxCurrent = idx; return true; } /// <summary> /// If the current node is an attribute or namespace (not content), return false. Otherwise, /// move to the next content node. Return false if there are no more content nodes. /// </summary> public override bool MoveToNext() { return XPathNodeHelper.GetContentSibling(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// If the current node is an attribute or namespace (not content), return false. Otherwise, /// move to the previous (sibling) content node. Return false if there are no previous content nodes. /// </summary> public override bool MoveToPrevious() { // If parent exists, then this is a namespace, an attribute, or a collapsed text node, all of which do // not have previous siblings. if (_idxParent != 0) return false; return XPathNodeHelper.GetPreviousContentSibling(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Move to the first content-typed child of the current node. Return false if the current /// node has no content children. /// </summary> public override bool MoveToFirstChild() { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Virtualize collapsed text nodes _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } return XPathNodeHelper.GetContentChild(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Position the navigator on the parent of the current node. If the current node has no parent, /// return false. /// </summary> public override bool MoveToParent() { if (_idxParent != 0) { // 1. For attribute nodes, element parent is always stored in order to make node-order // comparison simpler. // 2. For namespace nodes, parent is always stored in navigator in order to virtualize // XPath 1.0 namespaces. // 3. For collapsed text nodes, element parent is always stored in navigator. Debug.Assert(_pageParent != null); _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetParent(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Position this navigator to the same position as the "other" navigator. If the "other" navigator /// is not of the same type as this navigator, then return false. /// </summary> public override bool MoveTo(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { _pageCurrent = that._pageCurrent; _idxCurrent = that._idxCurrent; _pageParent = that._pageParent; _idxParent = that._idxParent; return true; } return false; } /// <summary> /// Position to the navigator to the element whose id is equal to the specified "id" string. /// </summary> public override bool MoveToId(string id) { XPathNode[] page; int idx; idx = _pageCurrent[_idxCurrent].Document.LookupIdElement(id, out page); if (idx != 0) { // Move to ID element and clear parent state Debug.Assert(page[idx].NodeType == XPathNodeType.Element); _pageCurrent = page; _idxCurrent = idx; _pageParent = null; _idxParent = 0; return true; } return false; } /// <summary> /// Returns true if this navigator is positioned to the same node as the "other" navigator. Returns false /// if not, or if the "other" navigator is not the same type as this navigator. /// </summary> public override bool IsSamePosition(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { return _idxCurrent == that._idxCurrent && _pageCurrent == that._pageCurrent && _idxParent == that._idxParent && _pageParent == that._pageParent; } return false; } /// <summary> /// Returns true if the current node has children. /// </summary> public override bool HasChildren { get { return _pageCurrent[_idxCurrent].HasContentChild; } } /// <summary> /// Position the navigator on the root node of the current document. /// </summary> public override void MoveToRoot() { if (_idxParent != 0) { // Clear parent state _pageParent = null; _idxParent = 0; } _idxCurrent = _pageCurrent[_idxCurrent].GetRoot(out _pageCurrent); } /// <summary> /// Move to the first element child of the current node with the specified name. Return false /// if the current node has no matching element children. /// </summary> public override bool MoveToChild(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; return XPathNodeHelper.GetElementChild(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the first element sibling of the current node with the specified name. Return false /// if the current node has no matching element siblings. /// </summary> public override bool MoveToNext(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; return XPathNodeHelper.GetElementSibling(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the first content child of the current node with the specified type. Return false /// if the current node has no matching children. /// </summary> public override bool MoveToChild(XPathNodeType type) { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Only XPathNodeType.Text and XPathNodeType.All matches collapsed text node if (type != XPathNodeType.Text && type != XPathNodeType.All) return false; // Virtualize collapsed text nodes _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } return XPathNodeHelper.GetContentChild(ref _pageCurrent, ref _idxCurrent, type); } /// <summary> /// Move to the first content sibling of the current node with the specified type. Return false /// if the current node has no matching siblings. /// </summary> public override bool MoveToNext(XPathNodeType type) { return XPathNodeHelper.GetContentSibling(ref _pageCurrent, ref _idxCurrent, type); } /// <summary> /// Move to the next element that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered) /// 3. Has the specified QName /// Return false if the current node has no matching following elements. /// </summary> public override bool MoveToFollowing(string localName, string namespaceURI, XPathNavigator end) { XPathNode[] pageEnd; int idxEnd; if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; // Get node on which scan ends (null if rest of document should be scanned) idxEnd = GetFollowingEnd(end as XPathDocumentNavigator, false, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { if (!XPathNodeHelper.GetElementFollowing(ref _pageParent, ref _idxParent, pageEnd, idxEnd, _atomizedLocalName, namespaceURI)) return false; _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetElementFollowing(ref _pageCurrent, ref _idxCurrent, pageEnd, idxEnd, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the next node that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered) /// 3. Has the specified XPathNodeType /// Return false if the current node has no matching following nodes. /// </summary> public override bool MoveToFollowing(XPathNodeType type, XPathNavigator end) { XPathDocumentNavigator endTiny = end as XPathDocumentNavigator; XPathNode[] page, pageEnd; int idx, idxEnd; // If searching for text, make sure to handle collapsed text nodes correctly if (type == XPathNodeType.Text || type == XPathNodeType.All) { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Positioned on an element with collapsed text, so return the virtual text node, assuming it's before "end" if (endTiny != null && _idxCurrent == endTiny._idxParent && _pageCurrent == endTiny._pageParent) { // "end" is positioned to a virtual attribute, namespace, or text node return false; } _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } if (type == XPathNodeType.Text) { // Get node on which scan ends (null if rest of document should be scanned, parent if positioned on virtual node) idxEnd = GetFollowingEnd(endTiny, true, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { page = _pageParent; idx = _idxParent; } else { page = _pageCurrent; idx = _idxCurrent; } // If ending node is a virtual node, and current node is its parent, then we're done if (endTiny != null && endTiny._idxParent != 0 && idx == idxEnd && page == pageEnd) return false; // Get all virtual (collapsed) and physical text nodes which follow the current node if (!XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd)) return false; if (page[idx].NodeType == XPathNodeType.Element) { // Virtualize collapsed text nodes Debug.Assert(page[idx].HasCollapsedText); _idxCurrent = page[idx].Document.GetCollapsedTextNode(out _pageCurrent); _pageParent = page; _idxParent = idx; } else { // Physical text node Debug.Assert(page[idx].IsText); _pageCurrent = page; _idxCurrent = idx; _pageParent = null; _idxParent = 0; } return true; } } // Get node on which scan ends (null if rest of document should be scanned, parent + 1 if positioned on virtual node) idxEnd = GetFollowingEnd(endTiny, false, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { if (!XPathNodeHelper.GetContentFollowing(ref _pageParent, ref _idxParent, pageEnd, idxEnd, type)) return false; _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetContentFollowing(ref _pageCurrent, ref _idxCurrent, pageEnd, idxEnd, type); } /// <summary> /// Return an iterator that ranges over all children of the current node that match the specified XPathNodeType. /// </summary> public override XPathNodeIterator SelectChildren(XPathNodeType type) { return new XPathDocumentKindChildIterator(this, type); } /// <summary> /// Return an iterator that ranges over all children of the current node that match the specified QName. /// </summary> public override XPathNodeIterator SelectChildren(string name, string namespaceURI) { // If local name is wildcard, then call XPathNavigator.SelectChildren if (name == null || name.Length == 0) return base.SelectChildren(name, namespaceURI); return new XPathDocumentElementChildIterator(this, name, namespaceURI); } /// <summary> /// Return an iterator that ranges over all descendants of the current node that match the specified /// XPathNodeType. If matchSelf is true, then also perform the match on the current node. /// </summary> public override XPathNodeIterator SelectDescendants(XPathNodeType type, bool matchSelf) { return new XPathDocumentKindDescendantIterator(this, type, matchSelf); } /// <summary> /// Return an iterator that ranges over all descendants of the current node that match the specified /// QName. If matchSelf is true, then also perform the match on the current node. /// </summary> public override XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf) { // If local name is wildcard, then call XPathNavigator.SelectDescendants if (name == null || name.Length == 0) return base.SelectDescendants(name, namespaceURI, matchSelf); return new XPathDocumentElementDescendantIterator(this, name, namespaceURI, matchSelf); } /// <summary> /// Returns: /// XmlNodeOrder.Unknown -- This navigator and the "other" navigator are not of the same type, or the /// navigator's are not positioned on nodes in the same document. /// XmlNodeOrder.Before -- This navigator's current node is before the "other" navigator's current node /// in document order. /// XmlNodeOrder.After -- This navigator's current node is after the "other" navigator's current node /// in document order. /// XmlNodeOrder.Same -- This navigator is positioned on the same node as the "other" navigator. /// </summary> public override XmlNodeOrder ComparePosition(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { XPathDocument thisDoc = _pageCurrent[_idxCurrent].Document; XPathDocument thatDoc = that._pageCurrent[that._idxCurrent].Document; if ((object)thisDoc == (object)thatDoc) { int locThis = GetPrimaryLocation(); int locThat = that.GetPrimaryLocation(); if (locThis == locThat) { locThis = GetSecondaryLocation(); locThat = that.GetSecondaryLocation(); if (locThis == locThat) return XmlNodeOrder.Same; } return (locThis < locThat) ? XmlNodeOrder.Before : XmlNodeOrder.After; } } return XmlNodeOrder.Unknown; } /// <summary> /// Return true if the "other" navigator's current node is a descendant of this navigator's current node. /// </summary> public override bool IsDescendant(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { XPathNode[] pageThat; int idxThat; // If that current node's parent is virtualized, then start with the virtual parent if (that._idxParent != 0) { pageThat = that._pageParent; idxThat = that._idxParent; } else { idxThat = that._pageCurrent[that._idxCurrent].GetParent(out pageThat); } while (idxThat != 0) { if (idxThat == _idxCurrent && pageThat == _pageCurrent) return true; idxThat = pageThat[idxThat].GetParent(out pageThat); } } return false; } /// <summary> /// Construct a primary location for this navigator. The location is an integer that can be /// easily compared with other locations in the same document in order to determine the relative /// document order of two nodes. If two locations compare equal, then secondary locations should /// be compared. /// </summary> private int GetPrimaryLocation() { // Is the current node virtualized? if (_idxParent == 0) { // No, so primary location should be derived from current node return XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); } // Yes, so primary location should be derived from parent node return XPathNodeHelper.GetLocation(_pageParent, _idxParent); } /// <summary> /// Construct a secondary location for this navigator. This location should only be used if /// primary locations previously compared equal. /// </summary> private int GetSecondaryLocation() { // Is the current node virtualized? if (_idxParent == 0) { // No, so secondary location is int.MinValue (always first) return int.MinValue; } // Yes, so secondary location should be derived from current node // This happens with attributes nodes, namespace nodes, collapsed text nodes, and atomic values switch (_pageCurrent[_idxCurrent].NodeType) { case XPathNodeType.Namespace: // Namespace nodes come first (make location negative, but greater than int.MinValue) return int.MinValue + 1 + XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); case XPathNodeType.Attribute: // Attribute nodes come next (location is always positive) return XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); default: // Collapsed text nodes are always last return int.MaxValue; } } /// <summary> /// Create a unique id for the current node. This is used by the generate-id() function. /// </summary> internal override string UniqueId { get { // 32-bit integer is split into 5-bit groups, the maximum number of groups is 7 char[] buf = new char[1 + 7 + 1 + 7]; int idx = 0; int loc; // Ensure distinguishing attributes, namespaces and child nodes buf[idx++] = NodeTypeLetter[(int)_pageCurrent[_idxCurrent].NodeType]; // If the current node is virtualized, code its parent if (_idxParent != 0) { loc = (_pageParent[0].PageInfo.PageNumber - 1) << 16 | (_idxParent - 1); do { buf[idx++] = UniqueIdTbl[loc & 0x1f]; loc >>= 5; } while (loc != 0); buf[idx++] = '0'; } // Code the node itself loc = (_pageCurrent[0].PageInfo.PageNumber - 1) << 16 | (_idxCurrent - 1); do { buf[idx++] = UniqueIdTbl[loc & 0x1f]; loc >>= 5; } while (loc != 0); return new string(buf, 0, idx); } } public override object UnderlyingObject { get { // Since we don't have any underlying PUBLIC object // the best one we can return is a clone of the navigator. // Note that it should be a clone as the user might Move the returned navigator // around and thus cause unexpected behavior of the caller of this class (For example the validator) return this.Clone(); } } //----------------------------------------------- // IXmlLineInfo //----------------------------------------------- /// <summary> /// Return true if line number information is recorded in the cache. /// </summary> public bool HasLineInfo() { return _pageCurrent[_idxCurrent].Document.HasLineInfo; } /// <summary> /// Return the source line number of the current node. /// </summary> public int LineNumber { get { // If the current node is a collapsed text node, then return parent element's line number if (_idxParent != 0 && NodeType == XPathNodeType.Text) return _pageParent[_idxParent].LineNumber; return _pageCurrent[_idxCurrent].LineNumber; } } /// <summary> /// Return the source line position of the current node. /// </summary> public int LinePosition { get { // If the current node is a collapsed text node, then get position from parent element if (_idxParent != 0 && NodeType == XPathNodeType.Text) return _pageParent[_idxParent].CollapsedLinePosition; return _pageCurrent[_idxCurrent].LinePosition; } } //----------------------------------------------- // Helper methods //----------------------------------------------- /// <summary> /// Get hashcode based on current position of the navigator. /// </summary> public int GetPositionHashCode() { return _idxCurrent ^ _idxParent; } /// <summary> /// Return true if navigator is positioned to an element having the specified name. /// </summary> public bool IsElementMatch(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; // Cannot be an element if parent is stored if (_idxParent != 0) return false; return _pageCurrent[_idxCurrent].ElementMatch(_atomizedLocalName, namespaceURI); } /// <summary> /// Return true if navigator is positioned to a content node of the specified kind. Whitespace/SignficantWhitespace/Text are /// all treated the same (i.e. they all match each other). /// </summary> public bool IsContentKindMatch(XPathNodeType typ) { return (((1 << (int)_pageCurrent[_idxCurrent].NodeType) & GetContentKindMask(typ)) != 0); } /// <summary> /// Return true if navigator is positioned to a node of the specified kind. Whitespace/SignficantWhitespace/Text are /// all treated the same (i.e. they all match each other). /// </summary> public bool IsKindMatch(XPathNodeType typ) { return (((1 << (int)_pageCurrent[_idxCurrent].NodeType) & GetKindMask(typ)) != 0); } /// <summary> /// "end" is positioned on a node which terminates a following scan. Return the page and index of "end" if it /// is positioned to a non-virtual node. If "end" is positioned to a virtual node: /// 1. If useParentOfVirtual is true, then return the page and index of the virtual node's parent /// 2. If useParentOfVirtual is false, then return the page and index of the virtual node's parent + 1. /// </summary> private int GetFollowingEnd(XPathDocumentNavigator end, bool useParentOfVirtual, out XPathNode[] pageEnd) { // If ending navigator is positioned to a node in another document, then return null if (end != null && _pageCurrent[_idxCurrent].Document == end._pageCurrent[end._idxCurrent].Document) { // If the ending navigator is not positioned on a virtual node, then return its current node if (end._idxParent == 0) { pageEnd = end._pageCurrent; return end._idxCurrent; } // If the ending navigator is positioned on an attribute, namespace, or virtual text node, then use the // next physical node instead, as the results will be the same. pageEnd = end._pageParent; return (useParentOfVirtual) ? end._idxParent : end._idxParent + 1; } // No following, so set pageEnd to null and return an index of 0 pageEnd = null; return 0; } } }
// ZlibCodec.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-November-03 15:40:51> // // ------------------------------------------------------------------ // // This module defines a Codec for ZLIB compression and // decompression. This code extends code that was based the jzlib // implementation of zlib, but this code is completely novel. The codec // class is new, and encapsulates some behaviors that are new, and some // that were present in other classes in the jzlib code base. In // keeping with the license for jzlib, the copyright to the jzlib code // is included below. // // ------------------------------------------------------------------ // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the distribution. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. // // ----------------------------------------------------------------------- // // This program is based on zlib-1.1.3; credit to authors // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) // and contributors of zlib. // // ----------------------------------------------------------------------- using System; namespace SharpCompress.Compressor.Deflate { /// <summary> /// Encoder and Decoder for ZLIB and DEFLATE (IETF RFC1950 and RFC1951). /// </summary> /// /// <remarks> /// This class compresses and decompresses data according to the Deflate algorithm /// and optionally, the ZLIB format, as documented in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950 - ZLIB</see> and <see /// href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951 - DEFLATE</see>. /// </remarks> internal sealed class ZlibCodec { /// <summary> /// The buffer from which data is taken. /// </summary> public byte[] InputBuffer; /// <summary> /// An index into the InputBuffer array, indicating where to start reading. /// </summary> public int NextIn; /// <summary> /// The number of bytes available in the InputBuffer, starting at NextIn. /// </summary> /// <remarks> /// Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call. /// The class will update this number as calls to Inflate/Deflate are made. /// </remarks> public int AvailableBytesIn; /// <summary> /// Total number of bytes read so far, through all calls to Inflate()/Deflate(). /// </summary> public long TotalBytesIn; /// <summary> /// Buffer to store output data. /// </summary> public byte[] OutputBuffer; /// <summary> /// An index into the OutputBuffer array, indicating where to start writing. /// </summary> public int NextOut; /// <summary> /// The number of bytes available in the OutputBuffer, starting at NextOut. /// </summary> /// <remarks> /// Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call. /// The class will update this number as calls to Inflate/Deflate are made. /// </remarks> public int AvailableBytesOut; /// <summary> /// Total number of bytes written to the output so far, through all calls to Inflate()/Deflate(). /// </summary> public long TotalBytesOut; /// <summary> /// used for diagnostics, when something goes wrong! /// </summary> public System.String Message; internal DeflateManager dstate; internal InflateManager istate; internal uint _Adler32; /// <summary> /// The compression level to use in this codec. Useful only in compression mode. /// </summary> public CompressionLevel CompressLevel = CompressionLevel.Default; /// <summary> /// The number of Window Bits to use. /// </summary> /// <remarks> /// This gauges the size of the sliding window, and hence the /// compression effectiveness as well as memory consumption. It's best to just leave this /// setting alone if you don't know what it is. The maximum value is 15 bits, which implies /// a 32k window. /// </remarks> public int WindowBits = ZlibConstants.WindowBitsDefault; /// <summary> /// The compression strategy to use. /// </summary> /// <remarks> /// This is only effective in compression. The theory offered by ZLIB is that different /// strategies could potentially produce significant differences in compression behavior /// for different data sets. Unfortunately I don't have any good recommendations for how /// to set it differently. When I tested changing the strategy I got minimally different /// compression performance. It's best to leave this property alone if you don't have a /// good feel for it. Or, you may want to produce a test harness that runs through the /// different strategy options and evaluates them on different file types. If you do that, /// let me know your results. /// </remarks> public CompressionStrategy Strategy = CompressionStrategy.Default; /// <summary> /// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this. /// </summary> public int Adler32 { get { return (int) _Adler32; } } /// <summary> /// Create a ZlibCodec. /// </summary> /// <remarks> /// If you use this default constructor, you will later have to explicitly call /// InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress /// or decompress. /// </remarks> public ZlibCodec() { } /// <summary> /// Create a ZlibCodec that either compresses or decompresses. /// </summary> /// <param name="mode"> /// Indicates whether the codec should compress (deflate) or decompress (inflate). /// </param> public ZlibCodec(CompressionMode mode) { if (mode == CompressionMode.Compress) { int rc = InitializeDeflate(); if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for deflate."); } else if (mode == CompressionMode.Decompress) { int rc = InitializeInflate(); if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for inflate."); } else throw new ZlibException("Invalid ZlibStreamFlavor."); } /// <summary> /// Initialize the inflation state. /// </summary> /// <remarks> /// It is not necessary to call this before using the ZlibCodec to inflate data; /// It is implicitly called when you call the constructor. /// </remarks> /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate() { return InitializeInflate(this.WindowBits); } /// <summary> /// Initialize the inflation state with an explicit flag to /// govern the handling of RFC1950 header bytes. /// </summary> /// /// <remarks> /// By default, the ZLIB header defined in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</see> is expected. If /// you want to read a zlib stream you should specify true for /// expectRfc1950Header. If you have a deflate stream, you will want to specify /// false. It is only necessary to invoke this initializer explicitly if you /// want to specify false. /// </remarks> /// /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte /// pair when reading the stream of data to be inflated.</param> /// /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate(bool expectRfc1950Header) { return InitializeInflate(this.WindowBits, expectRfc1950Header); } /// <summary> /// Initialize the ZlibCodec for inflation, with the specified number of window bits. /// </summary> /// <param name="windowBits">The number of window bits to use. If you need to ask what that is, /// then you shouldn't be calling this initializer.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeInflate(int windowBits) { this.WindowBits = windowBits; return InitializeInflate(windowBits, true); } /// <summary> /// Initialize the inflation state with an explicit flag to govern the handling of /// RFC1950 header bytes. /// </summary> /// /// <remarks> /// If you want to read a zlib stream you should specify true for /// expectRfc1950Header. In this case, the library will expect to find a ZLIB /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC /// 1950</see>, in the compressed stream. If you will be reading a DEFLATE or /// GZIP stream, which does not have such a header, you will want to specify /// false. /// </remarks> /// /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte pair when reading /// the stream of data to be inflated.</param> /// <param name="windowBits">The number of window bits to use. If you need to ask what that is, /// then you shouldn't be calling this initializer.</param> /// <returns>Z_OK if everything goes well.</returns> public int InitializeInflate(int windowBits, bool expectRfc1950Header) { this.WindowBits = windowBits; if (dstate != null) throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate()."); istate = new InflateManager(expectRfc1950Header); return istate.Initialize(this, windowBits); } /// <summary> /// Inflate the data in the InputBuffer, placing the result in the OutputBuffer. /// </summary> /// <remarks> /// You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and /// AvailableBytesOut before calling this method. /// </remarks> /// <example> /// <code> /// private void InflateBuffer() /// { /// int bufferSize = 1024; /// byte[] buffer = new byte[bufferSize]; /// ZlibCodec decompressor = new ZlibCodec(); /// /// Console.WriteLine("\n============================================"); /// Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length); /// MemoryStream ms = new MemoryStream(DecompressedBytes); /// /// int rc = decompressor.InitializeInflate(); /// /// decompressor.InputBuffer = CompressedBytes; /// decompressor.NextIn = 0; /// decompressor.AvailableBytesIn = CompressedBytes.Length; /// /// decompressor.OutputBuffer = buffer; /// /// // pass 1: inflate /// do /// { /// decompressor.NextOut = 0; /// decompressor.AvailableBytesOut = buffer.Length; /// rc = decompressor.Inflate(FlushType.None); /// /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END) /// throw new Exception("inflating: " + decompressor.Message); /// /// ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut); /// } /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0); /// /// // pass 2: finish and flush /// do /// { /// decompressor.NextOut = 0; /// decompressor.AvailableBytesOut = buffer.Length; /// rc = decompressor.Inflate(FlushType.Finish); /// /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK) /// throw new Exception("inflating: " + decompressor.Message); /// /// if (buffer.Length - decompressor.AvailableBytesOut &gt; 0) /// ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut); /// } /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0); /// /// decompressor.EndInflate(); /// } /// /// </code> /// </example> /// <param name="flush">The flush to use when inflating.</param> /// <returns>Z_OK if everything goes well.</returns> public int Inflate(FlushType flush) { if (istate == null) throw new ZlibException("No Inflate State!"); return istate.Inflate(flush); } /// <summary> /// Ends an inflation session. /// </summary> /// <remarks> /// Call this after successively calling Inflate(). This will cause all buffers to be flushed. /// After calling this you cannot call Inflate() without a intervening call to one of the /// InitializeInflate() overloads. /// </remarks> /// <returns>Z_OK if everything goes well.</returns> public int EndInflate() { if (istate == null) throw new ZlibException("No Inflate State!"); int ret = istate.End(); istate = null; return ret; } /// <summary> /// I don't know what this does! /// </summary> /// <returns>Z_OK if everything goes well.</returns> public int SyncInflate() { if (istate == null) throw new ZlibException("No Inflate State!"); return istate.Sync(); } /// <summary> /// Initialize the ZlibCodec for deflation operation. /// </summary> /// <remarks> /// The codec will use the MAX window bits and the default level of compression. /// </remarks> /// <example> /// <code> /// int bufferSize = 40000; /// byte[] CompressedBytes = new byte[bufferSize]; /// byte[] DecompressedBytes = new byte[bufferSize]; /// /// ZlibCodec compressor = new ZlibCodec(); /// /// compressor.InitializeDeflate(CompressionLevel.Default); /// /// compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress); /// compressor.NextIn = 0; /// compressor.AvailableBytesIn = compressor.InputBuffer.Length; /// /// compressor.OutputBuffer = CompressedBytes; /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = CompressedBytes.Length; /// /// while (compressor.TotalBytesIn != TextToCompress.Length &amp;&amp; compressor.TotalBytesOut &lt; bufferSize) /// { /// compressor.Deflate(FlushType.None); /// } /// /// while (true) /// { /// int rc= compressor.Deflate(FlushType.Finish); /// if (rc == ZlibConstants.Z_STREAM_END) break; /// } /// /// compressor.EndDeflate(); /// /// </code> /// </example> /// <returns>Z_OK if all goes well. You generally don't need to check the return code.</returns> public int InitializeDeflate() { return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel. /// </summary> /// <remarks> /// The codec will use the maximum window bits (15) and the specified /// CompressionLevel. It will emit a ZLIB stream as it compresses. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level) { this.CompressLevel = level; return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel, /// and the explicit flag governing whether to emit an RFC1950 header byte pair. /// </summary> /// <remarks> /// The codec will use the maximum window bits (15) and the specified CompressionLevel. /// If you want to generate a zlib stream, you should specify true for /// wantRfc1950Header. In this case, the library will emit a ZLIB /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC /// 1950</see>, in the compressed stream. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, bool wantRfc1950Header) { this.CompressLevel = level; return _InternalInitializeDeflate(wantRfc1950Header); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel, /// and the specified number of window bits. /// </summary> /// <remarks> /// The codec will use the specified number of window bits and the specified CompressionLevel. /// </remarks> /// <param name="level">The compression level for the codec.</param> /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, int bits) { this.CompressLevel = level; this.WindowBits = bits; return _InternalInitializeDeflate(true); } /// <summary> /// Initialize the ZlibCodec for deflation operation, using the specified /// CompressionLevel, the specified number of window bits, and the explicit flag /// governing whether to emit an RFC1950 header byte pair. /// </summary> /// /// <param name="level">The compression level for the codec.</param> /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param> /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param> /// <returns>Z_OK if all goes well.</returns> public int InitializeDeflate(CompressionLevel level, int bits, bool wantRfc1950Header) { this.CompressLevel = level; this.WindowBits = bits; return _InternalInitializeDeflate(wantRfc1950Header); } private int _InternalInitializeDeflate(bool wantRfc1950Header) { if (istate != null) throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate()."); dstate = new DeflateManager(); dstate.WantRfc1950HeaderBytes = wantRfc1950Header; return dstate.Initialize(this, this.CompressLevel, this.WindowBits, this.Strategy); } /// <summary> /// Deflate one batch of data. /// </summary> /// <remarks> /// You must have set InputBuffer and OutputBuffer before calling this method. /// </remarks> /// <example> /// <code> /// private void DeflateBuffer(CompressionLevel level) /// { /// int bufferSize = 1024; /// byte[] buffer = new byte[bufferSize]; /// ZlibCodec compressor = new ZlibCodec(); /// /// Console.WriteLine("\n============================================"); /// Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length); /// MemoryStream ms = new MemoryStream(); /// /// int rc = compressor.InitializeDeflate(level); /// /// compressor.InputBuffer = UncompressedBytes; /// compressor.NextIn = 0; /// compressor.AvailableBytesIn = UncompressedBytes.Length; /// /// compressor.OutputBuffer = buffer; /// /// // pass 1: deflate /// do /// { /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = buffer.Length; /// rc = compressor.Deflate(FlushType.None); /// /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END) /// throw new Exception("deflating: " + compressor.Message); /// /// ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut); /// } /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0); /// /// // pass 2: finish and flush /// do /// { /// compressor.NextOut = 0; /// compressor.AvailableBytesOut = buffer.Length; /// rc = compressor.Deflate(FlushType.Finish); /// /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK) /// throw new Exception("deflating: " + compressor.Message); /// /// if (buffer.Length - compressor.AvailableBytesOut &gt; 0) /// ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut); /// } /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0); /// /// compressor.EndDeflate(); /// /// ms.Seek(0, SeekOrigin.Begin); /// CompressedBytes = new byte[compressor.TotalBytesOut]; /// ms.Read(CompressedBytes, 0, CompressedBytes.Length); /// } /// </code> /// </example> /// <param name="flush">whether to flush all data as you deflate. Generally you will want to /// use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to /// flush everything. /// </param> /// <returns>Z_OK if all goes well.</returns> public int Deflate(FlushType flush) { if (dstate == null) throw new ZlibException("No Deflate State!"); return dstate.Deflate(flush); } /// <summary> /// End a deflation session. /// </summary> /// <remarks> /// Call this after making a series of one or more calls to Deflate(). All buffers are flushed. /// </remarks> /// <returns>Z_OK if all goes well.</returns> public int EndDeflate() { if (dstate == null) throw new ZlibException("No Deflate State!"); // TODO: dinoch Tue, 03 Nov 2009 15:39 (test this) //int ret = dstate.End(); dstate = null; return ZlibConstants.Z_OK; //ret; } /// <summary> /// Reset a codec for another deflation session. /// </summary> /// <remarks> /// Call this to reset the deflation state. For example if a thread is deflating /// non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first /// block and before the next Deflate(None) of the second block. /// </remarks> /// <returns>Z_OK if all goes well.</returns> public void ResetDeflate() { if (dstate == null) throw new ZlibException("No Deflate State!"); dstate.Reset(); } /// <summary> /// Set the CompressionStrategy and CompressionLevel for a deflation session. /// </summary> /// <param name="level">the level of compression to use.</param> /// <param name="strategy">the strategy to use for compression.</param> /// <returns>Z_OK if all goes well.</returns> public int SetDeflateParams(CompressionLevel level, CompressionStrategy strategy) { if (dstate == null) throw new ZlibException("No Deflate State!"); return dstate.SetParams(level, strategy); } /// <summary> /// Set the dictionary to be used for either Inflation or Deflation. /// </summary> /// <param name="dictionary">The dictionary bytes to use.</param> /// <returns>Z_OK if all goes well.</returns> public int SetDictionary(byte[] dictionary) { if (istate != null) return istate.SetDictionary(dictionary); if (dstate != null) return dstate.SetDictionary(dictionary); throw new ZlibException("No Inflate or Deflate state!"); } // Flush as much pending output as possible. All deflate() output goes // through this function so some applications may wish to modify it // to avoid allocating a large strm->next_out buffer and copying into it. // (See also read_buf()). internal void flush_pending() { int len = dstate.pendingCount; if (len > AvailableBytesOut) len = AvailableBytesOut; if (len == 0) return; if (dstate.pending.Length <= dstate.nextPending || OutputBuffer.Length <= NextOut || dstate.pending.Length < (dstate.nextPending + len) || OutputBuffer.Length < (NextOut + len)) { throw new ZlibException(String.Format("Invalid State. (pending.Length={0}, pendingCount={1})", dstate.pending.Length, dstate.pendingCount)); } Array.Copy(dstate.pending, dstate.nextPending, OutputBuffer, NextOut, len); NextOut += len; dstate.nextPending += len; TotalBytesOut += len; AvailableBytesOut -= len; dstate.pendingCount -= len; if (dstate.pendingCount == 0) { dstate.nextPending = 0; } } // Read a new buffer from the current input stream, update the adler32 // and total number of bytes read. All deflate() input goes through // this function so some applications may wish to modify it to avoid // allocating a large strm->next_in buffer and copying from it. // (See also flush_pending()). internal int read_buf(byte[] buf, int start, int size) { int len = AvailableBytesIn; if (len > size) len = size; if (len == 0) return 0; AvailableBytesIn -= len; if (dstate.WantRfc1950HeaderBytes) { _Adler32 = Adler.Adler32(_Adler32, InputBuffer, NextIn, len); } Array.Copy(InputBuffer, NextIn, buf, start, len); NextIn += len; TotalBytesIn += len; return len; } } }
// 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Moq; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CommentSelection { public class CommentUncommentSelectionCommandHandlerTests { private class MockCommentUncommentService : AbstractCommentUncommentService { private readonly bool _supportBlockComments; public MockCommentUncommentService(bool supportBlockComments) { _supportBlockComments = supportBlockComments; } public override string SingleLineCommentString { get { return "//"; } } public override bool SupportsBlockComment { get { return _supportBlockComments; } } public override string BlockCommentStartString { get { if (!_supportBlockComments) { throw new NotSupportedException(); } return "/*"; } } public override string BlockCommentEndString { get { if (!_supportBlockComments) { throw new NotSupportedException(); } return "*/"; } } } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Create() { Assert.NotNull( new MockCommentUncommentService( supportBlockComments: true)); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_EmptyLine() { var code = @"|start||end|"; CommentSelection(code, Enumerable.Empty<TextChange>(), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_NoSelectionAtEndOfLine() { var code = @"Some text on a line|start||end|"; CommentSelection(code, new[] { new TextChange(TextSpan.FromBounds(0, 0), "//") }, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_Whitespace() { var code = @" |start| |end| "; CommentSelection(code, Enumerable.Empty<TextChange>(), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_SingleLineBlockWithBlockSelection() { var code = @"this is |start| some |end| text"; var expectedChanges = new[] { new TextChange(new TextSpan(8, 0), "/*"), new TextChange(new TextSpan(14, 0), "*/"), }; CommentSelection(code, expectedChanges, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_MultilineWithBlockSelection() { var code = @"this is |start| some text that is |end| on multiple lines"; var expectedChanges = new[] { new TextChange(new TextSpan(0, 0), "//"), new TextChange(new TextSpan(16, 0), "//"), }; CommentSelection(code, expectedChanges, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_SingleLineBlockWithNoBlockSelection() { var code = @"this is |start| some |end| text"; CommentSelection(code, new[] { new TextChange(TextSpan.FromBounds(0, 0), "//") }, supportBlockComments: false); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(563915)] [WorkItem(530300)] public void Comment_MultilineIndented() { var code = @" class Foo { |start|void M() { }|end| } "; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "//"), }; CommentSelection( code, expectedChanges, supportBlockComments: false, expectedSelectedSpans: new[] { Span.FromBounds(16, 48) }); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(527190)] [WorkItem(563924)] public void Comment_ApplyTwice() { var code = @"|start|class C { void M() { } }|end| "; var textView = EditorFactory.CreateView(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, code); var selectedSpans = SetupSelection(textView); var expectedChanges = new[] { new TextChange(new TextSpan(0, 0), "//"), new TextChange(new TextSpan(9, 0), "//"), new TextChange(new TextSpan(12, 0), "//"), new TextChange(new TextSpan(30, 0), "//"), }; CommentSelection( textView, expectedChanges, supportBlockComments: false, expectedSelectedSpans: new[] { new Span(0, 39) }); expectedChanges = new[] { new TextChange(new TextSpan(0, 0), "//"), new TextChange(new TextSpan(11, 0), "//"), new TextChange(new TextSpan(16, 0), "//"), new TextChange(new TextSpan(36, 0), "//"), }; CommentSelection( textView, expectedChanges, supportBlockComments: false, expectedSelectedSpans: new[] { new Span(0, 47) }); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_SelectionEndsAtColumnZero() { var code = @" class Foo { |start| void M() { } |end|} "; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "//"), }; CommentSelection(code, expectedChanges, supportBlockComments: false); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_BoxSelectionAtStartOfLines() { var code = @" class Foo { |start||end| void M() |start||end| { |start||end| } } "; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "//"), }; CommentSelection(code, expectedChanges, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_BoxSelectionIndentedAtStart() { var code = @" class Foo { |start||end|void M() |start||end|{ |start||end|} } "; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "//"), }; CommentSelection(code, expectedChanges, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_BoxSelectionBlock() { var code = @" class Foo { |start|v|end|oid M() |start|{|end| |start|o|end|ther |start|}|end| } "; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "/*"), new TextChange(new TextSpan(21, 0), "*/"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "/*"), new TextChange(new TextSpan(42, 0), "*/"), new TextChange(new TextSpan(52, 0), "//"), }; CommentSelection(code, expectedChanges, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Comment_BoxSelectionBlockWithoutSupport() { var code = @" class Foo { |start|v|end|oid M() |start|{|end| |start|}|end| } "; var expectedChanges = new[] { new TextChange(new TextSpan(20, 0), "//"), new TextChange(new TextSpan(34, 0), "//"), new TextChange(new TextSpan(41, 0), "//"), }; CommentSelection(code, expectedChanges, supportBlockComments: false); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Uncomment_NoSelection() { var code = @"//Foo|start||end|Bar"; UncommentSelection(code, new[] { new TextChange(new TextSpan(0, 2), string.Empty) }, Span.FromBounds(0, 6), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Uncomment_MatchesBlockComment() { var code = @"Before |start|/* Some Commented Text */|end| after"; var expectedChanges = new[] { new TextChange(new TextSpan(7, 2), string.Empty), new TextChange(new TextSpan(30, 2), string.Empty), }; UncommentSelection(code, expectedChanges, Span.FromBounds(7, 28), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Uncomment_InWhitespaceOutsideBlockComment() { var code = @"Before |start| /* Some Commented Text */ |end| after"; var expectedChanges = new[] { new TextChange(new TextSpan(11, 2), string.Empty), new TextChange(new TextSpan(34, 2), string.Empty), }; UncommentSelection(code, expectedChanges, Span.FromBounds(11, 32), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Uncomment_IndentedSingleLineCommentsAndUncommentedLines() { var code = @" class C { |start| //void M() //{ //if (true) //{ SomethingNotCommented(); //} //} |end|}"; var expectedChanges = new[] { new TextChange(new TextSpan(18, 2), string.Empty), new TextChange(new TextSpan(34, 2), string.Empty), new TextChange(new TextSpan(47, 2), string.Empty), new TextChange(new TextSpan(68, 2), string.Empty), new TextChange(new TextSpan(119, 2), string.Empty), new TextChange(new TextSpan(128, 2), string.Empty), }; UncommentSelection(code, expectedChanges, Span.FromBounds(14, 119), supportBlockComments: true); } [Fact(Skip = "563927"), Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(563927)] public void Uncomment_BoxSelection() { var code = @" class Foo { |start|/*v*/|end|oid M() |start|//{ |end| |start|/*o*/|end|ther |start|//} |end| }"; var expectedChanges = new[] { new TextChange(new TextSpan(20, 2), string.Empty), new TextChange(new TextSpan(23, 2), string.Empty), new TextChange(new TextSpan(38, 2), string.Empty), new TextChange(new TextSpan(49, 2), string.Empty), new TextChange(new TextSpan(52, 2), string.Empty), new TextChange(new TextSpan(64, 2), string.Empty), }; var expectedSelectedSpans = new[] { Span.FromBounds(20, 21), Span.FromBounds(34, 34), Span.FromBounds(41, 42), Span.FromBounds(56, 56), }; UncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void Uncomment_PartOfMultipleComments() { var code = @" //|start|//namespace N ////{ //|end|//}"; var expectedChanges = new[] { new TextChange(new TextSpan(2, 2), string.Empty), new TextChange(new TextSpan(19, 2), string.Empty), new TextChange(new TextSpan(26, 2), string.Empty), }; UncommentSelection(code, expectedChanges, Span.FromBounds(2, 25), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(530300)] [WorkItem(563924)] public void Comment_NoSelectionAtStartOfLine() { var code = @"|start||end|using System;"; CommentSelection(code, new[] { new TextChange(TextSpan.FromBounds(0, 0), "//") }, new[] { new Span(0, 15) }, supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(932411)] public void Uncomment_NoSelectionInBlockComment() { var code = @"using /* Sy|start||end|stem.*/IO;"; UncommentSelection(code, expectedChanges: new[] { new TextChange(new TextSpan(6, 2), string.Empty), new TextChange(new TextSpan(16, 2), string.Empty) }, expectedSelectedSpan: new Span(6, 8), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(932411)] public void Uncomment_BlockCommentWithPreviousBlockComment() { var code = @"/* comment */using /* Sy|start||end|stem.*/IO;"; UncommentSelection(code, expectedChanges: new[] { new TextChange(new TextSpan(19, 2), string.Empty), new TextChange(new TextSpan(29, 2), string.Empty) }, expectedSelectedSpan: new Span(19, 8), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(932411)] public void Uncomment_InsideEndOfBlockComment() { var code = @"/*using System;*|start||end|/"; UncommentSelection(code, expectedChanges: new[] { new TextChange(new TextSpan(0, 2), string.Empty), new TextChange(new TextSpan(15, 2), string.Empty) }, expectedSelectedSpan: new Span(0, 13), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(932411)] public void Uncomment_AtBeginningOfEndOfBlockComment() { var code = @"/*using System;|start||end|*/"; UncommentSelection(code, expectedChanges: new[] { new TextChange(new TextSpan(0, 2), string.Empty), new TextChange(new TextSpan(15, 2), string.Empty) }, expectedSelectedSpan: new Span(0, 13), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(932411)] public void Uncomment_AtEndOfBlockComment() { var code = @"/*using System;*/|start||end|"; UncommentSelection(code, Enumerable.Empty<TextChange>(), new Span(17, 0), supportBlockComments: true); } [Fact, Trait(Traits.Feature, Traits.Features.CommentSelection)] [WorkItem(932411)] public void Uncomment_BlockCommentWithNoEnd() { var code = @"/*using |start||end|System;"; UncommentSelection(code, Enumerable.Empty<TextChange>(), new Span(8, 0), supportBlockComments: true); } private static void UncommentSelection(string code, IEnumerable<TextChange> expectedChanges, Span expectedSelectedSpan, bool supportBlockComments) { CommentOrUncommentSelection(code, expectedChanges, new[] { expectedSelectedSpan }, supportBlockComments, CommentUncommentSelectionCommandHandler.Operation.Uncomment); } private static void UncommentSelection(string code, IEnumerable<TextChange> expectedChanges, IEnumerable<Span> expectedSelectedSpans, bool supportBlockComments) { CommentOrUncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments, CommentUncommentSelectionCommandHandler.Operation.Uncomment); } private static void CommentSelection(string code, IEnumerable<TextChange> expectedChanges, bool supportBlockComments) { CommentOrUncommentSelection(code, expectedChanges, null /*expectedSelectedSpans*/, supportBlockComments, CommentUncommentSelectionCommandHandler.Operation.Comment); } private static void CommentSelection(string code, IEnumerable<TextChange> expectedChanges, IEnumerable<Span> expectedSelectedSpans, bool supportBlockComments) { CommentOrUncommentSelection(code, expectedChanges, expectedSelectedSpans, supportBlockComments, CommentUncommentSelectionCommandHandler.Operation.Comment); } private static void CommentSelection(ITextView textView, IEnumerable<TextChange> expectedChanges, IEnumerable<Span> expectedSelectedSpans, bool supportBlockComments) { CommentOrUncommentSelection(textView, expectedChanges, expectedSelectedSpans, supportBlockComments, CommentUncommentSelectionCommandHandler.Operation.Comment); } private static void CommentOrUncommentSelection( string code, IEnumerable<TextChange> expectedChanges, IEnumerable<Span> expectedSelectedSpans, bool supportBlockComments, CommentUncommentSelectionCommandHandler.Operation operation) { var textView = EditorFactory.CreateView(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, code); var selectedSpans = SetupSelection(textView); CommentOrUncommentSelection(textView, expectedChanges, expectedSelectedSpans, supportBlockComments, operation); } private static void CommentOrUncommentSelection( ITextView textView, IEnumerable<TextChange> expectedChanges, IEnumerable<Span> expectedSelectedSpans, bool supportBlockComments, CommentUncommentSelectionCommandHandler.Operation operation) { var commandHandler = new CommentUncommentSelectionCommandHandler(TestWaitIndicator.Default); var service = new MockCommentUncommentService(supportBlockComments); var trackingSpans = new List<ITrackingSpan>(); var textChanges = new List<TextChange>(); commandHandler.CollectEdits(service, textView.Selection.GetSnapshotSpansOnBuffer(textView.TextBuffer), textChanges, trackingSpans, operation); AssertEx.SetEqual(expectedChanges, textChanges); // Actually apply the edit to let the tracking spans adjust. using (var edit = textView.TextBuffer.CreateEdit()) { textChanges.Do(tc => edit.Replace(tc.Span.ToSpan(), tc.NewText)); edit.Apply(); } if (trackingSpans.Any()) { textView.SetSelection(trackingSpans.First().GetSpan(textView.TextSnapshot)); } if (expectedSelectedSpans != null) { AssertEx.Equal(expectedSelectedSpans, textView.Selection.SelectedSpans.Select(snapshotSpan => snapshotSpan.Span)); } } private static IEnumerable<Span> SetupSelection(IWpfTextView textView) { var spans = new List<Span>(); while (true) { var startOfSelection = FindAndRemoveMarker(textView, "|start|"); var endOfSelection = FindAndRemoveMarker(textView, "|end|"); if (startOfSelection < 0) { break; } else { spans.Add(Span.FromBounds(startOfSelection, endOfSelection)); } } var snapshot = textView.TextSnapshot; if (spans.Count == 1) { textView.Selection.Select(new SnapshotSpan(snapshot, spans.Single()), isReversed: false); textView.Caret.MoveTo(new SnapshotPoint(snapshot, spans.Single().End)); } else { textView.Selection.Mode = TextSelectionMode.Box; textView.Selection.Select(new VirtualSnapshotPoint(snapshot, spans.First().Start), new VirtualSnapshotPoint(snapshot, spans.Last().End)); textView.Caret.MoveTo(new SnapshotPoint(snapshot, spans.Last().End)); } return spans; } private static int FindAndRemoveMarker(ITextView textView, string marker) { var index = textView.TextSnapshot.GetText().IndexOf(marker, StringComparison.Ordinal); if (index >= 0) { textView.TextBuffer.Delete(new Span(index, marker.Length)); } return index; } } }
// <copyright file="BinomialTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2014 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> namespace MathNet.Numerics.UnitTests.DistributionTests.Discrete { using System; using System.Linq; using Distributions; using NUnit.Framework; /// <summary> /// Binomial distribution tests. /// </summary> [TestFixture, Category("Distributions")] public class BinomialTests { /// <summary> /// Can create binomial. /// </summary> /// <param name="p">Success probability.</param> /// <param name="n">Number of trials.</param> [TestCase(0.0, 4)] [TestCase(0.3, 3)] [TestCase(1.0, 2)] public void CanCreateBinomial(double p, int n) { var bernoulli = new Binomial(p, n); Assert.AreEqual(p, bernoulli.P); } /// <summary> /// Binomial create fails with bad parameters. /// </summary> /// <param name="p">Success probability.</param> /// <param name="n">Number of trials.</param> [TestCase(Double.NaN, 1)] [TestCase(-1.0, 1)] [TestCase(2.0, 1)] [TestCase(0.3, -2)] public void BinomialCreateFailsWithBadParameters(double p, int n) { Assert.That(() => new Binomial(p, n), Throws.ArgumentException); } /// <summary> /// Validate ToString. /// </summary> [Test] public void ValidateToString() { var b = new Binomial(0.3, 2); Assert.AreEqual("Binomial(p = 0.3, n = 2)", b.ToString()); } /// <summary> /// Validate entropy. /// </summary> /// <param name="p">Success probability.</param> /// <param name="n">Number of trials.</param> /// <param name="e">Expected value.</param> [TestCase(0.0, 4, 0.0)] [TestCase(0.3, 3, 1.1404671643037712668976423399228972051669206536461)] [TestCase(1.0, 2, 0.0)] public void ValidateEntropy(double p, int n, double e) { var b = new Binomial(p, n); AssertHelpers.AlmostEqualRelative(e, b.Entropy, 14); } /// <summary> /// Validate skewness /// </summary> /// <param name="p">Success probability.</param> /// <param name="n">Number of trials.</param> [TestCase(0.0, 4)] [TestCase(0.3, 3)] [TestCase(1.0, 2)] public void ValidateSkewness(double p, int n) { var b = new Binomial(p, n); Assert.AreEqual((1.0 - (2.0 * p)) / Math.Sqrt(n * p * (1.0 - p)), b.Skewness); } /// <summary> /// Validate mode. /// </summary> /// <param name="p">Success probability.</param> /// <param name="n">Number of trials.</param> /// <param name="m">Expected value.</param> [TestCase(0.0, 4, 0)] [TestCase(0.3, 3, 1)] [TestCase(1.0, 2, 2)] public void ValidateMode(double p, int n, int m) { var b = new Binomial(p, n); Assert.AreEqual(m, b.Mode); } /// <summary> /// Validate minimum. /// </summary> [Test] public void ValidateMinimum() { var b = new Binomial(0.3, 10); Assert.AreEqual(0, b.Minimum); } /// <summary> /// Validate maximum. /// </summary> [Test] public void ValidateMaximum() { var b = new Binomial(0.3, 10); Assert.AreEqual(10, b.Maximum); } /// <summary> /// Validate probability. /// </summary> /// <param name="p">Success probability.</param> /// <param name="n">Number of trials.</param> /// <param name="x">Input X value.</param> /// <param name="d">Expected value.</param> [TestCase(0.000000, 1, 0, 1.0)] [TestCase(0.000000, 1, 1, 0.0)] [TestCase(0.000000, 3, 0, 1.0)] [TestCase(0.000000, 3, 1, 0.0)] [TestCase(0.000000, 3, 3, 0.0)] [TestCase(0.000000, 10, 0, 1.0)] [TestCase(0.000000, 10, 1, 0.0)] [TestCase(0.000000, 10, 10, 0.0)] [TestCase(0.300000, 1, 0, 0.69999999999999995559107901499373838305473327636719)] [TestCase(0.300000, 1, 1, 0.2999999999999999888977697537484345957636833190918)] [TestCase(0.300000, 3, 0, 0.34299999999999993471888615204079956461021032657166)] [TestCase(0.300000, 3, 1, 0.44099999999999992772448109690231306411849135972008)] [TestCase(0.300000, 3, 3, 0.026999999999999997002397833512077451789759292859569)] [TestCase(0.300000, 10, 0, 0.02824752489999998207939855277004937778546385011091)] [TestCase(0.300000, 10, 1, 0.12106082099999992639752977030555903089040470780077)] [TestCase(0.300000, 10, 10, 0.0000059048999999999978147480206303047454017251032868501)] [TestCase(1.000000, 1, 0, 0.0)] [TestCase(1.000000, 1, 1, 1.0)] [TestCase(1.000000, 3, 0, 0.0)] [TestCase(1.000000, 3, 1, 0.0)] [TestCase(1.000000, 3, 3, 1.0)] [TestCase(1.000000, 10, 0, 0.0)] [TestCase(1.000000, 10, 1, 0.0)] [TestCase(1.000000, 10, 10, 1.0)] public void ValidateProbability(double p, int n, int x, double d) { var b = new Binomial(p, n); AssertHelpers.AlmostEqualRelative(d, b.Probability(x), 14); } /// <summary> /// Validate probability log. /// </summary> /// <param name="p">Success probability.</param> /// <param name="n">Number of trials.</param> /// <param name="x">Input X value.</param> /// <param name="dln">Expected value.</param> [TestCase(0.000000, 1, 0, 0.0)] [TestCase(0.000000, 1, 1, Double.NegativeInfinity)] [TestCase(0.000000, 3, 0, 0.0)] [TestCase(0.000000, 3, 1, Double.NegativeInfinity)] [TestCase(0.000000, 3, 3, Double.NegativeInfinity)] [TestCase(0.000000, 10, 0, 0.0)] [TestCase(0.000000, 10, 1, Double.NegativeInfinity)] [TestCase(0.000000, 10, 10, Double.NegativeInfinity)] [TestCase(0.300000, 1, 0, -0.3566749439387324423539544041072745145718090708995)] [TestCase(0.300000, 1, 1, -1.2039728043259360296301803719337238685164245381839)] [TestCase(0.300000, 3, 0, -1.0700248318161973270618632123218235437154272126985)] [TestCase(0.300000, 3, 1, -0.81871040353529122294284394322574719301255212216016)] [TestCase(0.300000, 3, 3, -3.6119184129778080888905411158011716055492736145517)] [TestCase(0.300000, 10, 0, -3.566749439387324423539544041072745145718090708995)] [TestCase(0.300000, 10, 1, -2.1114622067804823267977785542148302920616046876506)] [TestCase(0.300000, 10, 10, -12.039728043259360296301803719337238685164245381839)] [TestCase(1.000000, 1, 0, Double.NegativeInfinity)] [TestCase(1.000000, 1, 1, 0.0)] [TestCase(1.000000, 3, 0, Double.NegativeInfinity)] [TestCase(1.000000, 3, 1, Double.NegativeInfinity)] [TestCase(1.000000, 3, 3, 0.0)] [TestCase(1.000000, 10, 0, Double.NegativeInfinity)] [TestCase(1.000000, 10, 1, Double.NegativeInfinity)] [TestCase(1.000000, 10, 10, 0.0)] public void ValidateProbabilityLn(double p, int n, int x, double dln) { var b = new Binomial(p, n); AssertHelpers.AlmostEqualRelative(dln, b.ProbabilityLn(x), 14); } /// <summary> /// Can sample static. /// </summary> [Test] public void CanSampleStatic() { Binomial.Sample(new Random(0), 0.3, 5); } /// <summary> /// Can sample sequence static. /// </summary> [Test] public void CanSampleSequenceStatic() { var ied = Binomial.Samples(new Random(0), 0.3, 5); GC.KeepAlive(ied.Take(5).ToArray()); } /// <summary> /// Fail sample static with bad parameters. /// </summary> [Test] public void FailSampleStatic() { Assert.That(() => Binomial.Sample(new Random(0), -1.0, 5), Throws.ArgumentException); } /// <summary> /// Fail sample sequence static with bad parameters. /// </summary> [Test] public void FailSampleSequenceStatic() { Assert.That(() => Binomial.Samples(new Random(0), -1.0, 5).First(), Throws.ArgumentException); } /// <summary> /// Can sample. /// </summary> [Test] public void CanSample() { var n = new Binomial(0.3, 5); n.Sample(); } /// <summary> /// Can sample sequence. /// </summary> [Test] public void CanSampleSequence() { var n = new Binomial(0.3, 5); var ied = n.Samples(); GC.KeepAlive(ied.Take(5).ToArray()); } } }
namespace MyNotes.Migrations { using System; using System.Data.Entity.Migrations; public partial class Initial : DbMigration { public override void Up() { CreateTable( "dbo.CreditCards", c => new { Id = c.Int(nullable: false, identity: true), StripeId = c.String(), Name = c.String(nullable: false), Last4 = c.String(), Type = c.String(), Fingerprint = c.String(), AddressCity = c.String(nullable: false), AddressCountry = c.String(nullable: false), AddressLine1 = c.String(nullable: false), AddressLine2 = c.String(), AddressState = c.String(), AddressZip = c.String(nullable: false), Cvc = c.String(nullable: false, maxLength: 4), ExpirationMonth = c.String(nullable: false), ExpirationYear = c.String(nullable: false), CardCountry = c.String(), SaasEcomUserId = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Invoices", c => new { Id = c.Int(nullable: false, identity: true), StripeId = c.String(maxLength: 50), StripeCustomerId = c.String(maxLength: 50), Date = c.DateTime(), PeriodStart = c.DateTime(), PeriodEnd = c.DateTime(), Subtotal = c.Int(), Total = c.Int(), Attempted = c.Boolean(), Closed = c.Boolean(), Paid = c.Boolean(), AttemptCount = c.Int(), AmountDue = c.Int(), StartingBalance = c.Int(), EndingBalance = c.Int(), NextPaymentAttempt = c.DateTime(), ApplicationFee = c.Int(), Tax = c.Int(), TaxPercent = c.Decimal(precision: 18, scale: 2), Currency = c.String(), BillingAddress_Name = c.String(), BillingAddress_AddressLine1 = c.String(), BillingAddress_AddressLine2 = c.String(), BillingAddress_City = c.String(), BillingAddress_State = c.String(), BillingAddress_ZipCode = c.String(), BillingAddress_Country = c.String(), BillingAddress_Vat = c.String(), Description = c.String(), StatementDescriptor = c.String(), ReceiptNumber = c.String(), Forgiven = c.Boolean(nullable: false), Customer_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .Index(t => t.StripeId, unique: true) .Index(t => t.StripeCustomerId) .Index(t => t.Paid); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(), ClaimType = c.String(), ClaimValue = c.String(), SaasEcomUser_Id = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), SaasEcomUser_Id = c.String(maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), SaasEcomUser_Id = c.String(maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.RoleId); CreateTable( "dbo.Subscriptions", c => new { Id = c.Int(nullable: false, identity: true), Start = c.DateTime(), End = c.DateTime(), TrialStart = c.DateTime(), TrialEnd = c.DateTime(), SubscriptionPlanId = c.String(maxLength: 128), UserId = c.String(maxLength: 128), StripeId = c.String(maxLength: 50), Status = c.String(), TaxPercent = c.Decimal(nullable: false, precision: 18, scale: 2), ReasonToCancel = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.SubscriptionPlans", t => t.SubscriptionPlanId) .Index(t => t.SubscriptionPlanId) .Index(t => t.StripeId); CreateTable( "dbo.SubscriptionPlans", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false), Price = c.Double(nullable: false), Currency = c.String(), Interval = c.Int(nullable: false), TrialPeriodInDays = c.Int(nullable: false), Disabled = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.SubscriptionPlanProperties", c => new { Id = c.Int(nullable: false, identity: true), Key = c.String(), Value = c.String(), SubscriptionPlan_Id = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.SubscriptionPlans", t => t.SubscriptionPlan_Id, cascadeDelete: true) .Index(t => t.SubscriptionPlan_Id); CreateTable( "dbo.LineItems", c => new { Id = c.Int(nullable: false, identity: true), StripeLineItemId = c.String(), Type = c.String(), Amount = c.Int(), Currency = c.String(), Proration = c.Boolean(nullable: false), Period_Start = c.DateTime(), Period_End = c.DateTime(), Quantity = c.Int(), Plan_StripePlanId = c.String(), Plan_Interval = c.String(), Plan_Name = c.String(), Plan_Created = c.DateTime(), Plan_AmountInCents = c.Int(), Plan_Currency = c.String(), Plan_IntervalCount = c.Int(nullable: false), Plan_TrialPeriodDays = c.Int(), Plan_StatementDescriptor = c.String(), Invoice_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Invoices", t => t.Invoice_Id) .Index(t => t.Invoice_Id); CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), FirstName = c.String(), LastName = c.String(), RegistrationDate = c.DateTime(nullable: false), LastLoginTime = c.DateTime(nullable: false), StripeCustomerId = c.String(), IPAddress = c.String(), IPAddressCountry = c.String(), Delinquent = c.Boolean(nullable: false), LifetimeValue = c.Decimal(nullable: false, precision: 18, scale: 2), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); } public override void Down() { DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.LineItems", "Invoice_Id", "dbo.Invoices"); DropForeignKey("dbo.Subscriptions", "SubscriptionPlanId", "dbo.SubscriptionPlans"); DropForeignKey("dbo.SubscriptionPlanProperties", "SubscriptionPlan_Id", "dbo.SubscriptionPlans"); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.LineItems", new[] { "Invoice_Id" }); DropIndex("dbo.SubscriptionPlanProperties", new[] { "SubscriptionPlan_Id" }); DropIndex("dbo.Subscriptions", new[] { "StripeId" }); DropIndex("dbo.Subscriptions", new[] { "SubscriptionPlanId" }); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.Invoices", new[] { "Paid" }); DropIndex("dbo.Invoices", new[] { "StripeCustomerId" }); DropIndex("dbo.Invoices", new[] { "StripeId" }); DropTable("dbo.AspNetUsers"); DropTable("dbo.AspNetRoles"); DropTable("dbo.LineItems"); DropTable("dbo.SubscriptionPlanProperties"); DropTable("dbo.SubscriptionPlans"); DropTable("dbo.Subscriptions"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.Invoices"); DropTable("dbo.CreditCards"); } } }
// using Nito.AsyncEx; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Box.V2.Config; using Box.V2.Converter; using Box.V2.Exceptions; using Box.V2.Extensions; using Box.V2.Services; namespace Box.V2.Auth { /// <summary> /// Default auth repository implementation that will manage the life cycle of the authentication tokens. /// This class can be extended to provide your own token management implementation by overriding the virtual methods /// </summary> public class AuthRepository : IAuthRepository { protected IBoxConfig _config; protected IBoxService _service; protected IBoxConverter _converter; private readonly List<string> _expiredTokens = new List<string>(); private readonly SemaphoreSlim _mutex = new SemaphoreSlim(1); /// <summary> /// Fires when the authentication session is invalidated /// </summary> public event EventHandler SessionInvalidated; /// <summary> /// Fires when a new set of auth token and refresh token pair has been fetched /// </summary> public event EventHandler<SessionAuthenticatedEventArgs> SessionAuthenticated; /// <summary> /// Instantiates a new AuthRepository. /// </summary> /// <param name="boxConfig">The Box configuration that should be used.</param> /// <param name="boxService">The Box service that will be used to make the requests.</param> /// <param name="converter">How requests/responses will be serialized/deserialized respectively.</param> public AuthRepository(IBoxConfig boxConfig, IBoxService boxService, IBoxConverter converter) : this(boxConfig, boxService, converter, null) { } /// <summary> /// Instantiates a new AuthRepository /// </summary> /// <param name="boxConfig">The Box configuration that should be used</param> /// <param name="boxService">The Box service that will be used to make the requests</param> /// <param name="converter">How requests/responses will be serialized/deserialized respectively</param> /// <param name="session">The current authenticated session</param> public AuthRepository(IBoxConfig boxConfig, IBoxService boxService, IBoxConverter converter, OAuthSession session) { _config = boxConfig; _service = boxService; _converter = converter; Session = session; } /// <summary> /// The current session of the Box Client /// </summary> public OAuthSession Session { get; protected set; } #region Overrideable Methods /// <summary> /// Authenticates the session by exchanging the provided auth code for a Access/Refresh token pair /// </summary> /// <param name="authCode">Authorization Code. The authorization code is only valid for 30 seconds.</param> /// <returns>The session of the Box Client after authentification</returns> public virtual async Task<OAuthSession> AuthenticateAsync(string authCode) { OAuthSession session = await ExchangeAuthCode(authCode).ConfigureAwait(false); await _mutex.WaitAsync().ConfigureAwait(false); // using (await _mutex.LockAsync().ConfigureAwait(false)) try { Session = session; OnSessionAuthenticated(session); } finally { _mutex.Release(); } return session; } /// <summary> /// Refreshes the session by exchanging the access token for a new Access/Refresh token pair. In general, /// this method should not need to be called explicitly, as an automatic refresh is invoked when the SDK /// detects that the tokens have expired. /// </summary> /// <param name="accessToken">The access token to refresh.</param> /// <returns>Refreshed session of Box Client.</returns> public virtual async Task<OAuthSession> RefreshAccessTokenAsync(string accessToken) { OAuthSession session; await _mutex.WaitAsync().ConfigureAwait(false); // using (await _mutex.LockAsync().ConfigureAwait(false)) try { if (_expiredTokens.Contains(accessToken)) { session = Session; } else { // Add the expired token to the list so subsequent calls will get new acces token. Add // token to the list before making the network call. This way, if refresh fails, subsequent calls // with the same refresh token will not attempt the call. _expiredTokens.Add(accessToken); session = await ExchangeRefreshToken(Session.RefreshToken).ConfigureAwait(false); Session = session; OnSessionAuthenticated(session); } } finally { _mutex.Release(); } return session; } /// <summary> /// Logs the current session out by invalidating the current Access/Refresh tokens /// </summary> public virtual async Task LogoutAsync() { string token; await _mutex.WaitAsync().ConfigureAwait(false); //using (await _mutex.LockAsync().ConfigureAwait(false)) try { token = Session.AccessToken; } finally { _mutex.Release(); } await InvalidateTokens(token).ConfigureAwait(false); } #endregion /// <summary> /// Performs the authentication request using the provided auth code /// </summary> /// <param name="authCode">Authorization Code. The authorization code is only valid for 30 seconds.</param> /// <returns>The current session after exchanging Authorization Code</returns> protected async Task<OAuthSession> ExchangeAuthCode(string authCode) { if (string.IsNullOrWhiteSpace(authCode)) throw new ArgumentException("Auth code cannot be null or empty", "authCode"); BoxRequest boxRequest = new BoxRequest(_config.BoxApiHostUri, Constants.AuthTokenEndpointString) .Method(RequestMethod.Post) .Header(Constants.RequestParameters.UserAgent, _config.UserAgent) .Payload(Constants.RequestParameters.GrantType, Constants.RequestParameters.AuthorizationCode) .Payload(Constants.RequestParameters.Code, authCode) .Payload(Constants.RequestParameters.ClientId, _config.ClientId) .Payload(Constants.RequestParameters.ClientSecret, _config.ClientSecret) .Payload(Constants.RequestParameters.BoxDeviceId, _config.DeviceId) .Payload(Constants.RequestParameters.BoxDeviceName, _config.DeviceName); IBoxResponse<OAuthSession> boxResponse = await _service.ToResponseAsync<OAuthSession>(boxRequest).ConfigureAwait(false); boxResponse.ParseResults(_converter); return boxResponse.ResponseObject; } /// <summary> /// Performs the refresh request using the provided refresh token /// </summary> /// <param name="refreshToken">Refresh token used to exchange for a new access token. Each refresh_token is valid for one use in 60 days. Every time you get a new access_token by using a refresh_token, we reset your timer for the 60 day period and hand you a new refresh_token</param> /// <returns>Refreshed Box Client session</returns> protected async Task<OAuthSession> ExchangeRefreshToken(string refreshToken) { if (string.IsNullOrWhiteSpace(refreshToken)) throw new ArgumentException("Refresh token cannot be null or empty", "refreshToken"); BoxRequest boxRequest = new BoxRequest(_config.BoxApiHostUri, Constants.AuthTokenEndpointString) .Method(RequestMethod.Post) .Payload(Constants.RequestParameters.GrantType, Constants.RequestParameters.RefreshToken) .Payload(Constants.RequestParameters.RefreshToken, refreshToken) .Payload(Constants.RequestParameters.ClientId, _config.ClientId) .Payload(Constants.RequestParameters.ClientSecret, _config.ClientSecret) .Payload(Constants.RequestParameters.BoxDeviceId, _config.DeviceId) .Payload(Constants.RequestParameters.BoxDeviceName, _config.DeviceName); IBoxResponse<OAuthSession> boxResponse = await _service.ToResponseAsync<OAuthSession>(boxRequest).ConfigureAwait(false); if (boxResponse.Status == ResponseStatus.Success) { // Parse and return the new session boxResponse.ParseResults(_converter); return boxResponse.ResponseObject; } // The session has been invalidated, notify subscribers OnSessionInvalidated(); // As well as the caller throw BoxSessionInvalidatedException.GetResponseException("The API returned an error", boxResponse); } /// <summary> /// Performs the revoke request using the provided access token. This will invalidate both the access and refresh tokens /// </summary> /// <param name="accessToken">The access token to invalidate</param> protected async Task InvalidateTokens(string accessToken) { if (string.IsNullOrWhiteSpace(accessToken)) throw new ArgumentException("Access token cannot be null or empty", "accessToken"); BoxRequest boxRequest = new BoxRequest(_config.BoxApiHostUri, Constants.RevokeEndpointString) .Method(RequestMethod.Post) .Payload(Constants.RequestParameters.ClientId, _config.ClientId) .Payload(Constants.RequestParameters.ClientSecret, _config.ClientSecret) .Payload(Constants.RequestParameters.Token, accessToken); await _service.ToResponseAsync<OAuthSession>(boxRequest).ConfigureAwait(false); } /// <summary> /// Allows sub classes to invoke the SessionInvalidated event /// </summary> protected void OnSessionInvalidated() { SessionInvalidated?.Invoke(this, new EventArgs()); } /// <summary> /// Allows sub classes to invoke the SessionAuthenticated event. /// </summary> ///<param name="session">Authenticated session.</param> protected void OnSessionAuthenticated(OAuthSession session) { SessionAuthenticated?.Invoke(this, new SessionAuthenticatedEventArgs(session)); } } }